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