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