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