check if None
[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(self.options.keys())
31 else:
32 try:
33 if begin == 0:
34 candidates = self.options.keys()
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 if os.path.isfile(c['HISTORY_FILENAME']):
72 readline.read_history_file(c['HISTORY_FILENAME'])
73
74
75 def save_history():
76 """
77 Save history to file
78 """
79 readline.write_history_file(c['HISTORY_FILENAME'])
80
81
82 def init_interactive_shell(d):
83 """
84 Init the rainbow shell
85 """
86 readline.set_completer(RainbowCompleter(d).complete)
87 readline.parse_and_bind('set editing-mode vi')
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')
91 if 'libedit' in readline.__doc__:
92 readline.parse_and_bind("bind ^I rl_complete")
93 else:
94 readline.parse_and_bind("tab: complete")
95