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