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