##// END OF EJS Templates
Remove Jedi integration before 5.0...
Matthias Bussonnier -
Show More
@@ -1,1325 +1,1266 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 from __future__ import print_function
57 57
58 58 import __main__
59 59 import glob
60 60 import inspect
61 61 import itertools
62 62 import keyword
63 63 import os
64 64 import re
65 65 import sys
66 66 import unicodedata
67 67 import string
68 68
69 69 from traitlets.config.configurable import Configurable
70 70 from IPython.core.error import TryNext
71 71 from IPython.core.inputsplitter import ESC_MAGIC
72 72 from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol
73 73 from IPython.utils import generics
74 74 from IPython.utils.decorators import undoc
75 75 from IPython.utils.dir2 import dir2, get_real_method
76 76 from IPython.utils.process import arg_split
77 77 from IPython.utils.py3compat import builtin_mod, string_types, PY3, cast_unicode_py2
78 78 from traitlets import Bool, Enum, observe
79 79
80 import jedi
81 import jedi.api.helpers
82 import jedi.parser.user_context
83
84 80 #-----------------------------------------------------------------------------
85 81 # Globals
86 82 #-----------------------------------------------------------------------------
87 83
88 84 # Public API
89 85 __all__ = ['Completer','IPCompleter']
90 86
91 87 if sys.platform == 'win32':
92 88 PROTECTABLES = ' '
93 89 else:
94 90 PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&'
95 91
96 92
97 93 #-----------------------------------------------------------------------------
98 94 # Main functions and classes
99 95 #-----------------------------------------------------------------------------
100 96
101 97 def has_open_quotes(s):
102 98 """Return whether a string has open quotes.
103 99
104 100 This simply counts whether the number of quote characters of either type in
105 101 the string is odd.
106 102
107 103 Returns
108 104 -------
109 105 If there is an open quote, the quote character is returned. Else, return
110 106 False.
111 107 """
112 108 # We check " first, then ', so complex cases with nested quotes will get
113 109 # the " to take precedence.
114 110 if s.count('"') % 2:
115 111 return '"'
116 112 elif s.count("'") % 2:
117 113 return "'"
118 114 else:
119 115 return False
120 116
121 117
122 118 def protect_filename(s):
123 119 """Escape a string to protect certain characters."""
124 120
125 121 return "".join([(ch in PROTECTABLES and '\\' + ch or ch)
126 122 for ch in s])
127 123
128 124 def expand_user(path):
129 125 """Expand '~'-style usernames in strings.
130 126
131 127 This is similar to :func:`os.path.expanduser`, but it computes and returns
132 128 extra information that will be useful if the input was being used in
133 129 computing completions, and you wish to return the completions with the
134 130 original '~' instead of its expanded value.
135 131
136 132 Parameters
137 133 ----------
138 134 path : str
139 135 String to be expanded. If no ~ is present, the output is the same as the
140 136 input.
141 137
142 138 Returns
143 139 -------
144 140 newpath : str
145 141 Result of ~ expansion in the input path.
146 142 tilde_expand : bool
147 143 Whether any expansion was performed or not.
148 144 tilde_val : str
149 145 The value that ~ was replaced with.
150 146 """
151 147 # Default values
152 148 tilde_expand = False
153 149 tilde_val = ''
154 150 newpath = path
155 151
156 152 if path.startswith('~'):
157 153 tilde_expand = True
158 154 rest = len(path)-1
159 155 newpath = os.path.expanduser(path)
160 156 if rest:
161 157 tilde_val = newpath[:-rest]
162 158 else:
163 159 tilde_val = newpath
164 160
165 161 return newpath, tilde_expand, tilde_val
166 162
167 163
168 164 def compress_user(path, tilde_expand, tilde_val):
169 165 """Does the opposite of expand_user, with its outputs.
170 166 """
171 167 if tilde_expand:
172 168 return path.replace(tilde_val, '~')
173 169 else:
174 170 return path
175 171
176 172
177 173 def completions_sorting_key(word):
178 174 """key for sorting completions
179 175
180 176 This does several things:
181 177
182 178 - Lowercase all completions, so they are sorted alphabetically with
183 179 upper and lower case words mingled
184 180 - Demote any completions starting with underscores to the end
185 181 - Insert any %magic and %%cellmagic completions in the alphabetical order
186 182 by their name
187 183 """
188 184 # Case insensitive sort
189 185 word = word.lower()
190 186
191 187 prio1, prio2 = 0, 0
192 188
193 189 if word.startswith('__'):
194 190 prio1 = 2
195 191 elif word.startswith('_'):
196 192 prio1 = 1
197 193
198 194 if word.endswith('='):
199 195 prio1 = -1
200 196
201 197 if word.startswith('%%'):
202 198 # If there's another % in there, this is something else, so leave it alone
203 199 if not "%" in word[2:]:
204 200 word = word[2:]
205 201 prio2 = 2
206 202 elif word.startswith('%'):
207 203 if not "%" in word[1:]:
208 204 word = word[1:]
209 205 prio2 = 1
210 206
211 207 return prio1, word, prio2
212 208
213 209
214 210 @undoc
215 211 class Bunch(object): pass
216 212
217 213
218 214 DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
219 215 GREEDY_DELIMS = ' =\r\n'
220 216
221 217
222 218 class CompletionSplitter(object):
223 219 """An object to split an input line in a manner similar to readline.
224 220
225 221 By having our own implementation, we can expose readline-like completion in
226 222 a uniform manner to all frontends. This object only needs to be given the
227 223 line of text to be split and the cursor position on said line, and it
228 224 returns the 'word' to be completed on at the cursor after splitting the
229 225 entire line.
230 226
231 227 What characters are used as splitting delimiters can be controlled by
232 228 setting the `delims` attribute (this is a property that internally
233 229 automatically builds the necessary regular expression)"""
234 230
235 231 # Private interface
236 232
237 233 # A string of delimiter characters. The default value makes sense for
238 234 # IPython's most typical usage patterns.
239 235 _delims = DELIMS
240 236
241 237 # The expression (a normal string) to be compiled into a regular expression
242 238 # for actual splitting. We store it as an attribute mostly for ease of
243 239 # debugging, since this type of code can be so tricky to debug.
244 240 _delim_expr = None
245 241
246 242 # The regular expression that does the actual splitting
247 243 _delim_re = None
248 244
249 245 def __init__(self, delims=None):
250 246 delims = CompletionSplitter._delims if delims is None else delims
251 247 self.delims = delims
252 248
253 249 @property
254 250 def delims(self):
255 251 """Return the string of delimiter characters."""
256 252 return self._delims
257 253
258 254 @delims.setter
259 255 def delims(self, delims):
260 256 """Set the delimiters for line splitting."""
261 257 expr = '[' + ''.join('\\'+ c for c in delims) + ']'
262 258 self._delim_re = re.compile(expr)
263 259 self._delims = delims
264 260 self._delim_expr = expr
265 261
266 262 def split_line(self, line, cursor_pos=None):
267 263 """Split a line of text with a cursor at the given position.
268 264 """
269 265 l = line if cursor_pos is None else line[:cursor_pos]
270 266 return self._delim_re.split(l)[-1]
271 267
272 268
273 269 class Completer(Configurable):
274 270
275 271 greedy = Bool(False,
276 272 help="""Activate greedy completion
277 273 PENDING DEPRECTION. this is now mostly taken care of with Jedi.
278 274
279 275 This will enable completion on elements of lists, results of function calls, etc.,
280 276 but can be unsafe because the code is actually evaluated on TAB.
281 277 """
282 278 ).tag(config=True)
283 279
284 280
285 281 def __init__(self, namespace=None, global_namespace=None, **kwargs):
286 282 """Create a new completer for the command line.
287 283
288 284 Completer(namespace=ns, global_namespace=ns2) -> completer instance.
289 285
290 286 If unspecified, the default namespace where completions are performed
291 287 is __main__ (technically, __main__.__dict__). Namespaces should be
292 288 given as dictionaries.
293 289
294 290 An optional second namespace can be given. This allows the completer
295 291 to handle cases where both the local and global scopes need to be
296 292 distinguished.
297 293
298 294 Completer instances should be used as the completion mechanism of
299 295 readline via the set_completer() call:
300 296
301 297 readline.set_completer(Completer(my_namespace).complete)
302 298 """
303 299
304 300 # Don't bind to namespace quite yet, but flag whether the user wants a
305 301 # specific namespace or to use __main__.__dict__. This will allow us
306 302 # to bind to __main__.__dict__ at completion time, not now.
307 303 if namespace is None:
308 304 self.use_main_ns = 1
309 305 else:
310 306 self.use_main_ns = 0
311 307 self.namespace = namespace
312 308
313 309 # The global namespace, if given, can be bound directly
314 310 if global_namespace is None:
315 311 self.global_namespace = {}
316 312 else:
317 313 self.global_namespace = global_namespace
318 314
319 315 super(Completer, self).__init__(**kwargs)
320 316
321 317 def complete(self, text, state):
322 318 """Return the next possible completion for 'text'.
323 319
324 320 This is called successively with state == 0, 1, 2, ... until it
325 321 returns None. The completion should begin with 'text'.
326 322
327 323 """
328 324 if self.use_main_ns:
329 325 self.namespace = __main__.__dict__
330 326
331 327 if state == 0:
332 328 if "." in text:
333 329 self.matches = self.attr_matches(text)
334 330 else:
335 331 self.matches = self.global_matches(text)
336 332 try:
337 333 return self.matches[state]
338 334 except IndexError:
339 335 return None
340 336
341 337 def global_matches(self, text):
342 338 """Compute matches when text is a simple name.
343 339
344 340 Return a list of all keywords, built-in functions and names currently
345 341 defined in self.namespace or self.global_namespace that match.
346 342
347 343 """
348 344 matches = []
349 345 match_append = matches.append
350 346 n = len(text)
351 347 for lst in [keyword.kwlist,
352 348 builtin_mod.__dict__.keys(),
353 349 self.namespace.keys(),
354 350 self.global_namespace.keys()]:
355 351 for word in lst:
356 352 if word[:n] == text and word != "__builtins__":
357 353 match_append(word)
358 354 return [cast_unicode_py2(m) for m in matches]
359 355
360 356 def attr_matches(self, text):
361 357 """Compute matches when text contains a dot.
362 358
363 359 Assuming the text is of the form NAME.NAME....[NAME], and is
364 360 evaluatable in self.namespace or self.global_namespace, it will be
365 361 evaluated and its attributes (as revealed by dir()) are used as
366 362 possible completions. (For class instances, class members are are
367 363 also considered.)
368 364
369 365 WARNING: this can still invoke arbitrary C code, if an object
370 366 with a __getattr__ hook is evaluated.
371 367
372 368 """
373 369
374 370 # Another option, seems to work great. Catches things like ''.<tab>
375 371 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
376 372
377 373 if m:
378 374 expr, attr = m.group(1, 3)
379 375 elif self.greedy:
380 376 m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer)
381 377 if not m2:
382 378 return []
383 379 expr, attr = m2.group(1,2)
384 380 else:
385 381 return []
386 382
387 383 try:
388 384 obj = eval(expr, self.namespace)
389 385 except:
390 386 try:
391 387 obj = eval(expr, self.global_namespace)
392 388 except:
393 389 return []
394 390
395 391 if self.limit_to__all__ and hasattr(obj, '__all__'):
396 392 words = get__all__entries(obj)
397 393 else:
398 394 words = dir2(obj)
399 395
400 396 try:
401 397 words = generics.complete_object(obj, words)
402 398 except TryNext:
403 399 pass
404 400 except Exception:
405 401 # Silence errors from completion function
406 402 #raise # dbg
407 403 pass
408 404 # Build match list to return
409 405 n = len(attr)
410 406 return [u"%s.%s" % (expr, w) for w in words if w[:n] == attr ]
411 407
412 408
413 409 def get__all__entries(obj):
414 410 """returns the strings in the __all__ attribute"""
415 411 try:
416 412 words = getattr(obj, '__all__')
417 413 except:
418 414 return []
419 415
420 416 return [cast_unicode_py2(w) for w in words if isinstance(w, string_types)]
421 417
422 418
423 419 def match_dict_keys(keys, prefix, delims):
424 420 """Used by dict_key_matches, matching the prefix to a list of keys"""
425 421 if not prefix:
426 422 return None, 0, [repr(k) for k in keys
427 423 if isinstance(k, (string_types, bytes))]
428 424 quote_match = re.search('["\']', prefix)
429 425 quote = quote_match.group()
430 426 try:
431 427 prefix_str = eval(prefix + quote, {})
432 428 except Exception:
433 429 return None, 0, []
434 430
435 431 pattern = '[^' + ''.join('\\' + c for c in delims) + ']*$'
436 432 token_match = re.search(pattern, prefix, re.UNICODE)
437 433 token_start = token_match.start()
438 434 token_prefix = token_match.group()
439 435
440 436 # TODO: support bytes in Py3k
441 437 matched = []
442 438 for key in keys:
443 439 try:
444 440 if not key.startswith(prefix_str):
445 441 continue
446 442 except (AttributeError, TypeError, UnicodeError):
447 443 # Python 3+ TypeError on b'a'.startswith('a') or vice-versa
448 444 continue
449 445
450 446 # reformat remainder of key to begin with prefix
451 447 rem = key[len(prefix_str):]
452 448 # force repr wrapped in '
453 449 rem_repr = repr(rem + '"')
454 450 if rem_repr.startswith('u') and prefix[0] not in 'uU':
455 451 # Found key is unicode, but prefix is Py2 string.
456 452 # Therefore attempt to interpret key as string.
457 453 try:
458 454 rem_repr = repr(rem.encode('ascii') + '"')
459 455 except UnicodeEncodeError:
460 456 continue
461 457
462 458 rem_repr = rem_repr[1 + rem_repr.index("'"):-2]
463 459 if quote == '"':
464 460 # The entered prefix is quoted with ",
465 461 # but the match is quoted with '.
466 462 # A contained " hence needs escaping for comparison:
467 463 rem_repr = rem_repr.replace('"', '\\"')
468 464
469 465 # then reinsert prefix from start of token
470 466 matched.append('%s%s' % (token_prefix, rem_repr))
471 467 return quote, token_start, matched
472 468
473 469
474 470 def _safe_isinstance(obj, module, class_name):
475 471 """Checks if obj is an instance of module.class_name if loaded
476 472 """
477 473 return (module in sys.modules and
478 474 isinstance(obj, getattr(__import__(module), class_name)))
479 475
480 476
481 477 def back_unicode_name_matches(text):
482 478 u"""Match unicode characters back to unicode name
483 479
484 480 This does β˜ƒ -> \\snowman
485 481
486 482 Note that snowman is not a valid python3 combining character but will be expanded.
487 483 Though it will not recombine back to the snowman character by the completion machinery.
488 484
489 485 This will not either back-complete standard sequences like \\n, \\b ...
490 486
491 487 Used on Python 3 only.
492 488 """
493 489 if len(text)<2:
494 490 return u'', ()
495 491 maybe_slash = text[-2]
496 492 if maybe_slash != '\\':
497 493 return u'', ()
498 494
499 495 char = text[-1]
500 496 # no expand on quote for completion in strings.
501 497 # nor backcomplete standard ascii keys
502 498 if char in string.ascii_letters or char in ['"',"'"]:
503 499 return u'', ()
504 500 try :
505 501 unic = unicodedata.name(char)
506 502 return '\\'+char,['\\'+unic]
507 503 except KeyError:
508 504 pass
509 505 return u'', ()
510 506
511 507 def back_latex_name_matches(text):
512 508 u"""Match latex characters back to unicode name
513 509
514 510 This does ->\\sqrt
515 511
516 512 Used on Python 3 only.
517 513 """
518 514 if len(text)<2:
519 515 return u'', ()
520 516 maybe_slash = text[-2]
521 517 if maybe_slash != '\\':
522 518 return u'', ()
523 519
524 520
525 521 char = text[-1]
526 522 # no expand on quote for completion in strings.
527 523 # nor backcomplete standard ascii keys
528 524 if char in string.ascii_letters or char in ['"',"'"]:
529 525 return u'', ()
530 526 try :
531 527 latex = reverse_latex_symbol[char]
532 528 # '\\' replace the \ as well
533 529 return '\\'+char,[latex]
534 530 except KeyError:
535 531 pass
536 532 return u'', ()
537 533
538 534
539 535 class IPCompleter(Completer):
540 536 """Extension of the completer class with IPython-specific features"""
541 537
542 538 @observe('greedy')
543 539 def _greedy_changed(self, change):
544 540 """update the splitter and readline delims when greedy is changed"""
545 541 if change['new']:
546 542 self.splitter.delims = GREEDY_DELIMS
547 543 else:
548 544 self.splitter.delims = DELIMS
549 545
550 546 if self.readline:
551 547 self.readline.set_completer_delims(self.splitter.delims)
552 548
553 549 merge_completions = Bool(True,
554 550 help="""Whether to merge completion results into a single list
555 551
556 552 If False, only the completion results from the first non-empty
557 553 completer will be returned.
558 554 """
559 555 ).tag(config=True)
560 556 omit__names = Enum((0,1,2), default_value=2,
561 557 help="""Instruct the completer to omit private method names
562 558
563 559 Specifically, when completing on ``object.<tab>``.
564 560
565 561 When 2 [default]: all names that start with '_' will be excluded.
566 562
567 563 When 1: all 'magic' names (``__foo__``) will be excluded.
568 564
569 565 When 0: nothing will be excluded.
570 566 """
571 567 ).tag(config=True)
572 568 limit_to__all__ = Bool(False,
573 569 help="""
574 570 DEPRECATED as of version 5.0.
575 571
576 572 Instruct the completer to use __all__ for the completion
577 573
578 574 Specifically, when completing on ``object.<tab>``.
579 575
580 576 When True: only those names in obj.__all__ will be included.
581 577
582 578 When False [default]: the __all__ attribute is ignored
583 579 """,
584 580 ).tag(config=True)
585 581
586 582 def __init__(self, shell=None, namespace=None, global_namespace=None,
587 583 use_readline=True, config=None, **kwargs):
588 584 """IPCompleter() -> completer
589 585
590 586 Return a completer object suitable for use by the readline library
591 587 via readline.set_completer().
592 588
593 589 Inputs:
594 590
595 591 - shell: a pointer to the ipython shell itself. This is needed
596 592 because this completer knows about magic functions, and those can
597 593 only be accessed via the ipython instance.
598 594
599 595 - namespace: an optional dict where completions are performed.
600 596
601 597 - global_namespace: secondary optional dict for completions, to
602 598 handle cases (such as IPython embedded inside functions) where
603 599 both Python scopes are visible.
604 600
605 601 use_readline : bool, optional
606 602 If true, use the readline library. This completer can still function
607 603 without readline, though in that case callers must provide some extra
608 604 information on each call about the current line."""
609 605
610 606 self.magic_escape = ESC_MAGIC
611 607 self.splitter = CompletionSplitter()
612 608
613 609 # Readline configuration, only used by the rlcompleter method.
614 610 if use_readline:
615 611 # We store the right version of readline so that later code
616 612 import IPython.utils.rlineimpl as readline
617 613 self.readline = readline
618 614 else:
619 615 self.readline = None
620 616
621 617 # _greedy_changed() depends on splitter and readline being defined:
622 618 Completer.__init__(self, namespace=namespace, global_namespace=global_namespace,
623 619 config=config, **kwargs)
624 620
625 621 # List where completion matches will be stored
626 622 self.matches = []
627 623 self.shell = shell
628 624 # Regexp to split filenames with spaces in them
629 625 self.space_name_re = re.compile(r'([^\\] )')
630 626 # Hold a local ref. to glob.glob for speed
631 627 self.glob = glob.glob
632 628
633 629 # Determine if we are running on 'dumb' terminals, like (X)Emacs
634 630 # buffers, to avoid completion problems.
635 631 term = os.environ.get('TERM','xterm')
636 632 self.dumb_terminal = term in ['dumb','emacs']
637 633
638 634 # Special handling of backslashes needed in win32 platforms
639 635 if sys.platform == "win32":
640 636 self.clean_glob = self._clean_glob_win32
641 637 else:
642 638 self.clean_glob = self._clean_glob
643 639
644 640 #regexp to parse docstring for function signature
645 641 self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
646 642 self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
647 643 #use this if positional argument name is also needed
648 644 #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)')
649 645
650 646 # All active matcher routines for completion
651 647 self.matchers = [
648 self.python_matches,
652 649 self.file_matches,
653 650 self.magic_matches,
654 651 self.python_func_kw_matches,
655 652 self.dict_key_matches,
656 653 ]
657 654
658 655 def all_completions(self, text):
659 656 """
660 657 Wrapper around the complete method for the benefit of emacs
661 658 and pydb.
662 659 """
663 660 return self.complete(text)[1]
664 661
665 662 def _clean_glob(self, text):
666 663 return self.glob("%s*" % text)
667 664
668 665 def _clean_glob_win32(self,text):
669 666 return [f.replace("\\","/")
670 667 for f in self.glob("%s*" % text)]
671 668
672 669 def file_matches(self, text):
673 670 """Match filenames, expanding ~USER type strings.
674 671
675 672 Most of the seemingly convoluted logic in this completer is an
676 673 attempt to handle filenames with spaces in them. And yet it's not
677 674 quite perfect, because Python's readline doesn't expose all of the
678 675 GNU readline details needed for this to be done correctly.
679 676
680 677 For a filename with a space in it, the printed completions will be
681 678 only the parts after what's already been typed (instead of the
682 679 full completions, as is normally done). I don't think with the
683 680 current (as of Python 2.3) Python readline it's possible to do
684 681 better."""
685 682
686 683 # chars that require escaping with backslash - i.e. chars
687 684 # that readline treats incorrectly as delimiters, but we
688 685 # don't want to treat as delimiters in filename matching
689 686 # when escaped with backslash
690 687 if text.startswith('!'):
691 688 text = text[1:]
692 689 text_prefix = u'!'
693 690 else:
694 691 text_prefix = u''
695 692
696 693 text_until_cursor = self.text_until_cursor
697 694 # track strings with open quotes
698 695 open_quotes = has_open_quotes(text_until_cursor)
699 696
700 697 if '(' in text_until_cursor or '[' in text_until_cursor:
701 698 lsplit = text
702 699 else:
703 700 try:
704 701 # arg_split ~ shlex.split, but with unicode bugs fixed by us
705 702 lsplit = arg_split(text_until_cursor)[-1]
706 703 except ValueError:
707 704 # typically an unmatched ", or backslash without escaped char.
708 705 if open_quotes:
709 706 lsplit = text_until_cursor.split(open_quotes)[-1]
710 707 else:
711 708 return []
712 709 except IndexError:
713 710 # tab pressed on empty line
714 711 lsplit = ""
715 712
716 713 if not open_quotes and lsplit != protect_filename(lsplit):
717 714 # if protectables are found, do matching on the whole escaped name
718 715 has_protectables = True
719 716 text0,text = text,lsplit
720 717 else:
721 718 has_protectables = False
722 719 text = os.path.expanduser(text)
723 720
724 721 if text == "":
725 722 return [text_prefix + cast_unicode_py2(protect_filename(f)) for f in self.glob("*")]
726 723
727 724 # Compute the matches from the filesystem
728 725 m0 = self.clean_glob(text.replace('\\',''))
729 726
730 727 if has_protectables:
731 728 # If we had protectables, we need to revert our changes to the
732 729 # beginning of filename so that we don't double-write the part
733 730 # of the filename we have so far
734 731 len_lsplit = len(lsplit)
735 732 matches = [text_prefix + text0 +
736 733 protect_filename(f[len_lsplit:]) for f in m0]
737 734 else:
738 735 if open_quotes:
739 736 # if we have a string with an open quote, we don't need to
740 737 # protect the names at all (and we _shouldn't_, as it
741 738 # would cause bugs when the filesystem call is made).
742 739 matches = m0
743 740 else:
744 741 matches = [text_prefix +
745 742 protect_filename(f) for f in m0]
746 743
747 744 # Mark directories in input list by appending '/' to their names.
748 745 return [cast_unicode_py2(x+'/') if os.path.isdir(x) else x for x in matches]
749 746
750 747 def magic_matches(self, text):
751 748 """Match magics"""
752 749 # Get all shell magics now rather than statically, so magics loaded at
753 750 # runtime show up too.
754 751 lsm = self.shell.magics_manager.lsmagic()
755 752 line_magics = lsm['line']
756 753 cell_magics = lsm['cell']
757 754 pre = self.magic_escape
758 755 pre2 = pre+pre
759 756
760 757 # Completion logic:
761 758 # - user gives %%: only do cell magics
762 759 # - user gives %: do both line and cell magics
763 760 # - no prefix: do both
764 761 # In other words, line magics are skipped if the user gives %% explicitly
765 762 bare_text = text.lstrip(pre)
766 763 comp = [ pre2+m for m in cell_magics if m.startswith(bare_text)]
767 764 if not text.startswith(pre2):
768 765 comp += [ pre+m for m in line_magics if m.startswith(bare_text)]
769 766 return [cast_unicode_py2(c) for c in comp]
770 767
771 def python_jedi_matches(self, text, line_buffer, cursor_pos):
772 """Match attributes or global Python names using Jedi."""
773 if line_buffer.startswith('aimport ') or line_buffer.startswith('%aimport '):
774 return ()
775 namespaces = []
776 if self.namespace is None:
777 import __main__
778 namespaces.append(__main__.__dict__)
779 else:
780 namespaces.append(self.namespace)
781 if self.global_namespace is not None:
782 namespaces.append(self.global_namespace)
783
784 # cursor_pos is an it, jedi wants line and column
785
786 interpreter = jedi.Interpreter(line_buffer, namespaces, column=cursor_pos)
787 path = jedi.parser.user_context.UserContext(line_buffer, \
788 (1, len(line_buffer))).get_path_until_cursor()
789 path, dot, like = jedi.api.helpers.completion_parts(path)
790 if text.startswith('.'):
791 # text will be `.` on completions like `a[0].<tab>`
792 before = dot
793 else:
794 before = line_buffer[:len(line_buffer) - len(like)]
795
796
797 def trim_start(completion):
798 """completions need to start with `text`, trim the beginning until it does"""
799 ltext = text.lower()
800 lcomp = completion.lower()
801 if ltext in lcomp and not (lcomp.startswith(ltext)):
802 start_index = lcomp.index(ltext)
803 if cursor_pos:
804 if start_index >= cursor_pos:
805 start_index = min(start_index, cursor_pos)
806 return completion[start_index:]
807 return completion
808
809 completions = interpreter.completions()
810
811 completion_text = [c.name_with_symbols for c in completions]
812
813 if self.omit__names:
814 if self.omit__names == 1:
815 # true if txt is _not_ a __ name, false otherwise:
816 no__name = lambda txt: not txt.startswith('__')
817 else:
818 # true if txt is _not_ a _ name, false otherwise:
819 no__name = lambda txt: not txt.startswith('_')
820 completion_text = filter(no__name, completion_text)
821
822
823 return [trim_start(before + c_text) for c_text in completion_text]
824
825 768
826 769 def python_matches(self, text):
827 770 """Match attributes or global python names"""
828 771 if "." in text:
829 772 try:
830 773 matches = self.attr_matches(text)
831 774 if text.endswith('.') and self.omit__names:
832 775 if self.omit__names == 1:
833 776 # true if txt is _not_ a __ name, false otherwise:
834 777 no__name = (lambda txt:
835 778 re.match(r'.*\.__.*?__',txt) is None)
836 779 else:
837 780 # true if txt is _not_ a _ name, false otherwise:
838 781 no__name = (lambda txt:
839 782 re.match(r'\._.*?',txt[txt.rindex('.'):]) is None)
840 783 matches = filter(no__name, matches)
841 784 except NameError:
842 785 # catches <undefined attributes>.<tab>
843 786 matches = []
844 787 else:
845 788 matches = self.global_matches(text)
846 789 return matches
847 790
848 791 def _default_arguments_from_docstring(self, doc):
849 792 """Parse the first line of docstring for call signature.
850 793
851 794 Docstring should be of the form 'min(iterable[, key=func])\n'.
852 795 It can also parse cython docstring of the form
853 796 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'.
854 797 """
855 798 if doc is None:
856 799 return []
857 800
858 801 #care only the firstline
859 802 line = doc.lstrip().splitlines()[0]
860 803
861 804 #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
862 805 #'min(iterable[, key=func])\n' -> 'iterable[, key=func]'
863 806 sig = self.docstring_sig_re.search(line)
864 807 if sig is None:
865 808 return []
866 809 # iterable[, key=func]' -> ['iterable[' ,' key=func]']
867 810 sig = sig.groups()[0].split(',')
868 811 ret = []
869 812 for s in sig:
870 813 #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
871 814 ret += self.docstring_kwd_re.findall(s)
872 815 return ret
873 816
874 817 def _default_arguments(self, obj):
875 818 """Return the list of default arguments of obj if it is callable,
876 819 or empty list otherwise."""
877 820 call_obj = obj
878 821 ret = []
879 822 if inspect.isbuiltin(obj):
880 823 pass
881 824 elif not (inspect.isfunction(obj) or inspect.ismethod(obj)):
882 825 if inspect.isclass(obj):
883 826 #for cython embededsignature=True the constructor docstring
884 827 #belongs to the object itself not __init__
885 828 ret += self._default_arguments_from_docstring(
886 829 getattr(obj, '__doc__', ''))
887 830 # for classes, check for __init__,__new__
888 831 call_obj = (getattr(obj, '__init__', None) or
889 832 getattr(obj, '__new__', None))
890 833 # for all others, check if they are __call__able
891 834 elif hasattr(obj, '__call__'):
892 835 call_obj = obj.__call__
893 836 ret += self._default_arguments_from_docstring(
894 837 getattr(call_obj, '__doc__', ''))
895 838
896 839 if PY3:
897 840 _keeps = (inspect.Parameter.KEYWORD_ONLY,
898 841 inspect.Parameter.POSITIONAL_OR_KEYWORD)
899 842 signature = inspect.signature
900 843 else:
901 844 import IPython.utils.signatures
902 845 _keeps = (IPython.utils.signatures.Parameter.KEYWORD_ONLY,
903 846 IPython.utils.signatures.Parameter.POSITIONAL_OR_KEYWORD)
904 847 signature = IPython.utils.signatures.signature
905 848
906 849 try:
907 850 sig = signature(call_obj)
908 851 ret.extend(k for k, v in sig.parameters.items() if
909 852 v.kind in _keeps)
910 853 except ValueError:
911 854 pass
912 855
913 856 return list(set(ret))
914 857
915 858 def python_func_kw_matches(self,text):
916 859 """Match named parameters (kwargs) of the last open function"""
917 860
918 861 if "." in text: # a parameter cannot be dotted
919 862 return []
920 863 try: regexp = self.__funcParamsRegex
921 864 except AttributeError:
922 865 regexp = self.__funcParamsRegex = re.compile(r'''
923 866 '.*?(?<!\\)' | # single quoted strings or
924 867 ".*?(?<!\\)" | # double quoted strings or
925 868 \w+ | # identifier
926 869 \S # other characters
927 870 ''', re.VERBOSE | re.DOTALL)
928 871 # 1. find the nearest identifier that comes before an unclosed
929 872 # parenthesis before the cursor
930 873 # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo"
931 874 tokens = regexp.findall(self.text_until_cursor)
932 875 tokens.reverse()
933 876 iterTokens = iter(tokens); openPar = 0
934 877
935 878 for token in iterTokens:
936 879 if token == ')':
937 880 openPar -= 1
938 881 elif token == '(':
939 882 openPar += 1
940 883 if openPar > 0:
941 884 # found the last unclosed parenthesis
942 885 break
943 886 else:
944 887 return []
945 888 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
946 889 ids = []
947 890 isId = re.compile(r'\w+$').match
948 891
949 892 while True:
950 893 try:
951 894 ids.append(next(iterTokens))
952 895 if not isId(ids[-1]):
953 896 ids.pop(); break
954 897 if not next(iterTokens) == '.':
955 898 break
956 899 except StopIteration:
957 900 break
958 901 # lookup the candidate callable matches either using global_matches
959 902 # or attr_matches for dotted names
960 903 if len(ids) == 1:
961 904 callableMatches = self.global_matches(ids[0])
962 905 else:
963 906 callableMatches = self.attr_matches('.'.join(ids[::-1]))
964 907 argMatches = []
965 908 for callableMatch in callableMatches:
966 909 try:
967 910 namedArgs = self._default_arguments(eval(callableMatch,
968 911 self.namespace))
969 912 except:
970 913 continue
971 914
972 915 for namedArg in namedArgs:
973 916 if namedArg.startswith(text):
974 917 argMatches.append(u"%s=" %namedArg)
975 918 return argMatches
976 919
977 920 def dict_key_matches(self, text):
978 921 "Match string keys in a dictionary, after e.g. 'foo[' "
979 922 def get_keys(obj):
980 923 # Objects can define their own completions by defining an
981 924 # _ipy_key_completions_() method.
982 925 method = get_real_method(obj, '_ipython_key_completions_')
983 926 if method is not None:
984 927 return method()
985 928
986 929 # Special case some common in-memory dict-like types
987 930 if isinstance(obj, dict) or\
988 931 _safe_isinstance(obj, 'pandas', 'DataFrame'):
989 932 try:
990 933 return list(obj.keys())
991 934 except Exception:
992 935 return []
993 936 elif _safe_isinstance(obj, 'numpy', 'ndarray') or\
994 937 _safe_isinstance(obj, 'numpy', 'void'):
995 938 return obj.dtype.names or []
996 939 return []
997 940
998 941 try:
999 942 regexps = self.__dict_key_regexps
1000 943 except AttributeError:
1001 944 dict_key_re_fmt = r'''(?x)
1002 945 ( # match dict-referring expression wrt greedy setting
1003 946 %s
1004 947 )
1005 948 \[ # open bracket
1006 949 \s* # and optional whitespace
1007 950 ([uUbB]? # string prefix (r not handled)
1008 951 (?: # unclosed string
1009 952 '(?:[^']|(?<!\\)\\')*
1010 953 |
1011 954 "(?:[^"]|(?<!\\)\\")*
1012 955 )
1013 956 )?
1014 957 $
1015 958 '''
1016 959 regexps = self.__dict_key_regexps = {
1017 960 False: re.compile(dict_key_re_fmt % '''
1018 961 # identifiers separated by .
1019 962 (?!\d)\w+
1020 963 (?:\.(?!\d)\w+)*
1021 964 '''),
1022 965 True: re.compile(dict_key_re_fmt % '''
1023 966 .+
1024 967 ''')
1025 968 }
1026 969
1027 970 match = regexps[self.greedy].search(self.text_until_cursor)
1028 971 if match is None:
1029 972 return []
1030 973
1031 974 expr, prefix = match.groups()
1032 975 try:
1033 976 obj = eval(expr, self.namespace)
1034 977 except Exception:
1035 978 try:
1036 979 obj = eval(expr, self.global_namespace)
1037 980 except Exception:
1038 981 return []
1039 982
1040 983 keys = get_keys(obj)
1041 984 if not keys:
1042 985 return keys
1043 986 closing_quote, token_offset, matches = match_dict_keys(keys, prefix, self.splitter.delims)
1044 987 if not matches:
1045 988 return matches
1046 989
1047 990 # get the cursor position of
1048 991 # - the text being completed
1049 992 # - the start of the key text
1050 993 # - the start of the completion
1051 994 text_start = len(self.text_until_cursor) - len(text)
1052 995 if prefix:
1053 996 key_start = match.start(2)
1054 997 completion_start = key_start + token_offset
1055 998 else:
1056 999 key_start = completion_start = match.end()
1057 1000
1058 1001 # grab the leading prefix, to make sure all completions start with `text`
1059 1002 if text_start > key_start:
1060 1003 leading = ''
1061 1004 else:
1062 1005 leading = text[text_start:completion_start]
1063 1006
1064 1007 # the index of the `[` character
1065 1008 bracket_idx = match.end(1)
1066 1009
1067 1010 # append closing quote and bracket as appropriate
1068 1011 # this is *not* appropriate if the opening quote or bracket is outside
1069 1012 # the text given to this method
1070 1013 suf = ''
1071 1014 continuation = self.line_buffer[len(self.text_until_cursor):]
1072 1015 if key_start > text_start and closing_quote:
1073 1016 # quotes were opened inside text, maybe close them
1074 1017 if continuation.startswith(closing_quote):
1075 1018 continuation = continuation[len(closing_quote):]
1076 1019 else:
1077 1020 suf += closing_quote
1078 1021 if bracket_idx > text_start:
1079 1022 # brackets were opened inside text, maybe close them
1080 1023 if not continuation.startswith(']'):
1081 1024 suf += ']'
1082 1025
1083 1026 return [leading + k + suf for k in matches]
1084 1027
1085 1028 def unicode_name_matches(self, text):
1086 1029 u"""Match Latex-like syntax for unicode characters base
1087 1030 on the name of the character.
1088 1031
1089 1032 This does \\GREEK SMALL LETTER ETA -> Ξ·
1090 1033
1091 1034 Works only on valid python 3 identifier, or on combining characters that
1092 1035 will combine to form a valid identifier.
1093 1036
1094 1037 Used on Python 3 only.
1095 1038 """
1096 1039 slashpos = text.rfind('\\')
1097 1040 if slashpos > -1:
1098 1041 s = text[slashpos+1:]
1099 1042 try :
1100 1043 unic = unicodedata.lookup(s)
1101 1044 # allow combining chars
1102 1045 if ('a'+unic).isidentifier():
1103 1046 return '\\'+s,[unic]
1104 1047 except KeyError:
1105 1048 pass
1106 1049 return u'', []
1107 1050
1108 1051
1109 1052
1110 1053
1111 1054 def latex_matches(self, text):
1112 1055 u"""Match Latex syntax for unicode characters.
1113 1056
1114 1057 This does both \\alp -> \\alpha and \\alpha -> Ξ±
1115 1058
1116 1059 Used on Python 3 only.
1117 1060 """
1118 1061 slashpos = text.rfind('\\')
1119 1062 if slashpos > -1:
1120 1063 s = text[slashpos:]
1121 1064 if s in latex_symbols:
1122 1065 # Try to complete a full latex symbol to unicode
1123 1066 # \\alpha -> Ξ±
1124 1067 return s, [latex_symbols[s]]
1125 1068 else:
1126 1069 # If a user has partially typed a latex symbol, give them
1127 1070 # a full list of options \al -> [\aleph, \alpha]
1128 1071 matches = [k for k in latex_symbols if k.startswith(s)]
1129 1072 return s, matches
1130 1073 return u'', []
1131 1074
1132 1075 def dispatch_custom_completer(self, text):
1133 1076 line = self.line_buffer
1134 1077 if not line.strip():
1135 1078 return None
1136 1079
1137 1080 # Create a little structure to pass all the relevant information about
1138 1081 # the current completion to any custom completer.
1139 1082 event = Bunch()
1140 1083 event.line = line
1141 1084 event.symbol = text
1142 1085 cmd = line.split(None,1)[0]
1143 1086 event.command = cmd
1144 1087 event.text_until_cursor = self.text_until_cursor
1145 1088
1146 1089 # for foo etc, try also to find completer for %foo
1147 1090 if not cmd.startswith(self.magic_escape):
1148 1091 try_magic = self.custom_completers.s_matches(
1149 1092 self.magic_escape + cmd)
1150 1093 else:
1151 1094 try_magic = []
1152 1095
1153 1096 for c in itertools.chain(self.custom_completers.s_matches(cmd),
1154 1097 try_magic,
1155 1098 self.custom_completers.flat_matches(self.text_until_cursor)):
1156 1099 try:
1157 1100 res = c(event)
1158 1101 if res:
1159 1102 # first, try case sensitive match
1160 1103 withcase = [cast_unicode_py2(r) for r in res if r.startswith(text)]
1161 1104 if withcase:
1162 1105 return withcase
1163 1106 # if none, then case insensitive ones are ok too
1164 1107 text_low = text.lower()
1165 1108 return [cast_unicode_py2(r) for r in res if r.lower().startswith(text_low)]
1166 1109 except TryNext:
1167 1110 pass
1168 1111
1169 1112 return None
1170 1113
1171 1114 def complete(self, text=None, line_buffer=None, cursor_pos=None):
1172 1115 """Find completions for the given text and line context.
1173 1116
1174 1117 Note that both the text and the line_buffer are optional, but at least
1175 1118 one of them must be given.
1176 1119
1177 1120 Parameters
1178 1121 ----------
1179 1122 text : string, optional
1180 1123 Text to perform the completion on. If not given, the line buffer
1181 1124 is split using the instance's CompletionSplitter object.
1182 1125
1183 1126 line_buffer : string, optional
1184 1127 If not given, the completer attempts to obtain the current line
1185 1128 buffer via readline. This keyword allows clients which are
1186 1129 requesting for text completions in non-readline contexts to inform
1187 1130 the completer of the entire text.
1188 1131
1189 1132 cursor_pos : int, optional
1190 1133 Index of the cursor in the full line buffer. Should be provided by
1191 1134 remote frontends where kernel has no access to frontend state.
1192 1135
1193 1136 Returns
1194 1137 -------
1195 1138 text : str
1196 1139 Text that was actually used in the completion.
1197 1140
1198 1141 matches : list
1199 1142 A list of completion matches.
1200 1143 """
1201 1144 # if the cursor position isn't given, the only sane assumption we can
1202 1145 # make is that it's at the end of the line (the common case)
1203 1146 if cursor_pos is None:
1204 1147 cursor_pos = len(line_buffer) if text is None else len(text)
1205 1148
1206 1149 if PY3:
1207 1150
1208 1151 base_text = text if not line_buffer else line_buffer[:cursor_pos]
1209 1152 latex_text, latex_matches = self.latex_matches(base_text)
1210 1153 if latex_matches:
1211 1154 return latex_text, latex_matches
1212 1155 name_text = ''
1213 1156 name_matches = []
1214 1157 for meth in (self.unicode_name_matches, back_latex_name_matches, back_unicode_name_matches):
1215 1158 name_text, name_matches = meth(base_text)
1216 1159 if name_text:
1217 1160 return name_text, name_matches
1218 1161
1219 1162 # if text is either None or an empty string, rely on the line buffer
1220 1163 if not text:
1221 1164 text = self.splitter.split_line(line_buffer, cursor_pos)
1222 1165
1223 1166 # If no line buffer is given, assume the input text is all there was
1224 1167 if line_buffer is None:
1225 1168 line_buffer = text
1226 1169
1227 1170 self.line_buffer = line_buffer
1228 1171 self.text_until_cursor = self.line_buffer[:cursor_pos]
1229 1172
1230 1173 # Start with a clean slate of completions
1231 1174 self.matches[:] = []
1232 1175 custom_res = self.dispatch_custom_completer(text)
1233 1176 if custom_res is not None:
1234 1177 # did custom completers produce something?
1235 1178 self.matches = custom_res
1236 1179 else:
1237 1180 # Extend the list of completions with the results of each
1238 1181 # matcher, so we return results to the user from all
1239 1182 # namespaces.
1240 1183 if self.merge_completions:
1241 1184 self.matches = []
1242 1185 for matcher in self.matchers:
1243 1186 try:
1244 1187 self.matches.extend(matcher(text))
1245 1188 except:
1246 1189 # Show the ugly traceback if the matcher causes an
1247 1190 # exception, but do NOT crash the kernel!
1248 1191 sys.excepthook(*sys.exc_info())
1249 1192 else:
1250 1193 for matcher in self.matchers:
1251 1194 self.matches = matcher(text)
1252 1195 if self.matches:
1253 1196 break
1254 1197 # FIXME: we should extend our api to return a dict with completions for
1255 1198 # different types of objects. The rlcomplete() method could then
1256 1199 # simply collapse the dict into a list for readline, but we'd have
1257 1200 # richer completion semantics in other evironments.
1258 self.matches.extend(self.python_jedi_matches(text, line_buffer, cursor_pos))
1259
1260 1201 self.matches = sorted(set(self.matches), key=completions_sorting_key)
1261 1202
1262 1203 return text, self.matches
1263 1204
1264 1205 def rlcomplete(self, text, state):
1265 1206 """Return the state-th possible completion for 'text'.
1266 1207
1267 1208 This is called successively with state == 0, 1, 2, ... until it
1268 1209 returns None. The completion should begin with 'text'.
1269 1210
1270 1211 Parameters
1271 1212 ----------
1272 1213 text : string
1273 1214 Text to perform the completion on.
1274 1215
1275 1216 state : int
1276 1217 Counter used by readline.
1277 1218 """
1278 1219 if state==0:
1279 1220
1280 1221 self.line_buffer = line_buffer = self.readline.get_line_buffer()
1281 1222 cursor_pos = self.readline.get_endidx()
1282 1223
1283 1224 #io.rprint("\nRLCOMPLETE: %r %r %r" %
1284 1225 # (text, line_buffer, cursor_pos) ) # dbg
1285 1226
1286 1227 # if there is only a tab on a line with only whitespace, instead of
1287 1228 # the mostly useless 'do you want to see all million completions'
1288 1229 # message, just do the right thing and give the user his tab!
1289 1230 # Incidentally, this enables pasting of tabbed text from an editor
1290 1231 # (as long as autoindent is off).
1291 1232
1292 1233 # It should be noted that at least pyreadline still shows file
1293 1234 # completions - is there a way around it?
1294 1235
1295 1236 # don't apply this on 'dumb' terminals, such as emacs buffers, so
1296 1237 # we don't interfere with their own tab-completion mechanism.
1297 1238 if not (self.dumb_terminal or line_buffer.strip()):
1298 1239 self.readline.insert_text('\t')
1299 1240 sys.stdout.flush()
1300 1241 return None
1301 1242
1302 1243 # Note: debugging exceptions that may occur in completion is very
1303 1244 # tricky, because readline unconditionally silences them. So if
1304 1245 # during development you suspect a bug in the completion code, turn
1305 1246 # this flag on temporarily by uncommenting the second form (don't
1306 1247 # flip the value in the first line, as the '# dbg' marker can be
1307 1248 # automatically detected and is used elsewhere).
1308 1249 DEBUG = False
1309 1250 #DEBUG = True # dbg
1310 1251 if DEBUG:
1311 1252 try:
1312 1253 self.complete(text, line_buffer, cursor_pos)
1313 1254 except:
1314 1255 import traceback; traceback.print_exc()
1315 1256 else:
1316 1257 # The normal production version is here
1317 1258
1318 1259 # This method computes the self.matches array
1319 1260 self.complete(text, line_buffer, cursor_pos)
1320 1261
1321 1262 try:
1322 1263 return self.matches[state]
1323 1264 except IndexError:
1324 1265 return None
1325 1266
@@ -1,805 +1,796 b''
1 1 # encoding: utf-8
2 2 """Tests for the IPython tab-completion machinery."""
3 3
4 4 # Copyright (c) IPython Development Team.
5 5 # Distributed under the terms of the Modified BSD License.
6 6
7 7 import os
8 8 import sys
9 9 import unittest
10 10
11 11 from contextlib import contextmanager
12 12
13 13 import nose.tools as nt
14 14
15 15 from traitlets.config.loader import Config
16 16 from IPython import get_ipython
17 17 from IPython.core import completer
18 18 from IPython.external.decorators import knownfailureif
19 19 from IPython.utils.tempdir import TemporaryDirectory, TemporaryWorkingDirectory
20 20 from IPython.utils.generics import complete_object
21 21 from IPython.utils.py3compat import string_types, unicode_type
22 22 from IPython.testing import decorators as dec
23 23
24 24 #-----------------------------------------------------------------------------
25 25 # Test functions
26 26 #-----------------------------------------------------------------------------
27 27
28 28 @contextmanager
29 29 def greedy_completion():
30 30 ip = get_ipython()
31 31 greedy_original = ip.Completer.greedy
32 32 try:
33 33 ip.Completer.greedy = True
34 34 yield
35 35 finally:
36 36 ip.Completer.greedy = greedy_original
37 37
38 38 def test_protect_filename():
39 39 pairs = [ ('abc','abc'),
40 40 (' abc',r'\ abc'),
41 41 ('a bc',r'a\ bc'),
42 42 ('a bc',r'a\ \ bc'),
43 43 (' bc',r'\ \ bc'),
44 44 ]
45 45 # On posix, we also protect parens and other special characters
46 46 if sys.platform != 'win32':
47 47 pairs.extend( [('a(bc',r'a\(bc'),
48 48 ('a)bc',r'a\)bc'),
49 49 ('a( )bc',r'a\(\ \)bc'),
50 50 ('a[1]bc', r'a\[1\]bc'),
51 51 ('a{1}bc', r'a\{1\}bc'),
52 52 ('a#bc', r'a\#bc'),
53 53 ('a?bc', r'a\?bc'),
54 54 ('a=bc', r'a\=bc'),
55 55 ('a\\bc', r'a\\bc'),
56 56 ('a|bc', r'a\|bc'),
57 57 ('a;bc', r'a\;bc'),
58 58 ('a:bc', r'a\:bc'),
59 59 ("a'bc", r"a\'bc"),
60 60 ('a*bc', r'a\*bc'),
61 61 ('a"bc', r'a\"bc'),
62 62 ('a^bc', r'a\^bc'),
63 63 ('a&bc', r'a\&bc'),
64 64 ] )
65 65 # run the actual tests
66 66 for s1, s2 in pairs:
67 67 s1p = completer.protect_filename(s1)
68 68 nt.assert_equal(s1p, s2)
69 69
70 70
71 71 def check_line_split(splitter, test_specs):
72 72 for part1, part2, split in test_specs:
73 73 cursor_pos = len(part1)
74 74 line = part1+part2
75 75 out = splitter.split_line(line, cursor_pos)
76 76 nt.assert_equal(out, split)
77 77
78 78
79 79 def test_line_split():
80 80 """Basic line splitter test with default specs."""
81 81 sp = completer.CompletionSplitter()
82 82 # The format of the test specs is: part1, part2, expected answer. Parts 1
83 83 # and 2 are joined into the 'line' sent to the splitter, as if the cursor
84 84 # was at the end of part1. So an empty part2 represents someone hitting
85 85 # tab at the end of the line, the most common case.
86 86 t = [('run some/scrip', '', 'some/scrip'),
87 87 ('run scripts/er', 'ror.py foo', 'scripts/er'),
88 88 ('echo $HOM', '', 'HOM'),
89 89 ('print sys.pa', '', 'sys.pa'),
90 90 ('print(sys.pa', '', 'sys.pa'),
91 91 ("execfile('scripts/er", '', 'scripts/er'),
92 92 ('a[x.', '', 'x.'),
93 93 ('a[x.', 'y', 'x.'),
94 94 ('cd "some_file/', '', 'some_file/'),
95 95 ]
96 96 check_line_split(sp, t)
97 97 # Ensure splitting works OK with unicode by re-running the tests with
98 98 # all inputs turned into unicode
99 99 check_line_split(sp, [ map(unicode_type, p) for p in t] )
100 100
101 101
102 102 def test_custom_completion_error():
103 103 """Test that errors from custom attribute completers are silenced."""
104 104 ip = get_ipython()
105 105 class A(object): pass
106 106 ip.user_ns['a'] = A()
107 107
108 108 @complete_object.when_type(A)
109 109 def complete_A(a, existing_completions):
110 110 raise TypeError("this should be silenced")
111 111
112 112 ip.complete("a.")
113 113
114 114
115 115 def test_unicode_completions():
116 116 ip = get_ipython()
117 117 # Some strings that trigger different types of completion. Check them both
118 118 # in str and unicode forms
119 119 s = ['ru', '%ru', 'cd /', 'floa', 'float(x)/']
120 120 for t in s + list(map(unicode_type, s)):
121 121 # We don't need to check exact completion values (they may change
122 122 # depending on the state of the namespace, but at least no exceptions
123 123 # should be thrown and the return value should be a pair of text, list
124 124 # values.
125 125 text, matches = ip.complete(t)
126 126 nt.assert_true(isinstance(text, string_types))
127 127 nt.assert_true(isinstance(matches, list))
128 128
129 129 @dec.onlyif(sys.version_info[0] >= 3, 'This test only applies in Py>=3')
130 130 def test_latex_completions():
131 131 from IPython.core.latex_symbols import latex_symbols
132 132 import random
133 133 ip = get_ipython()
134 134 # Test some random unicode symbols
135 135 keys = random.sample(latex_symbols.keys(), 10)
136 136 for k in keys:
137 137 text, matches = ip.complete(k)
138 138 nt.assert_equal(len(matches),1)
139 139 nt.assert_equal(text, k)
140 140 nt.assert_equal(matches[0], latex_symbols[k])
141 141 # Test a more complex line
142 142 text, matches = ip.complete(u'print(\\alpha')
143 143 nt.assert_equals(text, u'\\alpha')
144 144 nt.assert_equals(matches[0], latex_symbols['\\alpha'])
145 145 # Test multiple matching latex symbols
146 146 text, matches = ip.complete(u'\\al')
147 147 nt.assert_in('\\alpha', matches)
148 148 nt.assert_in('\\aleph', matches)
149 149
150 150
151 151
152 152
153 153 @dec.onlyif(sys.version_info[0] >= 3, 'This test only apply on python3')
154 154 def test_back_latex_completion():
155 155 ip = get_ipython()
156 156
157 157 # do not return more than 1 matches fro \beta, only the latex one.
158 158 name, matches = ip.complete('\\Ξ²')
159 159 nt.assert_equal(len(matches), 1)
160 160 nt.assert_equal(matches[0], '\\beta')
161 161
162 162 @dec.onlyif(sys.version_info[0] >= 3, 'This test only apply on python3')
163 163 def test_back_unicode_completion():
164 164 ip = get_ipython()
165 165
166 166 name, matches = ip.complete('\\β…€')
167 167 nt.assert_equal(len(matches), 1)
168 168 nt.assert_equal(matches[0], '\\ROMAN NUMERAL FIVE')
169 169
170 170
171 171 @dec.onlyif(sys.version_info[0] >= 3, 'This test only apply on python3')
172 172 def test_forward_unicode_completion():
173 173 ip = get_ipython()
174 174
175 175 name, matches = ip.complete('\\ROMAN NUMERAL FIVE')
176 176 nt.assert_equal(len(matches), 1)
177 177 nt.assert_equal(matches[0], 'β…€')
178 178
179 179 @dec.onlyif(sys.version_info[0] >= 3, 'This test only apply on python3')
180 180 def test_no_ascii_back_completion():
181 181 ip = get_ipython()
182 182 with TemporaryWorkingDirectory(): # Avoid any filename completions
183 183 # single ascii letter that don't have yet completions
184 184 for letter in 'jJ' :
185 185 name, matches = ip.complete('\\'+letter)
186 186 nt.assert_equal(matches, [])
187 187
188 188
189 189
190 190
191 191 class CompletionSplitterTestCase(unittest.TestCase):
192 192 def setUp(self):
193 193 self.sp = completer.CompletionSplitter()
194 194
195 195 def test_delim_setting(self):
196 196 self.sp.delims = ' '
197 197 nt.assert_equal(self.sp.delims, ' ')
198 198 nt.assert_equal(self.sp._delim_expr, '[\ ]')
199 199
200 200 def test_spaces(self):
201 201 """Test with only spaces as split chars."""
202 202 self.sp.delims = ' '
203 203 t = [('foo', '', 'foo'),
204 204 ('run foo', '', 'foo'),
205 205 ('run foo', 'bar', 'foo'),
206 206 ]
207 207 check_line_split(self.sp, t)
208 208
209 209
210 210 def test_has_open_quotes1():
211 211 for s in ["'", "'''", "'hi' '"]:
212 212 nt.assert_equal(completer.has_open_quotes(s), "'")
213 213
214 214
215 215 def test_has_open_quotes2():
216 216 for s in ['"', '"""', '"hi" "']:
217 217 nt.assert_equal(completer.has_open_quotes(s), '"')
218 218
219 219
220 220 def test_has_open_quotes3():
221 221 for s in ["''", "''' '''", "'hi' 'ipython'"]:
222 222 nt.assert_false(completer.has_open_quotes(s))
223 223
224 224
225 225 def test_has_open_quotes4():
226 226 for s in ['""', '""" """', '"hi" "ipython"']:
227 227 nt.assert_false(completer.has_open_quotes(s))
228 228
229 229
230 230 @knownfailureif(sys.platform == 'win32', "abspath completions fail on Windows")
231 231 def test_abspath_file_completions():
232 232 ip = get_ipython()
233 233 with TemporaryDirectory() as tmpdir:
234 234 prefix = os.path.join(tmpdir, 'foo')
235 235 suffixes = ['1', '2']
236 236 names = [prefix+s for s in suffixes]
237 237 for n in names:
238 238 open(n, 'w').close()
239 239
240 240 # Check simple completion
241 241 c = ip.complete(prefix)[1]
242 242 nt.assert_equal(c, names)
243 243
244 244 # Now check with a function call
245 245 cmd = 'a = f("%s' % prefix
246 246 c = ip.complete(prefix, cmd)[1]
247 247 comp = [prefix+s for s in suffixes]
248 248 nt.assert_equal(c, comp)
249 249
250 250
251 251 def test_local_file_completions():
252 252 ip = get_ipython()
253 253 with TemporaryWorkingDirectory():
254 254 prefix = './foo'
255 255 suffixes = ['1', '2']
256 256 names = [prefix+s for s in suffixes]
257 257 for n in names:
258 258 open(n, 'w').close()
259 259
260 260 # Check simple completion
261 261 c = ip.complete(prefix)[1]
262 262 nt.assert_equal(c, names)
263 263
264 264 # Now check with a function call
265 265 cmd = 'a = f("%s' % prefix
266 266 c = ip.complete(prefix, cmd)[1]
267 267 comp = set(prefix+s for s in suffixes)
268 268 nt.assert_true(comp.issubset(set(c)))
269 269
270 270
271 271 def test_greedy_completions():
272 272 ip = get_ipython()
273 273 ip.ex('a=list(range(5))')
274 274 _,c = ip.complete('.',line='a[0].')
275 275 nt.assert_false('.real' in c,
276 276 "Shouldn't have completed on a[0]: %s"%c)
277 277 with greedy_completion():
278 278 def _(line, cursor_pos, expect, message):
279 279 _,c = ip.complete('.', line=line, cursor_pos=cursor_pos)
280 280 nt.assert_in(expect, c, message%c)
281 281
282 yield _, 'a[0].', 5, '.real', "Should have completed on a[0].: %s"
283 yield _, 'a[0].r', 6, '.real', "Should have completed on a[0].r: %s"
282 yield _, 'a[0].', 5, 'a[0].real', "Should have completed on a[0].: %s"
283 yield _, 'a[0].r', 6, 'a[0].real', "Should have completed on a[0].r: %s"
284 284
285 285 if sys.version_info > (3,4):
286 yield _, 'a[0].from_', 10, '.from_bytes', "Should have completed on a[0].from_: %s"
287
288
289 def _2():
290 # jedi bug, this will be empty, makeitfail for now,
291 # once jedi is fixed, switch to assert_in
292 # https://github.com/davidhalter/jedi/issues/718
293 _,c = ip.complete('.',line='a[0].from', cursor_pos=9)
294 nt.assert_not_in('.from_bytes', c, "Should not have completed on a[0].from (jedi bug), if fails, update test to assert_in: %s"%c)
295 yield _2
286 yield _, 'a[0].from_', 10, 'a[0].from_bytes', "Should have completed on a[0].from_: %s"
296 287
297 288
298 289
299 290 def test_omit__names():
300 291 # also happens to test IPCompleter as a configurable
301 292 ip = get_ipython()
302 293 ip._hidden_attr = 1
303 294 ip._x = {}
304 295 c = ip.Completer
305 296 ip.ex('ip=get_ipython()')
306 297 cfg = Config()
307 298 cfg.IPCompleter.omit__names = 0
308 299 c.update_config(cfg)
309 300 s,matches = c.complete('ip.')
310 301 nt.assert_in('ip.__str__', matches)
311 302 nt.assert_in('ip._hidden_attr', matches)
312 303 cfg = Config()
313 304 cfg.IPCompleter.omit__names = 1
314 305 c.update_config(cfg)
315 306 s,matches = c.complete('ip.')
316 307 nt.assert_not_in('ip.__str__', matches)
317 308 nt.assert_in('ip._hidden_attr', matches)
318 309 cfg = Config()
319 310 cfg.IPCompleter.omit__names = 2
320 311 c.update_config(cfg)
321 312 s,matches = c.complete('ip.')
322 313 nt.assert_not_in('ip.__str__', matches)
323 314 nt.assert_not_in('ip._hidden_attr', matches)
324 315 s,matches = c.complete('ip._x.')
325 316 nt.assert_in('ip._x.keys', matches)
326 317 del ip._hidden_attr
327 318
328 319
329 320 def test_limit_to__all__False_ok():
330 321 ip = get_ipython()
331 322 c = ip.Completer
332 323 ip.ex('class D: x=24')
333 324 ip.ex('d=D()')
334 325 cfg = Config()
335 326 cfg.IPCompleter.limit_to__all__ = False
336 327 c.update_config(cfg)
337 328 s, matches = c.complete('d.')
338 329 nt.assert_in('d.x', matches)
339 330
340 331
341 332 def test_get__all__entries_ok():
342 333 class A(object):
343 334 __all__ = ['x', 1]
344 335 words = completer.get__all__entries(A())
345 336 nt.assert_equal(words, ['x'])
346 337
347 338
348 339 def test_get__all__entries_no__all__ok():
349 340 class A(object):
350 341 pass
351 342 words = completer.get__all__entries(A())
352 343 nt.assert_equal(words, [])
353 344
354 345
355 346 def test_func_kw_completions():
356 347 ip = get_ipython()
357 348 c = ip.Completer
358 349 ip.ex('def myfunc(a=1,b=2): return a+b')
359 350 s, matches = c.complete(None, 'myfunc(1,b')
360 351 nt.assert_in('b=', matches)
361 352 # Simulate completing with cursor right after b (pos==10):
362 353 s, matches = c.complete(None, 'myfunc(1,b)', 10)
363 354 nt.assert_in('b=', matches)
364 355 s, matches = c.complete(None, 'myfunc(a="escaped\\")string",b')
365 356 nt.assert_in('b=', matches)
366 357 #builtin function
367 358 s, matches = c.complete(None, 'min(k, k')
368 359 nt.assert_in('key=', matches)
369 360
370 361
371 362 def test_default_arguments_from_docstring():
372 363 ip = get_ipython()
373 364 c = ip.Completer
374 365 kwd = c._default_arguments_from_docstring(
375 366 'min(iterable[, key=func]) -> value')
376 367 nt.assert_equal(kwd, ['key'])
377 368 #with cython type etc
378 369 kwd = c._default_arguments_from_docstring(
379 370 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)\n')
380 371 nt.assert_equal(kwd, ['ncall', 'resume', 'nsplit'])
381 372 #white spaces
382 373 kwd = c._default_arguments_from_docstring(
383 374 '\n Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)\n')
384 375 nt.assert_equal(kwd, ['ncall', 'resume', 'nsplit'])
385 376
386 377 def test_line_magics():
387 378 ip = get_ipython()
388 379 c = ip.Completer
389 380 s, matches = c.complete(None, 'lsmag')
390 381 nt.assert_in('%lsmagic', matches)
391 382 s, matches = c.complete(None, '%lsmag')
392 383 nt.assert_in('%lsmagic', matches)
393 384
394 385
395 386 def test_cell_magics():
396 387 from IPython.core.magic import register_cell_magic
397 388
398 389 @register_cell_magic
399 390 def _foo_cellm(line, cell):
400 391 pass
401 392
402 393 ip = get_ipython()
403 394 c = ip.Completer
404 395
405 396 s, matches = c.complete(None, '_foo_ce')
406 397 nt.assert_in('%%_foo_cellm', matches)
407 398 s, matches = c.complete(None, '%%_foo_ce')
408 399 nt.assert_in('%%_foo_cellm', matches)
409 400
410 401
411 402 def test_line_cell_magics():
412 403 from IPython.core.magic import register_line_cell_magic
413 404
414 405 @register_line_cell_magic
415 406 def _bar_cellm(line, cell):
416 407 pass
417 408
418 409 ip = get_ipython()
419 410 c = ip.Completer
420 411
421 412 # The policy here is trickier, see comments in completion code. The
422 413 # returned values depend on whether the user passes %% or not explicitly,
423 414 # and this will show a difference if the same name is both a line and cell
424 415 # magic.
425 416 s, matches = c.complete(None, '_bar_ce')
426 417 nt.assert_in('%_bar_cellm', matches)
427 418 nt.assert_in('%%_bar_cellm', matches)
428 419 s, matches = c.complete(None, '%_bar_ce')
429 420 nt.assert_in('%_bar_cellm', matches)
430 421 nt.assert_in('%%_bar_cellm', matches)
431 422 s, matches = c.complete(None, '%%_bar_ce')
432 423 nt.assert_not_in('%_bar_cellm', matches)
433 424 nt.assert_in('%%_bar_cellm', matches)
434 425
435 426
436 427 def test_magic_completion_order():
437 428
438 429 ip = get_ipython()
439 430 c = ip.Completer
440 431
441 432 # Test ordering of magics and non-magics with the same name
442 433 # We want the non-magic first
443 434
444 435 # Before importing matplotlib, there should only be one option:
445 436
446 437 text, matches = c.complete('mat')
447 438 nt.assert_equal(matches, ["%matplotlib"])
448 439
449 440
450 441 ip.run_cell("matplotlib = 1") # introduce name into namespace
451 442
452 443 # After the import, there should be two options, ordered like this:
453 444 text, matches = c.complete('mat')
454 445 nt.assert_equal(matches, ["matplotlib", "%matplotlib"])
455 446
456 447
457 448 ip.run_cell("timeit = 1") # define a user variable called 'timeit'
458 449
459 450 # Order of user variable and line and cell magics with same name:
460 451 text, matches = c.complete('timeit')
461 452 nt.assert_equal(matches, ["timeit", "%timeit","%%timeit"])
462 453
463 454
464 455 def test_dict_key_completion_string():
465 456 """Test dictionary key completion for string keys"""
466 457 ip = get_ipython()
467 458 complete = ip.Completer.complete
468 459
469 460 ip.user_ns['d'] = {'abc': None}
470 461
471 462 # check completion at different stages
472 463 _, matches = complete(line_buffer="d[")
473 464 nt.assert_in("'abc'", matches)
474 465 nt.assert_not_in("'abc']", matches)
475 466
476 467 _, matches = complete(line_buffer="d['")
477 468 nt.assert_in("abc", matches)
478 469 nt.assert_not_in("abc']", matches)
479 470
480 471 _, matches = complete(line_buffer="d['a")
481 472 nt.assert_in("abc", matches)
482 473 nt.assert_not_in("abc']", matches)
483 474
484 475 # check use of different quoting
485 476 _, matches = complete(line_buffer="d[\"")
486 477 nt.assert_in("abc", matches)
487 478 nt.assert_not_in('abc\"]', matches)
488 479
489 480 _, matches = complete(line_buffer="d[\"a")
490 481 nt.assert_in("abc", matches)
491 482 nt.assert_not_in('abc\"]', matches)
492 483
493 484 # check sensitivity to following context
494 485 _, matches = complete(line_buffer="d[]", cursor_pos=2)
495 486 nt.assert_in("'abc'", matches)
496 487
497 488 _, matches = complete(line_buffer="d['']", cursor_pos=3)
498 489 nt.assert_in("abc", matches)
499 490 nt.assert_not_in("abc'", matches)
500 491 nt.assert_not_in("abc']", matches)
501 492
502 493 # check multiple solutions are correctly returned and that noise is not
503 494 ip.user_ns['d'] = {'abc': None, 'abd': None, 'bad': None, object(): None,
504 495 5: None}
505 496
506 497 _, matches = complete(line_buffer="d['a")
507 498 nt.assert_in("abc", matches)
508 499 nt.assert_in("abd", matches)
509 500 nt.assert_not_in("bad", matches)
510 501 assert not any(m.endswith((']', '"', "'")) for m in matches), matches
511 502
512 503 # check escaping and whitespace
513 504 ip.user_ns['d'] = {'a\nb': None, 'a\'b': None, 'a"b': None, 'a word': None}
514 505 _, matches = complete(line_buffer="d['a")
515 506 nt.assert_in("a\\nb", matches)
516 507 nt.assert_in("a\\'b", matches)
517 508 nt.assert_in("a\"b", matches)
518 509 nt.assert_in("a word", matches)
519 510 assert not any(m.endswith((']', '"', "'")) for m in matches), matches
520 511
521 512 # - can complete on non-initial word of the string
522 513 _, matches = complete(line_buffer="d['a w")
523 514 nt.assert_in("word", matches)
524 515
525 516 # - understands quote escaping
526 517 _, matches = complete(line_buffer="d['a\\'")
527 518 nt.assert_in("b", matches)
528 519
529 520 # - default quoting should work like repr
530 521 _, matches = complete(line_buffer="d[")
531 522 nt.assert_in("\"a'b\"", matches)
532 523
533 524 # - when opening quote with ", possible to match with unescaped apostrophe
534 525 _, matches = complete(line_buffer="d[\"a'")
535 526 nt.assert_in("b", matches)
536 527
537 528 # need to not split at delims that readline won't split at
538 529 if '-' not in ip.Completer.splitter.delims:
539 530 ip.user_ns['d'] = {'before-after': None}
540 531 _, matches = complete(line_buffer="d['before-af")
541 532 nt.assert_in('before-after', matches)
542 533
543 534 def test_dict_key_completion_contexts():
544 535 """Test expression contexts in which dict key completion occurs"""
545 536 ip = get_ipython()
546 537 complete = ip.Completer.complete
547 538 d = {'abc': None}
548 539 ip.user_ns['d'] = d
549 540
550 541 class C:
551 542 data = d
552 543 ip.user_ns['C'] = C
553 544 ip.user_ns['get'] = lambda: d
554 545
555 546 def assert_no_completion(**kwargs):
556 547 _, matches = complete(**kwargs)
557 548 nt.assert_not_in('abc', matches)
558 549 nt.assert_not_in('abc\'', matches)
559 550 nt.assert_not_in('abc\']', matches)
560 551 nt.assert_not_in('\'abc\'', matches)
561 552 nt.assert_not_in('\'abc\']', matches)
562 553
563 554 def assert_completion(**kwargs):
564 555 _, matches = complete(**kwargs)
565 556 nt.assert_in("'abc'", matches)
566 557 nt.assert_not_in("'abc']", matches)
567 558
568 559 # no completion after string closed, even if reopened
569 560 assert_no_completion(line_buffer="d['a'")
570 561 assert_no_completion(line_buffer="d[\"a\"")
571 562 assert_no_completion(line_buffer="d['a' + ")
572 563 assert_no_completion(line_buffer="d['a' + '")
573 564
574 565 # completion in non-trivial expressions
575 566 assert_completion(line_buffer="+ d[")
576 567 assert_completion(line_buffer="(d[")
577 568 assert_completion(line_buffer="C.data[")
578 569
579 570 # greedy flag
580 571 def assert_completion(**kwargs):
581 572 _, matches = complete(**kwargs)
582 573 nt.assert_in("get()['abc']", matches)
583 574
584 575 assert_no_completion(line_buffer="get()[")
585 576 with greedy_completion():
586 577 assert_completion(line_buffer="get()[")
587 578 assert_completion(line_buffer="get()['")
588 579 assert_completion(line_buffer="get()['a")
589 580 assert_completion(line_buffer="get()['ab")
590 581 assert_completion(line_buffer="get()['abc")
591 582
592 583
593 584
594 585 @dec.onlyif(sys.version_info[0] >= 3, 'This test only applies in Py>=3')
595 586 def test_dict_key_completion_bytes():
596 587 """Test handling of bytes in dict key completion"""
597 588 ip = get_ipython()
598 589 complete = ip.Completer.complete
599 590
600 591 ip.user_ns['d'] = {'abc': None, b'abd': None}
601 592
602 593 _, matches = complete(line_buffer="d[")
603 594 nt.assert_in("'abc'", matches)
604 595 nt.assert_in("b'abd'", matches)
605 596
606 597 if False: # not currently implemented
607 598 _, matches = complete(line_buffer="d[b")
608 599 nt.assert_in("b'abd'", matches)
609 600 nt.assert_not_in("b'abc'", matches)
610 601
611 602 _, matches = complete(line_buffer="d[b'")
612 603 nt.assert_in("abd", matches)
613 604 nt.assert_not_in("abc", matches)
614 605
615 606 _, matches = complete(line_buffer="d[B'")
616 607 nt.assert_in("abd", matches)
617 608 nt.assert_not_in("abc", matches)
618 609
619 610 _, matches = complete(line_buffer="d['")
620 611 nt.assert_in("abc", matches)
621 612 nt.assert_not_in("abd", matches)
622 613
623 614
624 615 @dec.onlyif(sys.version_info[0] < 3, 'This test only applies in Py<3')
625 616 def test_dict_key_completion_unicode_py2():
626 617 """Test handling of unicode in dict key completion"""
627 618 ip = get_ipython()
628 619 complete = ip.Completer.complete
629 620
630 621 ip.user_ns['d'] = {u'abc': None,
631 622 u'a\u05d0b': None}
632 623
633 624 _, matches = complete(line_buffer="d[")
634 625 nt.assert_in("u'abc'", matches)
635 626 nt.assert_in("u'a\\u05d0b'", matches)
636 627
637 628 _, matches = complete(line_buffer="d['a")
638 629 nt.assert_in("abc", matches)
639 630 nt.assert_not_in("a\\u05d0b", matches)
640 631
641 632 _, matches = complete(line_buffer="d[u'a")
642 633 nt.assert_in("abc", matches)
643 634 nt.assert_in("a\\u05d0b", matches)
644 635
645 636 _, matches = complete(line_buffer="d[U'a")
646 637 nt.assert_in("abc", matches)
647 638 nt.assert_in("a\\u05d0b", matches)
648 639
649 640 # query using escape
650 641 _, matches = complete(line_buffer=u"d[u'a\\u05d0")
651 642 nt.assert_in("u05d0b", matches) # tokenized after \\
652 643
653 644 # query using character
654 645 _, matches = complete(line_buffer=u"d[u'a\u05d0")
655 646 nt.assert_in(u"a\u05d0b", matches)
656 647
657 648 with greedy_completion():
658 649 _, matches = complete(line_buffer="d[")
659 650 nt.assert_in("d[u'abc']", matches)
660 651 nt.assert_in("d[u'a\\u05d0b']", matches)
661 652
662 653 _, matches = complete(line_buffer="d['a")
663 654 nt.assert_in("d['abc']", matches)
664 655 nt.assert_not_in("d[u'a\\u05d0b']", matches)
665 656
666 657 _, matches = complete(line_buffer="d[u'a")
667 658 nt.assert_in("d[u'abc']", matches)
668 659 nt.assert_in("d[u'a\\u05d0b']", matches)
669 660
670 661 _, matches = complete(line_buffer="d[U'a")
671 662 nt.assert_in("d[U'abc']", matches)
672 663 nt.assert_in("d[U'a\\u05d0b']", matches)
673 664
674 665 # query using escape
675 666 _, matches = complete(line_buffer=u"d[u'a\\u05d0")
676 667 nt.assert_in("d[u'a\\u05d0b']", matches) # tokenized after \\
677 668
678 669 # query using character
679 670 _, matches = complete(line_buffer=u"d[u'a\u05d0")
680 671 nt.assert_in(u"d[u'a\u05d0b']", matches)
681 672
682 673
683 674 @dec.onlyif(sys.version_info[0] >= 3, 'This test only applies in Py>=3')
684 675 def test_dict_key_completion_unicode_py3():
685 676 """Test handling of unicode in dict key completion"""
686 677 ip = get_ipython()
687 678 complete = ip.Completer.complete
688 679
689 680 ip.user_ns['d'] = {u'a\u05d0': None}
690 681
691 682 # query using escape
692 683 _, matches = complete(line_buffer="d['a\\u05d0")
693 684 nt.assert_in("u05d0", matches) # tokenized after \\
694 685
695 686 # query using character
696 687 _, matches = complete(line_buffer="d['a\u05d0")
697 688 nt.assert_in(u"a\u05d0", matches)
698 689
699 690 with greedy_completion():
700 691 # query using escape
701 692 _, matches = complete(line_buffer="d['a\\u05d0")
702 693 nt.assert_in("d['a\\u05d0']", matches) # tokenized after \\
703 694
704 695 # query using character
705 696 _, matches = complete(line_buffer="d['a\u05d0")
706 697 nt.assert_in(u"d['a\u05d0']", matches)
707 698
708 699
709 700
710 701 @dec.skip_without('numpy')
711 702 def test_struct_array_key_completion():
712 703 """Test dict key completion applies to numpy struct arrays"""
713 704 import numpy
714 705 ip = get_ipython()
715 706 complete = ip.Completer.complete
716 707 ip.user_ns['d'] = numpy.array([], dtype=[('hello', 'f'), ('world', 'f')])
717 708 _, matches = complete(line_buffer="d['")
718 709 nt.assert_in("hello", matches)
719 710 nt.assert_in("world", matches)
720 711 # complete on the numpy struct itself
721 712 dt = numpy.dtype([('my_head', [('my_dt', '>u4'), ('my_df', '>u4')]),
722 713 ('my_data', '>f4', 5)])
723 714 x = numpy.zeros(2, dtype=dt)
724 715 ip.user_ns['d'] = x[1]
725 716 _, matches = complete(line_buffer="d['")
726 717 nt.assert_in("my_head", matches)
727 718 nt.assert_in("my_data", matches)
728 719 # complete on a nested level
729 720 with greedy_completion():
730 721 ip.user_ns['d'] = numpy.zeros(2, dtype=dt)
731 722 _, matches = complete(line_buffer="d[1]['my_head']['")
732 723 nt.assert_true(any(["my_dt" in m for m in matches]))
733 724 nt.assert_true(any(["my_df" in m for m in matches]))
734 725
735 726
736 727 @dec.skip_without('pandas')
737 728 def test_dataframe_key_completion():
738 729 """Test dict key completion applies to pandas DataFrames"""
739 730 import pandas
740 731 ip = get_ipython()
741 732 complete = ip.Completer.complete
742 733 ip.user_ns['d'] = pandas.DataFrame({'hello': [1], 'world': [2]})
743 734 _, matches = complete(line_buffer="d['")
744 735 nt.assert_in("hello", matches)
745 736 nt.assert_in("world", matches)
746 737
747 738
748 739 def test_dict_key_completion_invalids():
749 740 """Smoke test cases dict key completion can't handle"""
750 741 ip = get_ipython()
751 742 complete = ip.Completer.complete
752 743
753 744 ip.user_ns['no_getitem'] = None
754 745 ip.user_ns['no_keys'] = []
755 746 ip.user_ns['cant_call_keys'] = dict
756 747 ip.user_ns['empty'] = {}
757 748 ip.user_ns['d'] = {'abc': 5}
758 749
759 750 _, matches = complete(line_buffer="no_getitem['")
760 751 _, matches = complete(line_buffer="no_keys['")
761 752 _, matches = complete(line_buffer="cant_call_keys['")
762 753 _, matches = complete(line_buffer="empty['")
763 754 _, matches = complete(line_buffer="name_error['")
764 755 _, matches = complete(line_buffer="d['\\") # incomplete escape
765 756
766 757 class KeyCompletable(object):
767 758 def __init__(self, things=()):
768 759 self.things = things
769 760
770 761 def _ipython_key_completions_(self):
771 762 return list(self.things)
772 763
773 764 def test_object_key_completion():
774 765 ip = get_ipython()
775 766 ip.user_ns['key_completable'] = KeyCompletable(['qwerty', 'qwick'])
776 767
777 768 _, matches = ip.Completer.complete(line_buffer="key_completable['qw")
778 769 nt.assert_in('qwerty', matches)
779 770 nt.assert_in('qwick', matches)
780 771
781 772
782 773 def test_aimport_module_completer():
783 774 ip = get_ipython()
784 775 _, matches = ip.complete('i', '%aimport i')
785 776 nt.assert_in('io', matches)
786 777 nt.assert_not_in('int', matches)
787 778
788 779 def test_nested_import_module_completer():
789 780 ip = get_ipython()
790 781 _, matches = ip.complete(None, 'import IPython.co', 17)
791 782 nt.assert_in('IPython.core', matches)
792 783 nt.assert_not_in('import IPython.core', matches)
793 784 nt.assert_not_in('IPython.display', matches)
794 785
795 786 def test_import_module_completer():
796 787 ip = get_ipython()
797 788 _, matches = ip.complete('i', 'import i')
798 789 nt.assert_in('io', matches)
799 790 nt.assert_not_in('int', matches)
800 791
801 792 def test_from_module_completer():
802 793 ip = get_ipython()
803 794 _, matches = ip.complete('B', 'from io import B', 16)
804 795 nt.assert_in('BytesIO', matches)
805 796 nt.assert_not_in('BaseException', matches)
@@ -1,300 +1,299 b''
1 1 #!/usr/bin/env python
2 2 # -*- coding: utf-8 -*-
3 3 """Setup script for IPython.
4 4
5 5 Under Posix environments it works like a typical setup.py script.
6 6 Under Windows, the command sdist is not supported, since IPython
7 7 requires utilities which are not available under Windows."""
8 8
9 9 #-----------------------------------------------------------------------------
10 10 # Copyright (c) 2008-2011, IPython Development Team.
11 11 # Copyright (c) 2001-2007, Fernando Perez <fernando.perez@colorado.edu>
12 12 # Copyright (c) 2001, Janko Hauser <jhauser@zscout.de>
13 13 # Copyright (c) 2001, Nathaniel Gray <n8gray@caltech.edu>
14 14 #
15 15 # Distributed under the terms of the Modified BSD License.
16 16 #
17 17 # The full license is in the file COPYING.rst, distributed with this software.
18 18 #-----------------------------------------------------------------------------
19 19
20 20 #-----------------------------------------------------------------------------
21 21 # Minimal Python version sanity check
22 22 #-----------------------------------------------------------------------------
23 23 from __future__ import print_function
24 24
25 25 import sys
26 26
27 27 # This check is also made in IPython/__init__, don't forget to update both when
28 28 # changing Python version requirements.
29 29 v = sys.version_info
30 30 if v[:2] < (2,7) or (v[0] >= 3 and v[:2] < (3,3)):
31 31 error = "ERROR: IPython requires Python version 2.7 or 3.3 or above."
32 32 print(error, file=sys.stderr)
33 33 sys.exit(1)
34 34
35 35 PY3 = (sys.version_info[0] >= 3)
36 36
37 37 # At least we're on the python version we need, move on.
38 38
39 39 #-------------------------------------------------------------------------------
40 40 # Imports
41 41 #-------------------------------------------------------------------------------
42 42
43 43 # Stdlib imports
44 44 import os
45 45
46 46 from glob import glob
47 47
48 48 # BEFORE importing distutils, remove MANIFEST. distutils doesn't properly
49 49 # update it when the contents of directories change.
50 50 if os.path.exists('MANIFEST'): os.remove('MANIFEST')
51 51
52 52 from distutils.core import setup
53 53
54 54 # Our own imports
55 55 from setupbase import target_update
56 56
57 57 from setupbase import (
58 58 setup_args,
59 59 find_packages,
60 60 find_package_data,
61 61 check_package_data_first,
62 62 find_entry_points,
63 63 build_scripts_entrypt,
64 64 find_data_files,
65 65 git_prebuild,
66 66 install_symlinked,
67 67 install_lib_symlink,
68 68 install_scripts_for_symlink,
69 69 unsymlink,
70 70 )
71 71
72 72 isfile = os.path.isfile
73 73 pjoin = os.path.join
74 74
75 75 #-------------------------------------------------------------------------------
76 76 # Handle OS specific things
77 77 #-------------------------------------------------------------------------------
78 78
79 79 if os.name in ('nt','dos'):
80 80 os_name = 'windows'
81 81 else:
82 82 os_name = os.name
83 83
84 84 # Under Windows, 'sdist' has not been supported. Now that the docs build with
85 85 # Sphinx it might work, but let's not turn it on until someone confirms that it
86 86 # actually works.
87 87 if os_name == 'windows' and 'sdist' in sys.argv:
88 88 print('The sdist command is not available under Windows. Exiting.')
89 89 sys.exit(1)
90 90
91 91
92 92 #-------------------------------------------------------------------------------
93 93 # Things related to the IPython documentation
94 94 #-------------------------------------------------------------------------------
95 95
96 96 # update the manuals when building a source dist
97 97 if len(sys.argv) >= 2 and sys.argv[1] in ('sdist','bdist_rpm'):
98 98
99 99 # List of things to be updated. Each entry is a triplet of args for
100 100 # target_update()
101 101 to_update = [
102 102 ('docs/man/ipython.1.gz',
103 103 ['docs/man/ipython.1'],
104 104 'cd docs/man && gzip -9c ipython.1 > ipython.1.gz'),
105 105 ]
106 106
107 107
108 108 [ target_update(*t) for t in to_update ]
109 109
110 110 #---------------------------------------------------------------------------
111 111 # Find all the packages, package data, and data_files
112 112 #---------------------------------------------------------------------------
113 113
114 114 packages = find_packages()
115 115 package_data = find_package_data()
116 116
117 117 data_files = find_data_files()
118 118
119 119 setup_args['packages'] = packages
120 120 setup_args['package_data'] = package_data
121 121 setup_args['data_files'] = data_files
122 122
123 123 #---------------------------------------------------------------------------
124 124 # custom distutils commands
125 125 #---------------------------------------------------------------------------
126 126 # imports here, so they are after setuptools import if there was one
127 127 from distutils.command.sdist import sdist
128 128 from distutils.command.upload import upload
129 129
130 130 class UploadWindowsInstallers(upload):
131 131
132 132 description = "Upload Windows installers to PyPI (only used from tools/release_windows.py)"
133 133 user_options = upload.user_options + [
134 134 ('files=', 'f', 'exe file (or glob) to upload')
135 135 ]
136 136 def initialize_options(self):
137 137 upload.initialize_options(self)
138 138 meta = self.distribution.metadata
139 139 base = '{name}-{version}'.format(
140 140 name=meta.get_name(),
141 141 version=meta.get_version()
142 142 )
143 143 self.files = os.path.join('dist', '%s.*.exe' % base)
144 144
145 145 def run(self):
146 146 for dist_file in glob(self.files):
147 147 self.upload_file('bdist_wininst', 'any', dist_file)
148 148
149 149 setup_args['cmdclass'] = {
150 150 'build_py': \
151 151 check_package_data_first(git_prebuild('IPython')),
152 152 'sdist' : git_prebuild('IPython', sdist),
153 153 'upload_wininst' : UploadWindowsInstallers,
154 154 'symlink': install_symlinked,
155 155 'install_lib_symlink': install_lib_symlink,
156 156 'install_scripts_sym': install_scripts_for_symlink,
157 157 'unsymlink': unsymlink,
158 158 }
159 159
160 160
161 161 #---------------------------------------------------------------------------
162 162 # Handle scripts, dependencies, and setuptools specific things
163 163 #---------------------------------------------------------------------------
164 164
165 165 # For some commands, use setuptools. Note that we do NOT list install here!
166 166 # If you want a setuptools-enhanced install, just run 'setupegg.py install'
167 167 needs_setuptools = set(('develop', 'release', 'bdist_egg', 'bdist_rpm',
168 168 'bdist', 'bdist_dumb', 'bdist_wininst', 'bdist_wheel',
169 169 'egg_info', 'easy_install', 'upload', 'install_egg_info',
170 170 ))
171 171
172 172 if len(needs_setuptools.intersection(sys.argv)) > 0:
173 173 import setuptools
174 174
175 175 # This dict is used for passing extra arguments that are setuptools
176 176 # specific to setup
177 177 setuptools_extra_args = {}
178 178
179 179 # setuptools requirements
180 180
181 181 extras_require = dict(
182 182 parallel = ['ipyparallel'],
183 183 qtconsole = ['qtconsole'],
184 184 doc = ['Sphinx>=1.3'],
185 185 test = ['nose>=0.10.1', 'requests', 'testpath', 'pygments'],
186 186 terminal = [],
187 187 kernel = ['ipykernel'],
188 188 nbformat = ['nbformat'],
189 189 notebook = ['notebook', 'ipywidgets'],
190 190 nbconvert = ['nbconvert'],
191 191 )
192 192 install_requires = [
193 193 'setuptools>=18.5',
194 'jedi',
195 194 'decorator',
196 195 'pickleshare',
197 196 'simplegeneric>0.8',
198 197 'traitlets>=4.2',
199 198 'prompt_toolkit>=1.0.0,<2.0.0',
200 199 'pygments',
201 200 ]
202 201
203 202 # Platform-specific dependencies:
204 203 # This is the correct way to specify these,
205 204 # but requires pip >= 6. pip < 6 ignores these.
206 205
207 206 extras_require.update({
208 207 ':python_version == "2.7"': ['backports.shutil_get_terminal_size'],
209 208 ':python_version == "2.7" or python_version == "3.3"': ['pathlib2'],
210 209 ':sys_platform != "win32"': ['pexpect'],
211 210 ':sys_platform == "darwin"': ['appnope'],
212 211 ':sys_platform == "win32"': ['colorama'],
213 212 'test:python_version == "2.7"': ['mock'],
214 213 })
215 214 # FIXME: re-specify above platform dependencies for pip < 6
216 215 # These would result in non-portable bdists.
217 216 if not any(arg.startswith('bdist') for arg in sys.argv):
218 217 if sys.version_info < (3, 3):
219 218 extras_require['test'].append('mock')
220 219
221 220 if sys.platform == 'darwin':
222 221 install_requires.extend(['appnope'])
223 222 have_readline = False
224 223 try:
225 224 import readline
226 225 except ImportError:
227 226 pass
228 227 else:
229 228 if 'libedit' not in readline.__doc__:
230 229 have_readline = True
231 230 if not have_readline:
232 231 install_requires.extend(['gnureadline'])
233 232
234 233 if sys.platform.startswith('win'):
235 234 extras_require['terminal'].append('pyreadline>=2.0')
236 235 else:
237 236 install_requires.append('pexpect')
238 237
239 238 # workaround pypa/setuptools#147, where setuptools misspells
240 239 # platform_python_implementation as python_implementation
241 240 if 'setuptools' in sys.modules:
242 241 for key in list(extras_require):
243 242 if 'platform_python_implementation' in key:
244 243 new_key = key.replace('platform_python_implementation', 'python_implementation')
245 244 extras_require[new_key] = extras_require.pop(key)
246 245
247 246 everything = set()
248 247 for key, deps in extras_require.items():
249 248 if ':' not in key:
250 249 everything.update(deps)
251 250 extras_require['all'] = everything
252 251
253 252 if 'setuptools' in sys.modules:
254 253 setuptools_extra_args['zip_safe'] = False
255 254 setuptools_extra_args['entry_points'] = {
256 255 'console_scripts': find_entry_points(),
257 256 'pygments.lexers': [
258 257 'ipythonconsole = IPython.lib.lexers:IPythonConsoleLexer',
259 258 'ipython = IPython.lib.lexers:IPythonLexer',
260 259 'ipython3 = IPython.lib.lexers:IPython3Lexer',
261 260 ],
262 261 }
263 262 setup_args['extras_require'] = extras_require
264 263 requires = setup_args['install_requires'] = install_requires
265 264
266 265 # Script to be run by the windows binary installer after the default setup
267 266 # routine, to add shortcuts and similar windows-only things. Windows
268 267 # post-install scripts MUST reside in the scripts/ dir, otherwise distutils
269 268 # doesn't find them.
270 269 if 'bdist_wininst' in sys.argv:
271 270 if len(sys.argv) > 2 and \
272 271 ('sdist' in sys.argv or 'bdist_rpm' in sys.argv):
273 272 print("ERROR: bdist_wininst must be run alone. Exiting.", file=sys.stderr)
274 273 sys.exit(1)
275 274 setup_args['data_files'].append(
276 275 ['Scripts', ('scripts/ipython.ico', 'scripts/ipython_nb.ico')])
277 276 setup_args['scripts'] = [pjoin('scripts','ipython_win_post_install.py')]
278 277 setup_args['options'] = {"bdist_wininst":
279 278 {"install_script":
280 279 "ipython_win_post_install.py"}}
281 280
282 281 else:
283 282 # scripts has to be a non-empty list, or install_scripts isn't called
284 283 setup_args['scripts'] = [e.split('=')[0].strip() for e in find_entry_points()]
285 284
286 285 setup_args['cmdclass']['build_scripts'] = build_scripts_entrypt
287 286
288 287 #---------------------------------------------------------------------------
289 288 # Do the actual setup now
290 289 #---------------------------------------------------------------------------
291 290
292 291 setup_args.update(setuptools_extra_args)
293 292
294 293
295 294
296 295 def main():
297 296 setup(**setup_args)
298 297
299 298 if __name__ == '__main__':
300 299 main()
General Comments 0
You need to be logged in to leave comments. Login now