ss
[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:
30 self.current_candidates = sorted(self.options.keys())
94a5f62e 31 else:
d51b4107
O
32 try:
33 if begin == 0:
34 candidates = self.options.keys()
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:
42 self.current_candidates = [ w for w in candidates
43 if w.startswith(being_completed) ]
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 """
71 if os.path.isfile(HISTORY_FILENAME):
72 readline.read_history_file(HISTORY_FILENAME)
73
74
75def save_history():
76 """
77 Save history to file
78 """
79 readline.write_history_file(HISTORY_FILENAME)
80
81
d51b4107 82def init_interactive_shell(d):
94a5f62e 83 """
84 Init the rainbow shell
85 """
d51b4107 86 readline.set_completer(RainbowCompleter(d).complete)
94a5f62e 87 readline.parse_and_bind('set editing-mode vi')
affcb149
O
88 readline.parse_and_bind('set show-all-if-ambiguous on')
89 readline.parse_and_bind('set show-all-if-unmodified on')
90 readline.parse_and_bind('set skip-completed-text on')
4ac5fe72
O
91 if 'libedit' in readline.__doc__:
92 readline.parse_and_bind("bind ^I rl_complete")
93 else:
c91f75f2 94 readline.parse_and_bind("tab: complete")
95