-
Notifications
You must be signed in to change notification settings - Fork 83
/
Copy pathreadline_buffer.py
110 lines (90 loc) · 3.05 KB
/
readline_buffer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#!/usr/bin/env python3
# encoding: utf-8
#
# Copyright (c) 2008 Doug Hellmann All rights reserved.
#
"""
"""
#end_pymotw_header
try:
import gnureadline as readline
except ImportError:
import readline
import logging
LOG_FILENAME = '/tmp/completer.log'
logging.basicConfig(
format='%(message)s',
filename=LOG_FILENAME,
level=logging.DEBUG,
)
class BufferAwareCompleter:
def __init__(self, options):
self.options = options
self.current_candidates = []
def complete(self, text, state):
response = None
if state == 0:
# This is the first time for this text,
# so build a match list.
origline = readline.get_line_buffer()
begin = readline.get_begidx()
end = readline.get_endidx()
being_completed = origline[begin:end]
words = origline.split()
logging.debug('origline=%s', repr(origline))
logging.debug('begin=%s', begin)
logging.debug('end=%s', end)
logging.debug('being_completed=%s', being_completed)
logging.debug('words=%s', words)
if not words:
self.current_candidates = sorted(
self.options.keys()
)
else:
try:
if begin == 0:
# first word
candidates = self.options.keys()
else:
# later word
first = words[0]
candidates = self.options[first]
if being_completed:
# match options with portion of input
# being completed
self.current_candidates = [
w for w in candidates
if w.startswith(being_completed)
]
else:
# matching empty string,
# use all candidates
self.current_candidates = candidates
logging.debug('candidates=%s',
self.current_candidates)
except (KeyError, IndexError) as err:
logging.error('completion error: %s', err)
self.current_candidates = []
try:
response = self.current_candidates[state]
except IndexError:
response = None
logging.debug('complete(%s, %s) => %s',
repr(text), state, response)
return response
def input_loop():
line = ''
while line != 'stop':
line = input('Prompt ("stop" to quit): ')
print('Dispatch {}'.format(line))
# Register our completer function
completer = BufferAwareCompleter({
'list': ['files', 'directories'],
'print': ['byname', 'bysize'],
'stop': [],
})
readline.set_completer(completer.complete)
# Use the tab key for completion
readline.parse_and_bind('tab: complete')
# Prompt the user for text
input_loop()