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