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