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