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