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