add color for my nick and fix https open bug
[rainbowstream.git] / rainbowstream / interactive.py
CommitLineData
94a5f62e 1import readline
f5677fb1
O
2import os.path
3
4from .config import *
5
b2b933a9 6
94a5f62e 7class RainbowCompleter(object):
b2b933a9 8
94a5f62e 9 def __init__(self, options):
10 """
11 Init
12 """
d51b4107
O
13 self.options = options
14 self.current_candidates = []
94a5f62e 15 return
16
17 def complete(self, text, state):
18 """
19 Complete
20 """
21 response = None
22 if state == 0:
d51b4107
O
23 origline = readline.get_line_buffer()
24 begin = readline.get_begidx()
25 end = readline.get_endidx()
26 being_completed = origline[begin:end]
27 words = origline.split()
28
29 if not words:
c3bab4ef 30 self.current_candidates = sorted([c for c in self.options])
94a5f62e 31 else:
d51b4107
O
32 try:
33 if begin == 0:
c3bab4ef 34 candidates = [c for c in self.options]
affcb149
O
35 elif words[-1] in self.options[words[0]]:
36 candidates = []
d51b4107
O
37 else:
38 first = words[0]
39 candidates = self.options[first]
40
41 if being_completed:
422dd385
O
42 self.current_candidates = [w for w in candidates
43 if w.startswith(being_completed)]
d51b4107
O
44 else:
45 self.current_candidates = candidates
46
affcb149 47 except (KeyError, IndexError):
d51b4107 48 self.current_candidates = []
b2b933a9 49
94a5f62e 50 try:
d51b4107 51 response = self.current_candidates[state]
94a5f62e 52 except IndexError:
53 response = None
54 return response
55
56
f5677fb1
O
57def get_history_items():
58 """
59 Get all history item
60 """
61 return [
62 readline.get_history_item(i)
63 for i in xrange(1, readline.get_current_history_length() + 1)
64 ]
65
66
67def read_history():
68 """
69 Read history file
70 """
223d2e05 71 try:
632c6fa5 72 readline.read_history_file(c['HISTORY_FILENAME'])
223d2e05
O
73 except:
74 pass
f5677fb1
O
75
76
77def save_history():
78 """
79 Save history to file
80 """
223d2e05
O
81 try:
82 readline.write_history_file(c['HISTORY_FILENAME'])
83 except:
84 pass
f5677fb1
O
85
86
d51b4107 87def init_interactive_shell(d):
94a5f62e 88 """
89 Init the rainbow shell
90 """
d51b4107 91 readline.set_completer(RainbowCompleter(d).complete)
affcb149 92 readline.parse_and_bind('set skip-completed-text on')
4ac5fe72
O
93 if 'libedit' in readline.__doc__:
94 readline.parse_and_bind("bind ^I rl_complete")
95 else:
c91f75f2 96 readline.parse_and_bind("tab: complete")