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