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