##// END OF EJS Templates
Remove some unhelpful info from IPython.core.completer
Thomas Kluyver -
Show More
@@ -1,1157 +1,1155 b''
1 """Word completion for IPython.
1 """Word completion for IPython.
2
2
3 This module is a fork of the rlcompleter module in the Python standard
3 This module is a fork of the rlcompleter module in the Python standard
4 library. The original enhancements made to rlcompleter have been sent
4 library. The original enhancements made to rlcompleter have been sent
5 upstream and were accepted as of Python 2.3, but we need a lot more
5 upstream and were accepted as of Python 2.3, but we need a lot more
6 functionality specific to IPython, so this module will continue to live as an
6 functionality specific to IPython, so this module will continue to live as an
7 IPython-specific utility.
7 IPython-specific utility.
8
8
9 Original rlcompleter documentation:
9 Original rlcompleter documentation:
10
10
11 This requires the latest extension to the readline module (the
11 This requires the latest extension to the readline module (the
12 completes keywords, built-ins and globals in __main__; when completing
12 completes keywords, built-ins and globals in __main__; when completing
13 NAME.NAME..., it evaluates (!) the expression up to the last dot and
13 NAME.NAME..., it evaluates (!) the expression up to the last dot and
14 completes its attributes.
14 completes its attributes.
15
15
16 It's very cool to do "import string" type "string.", hit the
16 It's very cool to do "import string" type "string.", hit the
17 completion key (twice), and see the list of names defined by the
17 completion key (twice), and see the list of names defined by the
18 string module!
18 string module!
19
19
20 Tip: to use the tab key as the completion key, call
20 Tip: to use the tab key as the completion key, call
21
21
22 readline.parse_and_bind("tab: complete")
22 readline.parse_and_bind("tab: complete")
23
23
24 Notes:
24 Notes:
25
25
26 - Exceptions raised by the completer function are *ignored* (and
26 - Exceptions raised by the completer function are *ignored* (and
27 generally cause the completion to fail). This is a feature -- since
27 generally cause the completion to fail). This is a feature -- since
28 readline sets the tty device in raw (or cbreak) mode, printing a
28 readline sets the tty device in raw (or cbreak) mode, printing a
29 traceback wouldn't work well without some complicated hoopla to save,
29 traceback wouldn't work well without some complicated hoopla to save,
30 reset and restore the tty state.
30 reset and restore the tty state.
31
31
32 - The evaluation of the NAME.NAME... form may cause arbitrary
32 - The evaluation of the NAME.NAME... form may cause arbitrary
33 application defined code to be executed if an object with a
33 application defined code to be executed if an object with a
34 ``__getattr__`` hook is found. Since it is the responsibility of the
34 ``__getattr__`` hook is found. Since it is the responsibility of the
35 application (or the user) to enable this feature, I consider this an
35 application (or the user) to enable this feature, I consider this an
36 acceptable risk. More complicated expressions (e.g. function calls or
36 acceptable risk. More complicated expressions (e.g. function calls or
37 indexing operations) are *not* evaluated.
37 indexing operations) are *not* evaluated.
38
38
39 - GNU readline is also used by the built-in functions input() and
39 - GNU readline is also used by the built-in functions input() and
40 raw_input(), and thus these also benefit/suffer from the completer
40 raw_input(), and thus these also benefit/suffer from the completer
41 features. Clearly an interactive application can benefit by
41 features. Clearly an interactive application can benefit by
42 specifying its own completer function and using raw_input() for all
42 specifying its own completer function and using raw_input() for all
43 its input.
43 its input.
44
44
45 - When the original stdin is not a tty device, GNU readline is never
45 - When the original stdin is not a tty device, GNU readline is never
46 used, and this module (and the readline module) are silently inactive.
46 used, and this module (and the readline module) are silently inactive.
47 """
47 """
48
48
49 #*****************************************************************************
49 #*****************************************************************************
50 #
50 #
51 # Since this file is essentially a minimally modified copy of the rlcompleter
51 # Since this file is essentially a minimally modified copy of the rlcompleter
52 # module which is part of the standard Python distribution, I assume that the
52 # module which is part of the standard Python distribution, I assume that the
53 # proper procedure is to maintain its copyright as belonging to the Python
53 # proper procedure is to maintain its copyright as belonging to the Python
54 # Software Foundation (in addition to my own, for all new code).
54 # Software Foundation (in addition to my own, for all new code).
55 #
55 #
56 # Copyright (C) 2008 IPython Development Team
56 # Copyright (C) 2008 IPython Development Team
57 # Copyright (C) 2001 Fernando Perez. <fperez@colorado.edu>
57 # Copyright (C) 2001 Fernando Perez. <fperez@colorado.edu>
58 # Copyright (C) 2001 Python Software Foundation, www.python.org
58 # Copyright (C) 2001 Python Software Foundation, www.python.org
59 #
59 #
60 # Distributed under the terms of the BSD License. The full license is in
60 # Distributed under the terms of the BSD License. The full license is in
61 # the file COPYING, distributed as part of this software.
61 # the file COPYING, distributed as part of this software.
62 #
62 #
63 #*****************************************************************************
63 #*****************************************************************************
64
64
65 #-----------------------------------------------------------------------------
65 #-----------------------------------------------------------------------------
66 # Imports
66 # Imports
67 #-----------------------------------------------------------------------------
67 #-----------------------------------------------------------------------------
68
68
69 import __main__
69 import __main__
70 import glob
70 import glob
71 import inspect
71 import inspect
72 import itertools
72 import itertools
73 import keyword
73 import keyword
74 import os
74 import os
75 import re
75 import re
76 import sys
76 import sys
77
77
78 from IPython.config.configurable import Configurable
78 from IPython.config.configurable import Configurable
79 from IPython.core.error import TryNext
79 from IPython.core.error import TryNext
80 from IPython.core.inputsplitter import ESC_MAGIC
80 from IPython.core.inputsplitter import ESC_MAGIC
81 from IPython.utils import generics
81 from IPython.utils import generics
82 from IPython.utils import io
82 from IPython.utils import io
83 from IPython.utils.decorators import undoc
83 from IPython.utils.dir2 import dir2
84 from IPython.utils.dir2 import dir2
84 from IPython.utils.process import arg_split
85 from IPython.utils.process import arg_split
85 from IPython.utils.py3compat import builtin_mod, string_types
86 from IPython.utils.py3compat import builtin_mod, string_types
86 from IPython.utils.traitlets import CBool, Enum
87 from IPython.utils.traitlets import CBool, Enum
87
88
88 #-----------------------------------------------------------------------------
89 #-----------------------------------------------------------------------------
89 # Globals
90 # Globals
90 #-----------------------------------------------------------------------------
91 #-----------------------------------------------------------------------------
91
92
92 # Public API
93 # Public API
93 __all__ = ['Completer','IPCompleter']
94 __all__ = ['Completer','IPCompleter']
94
95
95 if sys.platform == 'win32':
96 if sys.platform == 'win32':
96 PROTECTABLES = ' '
97 PROTECTABLES = ' '
97 else:
98 else:
98 PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&'
99 PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&'
99
100
100
101
101 #-----------------------------------------------------------------------------
102 #-----------------------------------------------------------------------------
102 # Main functions and classes
103 # Main functions and classes
103 #-----------------------------------------------------------------------------
104 #-----------------------------------------------------------------------------
104
105
105 def has_open_quotes(s):
106 def has_open_quotes(s):
106 """Return whether a string has open quotes.
107 """Return whether a string has open quotes.
107
108
108 This simply counts whether the number of quote characters of either type in
109 This simply counts whether the number of quote characters of either type in
109 the string is odd.
110 the string is odd.
110
111
111 Returns
112 Returns
112 -------
113 -------
113 If there is an open quote, the quote character is returned. Else, return
114 If there is an open quote, the quote character is returned. Else, return
114 False.
115 False.
115 """
116 """
116 # We check " first, then ', so complex cases with nested quotes will get
117 # We check " first, then ', so complex cases with nested quotes will get
117 # the " to take precedence.
118 # the " to take precedence.
118 if s.count('"') % 2:
119 if s.count('"') % 2:
119 return '"'
120 return '"'
120 elif s.count("'") % 2:
121 elif s.count("'") % 2:
121 return "'"
122 return "'"
122 else:
123 else:
123 return False
124 return False
124
125
125
126
126 def protect_filename(s):
127 def protect_filename(s):
127 """Escape a string to protect certain characters."""
128 """Escape a string to protect certain characters."""
128
129
129 return "".join([(ch in PROTECTABLES and '\\' + ch or ch)
130 return "".join([(ch in PROTECTABLES and '\\' + ch or ch)
130 for ch in s])
131 for ch in s])
131
132
132 def expand_user(path):
133 def expand_user(path):
133 """Expand '~'-style usernames in strings.
134 """Expand '~'-style usernames in strings.
134
135
135 This is similar to :func:`os.path.expanduser`, but it computes and returns
136 This is similar to :func:`os.path.expanduser`, but it computes and returns
136 extra information that will be useful if the input was being used in
137 extra information that will be useful if the input was being used in
137 computing completions, and you wish to return the completions with the
138 computing completions, and you wish to return the completions with the
138 original '~' instead of its expanded value.
139 original '~' instead of its expanded value.
139
140
140 Parameters
141 Parameters
141 ----------
142 ----------
142 path : str
143 path : str
143 String to be expanded. If no ~ is present, the output is the same as the
144 String to be expanded. If no ~ is present, the output is the same as the
144 input.
145 input.
145
146
146 Returns
147 Returns
147 -------
148 -------
148 newpath : str
149 newpath : str
149 Result of ~ expansion in the input path.
150 Result of ~ expansion in the input path.
150 tilde_expand : bool
151 tilde_expand : bool
151 Whether any expansion was performed or not.
152 Whether any expansion was performed or not.
152 tilde_val : str
153 tilde_val : str
153 The value that ~ was replaced with.
154 The value that ~ was replaced with.
154 """
155 """
155 # Default values
156 # Default values
156 tilde_expand = False
157 tilde_expand = False
157 tilde_val = ''
158 tilde_val = ''
158 newpath = path
159 newpath = path
159
160
160 if path.startswith('~'):
161 if path.startswith('~'):
161 tilde_expand = True
162 tilde_expand = True
162 rest = len(path)-1
163 rest = len(path)-1
163 newpath = os.path.expanduser(path)
164 newpath = os.path.expanduser(path)
164 if rest:
165 if rest:
165 tilde_val = newpath[:-rest]
166 tilde_val = newpath[:-rest]
166 else:
167 else:
167 tilde_val = newpath
168 tilde_val = newpath
168
169
169 return newpath, tilde_expand, tilde_val
170 return newpath, tilde_expand, tilde_val
170
171
171
172
172 def compress_user(path, tilde_expand, tilde_val):
173 def compress_user(path, tilde_expand, tilde_val):
173 """Does the opposite of expand_user, with its outputs.
174 """Does the opposite of expand_user, with its outputs.
174 """
175 """
175 if tilde_expand:
176 if tilde_expand:
176 return path.replace(tilde_val, '~')
177 return path.replace(tilde_val, '~')
177 else:
178 else:
178 return path
179 return path
179
180
180
181
181
182
182 def penalize_magics_key(word):
183 def penalize_magics_key(word):
183 """key for sorting that penalizes magic commands in the ordering
184 """key for sorting that penalizes magic commands in the ordering
184
185
185 Normal words are left alone.
186 Normal words are left alone.
186
187
187 Magic commands have the initial % moved to the end, e.g.
188 Magic commands have the initial % moved to the end, e.g.
188 %matplotlib is transformed as follows:
189 %matplotlib is transformed as follows:
189
190
190 %matplotlib -> matplotlib%
191 %matplotlib -> matplotlib%
191
192
192 [The choice of the final % is arbitrary.]
193 [The choice of the final % is arbitrary.]
193
194
194 Since "matplotlib" < "matplotlib%" as strings,
195 Since "matplotlib" < "matplotlib%" as strings,
195 "timeit" will appear before the magic "%timeit" in the ordering
196 "timeit" will appear before the magic "%timeit" in the ordering
196
197
197 For consistency, move "%%" to the end, so cell magics appear *after*
198 For consistency, move "%%" to the end, so cell magics appear *after*
198 line magics with the same name.
199 line magics with the same name.
199
200
200 A check is performed that there are no other "%" in the string;
201 A check is performed that there are no other "%" in the string;
201 if there are, then the string is not a magic command and is left unchanged.
202 if there are, then the string is not a magic command and is left unchanged.
202
203
203 """
204 """
204
205
205 # Move any % signs from start to end of the key
206 # Move any % signs from start to end of the key
206 # provided there are no others elsewhere in the string
207 # provided there are no others elsewhere in the string
207
208
208 if word[:2] == "%%":
209 if word[:2] == "%%":
209 if not "%" in word[2:]:
210 if not "%" in word[2:]:
210 return word[2:] + "%%"
211 return word[2:] + "%%"
211
212
212 if word[:1] == "%":
213 if word[:1] == "%":
213 if not "%" in word[1:]:
214 if not "%" in word[1:]:
214 return word[1:] + "%"
215 return word[1:] + "%"
215
216
216 return word
217 return word
217
218
218
219
219
220 @undoc
220 class Bunch(object): pass
221 class Bunch(object): pass
221
222
222
223
223 DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
224 DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
224 GREEDY_DELIMS = ' =\r\n'
225 GREEDY_DELIMS = ' =\r\n'
225
226
226
227
227 class CompletionSplitter(object):
228 class CompletionSplitter(object):
228 """An object to split an input line in a manner similar to readline.
229 """An object to split an input line in a manner similar to readline.
229
230
230 By having our own implementation, we can expose readline-like completion in
231 By having our own implementation, we can expose readline-like completion in
231 a uniform manner to all frontends. This object only needs to be given the
232 a uniform manner to all frontends. This object only needs to be given the
232 line of text to be split and the cursor position on said line, and it
233 line of text to be split and the cursor position on said line, and it
233 returns the 'word' to be completed on at the cursor after splitting the
234 returns the 'word' to be completed on at the cursor after splitting the
234 entire line.
235 entire line.
235
236
236 What characters are used as splitting delimiters can be controlled by
237 What characters are used as splitting delimiters can be controlled by
237 setting the `delims` attribute (this is a property that internally
238 setting the `delims` attribute (this is a property that internally
238 automatically builds the necessary regular expression)"""
239 automatically builds the necessary regular expression)"""
239
240
240 # Private interface
241 # Private interface
241
242
242 # A string of delimiter characters. The default value makes sense for
243 # A string of delimiter characters. The default value makes sense for
243 # IPython's most typical usage patterns.
244 # IPython's most typical usage patterns.
244 _delims = DELIMS
245 _delims = DELIMS
245
246
246 # The expression (a normal string) to be compiled into a regular expression
247 # The expression (a normal string) to be compiled into a regular expression
247 # for actual splitting. We store it as an attribute mostly for ease of
248 # for actual splitting. We store it as an attribute mostly for ease of
248 # debugging, since this type of code can be so tricky to debug.
249 # debugging, since this type of code can be so tricky to debug.
249 _delim_expr = None
250 _delim_expr = None
250
251
251 # The regular expression that does the actual splitting
252 # The regular expression that does the actual splitting
252 _delim_re = None
253 _delim_re = None
253
254
254 def __init__(self, delims=None):
255 def __init__(self, delims=None):
255 delims = CompletionSplitter._delims if delims is None else delims
256 delims = CompletionSplitter._delims if delims is None else delims
256 self.delims = delims
257 self.delims = delims
257
258
258 @property
259 @property
259 def delims(self):
260 def delims(self):
260 """Return the string of delimiter characters."""
261 """Return the string of delimiter characters."""
261 return self._delims
262 return self._delims
262
263
263 @delims.setter
264 @delims.setter
264 def delims(self, delims):
265 def delims(self, delims):
265 """Set the delimiters for line splitting."""
266 """Set the delimiters for line splitting."""
266 expr = '[' + ''.join('\\'+ c for c in delims) + ']'
267 expr = '[' + ''.join('\\'+ c for c in delims) + ']'
267 self._delim_re = re.compile(expr)
268 self._delim_re = re.compile(expr)
268 self._delims = delims
269 self._delims = delims
269 self._delim_expr = expr
270 self._delim_expr = expr
270
271
271 def split_line(self, line, cursor_pos=None):
272 def split_line(self, line, cursor_pos=None):
272 """Split a line of text with a cursor at the given position.
273 """Split a line of text with a cursor at the given position.
273 """
274 """
274 l = line if cursor_pos is None else line[:cursor_pos]
275 l = line if cursor_pos is None else line[:cursor_pos]
275 return self._delim_re.split(l)[-1]
276 return self._delim_re.split(l)[-1]
276
277
277
278
278 class Completer(Configurable):
279 class Completer(Configurable):
279
280
280 greedy = CBool(False, config=True,
281 greedy = CBool(False, config=True,
281 help="""Activate greedy completion
282 help="""Activate greedy completion
282
283
283 This will enable completion on elements of lists, results of function calls, etc.,
284 This will enable completion on elements of lists, results of function calls, etc.,
284 but can be unsafe because the code is actually evaluated on TAB.
285 but can be unsafe because the code is actually evaluated on TAB.
285 """
286 """
286 )
287 )
287
288
288
289
289 def __init__(self, namespace=None, global_namespace=None, **kwargs):
290 def __init__(self, namespace=None, global_namespace=None, **kwargs):
290 """Create a new completer for the command line.
291 """Create a new completer for the command line.
291
292
292 Completer(namespace=ns,global_namespace=ns2) -> completer instance.
293 Completer(namespace=ns,global_namespace=ns2) -> completer instance.
293
294
294 If unspecified, the default namespace where completions are performed
295 If unspecified, the default namespace where completions are performed
295 is __main__ (technically, __main__.__dict__). Namespaces should be
296 is __main__ (technically, __main__.__dict__). Namespaces should be
296 given as dictionaries.
297 given as dictionaries.
297
298
298 An optional second namespace can be given. This allows the completer
299 An optional second namespace can be given. This allows the completer
299 to handle cases where both the local and global scopes need to be
300 to handle cases where both the local and global scopes need to be
300 distinguished.
301 distinguished.
301
302
302 Completer instances should be used as the completion mechanism of
303 Completer instances should be used as the completion mechanism of
303 readline via the set_completer() call:
304 readline via the set_completer() call:
304
305
305 readline.set_completer(Completer(my_namespace).complete)
306 readline.set_completer(Completer(my_namespace).complete)
306 """
307 """
307
308
308 # Don't bind to namespace quite yet, but flag whether the user wants a
309 # Don't bind to namespace quite yet, but flag whether the user wants a
309 # specific namespace or to use __main__.__dict__. This will allow us
310 # specific namespace or to use __main__.__dict__. This will allow us
310 # to bind to __main__.__dict__ at completion time, not now.
311 # to bind to __main__.__dict__ at completion time, not now.
311 if namespace is None:
312 if namespace is None:
312 self.use_main_ns = 1
313 self.use_main_ns = 1
313 else:
314 else:
314 self.use_main_ns = 0
315 self.use_main_ns = 0
315 self.namespace = namespace
316 self.namespace = namespace
316
317
317 # The global namespace, if given, can be bound directly
318 # The global namespace, if given, can be bound directly
318 if global_namespace is None:
319 if global_namespace is None:
319 self.global_namespace = {}
320 self.global_namespace = {}
320 else:
321 else:
321 self.global_namespace = global_namespace
322 self.global_namespace = global_namespace
322
323
323 super(Completer, self).__init__(**kwargs)
324 super(Completer, self).__init__(**kwargs)
324
325
325 def complete(self, text, state):
326 def complete(self, text, state):
326 """Return the next possible completion for 'text'.
327 """Return the next possible completion for 'text'.
327
328
328 This is called successively with state == 0, 1, 2, ... until it
329 This is called successively with state == 0, 1, 2, ... until it
329 returns None. The completion should begin with 'text'.
330 returns None. The completion should begin with 'text'.
330
331
331 """
332 """
332 if self.use_main_ns:
333 if self.use_main_ns:
333 self.namespace = __main__.__dict__
334 self.namespace = __main__.__dict__
334
335
335 if state == 0:
336 if state == 0:
336 if "." in text:
337 if "." in text:
337 self.matches = self.attr_matches(text)
338 self.matches = self.attr_matches(text)
338 else:
339 else:
339 self.matches = self.global_matches(text)
340 self.matches = self.global_matches(text)
340 try:
341 try:
341 return self.matches[state]
342 return self.matches[state]
342 except IndexError:
343 except IndexError:
343 return None
344 return None
344
345
345 def global_matches(self, text):
346 def global_matches(self, text):
346 """Compute matches when text is a simple name.
347 """Compute matches when text is a simple name.
347
348
348 Return a list of all keywords, built-in functions and names currently
349 Return a list of all keywords, built-in functions and names currently
349 defined in self.namespace or self.global_namespace that match.
350 defined in self.namespace or self.global_namespace that match.
350
351
351 """
352 """
352 #print 'Completer->global_matches, txt=%r' % text # dbg
353 #print 'Completer->global_matches, txt=%r' % text # dbg
353 matches = []
354 matches = []
354 match_append = matches.append
355 match_append = matches.append
355 n = len(text)
356 n = len(text)
356 for lst in [keyword.kwlist,
357 for lst in [keyword.kwlist,
357 builtin_mod.__dict__.keys(),
358 builtin_mod.__dict__.keys(),
358 self.namespace.keys(),
359 self.namespace.keys(),
359 self.global_namespace.keys()]:
360 self.global_namespace.keys()]:
360 for word in lst:
361 for word in lst:
361 if word[:n] == text and word != "__builtins__":
362 if word[:n] == text and word != "__builtins__":
362 match_append(word)
363 match_append(word)
363 return matches
364 return matches
364
365
365 def attr_matches(self, text):
366 def attr_matches(self, text):
366 """Compute matches when text contains a dot.
367 """Compute matches when text contains a dot.
367
368
368 Assuming the text is of the form NAME.NAME....[NAME], and is
369 Assuming the text is of the form NAME.NAME....[NAME], and is
369 evaluatable in self.namespace or self.global_namespace, it will be
370 evaluatable in self.namespace or self.global_namespace, it will be
370 evaluated and its attributes (as revealed by dir()) are used as
371 evaluated and its attributes (as revealed by dir()) are used as
371 possible completions. (For class instances, class members are are
372 possible completions. (For class instances, class members are are
372 also considered.)
373 also considered.)
373
374
374 WARNING: this can still invoke arbitrary C code, if an object
375 WARNING: this can still invoke arbitrary C code, if an object
375 with a __getattr__ hook is evaluated.
376 with a __getattr__ hook is evaluated.
376
377
377 """
378 """
378
379
379 #io.rprint('Completer->attr_matches, txt=%r' % text) # dbg
380 #io.rprint('Completer->attr_matches, txt=%r' % text) # dbg
380 # Another option, seems to work great. Catches things like ''.<tab>
381 # Another option, seems to work great. Catches things like ''.<tab>
381 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
382 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
382
383
383 if m:
384 if m:
384 expr, attr = m.group(1, 3)
385 expr, attr = m.group(1, 3)
385 elif self.greedy:
386 elif self.greedy:
386 m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer)
387 m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer)
387 if not m2:
388 if not m2:
388 return []
389 return []
389 expr, attr = m2.group(1,2)
390 expr, attr = m2.group(1,2)
390 else:
391 else:
391 return []
392 return []
392
393
393 try:
394 try:
394 obj = eval(expr, self.namespace)
395 obj = eval(expr, self.namespace)
395 except:
396 except:
396 try:
397 try:
397 obj = eval(expr, self.global_namespace)
398 obj = eval(expr, self.global_namespace)
398 except:
399 except:
399 return []
400 return []
400
401
401 if self.limit_to__all__ and hasattr(obj, '__all__'):
402 if self.limit_to__all__ and hasattr(obj, '__all__'):
402 words = get__all__entries(obj)
403 words = get__all__entries(obj)
403 else:
404 else:
404 words = dir2(obj)
405 words = dir2(obj)
405
406
406 try:
407 try:
407 words = generics.complete_object(obj, words)
408 words = generics.complete_object(obj, words)
408 except TryNext:
409 except TryNext:
409 pass
410 pass
410 except Exception:
411 except Exception:
411 # Silence errors from completion function
412 # Silence errors from completion function
412 #raise # dbg
413 #raise # dbg
413 pass
414 pass
414 # Build match list to return
415 # Build match list to return
415 n = len(attr)
416 n = len(attr)
416 res = ["%s.%s" % (expr, w) for w in words if w[:n] == attr ]
417 res = ["%s.%s" % (expr, w) for w in words if w[:n] == attr ]
417 return res
418 return res
418
419
419
420
420 def get__all__entries(obj):
421 def get__all__entries(obj):
421 """returns the strings in the __all__ attribute"""
422 """returns the strings in the __all__ attribute"""
422 try:
423 try:
423 words = getattr(obj, '__all__')
424 words = getattr(obj, '__all__')
424 except:
425 except:
425 return []
426 return []
426
427
427 return [w for w in words if isinstance(w, string_types)]
428 return [w for w in words if isinstance(w, string_types)]
428
429
429
430
430 def match_dict_keys(keys, prefix):
431 def match_dict_keys(keys, prefix):
431 """Used by dict_key_matches, matching the prefix to a list of keys"""
432 """Used by dict_key_matches, matching the prefix to a list of keys"""
432 if not prefix:
433 if not prefix:
433 return None, 0, [repr(k) for k in keys
434 return None, 0, [repr(k) for k in keys
434 if isinstance(k, (string_types, bytes))]
435 if isinstance(k, (string_types, bytes))]
435 quote_match = re.search('["\']', prefix)
436 quote_match = re.search('["\']', prefix)
436 quote = quote_match.group()
437 quote = quote_match.group()
437 try:
438 try:
438 prefix_str = eval(prefix + quote, {})
439 prefix_str = eval(prefix + quote, {})
439 except Exception:
440 except Exception:
440 return None, 0, []
441 return None, 0, []
441
442
442 token_match = re.search(r'\w*$', prefix, re.UNICODE)
443 token_match = re.search(r'\w*$', prefix, re.UNICODE)
443 token_start = token_match.start()
444 token_start = token_match.start()
444 token_prefix = token_match.group()
445 token_prefix = token_match.group()
445
446
446 # TODO: support bytes in Py3k
447 # TODO: support bytes in Py3k
447 matched = []
448 matched = []
448 for key in keys:
449 for key in keys:
449 try:
450 try:
450 if not key.startswith(prefix_str):
451 if not key.startswith(prefix_str):
451 continue
452 continue
452 except (AttributeError, TypeError, UnicodeError):
453 except (AttributeError, TypeError, UnicodeError):
453 # Python 3+ TypeError on b'a'.startswith('a') or vice-versa
454 # Python 3+ TypeError on b'a'.startswith('a') or vice-versa
454 continue
455 continue
455
456
456 # reformat remainder of key to begin with prefix
457 # reformat remainder of key to begin with prefix
457 rem = key[len(prefix_str):]
458 rem = key[len(prefix_str):]
458 # force repr wrapped in '
459 # force repr wrapped in '
459 rem_repr = repr(rem + '"')
460 rem_repr = repr(rem + '"')
460 if rem_repr.startswith('u') and prefix[0] not in 'uU':
461 if rem_repr.startswith('u') and prefix[0] not in 'uU':
461 # Found key is unicode, but prefix is Py2 string.
462 # Found key is unicode, but prefix is Py2 string.
462 # Therefore attempt to interpret key as string.
463 # Therefore attempt to interpret key as string.
463 try:
464 try:
464 rem_repr = repr(rem.encode('ascii') + '"')
465 rem_repr = repr(rem.encode('ascii') + '"')
465 except UnicodeEncodeError:
466 except UnicodeEncodeError:
466 continue
467 continue
467
468
468 rem_repr = rem_repr[1 + rem_repr.index("'"):-2]
469 rem_repr = rem_repr[1 + rem_repr.index("'"):-2]
469 if quote == '"':
470 if quote == '"':
470 # The entered prefix is quoted with ",
471 # The entered prefix is quoted with ",
471 # but the match is quoted with '.
472 # but the match is quoted with '.
472 # A contained " hence needs escaping for comparison:
473 # A contained " hence needs escaping for comparison:
473 rem_repr = rem_repr.replace('"', '\\"')
474 rem_repr = rem_repr.replace('"', '\\"')
474
475
475 # then reinsert prefix from start of token
476 # then reinsert prefix from start of token
476 matched.append('%s%s' % (token_prefix, rem_repr))
477 matched.append('%s%s' % (token_prefix, rem_repr))
477 return quote, token_start, matched
478 return quote, token_start, matched
478
479
479
480
480 def _safe_isinstance(obj, module, class_name):
481 def _safe_isinstance(obj, module, class_name):
481 """Checks if obj is an instance of module.class_name if loaded
482 """Checks if obj is an instance of module.class_name if loaded
482 """
483 """
483 return (module in sys.modules and
484 return (module in sys.modules and
484 isinstance(obj, getattr(__import__(module), class_name)))
485 isinstance(obj, getattr(__import__(module), class_name)))
485
486
486
487
487
488
488 class IPCompleter(Completer):
489 class IPCompleter(Completer):
489 """Extension of the completer class with IPython-specific features"""
490 """Extension of the completer class with IPython-specific features"""
490
491
491 def _greedy_changed(self, name, old, new):
492 def _greedy_changed(self, name, old, new):
492 """update the splitter and readline delims when greedy is changed"""
493 """update the splitter and readline delims when greedy is changed"""
493 if new:
494 if new:
494 self.splitter.delims = GREEDY_DELIMS
495 self.splitter.delims = GREEDY_DELIMS
495 else:
496 else:
496 self.splitter.delims = DELIMS
497 self.splitter.delims = DELIMS
497
498
498 if self.readline:
499 if self.readline:
499 self.readline.set_completer_delims(self.splitter.delims)
500 self.readline.set_completer_delims(self.splitter.delims)
500
501
501 merge_completions = CBool(True, config=True,
502 merge_completions = CBool(True, config=True,
502 help="""Whether to merge completion results into a single list
503 help="""Whether to merge completion results into a single list
503
504
504 If False, only the completion results from the first non-empty
505 If False, only the completion results from the first non-empty
505 completer will be returned.
506 completer will be returned.
506 """
507 """
507 )
508 )
508 omit__names = Enum((0,1,2), default_value=2, config=True,
509 omit__names = Enum((0,1,2), default_value=2, config=True,
509 help="""Instruct the completer to omit private method names
510 help="""Instruct the completer to omit private method names
510
511
511 Specifically, when completing on ``object.<tab>``.
512 Specifically, when completing on ``object.<tab>``.
512
513
513 When 2 [default]: all names that start with '_' will be excluded.
514 When 2 [default]: all names that start with '_' will be excluded.
514
515
515 When 1: all 'magic' names (``__foo__``) will be excluded.
516 When 1: all 'magic' names (``__foo__``) will be excluded.
516
517
517 When 0: nothing will be excluded.
518 When 0: nothing will be excluded.
518 """
519 """
519 )
520 )
520 limit_to__all__ = CBool(default_value=False, config=True,
521 limit_to__all__ = CBool(default_value=False, config=True,
521 help="""Instruct the completer to use __all__ for the completion
522 help="""Instruct the completer to use __all__ for the completion
522
523
523 Specifically, when completing on ``object.<tab>``.
524 Specifically, when completing on ``object.<tab>``.
524
525
525 When True: only those names in obj.__all__ will be included.
526 When True: only those names in obj.__all__ will be included.
526
527
527 When False [default]: the __all__ attribute is ignored
528 When False [default]: the __all__ attribute is ignored
528 """
529 """
529 )
530 )
530
531
531 def __init__(self, shell=None, namespace=None, global_namespace=None,
532 def __init__(self, shell=None, namespace=None, global_namespace=None,
532 use_readline=True, config=None, **kwargs):
533 use_readline=True, config=None, **kwargs):
533 """IPCompleter() -> completer
534 """IPCompleter() -> completer
534
535
535 Return a completer object suitable for use by the readline library
536 Return a completer object suitable for use by the readline library
536 via readline.set_completer().
537 via readline.set_completer().
537
538
538 Inputs:
539 Inputs:
539
540
540 - shell: a pointer to the ipython shell itself. This is needed
541 - shell: a pointer to the ipython shell itself. This is needed
541 because this completer knows about magic functions, and those can
542 because this completer knows about magic functions, and those can
542 only be accessed via the ipython instance.
543 only be accessed via the ipython instance.
543
544
544 - namespace: an optional dict where completions are performed.
545 - namespace: an optional dict where completions are performed.
545
546
546 - global_namespace: secondary optional dict for completions, to
547 - global_namespace: secondary optional dict for completions, to
547 handle cases (such as IPython embedded inside functions) where
548 handle cases (such as IPython embedded inside functions) where
548 both Python scopes are visible.
549 both Python scopes are visible.
549
550
550 use_readline : bool, optional
551 use_readline : bool, optional
551 If true, use the readline library. This completer can still function
552 If true, use the readline library. This completer can still function
552 without readline, though in that case callers must provide some extra
553 without readline, though in that case callers must provide some extra
553 information on each call about the current line."""
554 information on each call about the current line."""
554
555
555 self.magic_escape = ESC_MAGIC
556 self.magic_escape = ESC_MAGIC
556 self.splitter = CompletionSplitter()
557 self.splitter = CompletionSplitter()
557
558
558 # Readline configuration, only used by the rlcompleter method.
559 # Readline configuration, only used by the rlcompleter method.
559 if use_readline:
560 if use_readline:
560 # We store the right version of readline so that later code
561 # We store the right version of readline so that later code
561 import IPython.utils.rlineimpl as readline
562 import IPython.utils.rlineimpl as readline
562 self.readline = readline
563 self.readline = readline
563 else:
564 else:
564 self.readline = None
565 self.readline = None
565
566
566 # _greedy_changed() depends on splitter and readline being defined:
567 # _greedy_changed() depends on splitter and readline being defined:
567 Completer.__init__(self, namespace=namespace, global_namespace=global_namespace,
568 Completer.__init__(self, namespace=namespace, global_namespace=global_namespace,
568 config=config, **kwargs)
569 config=config, **kwargs)
569
570
570 # List where completion matches will be stored
571 # List where completion matches will be stored
571 self.matches = []
572 self.matches = []
572 self.shell = shell
573 self.shell = shell
573 # Regexp to split filenames with spaces in them
574 # Regexp to split filenames with spaces in them
574 self.space_name_re = re.compile(r'([^\\] )')
575 self.space_name_re = re.compile(r'([^\\] )')
575 # Hold a local ref. to glob.glob for speed
576 # Hold a local ref. to glob.glob for speed
576 self.glob = glob.glob
577 self.glob = glob.glob
577
578
578 # Determine if we are running on 'dumb' terminals, like (X)Emacs
579 # Determine if we are running on 'dumb' terminals, like (X)Emacs
579 # buffers, to avoid completion problems.
580 # buffers, to avoid completion problems.
580 term = os.environ.get('TERM','xterm')
581 term = os.environ.get('TERM','xterm')
581 self.dumb_terminal = term in ['dumb','emacs']
582 self.dumb_terminal = term in ['dumb','emacs']
582
583
583 # Special handling of backslashes needed in win32 platforms
584 # Special handling of backslashes needed in win32 platforms
584 if sys.platform == "win32":
585 if sys.platform == "win32":
585 self.clean_glob = self._clean_glob_win32
586 self.clean_glob = self._clean_glob_win32
586 else:
587 else:
587 self.clean_glob = self._clean_glob
588 self.clean_glob = self._clean_glob
588
589
589 #regexp to parse docstring for function signature
590 #regexp to parse docstring for function signature
590 self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
591 self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
591 self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
592 self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
592 #use this if positional argument name is also needed
593 #use this if positional argument name is also needed
593 #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)')
594 #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)')
594
595
595 # All active matcher routines for completion
596 # All active matcher routines for completion
596 self.matchers = [self.python_matches,
597 self.matchers = [self.python_matches,
597 self.file_matches,
598 self.file_matches,
598 self.magic_matches,
599 self.magic_matches,
599 self.python_func_kw_matches,
600 self.python_func_kw_matches,
600 self.dict_key_matches,
601 self.dict_key_matches,
601 ]
602 ]
602
603
603 def all_completions(self, text):
604 def all_completions(self, text):
604 """
605 """
605 Wrapper around the complete method for the benefit of emacs
606 Wrapper around the complete method for the benefit of emacs
606 and pydb.
607 and pydb.
607 """
608 """
608 return self.complete(text)[1]
609 return self.complete(text)[1]
609
610
610 def _clean_glob(self,text):
611 def _clean_glob(self,text):
611 return self.glob("%s*" % text)
612 return self.glob("%s*" % text)
612
613
613 def _clean_glob_win32(self,text):
614 def _clean_glob_win32(self,text):
614 return [f.replace("\\","/")
615 return [f.replace("\\","/")
615 for f in self.glob("%s*" % text)]
616 for f in self.glob("%s*" % text)]
616
617
617 def file_matches(self, text):
618 def file_matches(self, text):
618 """Match filenames, expanding ~USER type strings.
619 """Match filenames, expanding ~USER type strings.
619
620
620 Most of the seemingly convoluted logic in this completer is an
621 Most of the seemingly convoluted logic in this completer is an
621 attempt to handle filenames with spaces in them. And yet it's not
622 attempt to handle filenames with spaces in them. And yet it's not
622 quite perfect, because Python's readline doesn't expose all of the
623 quite perfect, because Python's readline doesn't expose all of the
623 GNU readline details needed for this to be done correctly.
624 GNU readline details needed for this to be done correctly.
624
625
625 For a filename with a space in it, the printed completions will be
626 For a filename with a space in it, the printed completions will be
626 only the parts after what's already been typed (instead of the
627 only the parts after what's already been typed (instead of the
627 full completions, as is normally done). I don't think with the
628 full completions, as is normally done). I don't think with the
628 current (as of Python 2.3) Python readline it's possible to do
629 current (as of Python 2.3) Python readline it's possible to do
629 better."""
630 better."""
630
631
631 #io.rprint('Completer->file_matches: <%r>' % text) # dbg
632 #io.rprint('Completer->file_matches: <%r>' % text) # dbg
632
633
633 # chars that require escaping with backslash - i.e. chars
634 # chars that require escaping with backslash - i.e. chars
634 # that readline treats incorrectly as delimiters, but we
635 # that readline treats incorrectly as delimiters, but we
635 # don't want to treat as delimiters in filename matching
636 # don't want to treat as delimiters in filename matching
636 # when escaped with backslash
637 # when escaped with backslash
637 if text.startswith('!'):
638 if text.startswith('!'):
638 text = text[1:]
639 text = text[1:]
639 text_prefix = '!'
640 text_prefix = '!'
640 else:
641 else:
641 text_prefix = ''
642 text_prefix = ''
642
643
643 text_until_cursor = self.text_until_cursor
644 text_until_cursor = self.text_until_cursor
644 # track strings with open quotes
645 # track strings with open quotes
645 open_quotes = has_open_quotes(text_until_cursor)
646 open_quotes = has_open_quotes(text_until_cursor)
646
647
647 if '(' in text_until_cursor or '[' in text_until_cursor:
648 if '(' in text_until_cursor or '[' in text_until_cursor:
648 lsplit = text
649 lsplit = text
649 else:
650 else:
650 try:
651 try:
651 # arg_split ~ shlex.split, but with unicode bugs fixed by us
652 # arg_split ~ shlex.split, but with unicode bugs fixed by us
652 lsplit = arg_split(text_until_cursor)[-1]
653 lsplit = arg_split(text_until_cursor)[-1]
653 except ValueError:
654 except ValueError:
654 # typically an unmatched ", or backslash without escaped char.
655 # typically an unmatched ", or backslash without escaped char.
655 if open_quotes:
656 if open_quotes:
656 lsplit = text_until_cursor.split(open_quotes)[-1]
657 lsplit = text_until_cursor.split(open_quotes)[-1]
657 else:
658 else:
658 return []
659 return []
659 except IndexError:
660 except IndexError:
660 # tab pressed on empty line
661 # tab pressed on empty line
661 lsplit = ""
662 lsplit = ""
662
663
663 if not open_quotes and lsplit != protect_filename(lsplit):
664 if not open_quotes and lsplit != protect_filename(lsplit):
664 # if protectables are found, do matching on the whole escaped name
665 # if protectables are found, do matching on the whole escaped name
665 has_protectables = True
666 has_protectables = True
666 text0,text = text,lsplit
667 text0,text = text,lsplit
667 else:
668 else:
668 has_protectables = False
669 has_protectables = False
669 text = os.path.expanduser(text)
670 text = os.path.expanduser(text)
670
671
671 if text == "":
672 if text == "":
672 return [text_prefix + protect_filename(f) for f in self.glob("*")]
673 return [text_prefix + protect_filename(f) for f in self.glob("*")]
673
674
674 # Compute the matches from the filesystem
675 # Compute the matches from the filesystem
675 m0 = self.clean_glob(text.replace('\\',''))
676 m0 = self.clean_glob(text.replace('\\',''))
676
677
677 if has_protectables:
678 if has_protectables:
678 # If we had protectables, we need to revert our changes to the
679 # If we had protectables, we need to revert our changes to the
679 # beginning of filename so that we don't double-write the part
680 # beginning of filename so that we don't double-write the part
680 # of the filename we have so far
681 # of the filename we have so far
681 len_lsplit = len(lsplit)
682 len_lsplit = len(lsplit)
682 matches = [text_prefix + text0 +
683 matches = [text_prefix + text0 +
683 protect_filename(f[len_lsplit:]) for f in m0]
684 protect_filename(f[len_lsplit:]) for f in m0]
684 else:
685 else:
685 if open_quotes:
686 if open_quotes:
686 # if we have a string with an open quote, we don't need to
687 # if we have a string with an open quote, we don't need to
687 # protect the names at all (and we _shouldn't_, as it
688 # protect the names at all (and we _shouldn't_, as it
688 # would cause bugs when the filesystem call is made).
689 # would cause bugs when the filesystem call is made).
689 matches = m0
690 matches = m0
690 else:
691 else:
691 matches = [text_prefix +
692 matches = [text_prefix +
692 protect_filename(f) for f in m0]
693 protect_filename(f) for f in m0]
693
694
694 #io.rprint('mm', matches) # dbg
695 #io.rprint('mm', matches) # dbg
695
696
696 # Mark directories in input list by appending '/' to their names.
697 # Mark directories in input list by appending '/' to their names.
697 matches = [x+'/' if os.path.isdir(x) else x for x in matches]
698 matches = [x+'/' if os.path.isdir(x) else x for x in matches]
698 return matches
699 return matches
699
700
700 def magic_matches(self, text):
701 def magic_matches(self, text):
701 """Match magics"""
702 """Match magics"""
702 #print 'Completer->magic_matches:',text,'lb',self.text_until_cursor # dbg
703 #print 'Completer->magic_matches:',text,'lb',self.text_until_cursor # dbg
703 # Get all shell magics now rather than statically, so magics loaded at
704 # Get all shell magics now rather than statically, so magics loaded at
704 # runtime show up too.
705 # runtime show up too.
705 lsm = self.shell.magics_manager.lsmagic()
706 lsm = self.shell.magics_manager.lsmagic()
706 line_magics = lsm['line']
707 line_magics = lsm['line']
707 cell_magics = lsm['cell']
708 cell_magics = lsm['cell']
708 pre = self.magic_escape
709 pre = self.magic_escape
709 pre2 = pre+pre
710 pre2 = pre+pre
710
711
711 # Completion logic:
712 # Completion logic:
712 # - user gives %%: only do cell magics
713 # - user gives %%: only do cell magics
713 # - user gives %: do both line and cell magics
714 # - user gives %: do both line and cell magics
714 # - no prefix: do both
715 # - no prefix: do both
715 # In other words, line magics are skipped if the user gives %% explicitly
716 # In other words, line magics are skipped if the user gives %% explicitly
716 bare_text = text.lstrip(pre)
717 bare_text = text.lstrip(pre)
717 comp = [ pre2+m for m in cell_magics if m.startswith(bare_text)]
718 comp = [ pre2+m for m in cell_magics if m.startswith(bare_text)]
718 if not text.startswith(pre2):
719 if not text.startswith(pre2):
719 comp += [ pre+m for m in line_magics if m.startswith(bare_text)]
720 comp += [ pre+m for m in line_magics if m.startswith(bare_text)]
720 return comp
721 return comp
721
722
722 def python_matches(self,text):
723 def python_matches(self,text):
723 """Match attributes or global python names"""
724 """Match attributes or global python names"""
724
725
725 #io.rprint('Completer->python_matches, txt=%r' % text) # dbg
726 #io.rprint('Completer->python_matches, txt=%r' % text) # dbg
726 if "." in text:
727 if "." in text:
727 try:
728 try:
728 matches = self.attr_matches(text)
729 matches = self.attr_matches(text)
729 if text.endswith('.') and self.omit__names:
730 if text.endswith('.') and self.omit__names:
730 if self.omit__names == 1:
731 if self.omit__names == 1:
731 # true if txt is _not_ a __ name, false otherwise:
732 # true if txt is _not_ a __ name, false otherwise:
732 no__name = (lambda txt:
733 no__name = (lambda txt:
733 re.match(r'.*\.__.*?__',txt) is None)
734 re.match(r'.*\.__.*?__',txt) is None)
734 else:
735 else:
735 # true if txt is _not_ a _ name, false otherwise:
736 # true if txt is _not_ a _ name, false otherwise:
736 no__name = (lambda txt:
737 no__name = (lambda txt:
737 re.match(r'.*\._.*?',txt) is None)
738 re.match(r'.*\._.*?',txt) is None)
738 matches = filter(no__name, matches)
739 matches = filter(no__name, matches)
739 except NameError:
740 except NameError:
740 # catches <undefined attributes>.<tab>
741 # catches <undefined attributes>.<tab>
741 matches = []
742 matches = []
742 else:
743 else:
743 matches = self.global_matches(text)
744 matches = self.global_matches(text)
744
745
745 return matches
746 return matches
746
747
747 def _default_arguments_from_docstring(self, doc):
748 def _default_arguments_from_docstring(self, doc):
748 """Parse the first line of docstring for call signature.
749 """Parse the first line of docstring for call signature.
749
750
750 Docstring should be of the form 'min(iterable[, key=func])\n'.
751 Docstring should be of the form 'min(iterable[, key=func])\n'.
751 It can also parse cython docstring of the form
752 It can also parse cython docstring of the form
752 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'.
753 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'.
753 """
754 """
754 if doc is None:
755 if doc is None:
755 return []
756 return []
756
757
757 #care only the firstline
758 #care only the firstline
758 line = doc.lstrip().splitlines()[0]
759 line = doc.lstrip().splitlines()[0]
759
760
760 #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
761 #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
761 #'min(iterable[, key=func])\n' -> 'iterable[, key=func]'
762 #'min(iterable[, key=func])\n' -> 'iterable[, key=func]'
762 sig = self.docstring_sig_re.search(line)
763 sig = self.docstring_sig_re.search(line)
763 if sig is None:
764 if sig is None:
764 return []
765 return []
765 # iterable[, key=func]' -> ['iterable[' ,' key=func]']
766 # iterable[, key=func]' -> ['iterable[' ,' key=func]']
766 sig = sig.groups()[0].split(',')
767 sig = sig.groups()[0].split(',')
767 ret = []
768 ret = []
768 for s in sig:
769 for s in sig:
769 #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
770 #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
770 ret += self.docstring_kwd_re.findall(s)
771 ret += self.docstring_kwd_re.findall(s)
771 return ret
772 return ret
772
773
773 def _default_arguments(self, obj):
774 def _default_arguments(self, obj):
774 """Return the list of default arguments of obj if it is callable,
775 """Return the list of default arguments of obj if it is callable,
775 or empty list otherwise."""
776 or empty list otherwise."""
776 call_obj = obj
777 call_obj = obj
777 ret = []
778 ret = []
778 if inspect.isbuiltin(obj):
779 if inspect.isbuiltin(obj):
779 pass
780 pass
780 elif not (inspect.isfunction(obj) or inspect.ismethod(obj)):
781 elif not (inspect.isfunction(obj) or inspect.ismethod(obj)):
781 if inspect.isclass(obj):
782 if inspect.isclass(obj):
782 #for cython embededsignature=True the constructor docstring
783 #for cython embededsignature=True the constructor docstring
783 #belongs to the object itself not __init__
784 #belongs to the object itself not __init__
784 ret += self._default_arguments_from_docstring(
785 ret += self._default_arguments_from_docstring(
785 getattr(obj, '__doc__', ''))
786 getattr(obj, '__doc__', ''))
786 # for classes, check for __init__,__new__
787 # for classes, check for __init__,__new__
787 call_obj = (getattr(obj, '__init__', None) or
788 call_obj = (getattr(obj, '__init__', None) or
788 getattr(obj, '__new__', None))
789 getattr(obj, '__new__', None))
789 # for all others, check if they are __call__able
790 # for all others, check if they are __call__able
790 elif hasattr(obj, '__call__'):
791 elif hasattr(obj, '__call__'):
791 call_obj = obj.__call__
792 call_obj = obj.__call__
792
793
793 ret += self._default_arguments_from_docstring(
794 ret += self._default_arguments_from_docstring(
794 getattr(call_obj, '__doc__', ''))
795 getattr(call_obj, '__doc__', ''))
795
796
796 try:
797 try:
797 args,_,_1,defaults = inspect.getargspec(call_obj)
798 args,_,_1,defaults = inspect.getargspec(call_obj)
798 if defaults:
799 if defaults:
799 ret+=args[-len(defaults):]
800 ret+=args[-len(defaults):]
800 except TypeError:
801 except TypeError:
801 pass
802 pass
802
803
803 return list(set(ret))
804 return list(set(ret))
804
805
805 def python_func_kw_matches(self,text):
806 def python_func_kw_matches(self,text):
806 """Match named parameters (kwargs) of the last open function"""
807 """Match named parameters (kwargs) of the last open function"""
807
808
808 if "." in text: # a parameter cannot be dotted
809 if "." in text: # a parameter cannot be dotted
809 return []
810 return []
810 try: regexp = self.__funcParamsRegex
811 try: regexp = self.__funcParamsRegex
811 except AttributeError:
812 except AttributeError:
812 regexp = self.__funcParamsRegex = re.compile(r'''
813 regexp = self.__funcParamsRegex = re.compile(r'''
813 '.*?(?<!\\)' | # single quoted strings or
814 '.*?(?<!\\)' | # single quoted strings or
814 ".*?(?<!\\)" | # double quoted strings or
815 ".*?(?<!\\)" | # double quoted strings or
815 \w+ | # identifier
816 \w+ | # identifier
816 \S # other characters
817 \S # other characters
817 ''', re.VERBOSE | re.DOTALL)
818 ''', re.VERBOSE | re.DOTALL)
818 # 1. find the nearest identifier that comes before an unclosed
819 # 1. find the nearest identifier that comes before an unclosed
819 # parenthesis before the cursor
820 # parenthesis before the cursor
820 # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo"
821 # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo"
821 tokens = regexp.findall(self.text_until_cursor)
822 tokens = regexp.findall(self.text_until_cursor)
822 tokens.reverse()
823 tokens.reverse()
823 iterTokens = iter(tokens); openPar = 0
824 iterTokens = iter(tokens); openPar = 0
824
825
825 for token in iterTokens:
826 for token in iterTokens:
826 if token == ')':
827 if token == ')':
827 openPar -= 1
828 openPar -= 1
828 elif token == '(':
829 elif token == '(':
829 openPar += 1
830 openPar += 1
830 if openPar > 0:
831 if openPar > 0:
831 # found the last unclosed parenthesis
832 # found the last unclosed parenthesis
832 break
833 break
833 else:
834 else:
834 return []
835 return []
835 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
836 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
836 ids = []
837 ids = []
837 isId = re.compile(r'\w+$').match
838 isId = re.compile(r'\w+$').match
838
839
839 while True:
840 while True:
840 try:
841 try:
841 ids.append(next(iterTokens))
842 ids.append(next(iterTokens))
842 if not isId(ids[-1]):
843 if not isId(ids[-1]):
843 ids.pop(); break
844 ids.pop(); break
844 if not next(iterTokens) == '.':
845 if not next(iterTokens) == '.':
845 break
846 break
846 except StopIteration:
847 except StopIteration:
847 break
848 break
848 # lookup the candidate callable matches either using global_matches
849 # lookup the candidate callable matches either using global_matches
849 # or attr_matches for dotted names
850 # or attr_matches for dotted names
850 if len(ids) == 1:
851 if len(ids) == 1:
851 callableMatches = self.global_matches(ids[0])
852 callableMatches = self.global_matches(ids[0])
852 else:
853 else:
853 callableMatches = self.attr_matches('.'.join(ids[::-1]))
854 callableMatches = self.attr_matches('.'.join(ids[::-1]))
854 argMatches = []
855 argMatches = []
855 for callableMatch in callableMatches:
856 for callableMatch in callableMatches:
856 try:
857 try:
857 namedArgs = self._default_arguments(eval(callableMatch,
858 namedArgs = self._default_arguments(eval(callableMatch,
858 self.namespace))
859 self.namespace))
859 except:
860 except:
860 continue
861 continue
861
862
862 for namedArg in namedArgs:
863 for namedArg in namedArgs:
863 if namedArg.startswith(text):
864 if namedArg.startswith(text):
864 argMatches.append("%s=" %namedArg)
865 argMatches.append("%s=" %namedArg)
865 return argMatches
866 return argMatches
866
867
867 def dict_key_matches(self, text):
868 def dict_key_matches(self, text):
868 def get_keys(obj):
869 def get_keys(obj):
869 # Only allow completion for known in-memory dict-like types
870 # Only allow completion for known in-memory dict-like types
870 if isinstance(obj, dict) or\
871 if isinstance(obj, dict) or\
871 _safe_isinstance(obj, 'pandas', 'DataFrame'):
872 _safe_isinstance(obj, 'pandas', 'DataFrame'):
872 try:
873 try:
873 return list(obj.keys())
874 return list(obj.keys())
874 except Exception:
875 except Exception:
875 return []
876 return []
876 elif _safe_isinstance(obj, 'numpy', 'ndarray'):
877 elif _safe_isinstance(obj, 'numpy', 'ndarray'):
877 return obj.dtype.names or []
878 return obj.dtype.names or []
878 return []
879 return []
879
880
880 try:
881 try:
881 regexps = self.__dict_key_regexps
882 regexps = self.__dict_key_regexps
882 except AttributeError:
883 except AttributeError:
883 dict_key_re_fmt = r'''(?x)
884 dict_key_re_fmt = r'''(?x)
884 ( # match dict-referring expression wrt greedy setting
885 ( # match dict-referring expression wrt greedy setting
885 %s
886 %s
886 )
887 )
887 \[ # open bracket
888 \[ # open bracket
888 \s* # and optional whitespace
889 \s* # and optional whitespace
889 ([uUbB]? # string prefix (r not handled)
890 ([uUbB]? # string prefix (r not handled)
890 (?: # unclosed string
891 (?: # unclosed string
891 '(?:[^']|(?<!\\)\\')*
892 '(?:[^']|(?<!\\)\\')*
892 |
893 |
893 "(?:[^"]|(?<!\\)\\")*
894 "(?:[^"]|(?<!\\)\\")*
894 )
895 )
895 )?
896 )?
896 $
897 $
897 '''
898 '''
898 regexps = self.__dict_key_regexps = {
899 regexps = self.__dict_key_regexps = {
899 False: re.compile(dict_key_re_fmt % '''
900 False: re.compile(dict_key_re_fmt % '''
900 # identifiers separated by .
901 # identifiers separated by .
901 (?!\d)\w+
902 (?!\d)\w+
902 (?:\.(?!\d)\w+)*
903 (?:\.(?!\d)\w+)*
903 '''),
904 '''),
904 True: re.compile(dict_key_re_fmt % '''
905 True: re.compile(dict_key_re_fmt % '''
905 .+
906 .+
906 ''')
907 ''')
907 }
908 }
908
909
909 match = regexps[self.greedy].search(self.text_until_cursor)
910 match = regexps[self.greedy].search(self.text_until_cursor)
910 if match is None:
911 if match is None:
911 return []
912 return []
912
913
913 expr, prefix = match.groups()
914 expr, prefix = match.groups()
914 try:
915 try:
915 obj = eval(expr, self.namespace)
916 obj = eval(expr, self.namespace)
916 except Exception:
917 except Exception:
917 try:
918 try:
918 obj = eval(expr, self.global_namespace)
919 obj = eval(expr, self.global_namespace)
919 except Exception:
920 except Exception:
920 return []
921 return []
921
922
922 keys = get_keys(obj)
923 keys = get_keys(obj)
923 if not keys:
924 if not keys:
924 return keys
925 return keys
925 closing_quote, token_offset, matches = match_dict_keys(keys, prefix)
926 closing_quote, token_offset, matches = match_dict_keys(keys, prefix)
926 if not matches:
927 if not matches:
927 return matches
928 return matches
928
929
929 # get the cursor position of
930 # get the cursor position of
930 # - the text being completed
931 # - the text being completed
931 # - the start of the key text
932 # - the start of the key text
932 # - the start of the completion
933 # - the start of the completion
933 text_start = len(self.text_until_cursor) - len(text)
934 text_start = len(self.text_until_cursor) - len(text)
934 if prefix:
935 if prefix:
935 key_start = match.start(2)
936 key_start = match.start(2)
936 completion_start = key_start + token_offset
937 completion_start = key_start + token_offset
937 else:
938 else:
938 key_start = completion_start = match.end()
939 key_start = completion_start = match.end()
939
940
940 # grab the leading prefix, to make sure all completions start with `text`
941 # grab the leading prefix, to make sure all completions start with `text`
941 if text_start > key_start:
942 if text_start > key_start:
942 leading = ''
943 leading = ''
943 else:
944 else:
944 leading = text[text_start:completion_start]
945 leading = text[text_start:completion_start]
945
946
946 # the index of the `[` character
947 # the index of the `[` character
947 bracket_idx = match.end(1)
948 bracket_idx = match.end(1)
948
949
949 # append closing quote and bracket as appropriate
950 # append closing quote and bracket as appropriate
950 # this is *not* appropriate if the opening quote or bracket is outside
951 # this is *not* appropriate if the opening quote or bracket is outside
951 # the text given to this method
952 # the text given to this method
952 suf = ''
953 suf = ''
953 continuation = self.line_buffer[len(self.text_until_cursor):]
954 continuation = self.line_buffer[len(self.text_until_cursor):]
954 if key_start > text_start and closing_quote:
955 if key_start > text_start and closing_quote:
955 # quotes were opened inside text, maybe close them
956 # quotes were opened inside text, maybe close them
956 if continuation.startswith(closing_quote):
957 if continuation.startswith(closing_quote):
957 continuation = continuation[len(closing_quote):]
958 continuation = continuation[len(closing_quote):]
958 else:
959 else:
959 suf += closing_quote
960 suf += closing_quote
960 if bracket_idx > text_start:
961 if bracket_idx > text_start:
961 # brackets were opened inside text, maybe close them
962 # brackets were opened inside text, maybe close them
962 if not continuation.startswith(']'):
963 if not continuation.startswith(']'):
963 suf += ']'
964 suf += ']'
964
965
965 return [leading + k + suf for k in matches]
966 return [leading + k + suf for k in matches]
966
967
967 def dispatch_custom_completer(self, text):
968 def dispatch_custom_completer(self, text):
968 #io.rprint("Custom! '%s' %s" % (text, self.custom_completers)) # dbg
969 #io.rprint("Custom! '%s' %s" % (text, self.custom_completers)) # dbg
969 line = self.line_buffer
970 line = self.line_buffer
970 if not line.strip():
971 if not line.strip():
971 return None
972 return None
972
973
973 # Create a little structure to pass all the relevant information about
974 # Create a little structure to pass all the relevant information about
974 # the current completion to any custom completer.
975 # the current completion to any custom completer.
975 event = Bunch()
976 event = Bunch()
976 event.line = line
977 event.line = line
977 event.symbol = text
978 event.symbol = text
978 cmd = line.split(None,1)[0]
979 cmd = line.split(None,1)[0]
979 event.command = cmd
980 event.command = cmd
980 event.text_until_cursor = self.text_until_cursor
981 event.text_until_cursor = self.text_until_cursor
981
982
982 #print "\ncustom:{%s]\n" % event # dbg
983 #print "\ncustom:{%s]\n" % event # dbg
983
984
984 # for foo etc, try also to find completer for %foo
985 # for foo etc, try also to find completer for %foo
985 if not cmd.startswith(self.magic_escape):
986 if not cmd.startswith(self.magic_escape):
986 try_magic = self.custom_completers.s_matches(
987 try_magic = self.custom_completers.s_matches(
987 self.magic_escape + cmd)
988 self.magic_escape + cmd)
988 else:
989 else:
989 try_magic = []
990 try_magic = []
990
991
991 for c in itertools.chain(self.custom_completers.s_matches(cmd),
992 for c in itertools.chain(self.custom_completers.s_matches(cmd),
992 try_magic,
993 try_magic,
993 self.custom_completers.flat_matches(self.text_until_cursor)):
994 self.custom_completers.flat_matches(self.text_until_cursor)):
994 #print "try",c # dbg
995 #print "try",c # dbg
995 try:
996 try:
996 res = c(event)
997 res = c(event)
997 if res:
998 if res:
998 # first, try case sensitive match
999 # first, try case sensitive match
999 withcase = [r for r in res if r.startswith(text)]
1000 withcase = [r for r in res if r.startswith(text)]
1000 if withcase:
1001 if withcase:
1001 return withcase
1002 return withcase
1002 # if none, then case insensitive ones are ok too
1003 # if none, then case insensitive ones are ok too
1003 text_low = text.lower()
1004 text_low = text.lower()
1004 return [r for r in res if r.lower().startswith(text_low)]
1005 return [r for r in res if r.lower().startswith(text_low)]
1005 except TryNext:
1006 except TryNext:
1006 pass
1007 pass
1007
1008
1008 return None
1009 return None
1009
1010
1010 def complete(self, text=None, line_buffer=None, cursor_pos=None):
1011 def complete(self, text=None, line_buffer=None, cursor_pos=None):
1011 """Find completions for the given text and line context.
1012 """Find completions for the given text and line context.
1012
1013
1013 This is called successively with state == 0, 1, 2, ... until it
1014 returns None. The completion should begin with 'text'.
1015
1016 Note that both the text and the line_buffer are optional, but at least
1014 Note that both the text and the line_buffer are optional, but at least
1017 one of them must be given.
1015 one of them must be given.
1018
1016
1019 Parameters
1017 Parameters
1020 ----------
1018 ----------
1021 text : string, optional
1019 text : string, optional
1022 Text to perform the completion on. If not given, the line buffer
1020 Text to perform the completion on. If not given, the line buffer
1023 is split using the instance's CompletionSplitter object.
1021 is split using the instance's CompletionSplitter object.
1024
1022
1025 line_buffer : string, optional
1023 line_buffer : string, optional
1026 If not given, the completer attempts to obtain the current line
1024 If not given, the completer attempts to obtain the current line
1027 buffer via readline. This keyword allows clients which are
1025 buffer via readline. This keyword allows clients which are
1028 requesting for text completions in non-readline contexts to inform
1026 requesting for text completions in non-readline contexts to inform
1029 the completer of the entire text.
1027 the completer of the entire text.
1030
1028
1031 cursor_pos : int, optional
1029 cursor_pos : int, optional
1032 Index of the cursor in the full line buffer. Should be provided by
1030 Index of the cursor in the full line buffer. Should be provided by
1033 remote frontends where kernel has no access to frontend state.
1031 remote frontends where kernel has no access to frontend state.
1034
1032
1035 Returns
1033 Returns
1036 -------
1034 -------
1037 text : str
1035 text : str
1038 Text that was actually used in the completion.
1036 Text that was actually used in the completion.
1039
1037
1040 matches : list
1038 matches : list
1041 A list of completion matches.
1039 A list of completion matches.
1042 """
1040 """
1043 #io.rprint('\nCOMP1 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg
1041 #io.rprint('\nCOMP1 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg
1044
1042
1045 # if the cursor position isn't given, the only sane assumption we can
1043 # if the cursor position isn't given, the only sane assumption we can
1046 # make is that it's at the end of the line (the common case)
1044 # make is that it's at the end of the line (the common case)
1047 if cursor_pos is None:
1045 if cursor_pos is None:
1048 cursor_pos = len(line_buffer) if text is None else len(text)
1046 cursor_pos = len(line_buffer) if text is None else len(text)
1049
1047
1050 # if text is either None or an empty string, rely on the line buffer
1048 # if text is either None or an empty string, rely on the line buffer
1051 if not text:
1049 if not text:
1052 text = self.splitter.split_line(line_buffer, cursor_pos)
1050 text = self.splitter.split_line(line_buffer, cursor_pos)
1053
1051
1054 # If no line buffer is given, assume the input text is all there was
1052 # If no line buffer is given, assume the input text is all there was
1055 if line_buffer is None:
1053 if line_buffer is None:
1056 line_buffer = text
1054 line_buffer = text
1057
1055
1058 self.line_buffer = line_buffer
1056 self.line_buffer = line_buffer
1059 self.text_until_cursor = self.line_buffer[:cursor_pos]
1057 self.text_until_cursor = self.line_buffer[:cursor_pos]
1060 #io.rprint('COMP2 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg
1058 #io.rprint('COMP2 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg
1061
1059
1062 # Start with a clean slate of completions
1060 # Start with a clean slate of completions
1063 self.matches[:] = []
1061 self.matches[:] = []
1064 custom_res = self.dispatch_custom_completer(text)
1062 custom_res = self.dispatch_custom_completer(text)
1065 if custom_res is not None:
1063 if custom_res is not None:
1066 # did custom completers produce something?
1064 # did custom completers produce something?
1067 self.matches = custom_res
1065 self.matches = custom_res
1068 else:
1066 else:
1069 # Extend the list of completions with the results of each
1067 # Extend the list of completions with the results of each
1070 # matcher, so we return results to the user from all
1068 # matcher, so we return results to the user from all
1071 # namespaces.
1069 # namespaces.
1072 if self.merge_completions:
1070 if self.merge_completions:
1073 self.matches = []
1071 self.matches = []
1074 for matcher in self.matchers:
1072 for matcher in self.matchers:
1075 try:
1073 try:
1076 self.matches.extend(matcher(text))
1074 self.matches.extend(matcher(text))
1077 except:
1075 except:
1078 # Show the ugly traceback if the matcher causes an
1076 # Show the ugly traceback if the matcher causes an
1079 # exception, but do NOT crash the kernel!
1077 # exception, but do NOT crash the kernel!
1080 sys.excepthook(*sys.exc_info())
1078 sys.excepthook(*sys.exc_info())
1081 else:
1079 else:
1082 for matcher in self.matchers:
1080 for matcher in self.matchers:
1083 self.matches = matcher(text)
1081 self.matches = matcher(text)
1084 if self.matches:
1082 if self.matches:
1085 break
1083 break
1086 # FIXME: we should extend our api to return a dict with completions for
1084 # FIXME: we should extend our api to return a dict with completions for
1087 # different types of objects. The rlcomplete() method could then
1085 # different types of objects. The rlcomplete() method could then
1088 # simply collapse the dict into a list for readline, but we'd have
1086 # simply collapse the dict into a list for readline, but we'd have
1089 # richer completion semantics in other evironments.
1087 # richer completion semantics in other evironments.
1090
1088
1091 # use penalize_magics_key to put magics after variables with same name
1089 # use penalize_magics_key to put magics after variables with same name
1092 self.matches = sorted(set(self.matches), key=penalize_magics_key)
1090 self.matches = sorted(set(self.matches), key=penalize_magics_key)
1093
1091
1094 #io.rprint('COMP TEXT, MATCHES: %r, %r' % (text, self.matches)) # dbg
1092 #io.rprint('COMP TEXT, MATCHES: %r, %r' % (text, self.matches)) # dbg
1095 return text, self.matches
1093 return text, self.matches
1096
1094
1097 def rlcomplete(self, text, state):
1095 def rlcomplete(self, text, state):
1098 """Return the state-th possible completion for 'text'.
1096 """Return the state-th possible completion for 'text'.
1099
1097
1100 This is called successively with state == 0, 1, 2, ... until it
1098 This is called successively with state == 0, 1, 2, ... until it
1101 returns None. The completion should begin with 'text'.
1099 returns None. The completion should begin with 'text'.
1102
1100
1103 Parameters
1101 Parameters
1104 ----------
1102 ----------
1105 text : string
1103 text : string
1106 Text to perform the completion on.
1104 Text to perform the completion on.
1107
1105
1108 state : int
1106 state : int
1109 Counter used by readline.
1107 Counter used by readline.
1110 """
1108 """
1111 if state==0:
1109 if state==0:
1112
1110
1113 self.line_buffer = line_buffer = self.readline.get_line_buffer()
1111 self.line_buffer = line_buffer = self.readline.get_line_buffer()
1114 cursor_pos = self.readline.get_endidx()
1112 cursor_pos = self.readline.get_endidx()
1115
1113
1116 #io.rprint("\nRLCOMPLETE: %r %r %r" %
1114 #io.rprint("\nRLCOMPLETE: %r %r %r" %
1117 # (text, line_buffer, cursor_pos) ) # dbg
1115 # (text, line_buffer, cursor_pos) ) # dbg
1118
1116
1119 # if there is only a tab on a line with only whitespace, instead of
1117 # if there is only a tab on a line with only whitespace, instead of
1120 # the mostly useless 'do you want to see all million completions'
1118 # the mostly useless 'do you want to see all million completions'
1121 # message, just do the right thing and give the user his tab!
1119 # message, just do the right thing and give the user his tab!
1122 # Incidentally, this enables pasting of tabbed text from an editor
1120 # Incidentally, this enables pasting of tabbed text from an editor
1123 # (as long as autoindent is off).
1121 # (as long as autoindent is off).
1124
1122
1125 # It should be noted that at least pyreadline still shows file
1123 # It should be noted that at least pyreadline still shows file
1126 # completions - is there a way around it?
1124 # completions - is there a way around it?
1127
1125
1128 # don't apply this on 'dumb' terminals, such as emacs buffers, so
1126 # don't apply this on 'dumb' terminals, such as emacs buffers, so
1129 # we don't interfere with their own tab-completion mechanism.
1127 # we don't interfere with their own tab-completion mechanism.
1130 if not (self.dumb_terminal or line_buffer.strip()):
1128 if not (self.dumb_terminal or line_buffer.strip()):
1131 self.readline.insert_text('\t')
1129 self.readline.insert_text('\t')
1132 sys.stdout.flush()
1130 sys.stdout.flush()
1133 return None
1131 return None
1134
1132
1135 # Note: debugging exceptions that may occur in completion is very
1133 # Note: debugging exceptions that may occur in completion is very
1136 # tricky, because readline unconditionally silences them. So if
1134 # tricky, because readline unconditionally silences them. So if
1137 # during development you suspect a bug in the completion code, turn
1135 # during development you suspect a bug in the completion code, turn
1138 # this flag on temporarily by uncommenting the second form (don't
1136 # this flag on temporarily by uncommenting the second form (don't
1139 # flip the value in the first line, as the '# dbg' marker can be
1137 # flip the value in the first line, as the '# dbg' marker can be
1140 # automatically detected and is used elsewhere).
1138 # automatically detected and is used elsewhere).
1141 DEBUG = False
1139 DEBUG = False
1142 #DEBUG = True # dbg
1140 #DEBUG = True # dbg
1143 if DEBUG:
1141 if DEBUG:
1144 try:
1142 try:
1145 self.complete(text, line_buffer, cursor_pos)
1143 self.complete(text, line_buffer, cursor_pos)
1146 except:
1144 except:
1147 import traceback; traceback.print_exc()
1145 import traceback; traceback.print_exc()
1148 else:
1146 else:
1149 # The normal production version is here
1147 # The normal production version is here
1150
1148
1151 # This method computes the self.matches array
1149 # This method computes the self.matches array
1152 self.complete(text, line_buffer, cursor_pos)
1150 self.complete(text, line_buffer, cursor_pos)
1153
1151
1154 try:
1152 try:
1155 return self.matches[state]
1153 return self.matches[state]
1156 except IndexError:
1154 except IndexError:
1157 return None
1155 return None
General Comments 0
You need to be logged in to leave comments. Login now