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