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