fix annoyed bug when new tweet disrupt prompt
[rainbowstream.git] / rainbowstream / rainbow.py
index 60773477fb24f3d0ecb993af76a52fd5a3bd395d..9e94fb8be49c3df5dfdcd941f4118ebecf1ff6db 100644 (file)
@@ -157,7 +157,9 @@ def init(args):
     files = os.listdir(os.path.dirname(__file__) + '/colorset')
     themes = [f.split('.')[0] for f in files if f.split('.')[-1] == 'json']
     g['themes'] = themes
-    g['prev_theme'] = c['THEME']
+    # Startup cmd
+    g['OSX_readline_bug'] = False
+    g['previous_cmd'] = ''
     # Semaphore init
     c['lock'] = False
     c['pause'] = False
@@ -199,7 +201,11 @@ def switch():
             g['stream_stop'] = True
             args.track_keywords = keyword
             # Start new thread
-            th = threading.Thread(target=stream, args=(c['PUBLIC_DOMAIN'], args))
+            th = threading.Thread(
+                target=stream,
+                args=(
+                    c['PUBLIC_DOMAIN'],
+                    args))
             th.daemon = True
             th.start()
         # Personal stream
@@ -207,7 +213,12 @@ def switch():
             # Kill old thread
             g['stream_stop'] = True
             # Start new thread
-            th = threading.Thread(target=stream, args=(c['USER_DOMAIN'], args, g['original_name']))
+            th = threading.Thread(
+                target=stream,
+                args=(
+                    c['USER_DOMAIN'],
+                    args,
+                    g['original_name']))
             th.daemon = True
             th.start()
         printNicely('')
@@ -508,7 +519,7 @@ def urlopen():
     try:
         if not g['stuff'].isdigit():
             return
-        tid = c['tweet_dict'][g['stuff']]
+        tid = c['tweet_dict'][int(g['stuff'])]
         tweet = t.statuses.show(id=tid)
         link_ary = [
             u for u in tweet['text'].split() if u.startswith('http://')]
@@ -1137,7 +1148,7 @@ def config():
             set_config(key, value)
             # Apply theme immediately
             if key == 'THEME':
-                c['THEME'] = reload_theme(value,c['THEME'])
+                c['THEME'] = reload_theme(value, c['THEME'])
                 g['decorated_name'] = lambda x: color_func(
                     c['DECORATED_NAME'])(
                     '[' + x + ']: ')
@@ -1167,14 +1178,13 @@ def theme():
         # Change theme
         try:
             # Load new theme
-            c['THEME'] = reload_theme(g['stuff'],c['THEME'])
+            c['THEME'] = reload_theme(g['stuff'], c['THEME'])
             # Redefine decorated_name
             g['decorated_name'] = lambda x: color_func(
                 c['DECORATED_NAME'])(
                 '[' + x + ']: ')
             printNicely(green('Theme changed.'))
-        except Exception as e:
-            print e
+        except:
             printNicely(red('No such theme exists.'))
 
 
@@ -1433,7 +1443,10 @@ def help():
         'stream': help_stream,
     }
     if g['stuff']:
-        d[g['stuff'].strip()]()
+        d.get(
+            g['stuff'].strip(),
+            lambda: printNicely(red('No such command.'))
+            )()
     else:
         printNicely(usage)
 
@@ -1607,18 +1620,22 @@ def listen():
     read_history()
     reset()
     while True:
-        # Prompt redraw is needed when user is typing
         # raw_input
         if g['prefix']:
             line = raw_input(g['decorated_name'](c['PREFIX']))
         else:
             line = raw_input()
+        # Save previous cmd in order to compare with readline buffer
+        g['previous_cmd'] = line.strip()
         try:
             cmd = line.split()[0]
         except:
             cmd = ''
+        # MacOSX readline bug (see "stream" function)
+        if g['OSX_readline_bug']:
+            cmd = cmd[1:]
+            g['OSX_readline_bug'] = False
         g['cmd'] = cmd
-        # Prompt redraw not need when raw_input done
         try:
             # Lock the semaphore
             c['lock'] = True
@@ -1696,6 +1713,17 @@ def stream(domain, args, name='Rainbow Stream'):
                     fil=args.filter,
                     ig=args.ignore,
                 )
+                # Current readline buffer
+                current_buffer = readline.get_line_buffer().strip()
+                # There is an unexpected behaviour in MacOSX readline
+                # After completely delete a word after typing it
+                # somehow readline buffer still contains the 1st character of that word
+                if g['previous_cmd'] != current_buffer:
+                    if len(current_buffer) == 1:
+                        current_buffer = ''
+                        g['OSX_readline_bug'] = True
+                    sys.stdout.write(g['decorated_name'](c['PREFIX']) + current_buffer)
+                    sys.stdout.flush()
             elif tweet.get('direct_message'):
                 print_message(tweet['direct_message'], check_semaphore=True)
     except TwitterHTTPError:
@@ -1720,7 +1748,12 @@ def fly():
         save_history()
         sys.exit()
     # Spawn stream thread
-    th = threading.Thread(target=stream, args=(c['USER_DOMAIN'], args, g['original_name']))
+    th = threading.Thread(
+        target=stream,
+        args=(
+            c['USER_DOMAIN'],
+            args,
+            g['original_name']))
     th.daemon = True
     th.start()
     # Start listen process