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