Skip to content

Commit 66a117c

Browse files
committed
Autocomplete dictionary keys if dictionary is declared globally.
1 parent f8ad90e commit 66a117c

File tree

2 files changed

+36
-2
lines changed

2 files changed

+36
-2
lines changed

bpython/autocomplete.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,36 @@ def __init__(self, namespace = None, config = None):
5353
else:
5454
self.autocomplete_mode = SUBSTRING
5555

56+
def complete(self, text, state):
57+
"""Return the next possible completion for 'text'.
58+
59+
This is called successively with state == 0, 1, 2, ... until it
60+
returns None. The completion should begin with 'text'.
61+
62+
"""
63+
if self.use_main_ns:
64+
self.namespace = __main__.__dict__
65+
66+
if state == 0:
67+
if "." in text:
68+
self.matches = self.attr_matches(text)
69+
#print self.matches
70+
# MAJA TODO: what if there's a dict in an object...?
71+
elif "[" in text:
72+
expr = text[:text.rindex('[')].lstrip()
73+
obj = eval(expr, self.locals)
74+
# use type() instead of hasattr?
75+
if obj and hasattr(obj,'keys') and obj.keys():
76+
self.matches = [expr + "[%r]" % k for k in obj.keys()]
77+
else:
78+
# empty dictionary
79+
self.matches = []
80+
else:
81+
self.matches = self.global_matches(text)
82+
try:
83+
return self.matches[state]
84+
except IndexError:
85+
return None
5686
def attr_matches(self, text):
5787
"""Taken from rlcompleter.py and bent to my will.
5888
"""

bpython/cli.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -507,11 +507,15 @@ def cw(self):
507507

508508
# look from right to left for a bad method character
509509
l = len(self.s)
510-
is_method_char = lambda c: c.isalnum() or c in ('.', '_')
510+
#MAJA is_method_or_dict_character, [ and \' major problem
511+
is_method_char = lambda c: c.isalnum() or c in ('.',
512+
'_', '[', '\'', ']')
511513

512514
if not self.s or not is_method_char(self.s[l-1]):
513515
return
514516

517+
#MAJA only dictionaries should have \' (TODO)
518+
515519
for i in range(1, l+1):
516520
if not is_method_char(self.s[-i]):
517521
i -= 1
@@ -1420,7 +1424,7 @@ def suspend(self):
14201424
os.kill(os.getpid(), signal.SIGSTOP)
14211425

14221426
def tab(self, back=False):
1423-
"""Process the tab key being hit.
1427+
"""Process the tab key being hit.
14241428
14251429
If there's only whitespace
14261430
in the line or the line is blank then process a normal tab,

0 commit comments

Comments
 (0)