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