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