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