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