Merge pull request #185 from Jorick/master
[rainbowstream.git] / rainbowstream / interactive.py
1 import readline
2 import os.path
3
4 from .config import *
5
6
7 class RainbowCompleter(object):
8
9 def __init__(self, options):
10 """
11 Init
12 """
13 self.options = options
14 self.current_candidates = []
15 return
16
17 def complete(self, text, state):
18 """
19 Complete
20 """
21 response = None
22 if state == 0:
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([c for c in self.options])
31 else:
32 try:
33 if begin == 0:
34 candidates = [c for c in self.options]
35 elif words[-1] in self.options[words[0]]:
36 candidates = []
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
47 except (KeyError, IndexError):
48 self.current_candidates = []
49
50 try:
51 response = self.current_candidates[state]
52 except IndexError:
53 response = None
54 return response
55
56
57 def 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
67 def read_history():
68 """
69 Read history file
70 """
71 try:
72 readline.read_history_file(c['HISTORY_FILENAME'])
73 except:
74 pass
75
76
77 def save_history():
78 """
79 Save history to file
80 """
81 try:
82 readline.write_history_file(c['HISTORY_FILENAME'])
83 except:
84 pass
85
86
87 def init_interactive_shell(d):
88 """
89 Init the rainbow shell
90 """
91 readline.set_completer(RainbowCompleter(d).complete)
92 readline.parse_and_bind('set skip-completed-text on')
93 if 'libedit' in readline.__doc__:
94 readline.parse_and_bind("bind ^I rl_complete")
95 else:
96 readline.parse_and_bind("tab: complete")