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