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