##// END OF EJS Templates
Show signature with Jedi....
Matthias Bussonnier -
Show More
@@ -0,0 +1,4 b''
1 Terminal IPython will now show the signature of the function while completing.
2 Only the currently highlighted function will show its signature on the line
3 below the completer by default. The functionality is recent so might be
4 limited, we welcome bug report and enhancement request on it.
@@ -1,1953 +1,2017 b''
1 # encoding: utf-8
2 1 """Completion for IPython.
3 2
4 3 This module started as fork of the rlcompleter module in the Python standard
5 4 library. The original enhancements made to rlcompleter have been sent
6 5 upstream and were accepted as of Python 2.3,
7 6
8 7 This module now support a wide variety of completion mechanism both available
9 8 for normal classic Python code, as well as completer for IPython specific
10 9 Syntax like magics.
11 10
12 11 Latex and Unicode completion
13 12 ============================
14 13
15 14 IPython and compatible frontends not only can complete your code, but can help
16 15 you to input a wide range of characters. In particular we allow you to insert
17 16 a unicode character using the tab completion mechanism.
18 17
19 18 Forward latex/unicode completion
20 19 --------------------------------
21 20
22 21 Forward completion allows you to easily type a unicode character using its latex
23 22 name, or unicode long description. To do so type a backslash follow by the
24 23 relevant name and press tab:
25 24
26 25
27 26 Using latex completion:
28 27
29 28 .. code::
30 29
31 30 \\alpha<tab>
32 31 Ξ±
33 32
34 33 or using unicode completion:
35 34
36 35
37 36 .. code::
38 37
39 38 \\greek small letter alpha<tab>
40 39 Ξ±
41 40
42 41
43 42 Only valid Python identifiers will complete. Combining characters (like arrow or
44 43 dots) are also available, unlike latex they need to be put after the their
45 44 counterpart that is to say, `F\\\\vec<tab>` is correct, not `\\\\vec<tab>F`.
46 45
47 46 Some browsers are known to display combining characters incorrectly.
48 47
49 48 Backward latex completion
50 49 -------------------------
51 50
52 51 It is sometime challenging to know how to type a character, if you are using
53 52 IPython, or any compatible frontend you can prepend backslash to the character
54 53 and press `<tab>` to expand it to its latex form.
55 54
56 55 .. code::
57 56
58 57 \\Ξ±<tab>
59 58 \\alpha
60 59
61 60
62 61 Both forward and backward completions can be deactivated by setting the
63 62 ``Completer.backslash_combining_completions`` option to ``False``.
64 63
65 64
66 65 Experimental
67 66 ============
68 67
69 68 Starting with IPython 6.0, this module can make use of the Jedi library to
70 69 generate completions both using static analysis of the code, and dynamically
71 70 inspecting multiple namespaces. The APIs attached to this new mechanism is
72 71 unstable and will raise unless use in an :any:`provisionalcompleter` context
73 72 manager.
74 73
75 74 You will find that the following are experimental:
76 75
77 76 - :any:`provisionalcompleter`
78 77 - :any:`IPCompleter.completions`
79 78 - :any:`Completion`
80 79 - :any:`rectify_completions`
81 80
82 81 .. note::
83 82
84 83 better name for :any:`rectify_completions` ?
85 84
86 85 We welcome any feedback on these new API, and we also encourage you to try this
87 86 module in debug mode (start IPython with ``--Completer.debug=True``) in order
88 87 to have extra logging information is :any:`jedi` is crashing, or if current
89 88 IPython completer pending deprecations are returning results not yet handled
90 by :any:`jedi`.
89 by :any:`jedi`
91 90
92 91 Using Jedi for tab completion allow snippets like the following to work without
93 92 having to execute any code:
94 93
95 94 >>> myvar = ['hello', 42]
96 95 ... myvar[1].bi<tab>
97 96
98 97 Tab completion will be able to infer that ``myvar[1]`` is a real number without
99 98 executing any code unlike the previously available ``IPCompleter.greedy``
100 99 option.
101 100
102 101 Be sure to update :any:`jedi` to the latest stable version or to try the
103 102 current development version to get better completions.
104 103 """
105 104
106 # skip module docstests
107 skip_doctest = True
108 105
109 106 # Copyright (c) IPython Development Team.
110 107 # Distributed under the terms of the Modified BSD License.
111 108 #
112 109 # Some of this code originated from rlcompleter in the Python standard library
113 110 # Copyright (C) 2001 Python Software Foundation, www.python.org
114 111
115 112
116 113 import __main__
117 114 import builtins as builtin_mod
118 115 import glob
119 116 import time
120 117 import inspect
121 118 import itertools
122 119 import keyword
123 120 import os
124 121 import re
125 122 import sys
126 123 import unicodedata
127 124 import string
128 125 import warnings
129 126
130 127 from contextlib import contextmanager
131 128 from importlib import import_module
132 129 from typing import Iterator, List, Tuple, Iterable, Union
133 130 from types import SimpleNamespace
134 131
135 132 from traitlets.config.configurable import Configurable
136 133 from IPython.core.error import TryNext
137 134 from IPython.core.inputsplitter import ESC_MAGIC
138 135 from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol
139 136 from IPython.core.oinspect import InspectColors
140 137 from IPython.utils import generics
141 138 from IPython.utils.dir2 import dir2, get_real_method
142 139 from IPython.utils.process import arg_split
143 140 from traitlets import Bool, Enum, observe, Int
144 141
142 # skip module docstests
143 skip_doctest = True
144
145 145 try:
146 146 import jedi
147 147 import jedi.api.helpers
148 import jedi.api.classes
148 149 JEDI_INSTALLED = True
149 150 except ImportError:
150 151 JEDI_INSTALLED = False
151 152 #-----------------------------------------------------------------------------
152 153 # Globals
153 154 #-----------------------------------------------------------------------------
154 155
155 156 # Public API
156 157 __all__ = ['Completer','IPCompleter']
157 158
158 159 if sys.platform == 'win32':
159 160 PROTECTABLES = ' '
160 161 else:
161 162 PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&'
162 163
163 164
164 165 _deprecation_readline_sentinel = object()
165 166
166 167
167 168 class ProvisionalCompleterWarning(FutureWarning):
168 169 """
169 170 Exception raise by an experimental feature in this module.
170 171
171 172 Wrap code in :any:`provisionalcompleter` context manager if you
172 173 are certain you want to use an unstable feature.
173 174 """
174 175 pass
175 176
176 177 warnings.filterwarnings('error', category=ProvisionalCompleterWarning)
177 178
178 179 @contextmanager
179 180 def provisionalcompleter(action='ignore'):
180 181 """
181 182
182 183
183 184 This contest manager has to be used in any place where unstable completer
184 185 behavior and API may be called.
185 186
186 187 >>> with provisionalcompleter():
187 188 ... completer.do_experimetal_things() # works
188 189
189 190 >>> completer.do_experimental_things() # raises.
190 191
191 192 .. note:: Unstable
192 193
193 194 By using this context manager you agree that the API in use may change
194 195 without warning, and that you won't complain if they do so.
195 196
196 197 You also understand that if the API is not to you liking you should report
197 198 a bug to explain your use case upstream and improve the API and will loose
198 199 credibility if you complain after the API is make stable.
199 200
200 201 We'll be happy to get your feedback , feature request and improvement on
201 202 any of the unstable APIs !
202 203 """
203 204 with warnings.catch_warnings():
204 205 warnings.filterwarnings(action, category=ProvisionalCompleterWarning)
205 206 yield
206 207
207 208
208 209 def has_open_quotes(s):
209 210 """Return whether a string has open quotes.
210 211
211 212 This simply counts whether the number of quote characters of either type in
212 213 the string is odd.
213 214
214 215 Returns
215 216 -------
216 217 If there is an open quote, the quote character is returned. Else, return
217 218 False.
218 219 """
219 220 # We check " first, then ', so complex cases with nested quotes will get
220 221 # the " to take precedence.
221 222 if s.count('"') % 2:
222 223 return '"'
223 224 elif s.count("'") % 2:
224 225 return "'"
225 226 else:
226 227 return False
227 228
228 229
229 230 def protect_filename(s, protectables=PROTECTABLES):
230 231 """Escape a string to protect certain characters."""
231 232 if set(s) & set(protectables):
232 233 if sys.platform == "win32":
233 234 return '"' + s + '"'
234 235 else:
235 236 return "".join(("\\" + c if c in protectables else c) for c in s)
236 237 else:
237 238 return s
238 239
239 240
240 def expand_user(path):
241 def expand_user(path:str) -> Tuple[str, bool, str]:
241 242 """Expand ``~``-style usernames in strings.
242 243
243 244 This is similar to :func:`os.path.expanduser`, but it computes and returns
244 245 extra information that will be useful if the input was being used in
245 246 computing completions, and you wish to return the completions with the
246 247 original '~' instead of its expanded value.
247 248
248 249 Parameters
249 250 ----------
250 251 path : str
251 252 String to be expanded. If no ~ is present, the output is the same as the
252 253 input.
253 254
254 255 Returns
255 256 -------
256 257 newpath : str
257 258 Result of ~ expansion in the input path.
258 259 tilde_expand : bool
259 260 Whether any expansion was performed or not.
260 261 tilde_val : str
261 262 The value that ~ was replaced with.
262 263 """
263 264 # Default values
264 265 tilde_expand = False
265 266 tilde_val = ''
266 267 newpath = path
267 268
268 269 if path.startswith('~'):
269 270 tilde_expand = True
270 271 rest = len(path)-1
271 272 newpath = os.path.expanduser(path)
272 273 if rest:
273 274 tilde_val = newpath[:-rest]
274 275 else:
275 276 tilde_val = newpath
276 277
277 278 return newpath, tilde_expand, tilde_val
278 279
279 280
280 def compress_user(path, tilde_expand, tilde_val):
281 def compress_user(path:str, tilde_expand:bool, tilde_val:str) -> str:
281 282 """Does the opposite of expand_user, with its outputs.
282 283 """
283 284 if tilde_expand:
284 285 return path.replace(tilde_val, '~')
285 286 else:
286 287 return path
287 288
288 289
289 290 def completions_sorting_key(word):
290 291 """key for sorting completions
291 292
292 293 This does several things:
293 294
294 295 - Lowercase all completions, so they are sorted alphabetically with
295 296 upper and lower case words mingled
296 297 - Demote any completions starting with underscores to the end
297 298 - Insert any %magic and %%cellmagic completions in the alphabetical order
298 299 by their name
299 300 """
300 301 # Case insensitive sort
301 302 word = word.lower()
302 303
303 304 prio1, prio2 = 0, 0
304 305
305 306 if word.startswith('__'):
306 307 prio1 = 2
307 308 elif word.startswith('_'):
308 309 prio1 = 1
309 310
310 311 if word.endswith('='):
311 312 prio1 = -1
312 313
313 314 if word.startswith('%%'):
314 315 # If there's another % in there, this is something else, so leave it alone
315 316 if not "%" in word[2:]:
316 317 word = word[2:]
317 318 prio2 = 2
318 319 elif word.startswith('%'):
319 320 if not "%" in word[1:]:
320 321 word = word[1:]
321 322 prio2 = 1
322 323
323 324 return prio1, word, prio2
324 325
325 326
326 327 class _FakeJediCompletion:
327 328 """
328 329 This is a workaround to communicate to the UI that Jedi has crashed and to
329 330 report a bug. Will be used only id :any:`IPCompleter.debug` is set to true.
330 331
331 332 Added in IPython 6.0 so should likely be removed for 7.0
332 333
333 334 """
334 335
335 336 def __init__(self, name):
336 337
337 338 self.name = name
338 339 self.complete = name
339 340 self.type = 'crashed'
340 341 self.name_with_symbols = name
342 self.signature = ''
343 self._origin = 'fake'
341 344
342 345 def __repr__(self):
343 346 return '<Fake completion object jedi has crashed>'
344 347
345 348
346 349 class Completion:
347 350 """
348 351 Completion object used and return by IPython completers.
349 352
350 353 .. warning:: Unstable
351 354
352 355 This function is unstable, API may change without warning.
353 356 It will also raise unless use in proper context manager.
354 357
355 358 This act as a middle ground :any:`Completion` object between the
356 359 :any:`jedi.api.classes.Completion` object and the Prompt Toolkit completion
357 360 object. While Jedi need a lot of information about evaluator and how the
358 361 code should be ran/inspected, PromptToolkit (and other frontend) mostly
359 362 need user facing information.
360 363
361 364 - Which range should be replaced replaced by what.
362 365 - Some metadata (like completion type), or meta informations to displayed to
363 366 the use user.
364 367
365 368 For debugging purpose we can also store the origin of the completion (``jedi``,
366 369 ``IPython.python_matches``, ``IPython.magics_matches``...).
367 370 """
368 371
369 def __init__(self, start: int, end: int, text: str, *, type: str=None, _origin='') -> None:
372 __slots__ = ['start', 'end', 'text', 'type', 'signature', '_origin']
373
374 def __init__(self, start: int, end: int, text: str, *, type: str=None, _origin='', signature='') -> None:
370 375 warnings.warn("``Completion`` is a provisional API (as of IPython 6.0). "
371 376 "It may change without warnings. "
372 377 "Use in corresponding context manager.",
373 378 category=ProvisionalCompleterWarning, stacklevel=2)
374 379
375 380 self.start = start
376 381 self.end = end
377 382 self.text = text
378 383 self.type = type
384 self.signature = signature
379 385 self._origin = _origin
380 386
381 387 def __repr__(self):
382 return '<Completion start=%s end=%s text=%r type=%r>' % (self.start, self.end, self.text, self.type or '?')
388 return '<Completion start=%s end=%s text=%r type=%r, signature=%r,>' % \
389 (self.start, self.end, self.text, self.type or '?', self.signature or '?')
383 390
384 391 def __eq__(self, other)->Bool:
385 392 """
386 393 Equality and hash do not hash the type (as some completer may not be
387 394 able to infer the type), but are use to (partially) de-duplicate
388 395 completion.
389 396
390 397 Completely de-duplicating completion is a bit tricker that just
391 398 comparing as it depends on surrounding text, which Completions are not
392 399 aware of.
393 400 """
394 401 return self.start == other.start and \
395 402 self.end == other.end and \
396 403 self.text == other.text
397 404
398 405 def __hash__(self):
399 406 return hash((self.start, self.end, self.text))
400 407
401 408
402 409 _IC = Iterable[Completion]
403 410
404 411
405 412 def _deduplicate_completions(text: str, completions: _IC)-> _IC:
406 413 """
407 414 Deduplicate a set of completions.
408 415
409 416 .. warning:: Unstable
410 417
411 418 This function is unstable, API may change without warning.
412 419
413 420 Parameters
414 421 ----------
415 422 text: str
416 423 text that should be completed.
417 424 completions: Iterator[Completion]
418 425 iterator over the completions to deduplicate
419 426
427 Yields
428 ------
429 `Completions` objects
430
420 431
421 432 Completions coming from multiple sources, may be different but end up having
422 433 the same effect when applied to ``text``. If this is the case, this will
423 434 consider completions as equal and only emit the first encountered.
424 435
425 436 Not folded in `completions()` yet for debugging purpose, and to detect when
426 437 the IPython completer does return things that Jedi does not, but should be
427 438 at some point.
428 439 """
429 440 completions = list(completions)
430 441 if not completions:
431 442 return
432 443
433 444 new_start = min(c.start for c in completions)
434 445 new_end = max(c.end for c in completions)
435 446
436 447 seen = set()
437 448 for c in completions:
438 449 new_text = text[new_start:c.start] + c.text + text[c.end:new_end]
439 450 if new_text not in seen:
440 451 yield c
441 452 seen.add(new_text)
442 453
443 454
444 455 def rectify_completions(text: str, completions: _IC, *, _debug=False)->_IC:
445 456 """
446 457 Rectify a set of completions to all have the same ``start`` and ``end``
447 458
448 459 .. warning:: Unstable
449 460
450 461 This function is unstable, API may change without warning.
451 462 It will also raise unless use in proper context manager.
452 463
453 464 Parameters
454 465 ----------
455 466 text: str
456 467 text that should be completed.
457 468 completions: Iterator[Completion]
458 469 iterator over the completions to rectify
459 470
460 471
461 472 :any:`jedi.api.classes.Completion` s returned by Jedi may not have the same start and end, though
462 473 the Jupyter Protocol requires them to behave like so. This will readjust
463 474 the completion to have the same ``start`` and ``end`` by padding both
464 475 extremities with surrounding text.
465 476
466 477 During stabilisation should support a ``_debug`` option to log which
467 478 completion are return by the IPython completer and not found in Jedi in
468 479 order to make upstream bug report.
469 480 """
470 481 warnings.warn("`rectify_completions` is a provisional API (as of IPython 6.0). "
471 482 "It may change without warnings. "
472 483 "Use in corresponding context manager.",
473 484 category=ProvisionalCompleterWarning, stacklevel=2)
474 485
475 486 completions = list(completions)
476 487 if not completions:
477 488 return
478 489 starts = (c.start for c in completions)
479 490 ends = (c.end for c in completions)
480 491
481 492 new_start = min(starts)
482 493 new_end = max(ends)
483 494
484 495 seen_jedi = set()
485 496 seen_python_matches = set()
486 497 for c in completions:
487 498 new_text = text[new_start:c.start] + c.text + text[c.end:new_end]
488 499 if c._origin == 'jedi':
489 500 seen_jedi.add(new_text)
490 501 elif c._origin == 'IPCompleter.python_matches':
491 502 seen_python_matches.add(new_text)
492 yield Completion(new_start, new_end, new_text, type=c.type, _origin=c._origin)
503 yield Completion(new_start, new_end, new_text, type=c.type, _origin=c._origin, signature=c.signature)
493 504 diff = seen_python_matches.difference(seen_jedi)
494 505 if diff and _debug:
495 506 print('IPython.python matches have extras:', diff)
496 507
497 508
498 509 if sys.platform == 'win32':
499 510 DELIMS = ' \t\n`!@#$^&*()=+[{]}|;\'",<>?'
500 511 else:
501 512 DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
502 513
503 514 GREEDY_DELIMS = ' =\r\n'
504 515
505 516
506 517 class CompletionSplitter(object):
507 518 """An object to split an input line in a manner similar to readline.
508 519
509 520 By having our own implementation, we can expose readline-like completion in
510 521 a uniform manner to all frontends. This object only needs to be given the
511 522 line of text to be split and the cursor position on said line, and it
512 523 returns the 'word' to be completed on at the cursor after splitting the
513 524 entire line.
514 525
515 526 What characters are used as splitting delimiters can be controlled by
516 527 setting the ``delims`` attribute (this is a property that internally
517 528 automatically builds the necessary regular expression)"""
518 529
519 530 # Private interface
520 531
521 532 # A string of delimiter characters. The default value makes sense for
522 533 # IPython's most typical usage patterns.
523 534 _delims = DELIMS
524 535
525 536 # The expression (a normal string) to be compiled into a regular expression
526 537 # for actual splitting. We store it as an attribute mostly for ease of
527 538 # debugging, since this type of code can be so tricky to debug.
528 539 _delim_expr = None
529 540
530 541 # The regular expression that does the actual splitting
531 542 _delim_re = None
532 543
533 544 def __init__(self, delims=None):
534 545 delims = CompletionSplitter._delims if delims is None else delims
535 546 self.delims = delims
536 547
537 548 @property
538 549 def delims(self):
539 550 """Return the string of delimiter characters."""
540 551 return self._delims
541 552
542 553 @delims.setter
543 554 def delims(self, delims):
544 555 """Set the delimiters for line splitting."""
545 556 expr = '[' + ''.join('\\'+ c for c in delims) + ']'
546 557 self._delim_re = re.compile(expr)
547 558 self._delims = delims
548 559 self._delim_expr = expr
549 560
550 561 def split_line(self, line, cursor_pos=None):
551 562 """Split a line of text with a cursor at the given position.
552 563 """
553 564 l = line if cursor_pos is None else line[:cursor_pos]
554 565 return self._delim_re.split(l)[-1]
555 566
556 567
557 568
558 569 class Completer(Configurable):
559 570
560 571 greedy = Bool(False,
561 572 help="""Activate greedy completion
562 573 PENDING DEPRECTION. this is now mostly taken care of with Jedi.
563 574
564 575 This will enable completion on elements of lists, results of function calls, etc.,
565 576 but can be unsafe because the code is actually evaluated on TAB.
566 577 """
567 578 ).tag(config=True)
568 579
569 580 use_jedi = Bool(default_value=JEDI_INSTALLED,
570 581 help="Experimental: Use Jedi to generate autocompletions. "
571 582 "Default to True if jedi is installed").tag(config=True)
572 583
573 584 jedi_compute_type_timeout = Int(default_value=400,
574 585 help="""Experimental: restrict time (in milliseconds) during which Jedi can compute types.
575 586 Set to 0 to stop computing types. Non-zero value lower than 100ms may hurt
576 587 performance by preventing jedi to build its cache.
577 588 """).tag(config=True)
578 589
579 590 debug = Bool(default_value=False,
580 591 help='Enable debug for the Completer. Mostly print extra '
581 592 'information for experimental jedi integration.')\
582 593 .tag(config=True)
583 594
584 595 backslash_combining_completions = Bool(True,
585 596 help="Enable unicode completions, e.g. \\alpha<tab> . "
586 597 "Includes completion of latex commands, unicode names, and expanding "
587 598 "unicode characters back to latex commands.").tag(config=True)
588 599
589 600
590 601
591 602 def __init__(self, namespace=None, global_namespace=None, **kwargs):
592 603 """Create a new completer for the command line.
593 604
594 605 Completer(namespace=ns, global_namespace=ns2) -> completer instance.
595 606
596 607 If unspecified, the default namespace where completions are performed
597 608 is __main__ (technically, __main__.__dict__). Namespaces should be
598 609 given as dictionaries.
599 610
600 611 An optional second namespace can be given. This allows the completer
601 612 to handle cases where both the local and global scopes need to be
602 613 distinguished.
603 614 """
604 615
605 616 # Don't bind to namespace quite yet, but flag whether the user wants a
606 617 # specific namespace or to use __main__.__dict__. This will allow us
607 618 # to bind to __main__.__dict__ at completion time, not now.
608 619 if namespace is None:
609 620 self.use_main_ns = True
610 621 else:
611 622 self.use_main_ns = False
612 623 self.namespace = namespace
613 624
614 625 # The global namespace, if given, can be bound directly
615 626 if global_namespace is None:
616 627 self.global_namespace = {}
617 628 else:
618 629 self.global_namespace = global_namespace
619 630
620 631 super(Completer, self).__init__(**kwargs)
621 632
622 633 def complete(self, text, state):
623 634 """Return the next possible completion for 'text'.
624 635
625 636 This is called successively with state == 0, 1, 2, ... until it
626 637 returns None. The completion should begin with 'text'.
627 638
628 639 """
629 640 if self.use_main_ns:
630 641 self.namespace = __main__.__dict__
631 642
632 643 if state == 0:
633 644 if "." in text:
634 645 self.matches = self.attr_matches(text)
635 646 else:
636 647 self.matches = self.global_matches(text)
637 648 try:
638 649 return self.matches[state]
639 650 except IndexError:
640 651 return None
641 652
642 653 def global_matches(self, text):
643 654 """Compute matches when text is a simple name.
644 655
645 656 Return a list of all keywords, built-in functions and names currently
646 657 defined in self.namespace or self.global_namespace that match.
647 658
648 659 """
649 660 matches = []
650 661 match_append = matches.append
651 662 n = len(text)
652 663 for lst in [keyword.kwlist,
653 664 builtin_mod.__dict__.keys(),
654 665 self.namespace.keys(),
655 666 self.global_namespace.keys()]:
656 667 for word in lst:
657 668 if word[:n] == text and word != "__builtins__":
658 669 match_append(word)
659 670
660 671 snake_case_re = re.compile(r"[^_]+(_[^_]+)+?\Z")
661 672 for lst in [self.namespace.keys(),
662 673 self.global_namespace.keys()]:
663 674 shortened = {"_".join([sub[0] for sub in word.split('_')]) : word
664 675 for word in lst if snake_case_re.match(word)}
665 676 for word in shortened.keys():
666 677 if word[:n] == text and word != "__builtins__":
667 678 match_append(shortened[word])
668 679 return matches
669 680
670 681 def attr_matches(self, text):
671 682 """Compute matches when text contains a dot.
672 683
673 684 Assuming the text is of the form NAME.NAME....[NAME], and is
674 685 evaluatable in self.namespace or self.global_namespace, it will be
675 686 evaluated and its attributes (as revealed by dir()) are used as
676 687 possible completions. (For class instances, class members are are
677 688 also considered.)
678 689
679 690 WARNING: this can still invoke arbitrary C code, if an object
680 691 with a __getattr__ hook is evaluated.
681 692
682 693 """
683 694
684 695 # Another option, seems to work great. Catches things like ''.<tab>
685 696 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
686 697
687 698 if m:
688 699 expr, attr = m.group(1, 3)
689 700 elif self.greedy:
690 701 m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer)
691 702 if not m2:
692 703 return []
693 704 expr, attr = m2.group(1,2)
694 705 else:
695 706 return []
696 707
697 708 try:
698 709 obj = eval(expr, self.namespace)
699 710 except:
700 711 try:
701 712 obj = eval(expr, self.global_namespace)
702 713 except:
703 714 return []
704 715
705 716 if self.limit_to__all__ and hasattr(obj, '__all__'):
706 717 words = get__all__entries(obj)
707 718 else:
708 719 words = dir2(obj)
709 720
710 721 try:
711 722 words = generics.complete_object(obj, words)
712 723 except TryNext:
713 724 pass
714 725 except AssertionError:
715 726 raise
716 727 except Exception:
717 728 # Silence errors from completion function
718 729 #raise # dbg
719 730 pass
720 731 # Build match list to return
721 732 n = len(attr)
722 733 return [u"%s.%s" % (expr, w) for w in words if w[:n] == attr ]
723 734
724 735
725 736 def get__all__entries(obj):
726 737 """returns the strings in the __all__ attribute"""
727 738 try:
728 739 words = getattr(obj, '__all__')
729 740 except:
730 741 return []
731 742
732 743 return [w for w in words if isinstance(w, str)]
733 744
734 745
735 746 def match_dict_keys(keys: List[str], prefix: str, delims: str):
736 747 """Used by dict_key_matches, matching the prefix to a list of keys
737 748
738 749 Parameters
739 750 ==========
740 751 keys:
741 752 list of keys in dictionary currently being completed.
742 753 prefix:
743 754 Part of the text already typed by the user. e.g. `mydict[b'fo`
744 755 delims:
745 756 String of delimiters to consider when finding the current key.
746 757
747 758 Returns
748 759 =======
749 760
750 761 A tuple of three elements: ``quote``, ``token_start``, ``matched``, with
751 762 ``quote`` being the quote that need to be used to close current string.
752 763 ``token_start`` the position where the replacement should start occurring,
753 764 ``matches`` a list of replacement/completion
754 765
755 766 """
756 767 if not prefix:
757 768 return None, 0, [repr(k) for k in keys
758 769 if isinstance(k, (str, bytes))]
759 770 quote_match = re.search('["\']', prefix)
760 771 quote = quote_match.group()
761 772 try:
762 773 prefix_str = eval(prefix + quote, {})
763 774 except Exception:
764 775 return None, 0, []
765 776
766 777 pattern = '[^' + ''.join('\\' + c for c in delims) + ']*$'
767 778 token_match = re.search(pattern, prefix, re.UNICODE)
768 779 token_start = token_match.start()
769 780 token_prefix = token_match.group()
770 781
771 782 matched = []
772 783 for key in keys:
773 784 try:
774 785 if not key.startswith(prefix_str):
775 786 continue
776 787 except (AttributeError, TypeError, UnicodeError):
777 788 # Python 3+ TypeError on b'a'.startswith('a') or vice-versa
778 789 continue
779 790
780 791 # reformat remainder of key to begin with prefix
781 792 rem = key[len(prefix_str):]
782 793 # force repr wrapped in '
783 794 rem_repr = repr(rem + '"') if isinstance(rem, str) else repr(rem + b'"')
784 795 if rem_repr.startswith('u') and prefix[0] not in 'uU':
785 796 # Found key is unicode, but prefix is Py2 string.
786 797 # Therefore attempt to interpret key as string.
787 798 try:
788 799 rem_repr = repr(rem.encode('ascii') + '"')
789 800 except UnicodeEncodeError:
790 801 continue
791 802
792 803 rem_repr = rem_repr[1 + rem_repr.index("'"):-2]
793 804 if quote == '"':
794 805 # The entered prefix is quoted with ",
795 806 # but the match is quoted with '.
796 807 # A contained " hence needs escaping for comparison:
797 808 rem_repr = rem_repr.replace('"', '\\"')
798 809
799 810 # then reinsert prefix from start of token
800 811 matched.append('%s%s' % (token_prefix, rem_repr))
801 812 return quote, token_start, matched
802 813
803 814
804 815 def cursor_to_position(text:str, line:int, column:int)->int:
805 816 """
806 817
807 818 Convert the (line,column) position of the cursor in text to an offset in a
808 819 string.
809 820
810 821 Parameters
811 822 ----------
812 823
813 824 text : str
814 825 The text in which to calculate the cursor offset
815 826 line : int
816 827 Line of the cursor; 0-indexed
817 828 column : int
818 829 Column of the cursor 0-indexed
819 830
820 831 Return
821 832 ------
822 833 Position of the cursor in ``text``, 0-indexed.
823 834
824 835 See Also
825 836 --------
826 837 position_to_cursor: reciprocal of this function
827 838
828 839 """
829 840 lines = text.split('\n')
830 841 assert line <= len(lines), '{} <= {}'.format(str(line), str(len(lines)))
831 842
832 843 return sum(len(l) + 1 for l in lines[:line]) + column
833 844
834 845 def position_to_cursor(text:str, offset:int)->Tuple[int, int]:
835 846 """
836 847 Convert the position of the cursor in text (0 indexed) to a line
837 848 number(0-indexed) and a column number (0-indexed) pair
838 849
839 850 Position should be a valid position in ``text``.
840 851
841 852 Parameters
842 853 ----------
843 854
844 855 text : str
845 856 The text in which to calculate the cursor offset
846 857 offset : int
847 858 Position of the cursor in ``text``, 0-indexed.
848 859
849 860 Return
850 861 ------
851 862 (line, column) : (int, int)
852 863 Line of the cursor; 0-indexed, column of the cursor 0-indexed
853 864
854 865
855 866 See Also
856 867 --------
857 868 cursor_to_position : reciprocal of this function
858 869
859 870
860 871 """
861 872
862 873 assert 0 < offset <= len(text) , "0 < %s <= %s" % (offset , len(text))
863 874
864 875 before = text[:offset]
865 876 blines = before.split('\n') # ! splitnes trim trailing \n
866 877 line = before.count('\n')
867 878 col = len(blines[-1])
868 879 return line, col
869 880
870 881
871 882 def _safe_isinstance(obj, module, class_name):
872 883 """Checks if obj is an instance of module.class_name if loaded
873 884 """
874 885 return (module in sys.modules and
875 886 isinstance(obj, getattr(import_module(module), class_name)))
876 887
877 888
878 889 def back_unicode_name_matches(text):
879 890 u"""Match unicode characters back to unicode name
880 891
881 892 This does ``β˜ƒ`` -> ``\\snowman``
882 893
883 894 Note that snowman is not a valid python3 combining character but will be expanded.
884 895 Though it will not recombine back to the snowman character by the completion machinery.
885 896
886 897 This will not either back-complete standard sequences like \\n, \\b ...
887 898
888 899 Used on Python 3 only.
889 900 """
890 901 if len(text)<2:
891 902 return u'', ()
892 903 maybe_slash = text[-2]
893 904 if maybe_slash != '\\':
894 905 return u'', ()
895 906
896 907 char = text[-1]
897 908 # no expand on quote for completion in strings.
898 909 # nor backcomplete standard ascii keys
899 910 if char in string.ascii_letters or char in ['"',"'"]:
900 911 return u'', ()
901 912 try :
902 913 unic = unicodedata.name(char)
903 914 return '\\'+char,['\\'+unic]
904 915 except KeyError:
905 916 pass
906 917 return u'', ()
907 918
908 919 def back_latex_name_matches(text:str):
909 920 """Match latex characters back to unicode name
910 921
911 922 This does ``\\β„΅`` -> ``\\aleph``
912 923
913 924 Used on Python 3 only.
914 925 """
915 926 if len(text)<2:
916 927 return u'', ()
917 928 maybe_slash = text[-2]
918 929 if maybe_slash != '\\':
919 930 return u'', ()
920 931
921 932
922 933 char = text[-1]
923 934 # no expand on quote for completion in strings.
924 935 # nor backcomplete standard ascii keys
925 936 if char in string.ascii_letters or char in ['"',"'"]:
926 937 return u'', ()
927 938 try :
928 939 latex = reverse_latex_symbol[char]
929 940 # '\\' replace the \ as well
930 941 return '\\'+char,[latex]
931 942 except KeyError:
932 943 pass
933 944 return u'', ()
934 945
935 946
947 def _formatparamchildren(parameter) -> str:
948 """
949 Get parameter name and value from Jedi Private API
950
951 Jedi does not expose a simple way to get `param=value` from its API.
952
953 Prameter
954 ========
955
956 parameter:
957 Jedi's function `Param`
958
959 Returns
960 =======
961
962 A string like 'a', 'b=1', '*args', '**kwargs'
963
964
965 """
966 description = parameter.description
967 if not description.startswith('param '):
968 raise ValueError('Jedi function parameter description have change format.'
969 'Expected "param ...", found %r".' % description)
970 return description[6:]
971
972 def _make_signature(completion)-> str:
973 """
974 Make the signature from a jedi completion
975
976 Parameter
977 =========
978
979 completion: jedi.Completion
980 object does not complete a function type
981
982 Returns
983 =======
984
985 a string consisting of the function signature, with the parenthesis but
986 without the function name. example:
987 `(a, *args, b=1, **kwargs)`
988
989 """
990
991 return '(%s)'% ', '.join([f for f in (_formatparamchildren(p) for p in completion.params) if f])
992
936 993 class IPCompleter(Completer):
937 994 """Extension of the completer class with IPython-specific features"""
938 995
939 996 @observe('greedy')
940 997 def _greedy_changed(self, change):
941 998 """update the splitter and readline delims when greedy is changed"""
942 999 if change['new']:
943 1000 self.splitter.delims = GREEDY_DELIMS
944 1001 else:
945 1002 self.splitter.delims = DELIMS
946 1003
947 1004 merge_completions = Bool(True,
948 1005 help="""Whether to merge completion results into a single list
949 1006
950 1007 If False, only the completion results from the first non-empty
951 1008 completer will be returned.
952 1009 """
953 1010 ).tag(config=True)
954 1011 omit__names = Enum((0,1,2), default_value=2,
955 1012 help="""Instruct the completer to omit private method names
956 1013
957 1014 Specifically, when completing on ``object.<tab>``.
958 1015
959 1016 When 2 [default]: all names that start with '_' will be excluded.
960 1017
961 1018 When 1: all 'magic' names (``__foo__``) will be excluded.
962 1019
963 1020 When 0: nothing will be excluded.
964 1021 """
965 1022 ).tag(config=True)
966 1023 limit_to__all__ = Bool(False,
967 1024 help="""
968 1025 DEPRECATED as of version 5.0.
969 1026
970 1027 Instruct the completer to use __all__ for the completion
971 1028
972 1029 Specifically, when completing on ``object.<tab>``.
973 1030
974 1031 When True: only those names in obj.__all__ will be included.
975 1032
976 1033 When False [default]: the __all__ attribute is ignored
977 1034 """,
978 1035 ).tag(config=True)
979 1036
980 1037 @observe('limit_to__all__')
981 1038 def _limit_to_all_changed(self, change):
982 1039 warnings.warn('`IPython.core.IPCompleter.limit_to__all__` configuration '
983 1040 'value has been deprecated since IPython 5.0, will be made to have '
984 1041 'no effects and then removed in future version of IPython.',
985 1042 UserWarning)
986 1043
987 1044 def __init__(self, shell=None, namespace=None, global_namespace=None,
988 1045 use_readline=_deprecation_readline_sentinel, config=None, **kwargs):
989 1046 """IPCompleter() -> completer
990 1047
991 1048 Return a completer object.
992 1049
993 1050 Parameters
994 1051 ----------
995 1052
996 1053 shell
997 1054 a pointer to the ipython shell itself. This is needed
998 1055 because this completer knows about magic functions, and those can
999 1056 only be accessed via the ipython instance.
1000 1057
1001 1058 namespace : dict, optional
1002 1059 an optional dict where completions are performed.
1003 1060
1004 1061 global_namespace : dict, optional
1005 1062 secondary optional dict for completions, to
1006 1063 handle cases (such as IPython embedded inside functions) where
1007 1064 both Python scopes are visible.
1008 1065
1009 1066 use_readline : bool, optional
1010 1067 DEPRECATED, ignored since IPython 6.0, will have no effects
1011 1068 """
1012 1069
1013 1070 self.magic_escape = ESC_MAGIC
1014 1071 self.splitter = CompletionSplitter()
1015 1072
1016 1073 if use_readline is not _deprecation_readline_sentinel:
1017 1074 warnings.warn('The `use_readline` parameter is deprecated and ignored since IPython 6.0.',
1018 1075 DeprecationWarning, stacklevel=2)
1019 1076
1020 1077 # _greedy_changed() depends on splitter and readline being defined:
1021 1078 Completer.__init__(self, namespace=namespace, global_namespace=global_namespace,
1022 1079 config=config, **kwargs)
1023 1080
1024 1081 # List where completion matches will be stored
1025 1082 self.matches = []
1026 1083 self.shell = shell
1027 1084 # Regexp to split filenames with spaces in them
1028 1085 self.space_name_re = re.compile(r'([^\\] )')
1029 1086 # Hold a local ref. to glob.glob for speed
1030 1087 self.glob = glob.glob
1031 1088
1032 1089 # Determine if we are running on 'dumb' terminals, like (X)Emacs
1033 1090 # buffers, to avoid completion problems.
1034 1091 term = os.environ.get('TERM','xterm')
1035 1092 self.dumb_terminal = term in ['dumb','emacs']
1036 1093
1037 1094 # Special handling of backslashes needed in win32 platforms
1038 1095 if sys.platform == "win32":
1039 1096 self.clean_glob = self._clean_glob_win32
1040 1097 else:
1041 1098 self.clean_glob = self._clean_glob
1042 1099
1043 1100 #regexp to parse docstring for function signature
1044 1101 self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
1045 1102 self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
1046 1103 #use this if positional argument name is also needed
1047 1104 #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)')
1048 1105
1049 1106 # All active matcher routines for completion
1050 1107 self.matchers = [
1051 1108 self.python_matches,
1052 1109 self.file_matches,
1053 1110 self.magic_matches,
1054 1111 self.python_func_kw_matches,
1055 1112 self.dict_key_matches,
1056 1113 ]
1057 1114 self.magic_arg_matchers = [
1058 1115 self.magic_config_matches,
1059 1116 self.magic_color_matches,
1060 1117 ]
1061 1118
1062 1119 # This is set externally by InteractiveShell
1063 1120 self.custom_completers = None
1064 1121
1065 1122 def all_completions(self, text):
1066 1123 """
1067 1124 Wrapper around the complete method for the benefit of emacs.
1068 1125 """
1069 1126 return self.complete(text)[1]
1070 1127
1071 1128 def _clean_glob(self, text):
1072 1129 return self.glob("%s*" % text)
1073 1130
1074 1131 def _clean_glob_win32(self,text):
1075 1132 return [f.replace("\\","/")
1076 1133 for f in self.glob("%s*" % text)]
1077 1134
1078 1135 def file_matches(self, text):
1079 1136 """Match filenames, expanding ~USER type strings.
1080 1137
1081 1138 Most of the seemingly convoluted logic in this completer is an
1082 1139 attempt to handle filenames with spaces in them. And yet it's not
1083 1140 quite perfect, because Python's readline doesn't expose all of the
1084 1141 GNU readline details needed for this to be done correctly.
1085 1142
1086 1143 For a filename with a space in it, the printed completions will be
1087 1144 only the parts after what's already been typed (instead of the
1088 1145 full completions, as is normally done). I don't think with the
1089 1146 current (as of Python 2.3) Python readline it's possible to do
1090 1147 better."""
1091 1148
1092 1149 # chars that require escaping with backslash - i.e. chars
1093 1150 # that readline treats incorrectly as delimiters, but we
1094 1151 # don't want to treat as delimiters in filename matching
1095 1152 # when escaped with backslash
1096 1153 if text.startswith('!'):
1097 1154 text = text[1:]
1098 1155 text_prefix = u'!'
1099 1156 else:
1100 1157 text_prefix = u''
1101 1158
1102 1159 text_until_cursor = self.text_until_cursor
1103 1160 # track strings with open quotes
1104 1161 open_quotes = has_open_quotes(text_until_cursor)
1105 1162
1106 1163 if '(' in text_until_cursor or '[' in text_until_cursor:
1107 1164 lsplit = text
1108 1165 else:
1109 1166 try:
1110 1167 # arg_split ~ shlex.split, but with unicode bugs fixed by us
1111 1168 lsplit = arg_split(text_until_cursor)[-1]
1112 1169 except ValueError:
1113 1170 # typically an unmatched ", or backslash without escaped char.
1114 1171 if open_quotes:
1115 1172 lsplit = text_until_cursor.split(open_quotes)[-1]
1116 1173 else:
1117 1174 return []
1118 1175 except IndexError:
1119 1176 # tab pressed on empty line
1120 1177 lsplit = ""
1121 1178
1122 1179 if not open_quotes and lsplit != protect_filename(lsplit):
1123 1180 # if protectables are found, do matching on the whole escaped name
1124 1181 has_protectables = True
1125 1182 text0,text = text,lsplit
1126 1183 else:
1127 1184 has_protectables = False
1128 1185 text = os.path.expanduser(text)
1129 1186
1130 1187 if text == "":
1131 1188 return [text_prefix + protect_filename(f) for f in self.glob("*")]
1132 1189
1133 1190 # Compute the matches from the filesystem
1134 1191 if sys.platform == 'win32':
1135 1192 m0 = self.clean_glob(text)
1136 1193 else:
1137 1194 m0 = self.clean_glob(text.replace('\\', ''))
1138 1195
1139 1196 if has_protectables:
1140 1197 # If we had protectables, we need to revert our changes to the
1141 1198 # beginning of filename so that we don't double-write the part
1142 1199 # of the filename we have so far
1143 1200 len_lsplit = len(lsplit)
1144 1201 matches = [text_prefix + text0 +
1145 1202 protect_filename(f[len_lsplit:]) for f in m0]
1146 1203 else:
1147 1204 if open_quotes:
1148 1205 # if we have a string with an open quote, we don't need to
1149 1206 # protect the names beyond the quote (and we _shouldn't_, as
1150 1207 # it would cause bugs when the filesystem call is made).
1151 1208 matches = m0 if sys.platform == "win32" else\
1152 1209 [protect_filename(f, open_quotes) for f in m0]
1153 1210 else:
1154 1211 matches = [text_prefix +
1155 1212 protect_filename(f) for f in m0]
1156 1213
1157 1214 # Mark directories in input list by appending '/' to their names.
1158 1215 return [x+'/' if os.path.isdir(x) else x for x in matches]
1159 1216
1160 1217 def magic_matches(self, text):
1161 1218 """Match magics"""
1162 1219 # Get all shell magics now rather than statically, so magics loaded at
1163 1220 # runtime show up too.
1164 1221 lsm = self.shell.magics_manager.lsmagic()
1165 1222 line_magics = lsm['line']
1166 1223 cell_magics = lsm['cell']
1167 1224 pre = self.magic_escape
1168 1225 pre2 = pre+pre
1169 1226
1170 1227 # Completion logic:
1171 1228 # - user gives %%: only do cell magics
1172 1229 # - user gives %: do both line and cell magics
1173 1230 # - no prefix: do both
1174 1231 # In other words, line magics are skipped if the user gives %% explicitly
1175 1232 #
1176 1233 # We also exclude magics that match any currently visible names:
1177 1234 # https://github.com/ipython/ipython/issues/4877
1178 1235 bare_text = text.lstrip(pre)
1179 1236 global_matches = self.global_matches(bare_text)
1180 1237 matches = lambda magic: magic.startswith(bare_text) \
1181 1238 and magic not in global_matches
1182 1239 comp = [ pre2+m for m in cell_magics if matches(m)]
1183 1240 if not text.startswith(pre2):
1184 1241 comp += [ pre+m for m in line_magics if matches(m)]
1185 1242
1186 1243 return comp
1187 1244
1188 1245 def magic_config_matches(self, text:str) -> List[str]:
1189 1246 """ Match class names and attributes for %config magic """
1190 1247 texts = text.strip().split()
1191 1248
1192 1249 if len(texts) > 0 and (texts[0] == 'config' or texts[0] == '%config'):
1193 1250 # get all configuration classes
1194 1251 classes = sorted(set([ c for c in self.shell.configurables
1195 1252 if c.__class__.class_traits(config=True)
1196 1253 ]), key=lambda x: x.__class__.__name__)
1197 1254 classnames = [ c.__class__.__name__ for c in classes ]
1198 1255
1199 1256 # return all classnames if config or %config is given
1200 1257 if len(texts) == 1:
1201 1258 return classnames
1202 1259
1203 1260 # match classname
1204 1261 classname_texts = texts[1].split('.')
1205 1262 classname = classname_texts[0]
1206 1263 classname_matches = [ c for c in classnames
1207 1264 if c.startswith(classname) ]
1208 1265
1209 1266 # return matched classes or the matched class with attributes
1210 1267 if texts[1].find('.') < 0:
1211 1268 return classname_matches
1212 1269 elif len(classname_matches) == 1 and \
1213 1270 classname_matches[0] == classname:
1214 1271 cls = classes[classnames.index(classname)].__class__
1215 1272 help = cls.class_get_help()
1216 1273 # strip leading '--' from cl-args:
1217 1274 help = re.sub(re.compile(r'^--', re.MULTILINE), '', help)
1218 1275 return [ attr.split('=')[0]
1219 1276 for attr in help.strip().splitlines()
1220 1277 if attr.startswith(texts[1]) ]
1221 1278 return []
1222 1279
1223 1280 def magic_color_matches(self, text:str) -> List[str] :
1224 1281 """ Match color schemes for %colors magic"""
1225 1282 texts = text.strip().split()
1226 1283
1227 1284 if len(texts) > 0 and (texts[0] == 'colors' or texts[0] == '%colors'):
1228 1285 prefix = texts[1] if len(texts) > 1 else ''
1229 1286 return [ color for color in InspectColors.keys()
1230 1287 if color.startswith(prefix) ]
1231 1288 return []
1232 1289
1233 1290 def _jedi_matches(self, cursor_column:int, cursor_line:int, text:str):
1234 1291 """
1235 1292
1236 1293 Return a list of :any:`jedi.api.Completions` object from a ``text`` and
1237 1294 cursor position.
1238 1295
1239 1296 Parameters
1240 1297 ----------
1241 1298 cursor_column : int
1242 1299 column position of the cursor in ``text``, 0-indexed.
1243 1300 cursor_line : int
1244 1301 line position of the cursor in ``text``, 0-indexed
1245 1302 text : str
1246 1303 text to complete
1247 1304
1248 1305 Debugging
1249 1306 ---------
1250 1307
1251 1308 If ``IPCompleter.debug`` is ``True`` may return a :any:`_FakeJediCompletion`
1252 1309 object containing a string with the Jedi debug information attached.
1253 1310 """
1254 1311 namespaces = [self.namespace]
1255 1312 if self.global_namespace is not None:
1256 1313 namespaces.append(self.global_namespace)
1257 1314
1258 1315 completion_filter = lambda x:x
1259 1316 # cursor_pos is an it, jedi wants line and column
1260 1317 offset = cursor_to_position(text, cursor_line, cursor_column)
1261 1318 # filter output if we are completing for object members
1262 1319 if offset:
1263 1320 pre = text[offset-1]
1264 1321 if pre == '.':
1265 1322 if self.omit__names == 2:
1266 1323 completion_filter = lambda c:not c.name.startswith('_')
1267 1324 elif self.omit__names == 1:
1268 1325 completion_filter = lambda c:not (c.name.startswith('__') and c.name.endswith('__'))
1269 1326 elif self.omit__names == 0:
1270 1327 completion_filter = lambda x:x
1271 1328 else:
1272 1329 raise ValueError("Don't understand self.omit__names == {}".format(self.omit__names))
1273 1330
1274 1331 interpreter = jedi.Interpreter(
1275 1332 text, namespaces, column=cursor_column, line=cursor_line + 1)
1276 1333
1277 1334 try_jedi = False
1278 1335
1279 1336 try:
1280 1337 # should we check the type of the node is Error ?
1281 1338 from jedi.parser.tree import ErrorLeaf
1282 1339 next_to_last_tree = interpreter._get_module().tree_node.children[-2]
1283 1340 completing_string = False
1284 1341 if isinstance(next_to_last_tree, ErrorLeaf):
1285 1342 completing_string = interpreter._get_module().tree_node.children[-2].value[0] in {'"', "'"}
1286 1343 # if we are in a string jedi is likely not the right candidate for
1287 1344 # now. Skip it.
1288 1345 try_jedi = not completing_string
1289 1346 except Exception as e:
1290 1347 # many of things can go wrong, we are using private API just don't crash.
1291 1348 if self.debug:
1292 1349 print("Error detecting if completing a non-finished string :", e, '|')
1293 1350
1294 1351 if not try_jedi:
1295 1352 return []
1296 1353 try:
1297 1354 return filter(completion_filter, interpreter.completions())
1298 1355 except Exception as e:
1299 1356 if self.debug:
1300 1357 return [_FakeJediCompletion('Oops Jedi has crashed, please report a bug with the following:\n"""\n%s\ns"""' % (e))]
1301 1358 else:
1302 1359 return []
1303 1360
1304 1361 def python_matches(self, text):
1305 1362 """Match attributes or global python names"""
1306 1363 if "." in text:
1307 1364 try:
1308 1365 matches = self.attr_matches(text)
1309 1366 if text.endswith('.') and self.omit__names:
1310 1367 if self.omit__names == 1:
1311 1368 # true if txt is _not_ a __ name, false otherwise:
1312 1369 no__name = (lambda txt:
1313 1370 re.match(r'.*\.__.*?__',txt) is None)
1314 1371 else:
1315 1372 # true if txt is _not_ a _ name, false otherwise:
1316 1373 no__name = (lambda txt:
1317 1374 re.match(r'\._.*?',txt[txt.rindex('.'):]) is None)
1318 1375 matches = filter(no__name, matches)
1319 1376 except NameError:
1320 1377 # catches <undefined attributes>.<tab>
1321 1378 matches = []
1322 1379 else:
1323 1380 matches = self.global_matches(text)
1324 1381 return matches
1325 1382
1326 1383 def _default_arguments_from_docstring(self, doc):
1327 1384 """Parse the first line of docstring for call signature.
1328 1385
1329 1386 Docstring should be of the form 'min(iterable[, key=func])\n'.
1330 1387 It can also parse cython docstring of the form
1331 1388 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'.
1332 1389 """
1333 1390 if doc is None:
1334 1391 return []
1335 1392
1336 1393 #care only the firstline
1337 1394 line = doc.lstrip().splitlines()[0]
1338 1395
1339 1396 #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
1340 1397 #'min(iterable[, key=func])\n' -> 'iterable[, key=func]'
1341 1398 sig = self.docstring_sig_re.search(line)
1342 1399 if sig is None:
1343 1400 return []
1344 1401 # iterable[, key=func]' -> ['iterable[' ,' key=func]']
1345 1402 sig = sig.groups()[0].split(',')
1346 1403 ret = []
1347 1404 for s in sig:
1348 1405 #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
1349 1406 ret += self.docstring_kwd_re.findall(s)
1350 1407 return ret
1351 1408
1352 1409 def _default_arguments(self, obj):
1353 1410 """Return the list of default arguments of obj if it is callable,
1354 1411 or empty list otherwise."""
1355 1412 call_obj = obj
1356 1413 ret = []
1357 1414 if inspect.isbuiltin(obj):
1358 1415 pass
1359 1416 elif not (inspect.isfunction(obj) or inspect.ismethod(obj)):
1360 1417 if inspect.isclass(obj):
1361 1418 #for cython embededsignature=True the constructor docstring
1362 1419 #belongs to the object itself not __init__
1363 1420 ret += self._default_arguments_from_docstring(
1364 1421 getattr(obj, '__doc__', ''))
1365 1422 # for classes, check for __init__,__new__
1366 1423 call_obj = (getattr(obj, '__init__', None) or
1367 1424 getattr(obj, '__new__', None))
1368 1425 # for all others, check if they are __call__able
1369 1426 elif hasattr(obj, '__call__'):
1370 1427 call_obj = obj.__call__
1371 1428 ret += self._default_arguments_from_docstring(
1372 1429 getattr(call_obj, '__doc__', ''))
1373 1430
1374 1431 _keeps = (inspect.Parameter.KEYWORD_ONLY,
1375 1432 inspect.Parameter.POSITIONAL_OR_KEYWORD)
1376 1433
1377 1434 try:
1378 1435 sig = inspect.signature(call_obj)
1379 1436 ret.extend(k for k, v in sig.parameters.items() if
1380 1437 v.kind in _keeps)
1381 1438 except ValueError:
1382 1439 pass
1383 1440
1384 1441 return list(set(ret))
1385 1442
1386 1443 def python_func_kw_matches(self,text):
1387 1444 """Match named parameters (kwargs) of the last open function"""
1388 1445
1389 1446 if "." in text: # a parameter cannot be dotted
1390 1447 return []
1391 1448 try: regexp = self.__funcParamsRegex
1392 1449 except AttributeError:
1393 1450 regexp = self.__funcParamsRegex = re.compile(r'''
1394 1451 '.*?(?<!\\)' | # single quoted strings or
1395 1452 ".*?(?<!\\)" | # double quoted strings or
1396 1453 \w+ | # identifier
1397 1454 \S # other characters
1398 1455 ''', re.VERBOSE | re.DOTALL)
1399 1456 # 1. find the nearest identifier that comes before an unclosed
1400 1457 # parenthesis before the cursor
1401 1458 # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo"
1402 1459 tokens = regexp.findall(self.text_until_cursor)
1403 1460 iterTokens = reversed(tokens); openPar = 0
1404 1461
1405 1462 for token in iterTokens:
1406 1463 if token == ')':
1407 1464 openPar -= 1
1408 1465 elif token == '(':
1409 1466 openPar += 1
1410 1467 if openPar > 0:
1411 1468 # found the last unclosed parenthesis
1412 1469 break
1413 1470 else:
1414 1471 return []
1415 1472 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
1416 1473 ids = []
1417 1474 isId = re.compile(r'\w+$').match
1418 1475
1419 1476 while True:
1420 1477 try:
1421 1478 ids.append(next(iterTokens))
1422 1479 if not isId(ids[-1]):
1423 1480 ids.pop(); break
1424 1481 if not next(iterTokens) == '.':
1425 1482 break
1426 1483 except StopIteration:
1427 1484 break
1428 1485
1429 1486 # Find all named arguments already assigned to, as to avoid suggesting
1430 1487 # them again
1431 1488 usedNamedArgs = set()
1432 1489 par_level = -1
1433 1490 for token, next_token in zip(tokens, tokens[1:]):
1434 1491 if token == '(':
1435 1492 par_level += 1
1436 1493 elif token == ')':
1437 1494 par_level -= 1
1438 1495
1439 1496 if par_level != 0:
1440 1497 continue
1441 1498
1442 1499 if next_token != '=':
1443 1500 continue
1444 1501
1445 1502 usedNamedArgs.add(token)
1446 1503
1447 1504 # lookup the candidate callable matches either using global_matches
1448 1505 # or attr_matches for dotted names
1449 1506 if len(ids) == 1:
1450 1507 callableMatches = self.global_matches(ids[0])
1451 1508 else:
1452 1509 callableMatches = self.attr_matches('.'.join(ids[::-1]))
1453 1510 argMatches = []
1454 1511 for callableMatch in callableMatches:
1455 1512 try:
1456 1513 namedArgs = self._default_arguments(eval(callableMatch,
1457 1514 self.namespace))
1458 1515 except:
1459 1516 continue
1460 1517
1461 1518 # Remove used named arguments from the list, no need to show twice
1462 1519 for namedArg in set(namedArgs) - usedNamedArgs:
1463 1520 if namedArg.startswith(text):
1464 1521 argMatches.append(u"%s=" %namedArg)
1465 1522 return argMatches
1466 1523
1467 1524 def dict_key_matches(self, text):
1468 1525 "Match string keys in a dictionary, after e.g. 'foo[' "
1469 1526 def get_keys(obj):
1470 1527 # Objects can define their own completions by defining an
1471 1528 # _ipy_key_completions_() method.
1472 1529 method = get_real_method(obj, '_ipython_key_completions_')
1473 1530 if method is not None:
1474 1531 return method()
1475 1532
1476 1533 # Special case some common in-memory dict-like types
1477 1534 if isinstance(obj, dict) or\
1478 1535 _safe_isinstance(obj, 'pandas', 'DataFrame'):
1479 1536 try:
1480 1537 return list(obj.keys())
1481 1538 except Exception:
1482 1539 return []
1483 1540 elif _safe_isinstance(obj, 'numpy', 'ndarray') or\
1484 1541 _safe_isinstance(obj, 'numpy', 'void'):
1485 1542 return obj.dtype.names or []
1486 1543 return []
1487 1544
1488 1545 try:
1489 1546 regexps = self.__dict_key_regexps
1490 1547 except AttributeError:
1491 1548 dict_key_re_fmt = r'''(?x)
1492 1549 ( # match dict-referring expression wrt greedy setting
1493 1550 %s
1494 1551 )
1495 1552 \[ # open bracket
1496 1553 \s* # and optional whitespace
1497 1554 ([uUbB]? # string prefix (r not handled)
1498 1555 (?: # unclosed string
1499 1556 '(?:[^']|(?<!\\)\\')*
1500 1557 |
1501 1558 "(?:[^"]|(?<!\\)\\")*
1502 1559 )
1503 1560 )?
1504 1561 $
1505 1562 '''
1506 1563 regexps = self.__dict_key_regexps = {
1507 1564 False: re.compile(dict_key_re_fmt % '''
1508 1565 # identifiers separated by .
1509 1566 (?!\d)\w+
1510 1567 (?:\.(?!\d)\w+)*
1511 1568 '''),
1512 1569 True: re.compile(dict_key_re_fmt % '''
1513 1570 .+
1514 1571 ''')
1515 1572 }
1516 1573
1517 1574 match = regexps[self.greedy].search(self.text_until_cursor)
1518 1575 if match is None:
1519 1576 return []
1520 1577
1521 1578 expr, prefix = match.groups()
1522 1579 try:
1523 1580 obj = eval(expr, self.namespace)
1524 1581 except Exception:
1525 1582 try:
1526 1583 obj = eval(expr, self.global_namespace)
1527 1584 except Exception:
1528 1585 return []
1529 1586
1530 1587 keys = get_keys(obj)
1531 1588 if not keys:
1532 1589 return keys
1533 1590 closing_quote, token_offset, matches = match_dict_keys(keys, prefix, self.splitter.delims)
1534 1591 if not matches:
1535 1592 return matches
1536 1593
1537 1594 # get the cursor position of
1538 1595 # - the text being completed
1539 1596 # - the start of the key text
1540 1597 # - the start of the completion
1541 1598 text_start = len(self.text_until_cursor) - len(text)
1542 1599 if prefix:
1543 1600 key_start = match.start(2)
1544 1601 completion_start = key_start + token_offset
1545 1602 else:
1546 1603 key_start = completion_start = match.end()
1547 1604
1548 1605 # grab the leading prefix, to make sure all completions start with `text`
1549 1606 if text_start > key_start:
1550 1607 leading = ''
1551 1608 else:
1552 1609 leading = text[text_start:completion_start]
1553 1610
1554 1611 # the index of the `[` character
1555 1612 bracket_idx = match.end(1)
1556 1613
1557 1614 # append closing quote and bracket as appropriate
1558 1615 # this is *not* appropriate if the opening quote or bracket is outside
1559 1616 # the text given to this method
1560 1617 suf = ''
1561 1618 continuation = self.line_buffer[len(self.text_until_cursor):]
1562 1619 if key_start > text_start and closing_quote:
1563 1620 # quotes were opened inside text, maybe close them
1564 1621 if continuation.startswith(closing_quote):
1565 1622 continuation = continuation[len(closing_quote):]
1566 1623 else:
1567 1624 suf += closing_quote
1568 1625 if bracket_idx > text_start:
1569 1626 # brackets were opened inside text, maybe close them
1570 1627 if not continuation.startswith(']'):
1571 1628 suf += ']'
1572 1629
1573 1630 return [leading + k + suf for k in matches]
1574 1631
1575 1632 def unicode_name_matches(self, text):
1576 1633 u"""Match Latex-like syntax for unicode characters base
1577 1634 on the name of the character.
1578 1635
1579 1636 This does ``\\GREEK SMALL LETTER ETA`` -> ``Ξ·``
1580 1637
1581 1638 Works only on valid python 3 identifier, or on combining characters that
1582 1639 will combine to form a valid identifier.
1583 1640
1584 1641 Used on Python 3 only.
1585 1642 """
1586 1643 slashpos = text.rfind('\\')
1587 1644 if slashpos > -1:
1588 1645 s = text[slashpos+1:]
1589 1646 try :
1590 1647 unic = unicodedata.lookup(s)
1591 1648 # allow combining chars
1592 1649 if ('a'+unic).isidentifier():
1593 1650 return '\\'+s,[unic]
1594 1651 except KeyError:
1595 1652 pass
1596 1653 return u'', []
1597 1654
1598 1655
1599 1656 def latex_matches(self, text):
1600 1657 u"""Match Latex syntax for unicode characters.
1601 1658
1602 1659 This does both ``\\alp`` -> ``\\alpha`` and ``\\alpha`` -> ``Ξ±``
1603 1660
1604 1661 Used on Python 3 only.
1605 1662 """
1606 1663 slashpos = text.rfind('\\')
1607 1664 if slashpos > -1:
1608 1665 s = text[slashpos:]
1609 1666 if s in latex_symbols:
1610 1667 # Try to complete a full latex symbol to unicode
1611 1668 # \\alpha -> Ξ±
1612 1669 return s, [latex_symbols[s]]
1613 1670 else:
1614 1671 # If a user has partially typed a latex symbol, give them
1615 1672 # a full list of options \al -> [\aleph, \alpha]
1616 1673 matches = [k for k in latex_symbols if k.startswith(s)]
1617 1674 return s, matches
1618 1675 return u'', []
1619 1676
1620 1677 def dispatch_custom_completer(self, text):
1621 1678 if not self.custom_completers:
1622 1679 return
1623 1680
1624 1681 line = self.line_buffer
1625 1682 if not line.strip():
1626 1683 return None
1627 1684
1628 1685 # Create a little structure to pass all the relevant information about
1629 1686 # the current completion to any custom completer.
1630 1687 event = SimpleNamespace()
1631 1688 event.line = line
1632 1689 event.symbol = text
1633 1690 cmd = line.split(None,1)[0]
1634 1691 event.command = cmd
1635 1692 event.text_until_cursor = self.text_until_cursor
1636 1693
1637 1694 # for foo etc, try also to find completer for %foo
1638 1695 if not cmd.startswith(self.magic_escape):
1639 1696 try_magic = self.custom_completers.s_matches(
1640 1697 self.magic_escape + cmd)
1641 1698 else:
1642 1699 try_magic = []
1643 1700
1644 1701 for c in itertools.chain(self.custom_completers.s_matches(cmd),
1645 1702 try_magic,
1646 1703 self.custom_completers.flat_matches(self.text_until_cursor)):
1647 1704 try:
1648 1705 res = c(event)
1649 1706 if res:
1650 1707 # first, try case sensitive match
1651 1708 withcase = [r for r in res if r.startswith(text)]
1652 1709 if withcase:
1653 1710 return withcase
1654 1711 # if none, then case insensitive ones are ok too
1655 1712 text_low = text.lower()
1656 1713 return [r for r in res if r.lower().startswith(text_low)]
1657 1714 except TryNext:
1658 1715 pass
1659 1716
1660 1717 return None
1661 1718
1662 1719 def completions(self, text: str, offset: int)->Iterator[Completion]:
1663 1720 """
1664 1721 Returns an iterator over the possible completions
1665 1722
1666 1723 .. warning:: Unstable
1667 1724
1668 1725 This function is unstable, API may change without warning.
1669 1726 It will also raise unless use in proper context manager.
1670 1727
1671 1728 Parameters
1672 1729 ----------
1673 1730
1674 1731 text:str
1675 1732 Full text of the current input, multi line string.
1676 1733 offset:int
1677 1734 Integer representing the position of the cursor in ``text``. Offset
1678 1735 is 0-based indexed.
1679 1736
1680 1737 Yields
1681 1738 ------
1682 1739 :any:`Completion` object
1683 1740
1684 1741
1685 1742 The cursor on a text can either be seen as being "in between"
1686 1743 characters or "On" a character depending on the interface visible to
1687 1744 the user. For consistency the cursor being on "in between" characters X
1688 1745 and Y is equivalent to the cursor being "on" character Y, that is to say
1689 1746 the character the cursor is on is considered as being after the cursor.
1690 1747
1691 1748 Combining characters may span more that one position in the
1692 1749 text.
1693 1750
1694 1751
1695 1752 .. note::
1696 1753
1697 1754 If ``IPCompleter.debug`` is :any:`True` will yield a ``--jedi/ipython--``
1698 1755 fake Completion token to distinguish completion returned by Jedi
1699 1756 and usual IPython completion.
1700 1757
1701 1758 .. note::
1702 1759
1703 1760 Completions are not completely deduplicated yet. If identical
1704 1761 completions are coming from different sources this function does not
1705 1762 ensure that each completion object will only be present once.
1706 1763 """
1707 1764 warnings.warn("_complete is a provisional API (as of IPython 6.0). "
1708 1765 "It may change without warnings. "
1709 1766 "Use in corresponding context manager.",
1710 1767 category=ProvisionalCompleterWarning, stacklevel=2)
1711 1768
1712 1769 seen = set()
1713 1770 for c in self._completions(text, offset, _timeout=self.jedi_compute_type_timeout/1000):
1714 1771 if c and (c in seen):
1715 1772 continue
1716 1773 yield c
1717 1774 seen.add(c)
1718 1775
1719 1776 def _completions(self, full_text: str, offset: int, *, _timeout)->Iterator[Completion]:
1720 1777 """
1721 1778 Core completion module.Same signature as :any:`completions`, with the
1722 1779 extra `timeout` parameter (in seconds).
1723 1780
1724 1781
1725 1782 Computing jedi's completion ``.type`` can be quite expensive (it is a
1726 1783 lazy property) and can require some warm-up, more warm up than just
1727 1784 computing the ``name`` of a completion. The warm-up can be :
1728 1785
1729 1786 - Long warm-up the first time a module is encountered after
1730 1787 install/update: actually build parse/inference tree.
1731 1788
1732 1789 - first time the module is encountered in a session: load tree from
1733 1790 disk.
1734 1791
1735 1792 We don't want to block completions for tens of seconds so we give the
1736 1793 completer a "budget" of ``_timeout`` seconds per invocation to compute
1737 1794 completions types, the completions that have not yet been computed will
1738 1795 be marked as "unknown" an will have a chance to be computed next round
1739 1796 are things get cached.
1740 1797
1741 1798 Keep in mind that Jedi is not the only thing treating the completion so
1742 1799 keep the timeout short-ish as if we take more than 0.3 second we still
1743 1800 have lots of processing to do.
1744 1801
1745 1802 """
1746 1803 deadline = time.monotonic() + _timeout
1747 1804
1748 1805
1749 1806 before = full_text[:offset]
1750 1807 cursor_line, cursor_column = position_to_cursor(full_text, offset)
1751 1808
1752 1809 matched_text, matches, matches_origin, jedi_matches = self._complete(
1753 1810 full_text=full_text, cursor_line=cursor_line, cursor_pos=cursor_column)
1754 1811
1755 1812 iter_jm = iter(jedi_matches)
1756 1813 if _timeout:
1757 1814 for jm in iter_jm:
1758 1815 try:
1759 1816 type_ = jm.type
1760 1817 except Exception:
1761 1818 if self.debug:
1762 1819 print("Error in Jedi getting type of ", jm)
1763 1820 type_ = None
1764 1821 delta = len(jm.name_with_symbols) - len(jm.complete)
1822 if type_ == 'function':
1823 signature = _make_signature(jm)
1824 else:
1825 signature = ''
1765 1826 yield Completion(start=offset - delta,
1766 1827 end=offset,
1767 1828 text=jm.name_with_symbols,
1768 1829 type=type_,
1830 signature=signature,
1769 1831 _origin='jedi')
1770 1832
1771 1833 if time.monotonic() > deadline:
1772 1834 break
1773 1835
1774 1836 for jm in iter_jm:
1775 1837 delta = len(jm.name_with_symbols) - len(jm.complete)
1776 1838 yield Completion(start=offset - delta,
1777 1839 end=offset,
1778 1840 text=jm.name_with_symbols,
1779 1841 type='<unknown>', # don't compute type for speed
1780 _origin='jedi')
1842 _origin='jedi',
1843 signature='')
1781 1844
1782 1845
1783 1846 start_offset = before.rfind(matched_text)
1784 1847
1785 1848 # TODO:
1786 1849 # Supress this, right now just for debug.
1787 1850 if jedi_matches and matches and self.debug:
1788 yield Completion(start=start_offset, end=offset, text='--jedi/ipython--', _origin='debug')
1851 yield Completion(start=start_offset, end=offset, text='--jedi/ipython--',
1852 _origin='debug', type='none', signature='')
1789 1853
1790 1854 # I'm unsure if this is always true, so let's assert and see if it
1791 1855 # crash
1792 1856 assert before.endswith(matched_text)
1793 1857 for m, t in zip(matches, matches_origin):
1794 yield Completion(start=start_offset, end=offset, text=m, _origin=t)
1858 yield Completion(start=start_offset, end=offset, text=m, _origin=t, signature='', type='<unknown>')
1795 1859
1796 1860
1797 1861 def complete(self, text=None, line_buffer=None, cursor_pos=None):
1798 1862 """Find completions for the given text and line context.
1799 1863
1800 1864 Note that both the text and the line_buffer are optional, but at least
1801 1865 one of them must be given.
1802 1866
1803 1867 Parameters
1804 1868 ----------
1805 1869 text : string, optional
1806 1870 Text to perform the completion on. If not given, the line buffer
1807 1871 is split using the instance's CompletionSplitter object.
1808 1872
1809 1873 line_buffer : string, optional
1810 1874 If not given, the completer attempts to obtain the current line
1811 1875 buffer via readline. This keyword allows clients which are
1812 1876 requesting for text completions in non-readline contexts to inform
1813 1877 the completer of the entire text.
1814 1878
1815 1879 cursor_pos : int, optional
1816 1880 Index of the cursor in the full line buffer. Should be provided by
1817 1881 remote frontends where kernel has no access to frontend state.
1818 1882
1819 1883 Returns
1820 1884 -------
1821 1885 text : str
1822 1886 Text that was actually used in the completion.
1823 1887
1824 1888 matches : list
1825 1889 A list of completion matches.
1826 1890
1827 1891
1828 1892 .. note::
1829 1893
1830 1894 This API is likely to be deprecated and replaced by
1831 1895 :any:`IPCompleter.completions` in the future.
1832 1896
1833 1897
1834 1898 """
1835 1899 warnings.warn('`Completer.complete` is pending deprecation since '
1836 1900 'IPython 6.0 and will be replaced by `Completer.completions`.',
1837 1901 PendingDeprecationWarning)
1838 1902 # potential todo, FOLD the 3rd throw away argument of _complete
1839 1903 # into the first 2 one.
1840 1904 return self._complete(line_buffer=line_buffer, cursor_pos=cursor_pos, text=text, cursor_line=0)[:2]
1841 1905
1842 1906 def _complete(self, *, cursor_line, cursor_pos, line_buffer=None, text=None,
1843 1907 full_text=None, return_jedi_results=True) -> Tuple[str, List[str], List[str], Iterable[_FakeJediCompletion]]:
1844 1908 """
1845 1909
1846 1910 Like complete but can also returns raw jedi completions as well as the
1847 1911 origin of the completion text. This could (and should) be made much
1848 1912 cleaner but that will be simpler once we drop the old (and stateful)
1849 1913 :any:`complete` API.
1850 1914
1851 1915
1852 1916 With current provisional API, cursor_pos act both (depending on the
1853 1917 caller) as the offset in the ``text`` or ``line_buffer``, or as the
1854 1918 ``column`` when passing multiline strings this could/should be renamed
1855 1919 but would add extra noise.
1856 1920 """
1857 1921
1858 1922 # if the cursor position isn't given, the only sane assumption we can
1859 1923 # make is that it's at the end of the line (the common case)
1860 1924 if cursor_pos is None:
1861 1925 cursor_pos = len(line_buffer) if text is None else len(text)
1862 1926
1863 1927 if self.use_main_ns:
1864 1928 self.namespace = __main__.__dict__
1865 1929
1866 1930 # if text is either None or an empty string, rely on the line buffer
1867 1931 if (not line_buffer) and full_text:
1868 1932 line_buffer = full_text.split('\n')[cursor_line]
1869 1933 if not text:
1870 1934 text = self.splitter.split_line(line_buffer, cursor_pos)
1871 1935
1872 1936 if self.backslash_combining_completions:
1873 1937 # allow deactivation of these on windows.
1874 1938 base_text = text if not line_buffer else line_buffer[:cursor_pos]
1875 1939 latex_text, latex_matches = self.latex_matches(base_text)
1876 1940 if latex_matches:
1877 1941 return latex_text, latex_matches, ['latex_matches']*len(latex_matches), ()
1878 1942 name_text = ''
1879 1943 name_matches = []
1880 1944 for meth in (self.unicode_name_matches, back_latex_name_matches, back_unicode_name_matches):
1881 1945 name_text, name_matches = meth(base_text)
1882 1946 if name_text:
1883 1947 return name_text, name_matches, [meth.__qualname__]*len(name_matches), ()
1884 1948
1885 1949
1886 1950 # If no line buffer is given, assume the input text is all there was
1887 1951 if line_buffer is None:
1888 1952 line_buffer = text
1889 1953
1890 1954 self.line_buffer = line_buffer
1891 1955 self.text_until_cursor = self.line_buffer[:cursor_pos]
1892 1956
1893 1957 # Do magic arg matches
1894 1958 for matcher in self.magic_arg_matchers:
1895 1959 matches = [(m, matcher.__qualname__) for m in matcher(line_buffer)]
1896 1960 if matches:
1897 1961 matches2 = [m[0] for m in matches]
1898 1962 origins = [m[1] for m in matches]
1899 1963 return text, matches2, origins, ()
1900 1964
1901 1965 # Start with a clean slate of completions
1902 1966 matches = []
1903 1967 custom_res = self.dispatch_custom_completer(text)
1904 1968 # FIXME: we should extend our api to return a dict with completions for
1905 1969 # different types of objects. The rlcomplete() method could then
1906 1970 # simply collapse the dict into a list for readline, but we'd have
1907 1971 # richer completion semantics in other evironments.
1908 1972 completions = ()
1909 1973 if self.use_jedi and return_jedi_results:
1910 1974 if not full_text:
1911 1975 full_text = line_buffer
1912 1976 completions = self._jedi_matches(
1913 1977 cursor_pos, cursor_line, full_text)
1914 1978 if custom_res is not None:
1915 1979 # did custom completers produce something?
1916 1980 matches = [(m, 'custom') for m in custom_res]
1917 1981 else:
1918 1982 # Extend the list of completions with the results of each
1919 1983 # matcher, so we return results to the user from all
1920 1984 # namespaces.
1921 1985 if self.merge_completions:
1922 1986 matches = []
1923 1987 for matcher in self.matchers:
1924 1988 try:
1925 1989 matches.extend([(m, matcher.__qualname__)
1926 1990 for m in matcher(text)])
1927 1991 except:
1928 1992 # Show the ugly traceback if the matcher causes an
1929 1993 # exception, but do NOT crash the kernel!
1930 1994 sys.excepthook(*sys.exc_info())
1931 1995 else:
1932 1996 for matcher in self.matchers:
1933 1997 matches = [(m, matcher.__qualname__)
1934 1998 for m in matcher(text)]
1935 1999 if matches:
1936 2000 break
1937 2001 seen = set()
1938 2002 filtered_matches = set()
1939 2003 for m in matches:
1940 2004 t, c = m
1941 2005 if t not in seen:
1942 2006 filtered_matches.add(m)
1943 2007 seen.add(t)
1944 2008
1945 2009 _filtered_matches = sorted(
1946 2010 set(filtered_matches), key=lambda x: completions_sorting_key(x[0]))
1947 2011
1948 2012 _matches = [m[0] for m in _filtered_matches]
1949 2013 origins = [m[1] for m in _filtered_matches]
1950 2014
1951 2015 self.matches = _matches
1952 2016
1953 2017 return text, _matches, origins, completions
@@ -1,352 +1,354 b''
1 1 # encoding: utf-8
2 2 """Implementations for various useful completers.
3 3
4 4 These are all loaded by default by IPython.
5 5 """
6 6 #-----------------------------------------------------------------------------
7 7 # Copyright (C) 2010-2011 The IPython Development Team.
8 8 #
9 9 # Distributed under the terms of the BSD License.
10 10 #
11 11 # The full license is in the file COPYING.txt, distributed with this software.
12 12 #-----------------------------------------------------------------------------
13 13
14 14 #-----------------------------------------------------------------------------
15 15 # Imports
16 16 #-----------------------------------------------------------------------------
17 17
18 18 # Stdlib imports
19 19 import glob
20 20 import inspect
21 21 import os
22 22 import re
23 23 import sys
24 24 from importlib import import_module
25 25 from importlib.machinery import all_suffixes
26 26
27 27
28 28 # Third-party imports
29 29 from time import time
30 30 from zipimport import zipimporter
31 31
32 32 # Our own imports
33 33 from IPython.core.completer import expand_user, compress_user
34 34 from IPython.core.error import TryNext
35 35 from IPython.utils._process_common import arg_split
36 36
37 37 # FIXME: this should be pulled in with the right call via the component system
38 38 from IPython import get_ipython
39 39
40 from typing import List
41
40 42 #-----------------------------------------------------------------------------
41 43 # Globals and constants
42 44 #-----------------------------------------------------------------------------
43 45 _suffixes = all_suffixes()
44 46
45 47 # Time in seconds after which the rootmodules will be stored permanently in the
46 48 # ipython ip.db database (kept in the user's .ipython dir).
47 49 TIMEOUT_STORAGE = 2
48 50
49 51 # Time in seconds after which we give up
50 52 TIMEOUT_GIVEUP = 20
51 53
52 54 # Regular expression for the python import statement
53 55 import_re = re.compile(r'(?P<name>[a-zA-Z_][a-zA-Z0-9_]*?)'
54 56 r'(?P<package>[/\\]__init__)?'
55 57 r'(?P<suffix>%s)$' %
56 58 r'|'.join(re.escape(s) for s in _suffixes))
57 59
58 60 # RE for the ipython %run command (python + ipython scripts)
59 61 magic_run_re = re.compile(r'.*(\.ipy|\.ipynb|\.py[w]?)$')
60 62
61 63 #-----------------------------------------------------------------------------
62 64 # Local utilities
63 65 #-----------------------------------------------------------------------------
64 66
65 67 def module_list(path):
66 68 """
67 69 Return the list containing the names of the modules available in the given
68 70 folder.
69 71 """
70 72 # sys.path has the cwd as an empty string, but isdir/listdir need it as '.'
71 73 if path == '':
72 74 path = '.'
73 75
74 76 # A few local constants to be used in loops below
75 77 pjoin = os.path.join
76 78
77 79 if os.path.isdir(path):
78 80 # Build a list of all files in the directory and all files
79 81 # in its subdirectories. For performance reasons, do not
80 82 # recurse more than one level into subdirectories.
81 83 files = []
82 84 for root, dirs, nondirs in os.walk(path, followlinks=True):
83 85 subdir = root[len(path)+1:]
84 86 if subdir:
85 87 files.extend(pjoin(subdir, f) for f in nondirs)
86 88 dirs[:] = [] # Do not recurse into additional subdirectories.
87 89 else:
88 90 files.extend(nondirs)
89 91
90 92 else:
91 93 try:
92 94 files = list(zipimporter(path)._files.keys())
93 95 except:
94 96 files = []
95 97
96 98 # Build a list of modules which match the import_re regex.
97 99 modules = []
98 100 for f in files:
99 101 m = import_re.match(f)
100 102 if m:
101 103 modules.append(m.group('name'))
102 104 return list(set(modules))
103 105
104 106
105 107 def get_root_modules():
106 108 """
107 109 Returns a list containing the names of all the modules available in the
108 110 folders of the pythonpath.
109 111
110 112 ip.db['rootmodules_cache'] maps sys.path entries to list of modules.
111 113 """
112 114 ip = get_ipython()
113 115 if ip is None:
114 116 # No global shell instance to store cached list of modules.
115 117 # Don't try to scan for modules every time.
116 118 return list(sys.builtin_module_names)
117 119
118 120 rootmodules_cache = ip.db.get('rootmodules_cache', {})
119 121 rootmodules = list(sys.builtin_module_names)
120 122 start_time = time()
121 123 store = False
122 124 for path in sys.path:
123 125 try:
124 126 modules = rootmodules_cache[path]
125 127 except KeyError:
126 128 modules = module_list(path)
127 129 try:
128 130 modules.remove('__init__')
129 131 except ValueError:
130 132 pass
131 133 if path not in ('', '.'): # cwd modules should not be cached
132 134 rootmodules_cache[path] = modules
133 135 if time() - start_time > TIMEOUT_STORAGE and not store:
134 136 store = True
135 137 print("\nCaching the list of root modules, please wait!")
136 138 print("(This will only be done once - type '%rehashx' to "
137 139 "reset cache!)\n")
138 140 sys.stdout.flush()
139 141 if time() - start_time > TIMEOUT_GIVEUP:
140 142 print("This is taking too long, we give up.\n")
141 143 return []
142 144 rootmodules.extend(modules)
143 145 if store:
144 146 ip.db['rootmodules_cache'] = rootmodules_cache
145 147 rootmodules = list(set(rootmodules))
146 148 return rootmodules
147 149
148 150
149 151 def is_importable(module, attr, only_modules):
150 152 if only_modules:
151 153 return inspect.ismodule(getattr(module, attr))
152 154 else:
153 155 return not(attr[:2] == '__' and attr[-2:] == '__')
154 156
155 157
156 def try_import(mod: str, only_modules=False):
158 def try_import(mod: str, only_modules=False) -> List[str]:
157 159 """
158 160 Try to import given module and return list of potential completions.
159 161 """
160 162 mod = mod.rstrip('.')
161 163 try:
162 164 m = import_module(mod)
163 165 except:
164 166 return []
165 167
166 168 m_is_init = hasattr(m, '__file__') and '__init__' in m.__file__
167 169
168 170 completions = []
169 171 if (not hasattr(m, '__file__')) or (not only_modules) or m_is_init:
170 172 completions.extend( [attr for attr in dir(m) if
171 173 is_importable(m, attr, only_modules)])
172 174
173 175 completions.extend(getattr(m, '__all__', []))
174 176 if m_is_init:
175 177 completions.extend(module_list(os.path.dirname(m.__file__)))
176 completions = {c for c in completions if isinstance(c, str)}
177 completions.discard('__init__')
178 return list(completions)
178 completions_set = {c for c in completions if isinstance(c, str)}
179 completions_set.discard('__init__')
180 return list(completions_set)
179 181
180 182
181 183 #-----------------------------------------------------------------------------
182 184 # Completion-related functions.
183 185 #-----------------------------------------------------------------------------
184 186
185 187 def quick_completer(cmd, completions):
186 188 """ Easily create a trivial completer for a command.
187 189
188 190 Takes either a list of completions, or all completions in string (that will
189 191 be split on whitespace).
190 192
191 193 Example::
192 194
193 195 [d:\ipython]|1> import ipy_completers
194 196 [d:\ipython]|2> ipy_completers.quick_completer('foo', ['bar','baz'])
195 197 [d:\ipython]|3> foo b<TAB>
196 198 bar baz
197 199 [d:\ipython]|3> foo ba
198 200 """
199 201
200 202 if isinstance(completions, str):
201 203 completions = completions.split()
202 204
203 205 def do_complete(self, event):
204 206 return completions
205 207
206 208 get_ipython().set_hook('complete_command',do_complete, str_key = cmd)
207 209
208 210 def module_completion(line):
209 211 """
210 212 Returns a list containing the completion possibilities for an import line.
211 213
212 214 The line looks like this :
213 215 'import xml.d'
214 216 'from xml.dom import'
215 217 """
216 218
217 219 words = line.split(' ')
218 220 nwords = len(words)
219 221
220 222 # from whatever <tab> -> 'import '
221 223 if nwords == 3 and words[0] == 'from':
222 224 return ['import ']
223 225
224 226 # 'from xy<tab>' or 'import xy<tab>'
225 227 if nwords < 3 and (words[0] in {'%aimport', 'import', 'from'}) :
226 228 if nwords == 1:
227 229 return get_root_modules()
228 230 mod = words[1].split('.')
229 231 if len(mod) < 2:
230 232 return get_root_modules()
231 233 completion_list = try_import('.'.join(mod[:-1]), True)
232 234 return ['.'.join(mod[:-1] + [el]) for el in completion_list]
233 235
234 236 # 'from xyz import abc<tab>'
235 237 if nwords >= 3 and words[0] == 'from':
236 238 mod = words[1]
237 239 return try_import(mod)
238 240
239 241 #-----------------------------------------------------------------------------
240 242 # Completers
241 243 #-----------------------------------------------------------------------------
242 244 # These all have the func(self, event) signature to be used as custom
243 245 # completers
244 246
245 247 def module_completer(self,event):
246 248 """Give completions after user has typed 'import ...' or 'from ...'"""
247 249
248 250 # This works in all versions of python. While 2.5 has
249 251 # pkgutil.walk_packages(), that particular routine is fairly dangerous,
250 252 # since it imports *EVERYTHING* on sys.path. That is: a) very slow b) full
251 253 # of possibly problematic side effects.
252 254 # This search the folders in the sys.path for available modules.
253 255
254 256 return module_completion(event.line)
255 257
256 258 # FIXME: there's a lot of logic common to the run, cd and builtin file
257 259 # completers, that is currently reimplemented in each.
258 260
259 261 def magic_run_completer(self, event):
260 262 """Complete files that end in .py or .ipy or .ipynb for the %run command.
261 263 """
262 264 comps = arg_split(event.line, strict=False)
263 265 # relpath should be the current token that we need to complete.
264 266 if (len(comps) > 1) and (not event.line.endswith(' ')):
265 267 relpath = comps[-1].strip("'\"")
266 268 else:
267 269 relpath = ''
268 270
269 271 #print("\nev=", event) # dbg
270 272 #print("rp=", relpath) # dbg
271 273 #print('comps=', comps) # dbg
272 274
273 275 lglob = glob.glob
274 276 isdir = os.path.isdir
275 277 relpath, tilde_expand, tilde_val = expand_user(relpath)
276 278
277 279 # Find if the user has already typed the first filename, after which we
278 280 # should complete on all files, since after the first one other files may
279 281 # be arguments to the input script.
280 282
281 283 if any(magic_run_re.match(c) for c in comps):
282 284 matches = [f.replace('\\','/') + ('/' if isdir(f) else '')
283 285 for f in lglob(relpath+'*')]
284 286 else:
285 287 dirs = [f.replace('\\','/') + "/" for f in lglob(relpath+'*') if isdir(f)]
286 288 pys = [f.replace('\\','/')
287 289 for f in lglob(relpath+'*.py') + lglob(relpath+'*.ipy') +
288 290 lglob(relpath+'*.ipynb') + lglob(relpath + '*.pyw')]
289 291
290 292 matches = dirs + pys
291 293
292 294 #print('run comp:', dirs+pys) # dbg
293 295 return [compress_user(p, tilde_expand, tilde_val) for p in matches]
294 296
295 297
296 298 def cd_completer(self, event):
297 299 """Completer function for cd, which only returns directories."""
298 300 ip = get_ipython()
299 301 relpath = event.symbol
300 302
301 303 #print(event) # dbg
302 304 if event.line.endswith('-b') or ' -b ' in event.line:
303 305 # return only bookmark completions
304 306 bkms = self.db.get('bookmarks', None)
305 307 if bkms:
306 308 return bkms.keys()
307 309 else:
308 310 return []
309 311
310 312 if event.symbol == '-':
311 313 width_dh = str(len(str(len(ip.user_ns['_dh']) + 1)))
312 314 # jump in directory history by number
313 315 fmt = '-%0' + width_dh +'d [%s]'
314 316 ents = [ fmt % (i,s) for i,s in enumerate(ip.user_ns['_dh'])]
315 317 if len(ents) > 1:
316 318 return ents
317 319 return []
318 320
319 321 if event.symbol.startswith('--'):
320 322 return ["--" + os.path.basename(d) for d in ip.user_ns['_dh']]
321 323
322 324 # Expand ~ in path and normalize directory separators.
323 325 relpath, tilde_expand, tilde_val = expand_user(relpath)
324 326 relpath = relpath.replace('\\','/')
325 327
326 328 found = []
327 329 for d in [f.replace('\\','/') + '/' for f in glob.glob(relpath+'*')
328 330 if os.path.isdir(f)]:
329 331 if ' ' in d:
330 332 # we don't want to deal with any of that, complex code
331 333 # for this is elsewhere
332 334 raise TryNext
333 335
334 336 found.append(d)
335 337
336 338 if not found:
337 339 if os.path.isdir(relpath):
338 340 return [compress_user(relpath, tilde_expand, tilde_val)]
339 341
340 342 # if no completions so far, try bookmarks
341 343 bks = self.db.get('bookmarks',{})
342 344 bkmatches = [s for s in bks if s.startswith(event.symbol)]
343 345 if bkmatches:
344 346 return bkmatches
345 347
346 348 raise TryNext
347 349
348 350 return [compress_user(p, tilde_expand, tilde_val) for p in found]
349 351
350 352 def reset_completer(self, event):
351 353 "A completer for %reset magic"
352 354 return '-f -s in out array dhist'.split()
@@ -1,949 +1,961 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 textwrap
10 10 import unittest
11 11
12 12 from contextlib import contextmanager
13 13
14 14 import nose.tools as nt
15 15
16 16 from traitlets.config.loader import Config
17 17 from IPython import get_ipython
18 18 from IPython.core import completer
19 19 from IPython.external.decorators import knownfailureif
20 20 from IPython.utils.tempdir import TemporaryDirectory, TemporaryWorkingDirectory
21 21 from IPython.utils.generics import complete_object
22 22 from IPython.testing import decorators as dec
23 23
24 24 from IPython.core.completer import (
25 25 Completion, provisionalcompleter, match_dict_keys, _deduplicate_completions)
26 26 from nose.tools import assert_in, assert_not_in
27 27
28 28 #-----------------------------------------------------------------------------
29 29 # Test functions
30 30 #-----------------------------------------------------------------------------
31 31
32 32 @contextmanager
33 33 def greedy_completion():
34 34 ip = get_ipython()
35 35 greedy_original = ip.Completer.greedy
36 36 try:
37 37 ip.Completer.greedy = True
38 38 yield
39 39 finally:
40 40 ip.Completer.greedy = greedy_original
41 41
42 42 def test_protect_filename():
43 43 if sys.platform == 'win32':
44 44 pairs = [('abc','abc'),
45 45 (' abc','" abc"'),
46 46 ('a bc','"a bc"'),
47 47 ('a bc','"a bc"'),
48 48 (' bc','" bc"'),
49 49 ]
50 50 else:
51 51 pairs = [('abc','abc'),
52 52 (' abc',r'\ abc'),
53 53 ('a bc',r'a\ bc'),
54 54 ('a bc',r'a\ \ bc'),
55 55 (' bc',r'\ \ bc'),
56 56 # On posix, we also protect parens and other special characters.
57 57 ('a(bc',r'a\(bc'),
58 58 ('a)bc',r'a\)bc'),
59 59 ('a( )bc',r'a\(\ \)bc'),
60 60 ('a[1]bc', r'a\[1\]bc'),
61 61 ('a{1}bc', r'a\{1\}bc'),
62 62 ('a#bc', r'a\#bc'),
63 63 ('a?bc', r'a\?bc'),
64 64 ('a=bc', r'a\=bc'),
65 65 ('a\\bc', r'a\\bc'),
66 66 ('a|bc', r'a\|bc'),
67 67 ('a;bc', r'a\;bc'),
68 68 ('a:bc', r'a\:bc'),
69 69 ("a'bc", r"a\'bc"),
70 70 ('a*bc', r'a\*bc'),
71 71 ('a"bc', r'a\"bc'),
72 72 ('a^bc', r'a\^bc'),
73 73 ('a&bc', r'a\&bc'),
74 74 ]
75 75 # run the actual tests
76 76 for s1, s2 in pairs:
77 77 s1p = completer.protect_filename(s1)
78 78 nt.assert_equal(s1p, s2)
79 79
80 80
81 81 def check_line_split(splitter, test_specs):
82 82 for part1, part2, split in test_specs:
83 83 cursor_pos = len(part1)
84 84 line = part1+part2
85 85 out = splitter.split_line(line, cursor_pos)
86 86 nt.assert_equal(out, split)
87 87
88 88
89 89 def test_line_split():
90 90 """Basic line splitter test with default specs."""
91 91 sp = completer.CompletionSplitter()
92 92 # The format of the test specs is: part1, part2, expected answer. Parts 1
93 93 # and 2 are joined into the 'line' sent to the splitter, as if the cursor
94 94 # was at the end of part1. So an empty part2 represents someone hitting
95 95 # tab at the end of the line, the most common case.
96 96 t = [('run some/scrip', '', 'some/scrip'),
97 97 ('run scripts/er', 'ror.py foo', 'scripts/er'),
98 98 ('echo $HOM', '', 'HOM'),
99 99 ('print sys.pa', '', 'sys.pa'),
100 100 ('print(sys.pa', '', 'sys.pa'),
101 101 ("execfile('scripts/er", '', 'scripts/er'),
102 102 ('a[x.', '', 'x.'),
103 103 ('a[x.', 'y', 'x.'),
104 104 ('cd "some_file/', '', 'some_file/'),
105 105 ]
106 106 check_line_split(sp, t)
107 107 # Ensure splitting works OK with unicode by re-running the tests with
108 108 # all inputs turned into unicode
109 109 check_line_split(sp, [ map(str, p) for p in t] )
110 110
111 111
112 112 def test_custom_completion_error():
113 113 """Test that errors from custom attribute completers are silenced."""
114 114 ip = get_ipython()
115 115 class A(object): pass
116 116 ip.user_ns['a'] = A()
117 117
118 118 @complete_object.when_type(A)
119 119 def complete_A(a, existing_completions):
120 120 raise TypeError("this should be silenced")
121 121
122 122 ip.complete("a.")
123 123
124 124
125 125 def test_unicode_completions():
126 126 ip = get_ipython()
127 127 # Some strings that trigger different types of completion. Check them both
128 128 # in str and unicode forms
129 129 s = ['ru', '%ru', 'cd /', 'floa', 'float(x)/']
130 130 for t in s + list(map(str, s)):
131 131 # We don't need to check exact completion values (they may change
132 132 # depending on the state of the namespace, but at least no exceptions
133 133 # should be thrown and the return value should be a pair of text, list
134 134 # values.
135 135 text, matches = ip.complete(t)
136 136 nt.assert_true(isinstance(text, str))
137 137 nt.assert_true(isinstance(matches, list))
138 138
139 139 def test_latex_completions():
140 140 from IPython.core.latex_symbols import latex_symbols
141 141 import random
142 142 ip = get_ipython()
143 143 # Test some random unicode symbols
144 144 keys = random.sample(latex_symbols.keys(), 10)
145 145 for k in keys:
146 146 text, matches = ip.complete(k)
147 147 nt.assert_equal(len(matches),1)
148 148 nt.assert_equal(text, k)
149 149 nt.assert_equal(matches[0], latex_symbols[k])
150 150 # Test a more complex line
151 151 text, matches = ip.complete(u'print(\\alpha')
152 152 nt.assert_equal(text, u'\\alpha')
153 153 nt.assert_equal(matches[0], latex_symbols['\\alpha'])
154 154 # Test multiple matching latex symbols
155 155 text, matches = ip.complete(u'\\al')
156 156 nt.assert_in('\\alpha', matches)
157 157 nt.assert_in('\\aleph', matches)
158 158
159 159
160 160
161 161
162 162 def test_back_latex_completion():
163 163 ip = get_ipython()
164 164
165 165 # do not return more than 1 matches fro \beta, only the latex one.
166 166 name, matches = ip.complete('\\Ξ²')
167 167 nt.assert_equal(len(matches), 1)
168 168 nt.assert_equal(matches[0], '\\beta')
169 169
170 170 def test_back_unicode_completion():
171 171 ip = get_ipython()
172 172
173 173 name, matches = ip.complete('\\β…€')
174 174 nt.assert_equal(len(matches), 1)
175 175 nt.assert_equal(matches[0], '\\ROMAN NUMERAL FIVE')
176 176
177 177
178 178 def test_forward_unicode_completion():
179 179 ip = get_ipython()
180 180
181 181 name, matches = ip.complete('\\ROMAN NUMERAL FIVE')
182 182 nt.assert_equal(len(matches), 1)
183 183 nt.assert_equal(matches[0], 'β…€')
184 184
185 185 @dec.knownfailureif(sys.platform == 'win32', 'Fails if there is a C:\\j... path')
186 186 def test_no_ascii_back_completion():
187 187 ip = get_ipython()
188 188 with TemporaryWorkingDirectory(): # Avoid any filename completions
189 189 # single ascii letter that don't have yet completions
190 190 for letter in 'jJ' :
191 191 name, matches = ip.complete('\\'+letter)
192 192 nt.assert_equal(matches, [])
193 193
194 194
195 195
196 196
197 197 class CompletionSplitterTestCase(unittest.TestCase):
198 198 def setUp(self):
199 199 self.sp = completer.CompletionSplitter()
200 200
201 201 def test_delim_setting(self):
202 202 self.sp.delims = ' '
203 203 nt.assert_equal(self.sp.delims, ' ')
204 204 nt.assert_equal(self.sp._delim_expr, '[\ ]')
205 205
206 206 def test_spaces(self):
207 207 """Test with only spaces as split chars."""
208 208 self.sp.delims = ' '
209 209 t = [('foo', '', 'foo'),
210 210 ('run foo', '', 'foo'),
211 211 ('run foo', 'bar', 'foo'),
212 212 ]
213 213 check_line_split(self.sp, t)
214 214
215 215
216 216 def test_has_open_quotes1():
217 217 for s in ["'", "'''", "'hi' '"]:
218 218 nt.assert_equal(completer.has_open_quotes(s), "'")
219 219
220 220
221 221 def test_has_open_quotes2():
222 222 for s in ['"', '"""', '"hi" "']:
223 223 nt.assert_equal(completer.has_open_quotes(s), '"')
224 224
225 225
226 226 def test_has_open_quotes3():
227 227 for s in ["''", "''' '''", "'hi' 'ipython'"]:
228 228 nt.assert_false(completer.has_open_quotes(s))
229 229
230 230
231 231 def test_has_open_quotes4():
232 232 for s in ['""', '""" """', '"hi" "ipython"']:
233 233 nt.assert_false(completer.has_open_quotes(s))
234 234
235 235
236 236 @knownfailureif(sys.platform == 'win32', "abspath completions fail on Windows")
237 237 def test_abspath_file_completions():
238 238 ip = get_ipython()
239 239 with TemporaryDirectory() as tmpdir:
240 240 prefix = os.path.join(tmpdir, 'foo')
241 241 suffixes = ['1', '2']
242 242 names = [prefix+s for s in suffixes]
243 243 for n in names:
244 244 open(n, 'w').close()
245 245
246 246 # Check simple completion
247 247 c = ip.complete(prefix)[1]
248 248 nt.assert_equal(c, names)
249 249
250 250 # Now check with a function call
251 251 cmd = 'a = f("%s' % prefix
252 252 c = ip.complete(prefix, cmd)[1]
253 253 comp = [prefix+s for s in suffixes]
254 254 nt.assert_equal(c, comp)
255 255
256 256
257 257 def test_local_file_completions():
258 258 ip = get_ipython()
259 259 with TemporaryWorkingDirectory():
260 260 prefix = './foo'
261 261 suffixes = ['1', '2']
262 262 names = [prefix+s for s in suffixes]
263 263 for n in names:
264 264 open(n, 'w').close()
265 265
266 266 # Check simple completion
267 267 c = ip.complete(prefix)[1]
268 268 nt.assert_equal(c, names)
269 269
270 270 # Now check with a function call
271 271 cmd = 'a = f("%s' % prefix
272 272 c = ip.complete(prefix, cmd)[1]
273 273 comp = set(prefix+s for s in suffixes)
274 274 nt.assert_true(comp.issubset(set(c)))
275 275
276 276
277 277 def test_quoted_file_completions():
278 278 ip = get_ipython()
279 279 with TemporaryWorkingDirectory():
280 280 name = "foo'bar"
281 281 open(name, 'w').close()
282 282
283 283 # Don't escape Windows
284 284 escaped = name if sys.platform == "win32" else "foo\\'bar"
285 285
286 286 # Single quote matches embedded single quote
287 287 text = "open('foo"
288 288 c = ip.Completer._complete(cursor_line=0,
289 289 cursor_pos=len(text),
290 290 full_text=text)[1]
291 291 nt.assert_equal(c, [escaped])
292 292
293 293 # Double quote requires no escape
294 294 text = 'open("foo'
295 295 c = ip.Completer._complete(cursor_line=0,
296 296 cursor_pos=len(text),
297 297 full_text=text)[1]
298 298 nt.assert_equal(c, [name])
299 299
300 300 # No quote requires an escape
301 301 text = '%ls foo'
302 302 c = ip.Completer._complete(cursor_line=0,
303 303 cursor_pos=len(text),
304 304 full_text=text)[1]
305 305 nt.assert_equal(c, [escaped])
306 306
307 307
308 308 def test_jedi():
309 309 """
310 310 A couple of issue we had with Jedi
311 311 """
312 312 ip = get_ipython()
313 313
314 314 def _test_complete(reason, s, comp, start=None, end=None):
315 315 l = len(s)
316 316 start = start if start is not None else l
317 317 end = end if end is not None else l
318 318 with provisionalcompleter():
319 319 completions = set(ip.Completer.completions(s, l))
320 320 assert_in(Completion(start, end, comp), completions, reason)
321 321
322 322 def _test_not_complete(reason, s, comp):
323 323 l = len(s)
324 324 with provisionalcompleter():
325 325 completions = set(ip.Completer.completions(s, l))
326 326 assert_not_in(Completion(l, l, comp), completions, reason)
327 327
328 328 import jedi
329 329 jedi_version = tuple(int(i) for i in jedi.__version__.split('.')[:3])
330 330 if jedi_version > (0, 10):
331 331 yield _test_complete, 'jedi >0.9 should complete and not crash', 'a=1;a.', 'real'
332 332 yield _test_complete, 'can infer first argument', 'a=(1,"foo");a[0].', 'real'
333 333 yield _test_complete, 'can infer second argument', 'a=(1,"foo");a[1].', 'capitalize'
334 334 yield _test_complete, 'cover duplicate completions', 'im', 'import', 0, 2
335 335
336 336 yield _test_not_complete, 'does not mix types', 'a=(1,"foo");a[0].', 'capitalize'
337 337
338 def test_completion_have_signature():
339 """
340 Lets make sure jedi is capable of pulling out the signature of the function we are completing.
341 """
342 ip = get_ipython()
343 with provisionalcompleter():
344 completions = ip.Completer.completions('ope', 3)
345 c = next(completions) # should be `open`
346 assert 'file' in c.signature, "Signature of function was not found by completer"
347 assert 'encoding' in c.signature, "Signature of function was not found by completer"
348
349
338 350 def test_deduplicate_completions():
339 351 """
340 352 Test that completions are correctly deduplicated (even if ranges are not the same)
341 353 """
342 354 ip = get_ipython()
343 355 ip.ex(textwrap.dedent('''
344 356 class Z:
345 357 zoo = 1
346 358 '''))
347 359 with provisionalcompleter():
348 360 l = list(_deduplicate_completions('Z.z', ip.Completer.completions('Z.z', 3)))
349 361
350 362 assert len(l) == 1, 'Completions (Z.z<tab>) correctly deduplicate: %s ' % l
351 363 assert l[0].text == 'zoo' # and not `it.accumulate`
352 364
353 365
354 366 def test_greedy_completions():
355 367 """
356 368 Test the capability of the Greedy completer.
357 369
358 370 Most of the test here do not really show off the greedy completer, for proof
359 371 each of the text bellow now pass with Jedi. The greedy completer is capable of more.
360 372
361 373 See the :any:`test_dict_key_completion_contexts`
362 374
363 375 """
364 376 ip = get_ipython()
365 377 ip.ex('a=list(range(5))')
366 378 _,c = ip.complete('.',line='a[0].')
367 379 nt.assert_false('.real' in c,
368 380 "Shouldn't have completed on a[0]: %s"%c)
369 381 with greedy_completion(), provisionalcompleter():
370 382 def _(line, cursor_pos, expect, message, completion):
371 383 _,c = ip.complete('.', line=line, cursor_pos=cursor_pos)
372 384 with provisionalcompleter():
373 385 completions = ip.Completer.completions(line, cursor_pos)
374 386 nt.assert_in(expect, c, message%c)
375 387 nt.assert_in(completion, completions)
376 388
377 389 yield _, 'a[0].', 5, 'a[0].real', "Should have completed on a[0].: %s", Completion(5,5, 'real')
378 390 yield _, 'a[0].r', 6, 'a[0].real', "Should have completed on a[0].r: %s", Completion(5,6, 'real')
379 391
380 392 if sys.version_info > (3, 4):
381 393 yield _, 'a[0].from_', 10, 'a[0].from_bytes', "Should have completed on a[0].from_: %s", Completion(5, 10, 'from_bytes')
382 394
383 395
384 396 def test_omit__names():
385 397 # also happens to test IPCompleter as a configurable
386 398 ip = get_ipython()
387 399 ip._hidden_attr = 1
388 400 ip._x = {}
389 401 c = ip.Completer
390 402 ip.ex('ip=get_ipython()')
391 403 cfg = Config()
392 404 cfg.IPCompleter.omit__names = 0
393 405 c.update_config(cfg)
394 406 with provisionalcompleter():
395 407 s,matches = c.complete('ip.')
396 408 completions = set(c.completions('ip.', 3))
397 409
398 410 nt.assert_in('ip.__str__', matches)
399 411 nt.assert_in(Completion(3, 3, '__str__'), completions)
400 412
401 413 nt.assert_in('ip._hidden_attr', matches)
402 414 nt.assert_in(Completion(3,3, "_hidden_attr"), completions)
403 415
404 416
405 417 cfg = Config()
406 418 cfg.IPCompleter.omit__names = 1
407 419 c.update_config(cfg)
408 420 with provisionalcompleter():
409 421 s,matches = c.complete('ip.')
410 422 completions = set(c.completions('ip.', 3))
411 423
412 424 nt.assert_not_in('ip.__str__', matches)
413 425 nt.assert_not_in(Completion(3,3,'__str__'), completions)
414 426
415 427 # nt.assert_in('ip._hidden_attr', matches)
416 428 nt.assert_in(Completion(3,3, "_hidden_attr"), completions)
417 429
418 430 cfg = Config()
419 431 cfg.IPCompleter.omit__names = 2
420 432 c.update_config(cfg)
421 433 with provisionalcompleter():
422 434 s,matches = c.complete('ip.')
423 435 completions = set(c.completions('ip.', 3))
424 436
425 437 nt.assert_not_in('ip.__str__', matches)
426 438 nt.assert_not_in(Completion(3,3,'__str__'), completions)
427 439
428 440 nt.assert_not_in('ip._hidden_attr', matches)
429 441 nt.assert_not_in(Completion(3,3, "_hidden_attr"), completions)
430 442
431 443 with provisionalcompleter():
432 444 s,matches = c.complete('ip._x.')
433 445 completions = set(c.completions('ip._x.', 6))
434 446
435 447 nt.assert_in('ip._x.keys', matches)
436 448 nt.assert_in(Completion(6,6, "keys"), completions)
437 449
438 450 del ip._hidden_attr
439 451 del ip._x
440 452
441 453
442 454 def test_limit_to__all__False_ok():
443 455 """
444 456 Limit to all is deprecated, once we remove it this test can go away.
445 457 """
446 458 ip = get_ipython()
447 459 c = ip.Completer
448 460 ip.ex('class D: x=24')
449 461 ip.ex('d=D()')
450 462 cfg = Config()
451 463 cfg.IPCompleter.limit_to__all__ = False
452 464 c.update_config(cfg)
453 465 s, matches = c.complete('d.')
454 466 nt.assert_in('d.x', matches)
455 467
456 468
457 469 def test_get__all__entries_ok():
458 470 class A(object):
459 471 __all__ = ['x', 1]
460 472 words = completer.get__all__entries(A())
461 473 nt.assert_equal(words, ['x'])
462 474
463 475
464 476 def test_get__all__entries_no__all__ok():
465 477 class A(object):
466 478 pass
467 479 words = completer.get__all__entries(A())
468 480 nt.assert_equal(words, [])
469 481
470 482
471 483 def test_func_kw_completions():
472 484 ip = get_ipython()
473 485 c = ip.Completer
474 486 ip.ex('def myfunc(a=1,b=2): return a+b')
475 487 s, matches = c.complete(None, 'myfunc(1,b')
476 488 nt.assert_in('b=', matches)
477 489 # Simulate completing with cursor right after b (pos==10):
478 490 s, matches = c.complete(None, 'myfunc(1,b)', 10)
479 491 nt.assert_in('b=', matches)
480 492 s, matches = c.complete(None, 'myfunc(a="escaped\\")string",b')
481 493 nt.assert_in('b=', matches)
482 494 #builtin function
483 495 s, matches = c.complete(None, 'min(k, k')
484 496 nt.assert_in('key=', matches)
485 497
486 498
487 499 def test_default_arguments_from_docstring():
488 500 ip = get_ipython()
489 501 c = ip.Completer
490 502 kwd = c._default_arguments_from_docstring(
491 503 'min(iterable[, key=func]) -> value')
492 504 nt.assert_equal(kwd, ['key'])
493 505 #with cython type etc
494 506 kwd = c._default_arguments_from_docstring(
495 507 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)\n')
496 508 nt.assert_equal(kwd, ['ncall', 'resume', 'nsplit'])
497 509 #white spaces
498 510 kwd = c._default_arguments_from_docstring(
499 511 '\n Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)\n')
500 512 nt.assert_equal(kwd, ['ncall', 'resume', 'nsplit'])
501 513
502 514 def test_line_magics():
503 515 ip = get_ipython()
504 516 c = ip.Completer
505 517 s, matches = c.complete(None, 'lsmag')
506 518 nt.assert_in('%lsmagic', matches)
507 519 s, matches = c.complete(None, '%lsmag')
508 520 nt.assert_in('%lsmagic', matches)
509 521
510 522
511 523 def test_cell_magics():
512 524 from IPython.core.magic import register_cell_magic
513 525
514 526 @register_cell_magic
515 527 def _foo_cellm(line, cell):
516 528 pass
517 529
518 530 ip = get_ipython()
519 531 c = ip.Completer
520 532
521 533 s, matches = c.complete(None, '_foo_ce')
522 534 nt.assert_in('%%_foo_cellm', matches)
523 535 s, matches = c.complete(None, '%%_foo_ce')
524 536 nt.assert_in('%%_foo_cellm', matches)
525 537
526 538
527 539 def test_line_cell_magics():
528 540 from IPython.core.magic import register_line_cell_magic
529 541
530 542 @register_line_cell_magic
531 543 def _bar_cellm(line, cell):
532 544 pass
533 545
534 546 ip = get_ipython()
535 547 c = ip.Completer
536 548
537 549 # The policy here is trickier, see comments in completion code. The
538 550 # returned values depend on whether the user passes %% or not explicitly,
539 551 # and this will show a difference if the same name is both a line and cell
540 552 # magic.
541 553 s, matches = c.complete(None, '_bar_ce')
542 554 nt.assert_in('%_bar_cellm', matches)
543 555 nt.assert_in('%%_bar_cellm', matches)
544 556 s, matches = c.complete(None, '%_bar_ce')
545 557 nt.assert_in('%_bar_cellm', matches)
546 558 nt.assert_in('%%_bar_cellm', matches)
547 559 s, matches = c.complete(None, '%%_bar_ce')
548 560 nt.assert_not_in('%_bar_cellm', matches)
549 561 nt.assert_in('%%_bar_cellm', matches)
550 562
551 563
552 564 def test_magic_completion_order():
553 565 ip = get_ipython()
554 566 c = ip.Completer
555 567
556 568 # Test ordering of line and cell magics.
557 569 text, matches = c.complete("timeit")
558 570 nt.assert_equal(matches, ["%timeit", "%%timeit"])
559 571
560 572
561 573 def test_magic_completion_shadowing():
562 574 ip = get_ipython()
563 575 c = ip.Completer
564 576
565 577 # Before importing matplotlib, %matplotlib magic should be the only option.
566 578 text, matches = c.complete("mat")
567 579 nt.assert_equal(matches, ["%matplotlib"])
568 580
569 581 # The newly introduced name should shadow the magic.
570 582 ip.run_cell("matplotlib = 1")
571 583 text, matches = c.complete("mat")
572 584 nt.assert_equal(matches, ["matplotlib"])
573 585
574 586 # After removing matplotlib from namespace, the magic should again be
575 587 # the only option.
576 588 del ip.user_ns["matplotlib"]
577 589 text, matches = c.complete("mat")
578 590 nt.assert_equal(matches, ["%matplotlib"])
579 591
580 592
581 593 def test_magic_config():
582 594 ip = get_ipython()
583 595 c = ip.Completer
584 596
585 597 s, matches = c.complete(None, 'conf')
586 598 nt.assert_in('%config', matches)
587 599 s, matches = c.complete(None, 'conf')
588 600 nt.assert_not_in('AliasManager', matches)
589 601 s, matches = c.complete(None, 'config ')
590 602 nt.assert_in('AliasManager', matches)
591 603 s, matches = c.complete(None, '%config ')
592 604 nt.assert_in('AliasManager', matches)
593 605 s, matches = c.complete(None, 'config Ali')
594 606 nt.assert_list_equal(['AliasManager'], matches)
595 607 s, matches = c.complete(None, '%config Ali')
596 608 nt.assert_list_equal(['AliasManager'], matches)
597 609 s, matches = c.complete(None, 'config AliasManager')
598 610 nt.assert_list_equal(['AliasManager'], matches)
599 611 s, matches = c.complete(None, '%config AliasManager')
600 612 nt.assert_list_equal(['AliasManager'], matches)
601 613 s, matches = c.complete(None, 'config AliasManager.')
602 614 nt.assert_in('AliasManager.default_aliases', matches)
603 615 s, matches = c.complete(None, '%config AliasManager.')
604 616 nt.assert_in('AliasManager.default_aliases', matches)
605 617 s, matches = c.complete(None, 'config AliasManager.de')
606 618 nt.assert_list_equal(['AliasManager.default_aliases'], matches)
607 619 s, matches = c.complete(None, 'config AliasManager.de')
608 620 nt.assert_list_equal(['AliasManager.default_aliases'], matches)
609 621
610 622
611 623 def test_magic_color():
612 624 ip = get_ipython()
613 625 c = ip.Completer
614 626
615 627 s, matches = c.complete(None, 'colo')
616 628 nt.assert_in('%colors', matches)
617 629 s, matches = c.complete(None, 'colo')
618 630 nt.assert_not_in('NoColor', matches)
619 631 s, matches = c.complete(None, 'colors ')
620 632 nt.assert_in('NoColor', matches)
621 633 s, matches = c.complete(None, '%colors ')
622 634 nt.assert_in('NoColor', matches)
623 635 s, matches = c.complete(None, 'colors NoCo')
624 636 nt.assert_list_equal(['NoColor'], matches)
625 637 s, matches = c.complete(None, '%colors NoCo')
626 638 nt.assert_list_equal(['NoColor'], matches)
627 639
628 640
629 641 def test_match_dict_keys():
630 642 """
631 643 Test that match_dict_keys works on a couple of use case does return what
632 644 expected, and does not crash
633 645 """
634 646 delims = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
635 647
636 648
637 649 keys = ['foo', b'far']
638 650 assert match_dict_keys(keys, "b'", delims=delims) == ("'", 2 ,['far'])
639 651 assert match_dict_keys(keys, "b'f", delims=delims) == ("'", 2 ,['far'])
640 652 assert match_dict_keys(keys, 'b"', delims=delims) == ('"', 2 ,['far'])
641 653 assert match_dict_keys(keys, 'b"f', delims=delims) == ('"', 2 ,['far'])
642 654
643 655 assert match_dict_keys(keys, "'", delims=delims) == ("'", 1 ,['foo'])
644 656 assert match_dict_keys(keys, "'f", delims=delims) == ("'", 1 ,['foo'])
645 657 assert match_dict_keys(keys, '"', delims=delims) == ('"', 1 ,['foo'])
646 658 assert match_dict_keys(keys, '"f', delims=delims) == ('"', 1 ,['foo'])
647 659
648 660 match_dict_keys
649 661
650 662
651 663 def test_dict_key_completion_string():
652 664 """Test dictionary key completion for string keys"""
653 665 ip = get_ipython()
654 666 complete = ip.Completer.complete
655 667
656 668 ip.user_ns['d'] = {'abc': None}
657 669
658 670 # check completion at different stages
659 671 _, matches = complete(line_buffer="d[")
660 672 nt.assert_in("'abc'", matches)
661 673 nt.assert_not_in("'abc']", matches)
662 674
663 675 _, matches = complete(line_buffer="d['")
664 676 nt.assert_in("abc", matches)
665 677 nt.assert_not_in("abc']", matches)
666 678
667 679 _, matches = complete(line_buffer="d['a")
668 680 nt.assert_in("abc", matches)
669 681 nt.assert_not_in("abc']", matches)
670 682
671 683 # check use of different quoting
672 684 _, matches = complete(line_buffer="d[\"")
673 685 nt.assert_in("abc", matches)
674 686 nt.assert_not_in('abc\"]', matches)
675 687
676 688 _, matches = complete(line_buffer="d[\"a")
677 689 nt.assert_in("abc", matches)
678 690 nt.assert_not_in('abc\"]', matches)
679 691
680 692 # check sensitivity to following context
681 693 _, matches = complete(line_buffer="d[]", cursor_pos=2)
682 694 nt.assert_in("'abc'", matches)
683 695
684 696 _, matches = complete(line_buffer="d['']", cursor_pos=3)
685 697 nt.assert_in("abc", matches)
686 698 nt.assert_not_in("abc'", matches)
687 699 nt.assert_not_in("abc']", matches)
688 700
689 701 # check multiple solutions are correctly returned and that noise is not
690 702 ip.user_ns['d'] = {'abc': None, 'abd': None, 'bad': None, object(): None,
691 703 5: None}
692 704
693 705 _, matches = complete(line_buffer="d['a")
694 706 nt.assert_in("abc", matches)
695 707 nt.assert_in("abd", matches)
696 708 nt.assert_not_in("bad", matches)
697 709 assert not any(m.endswith((']', '"', "'")) for m in matches), matches
698 710
699 711 # check escaping and whitespace
700 712 ip.user_ns['d'] = {'a\nb': None, 'a\'b': None, 'a"b': None, 'a word': None}
701 713 _, matches = complete(line_buffer="d['a")
702 714 nt.assert_in("a\\nb", matches)
703 715 nt.assert_in("a\\'b", matches)
704 716 nt.assert_in("a\"b", matches)
705 717 nt.assert_in("a word", matches)
706 718 assert not any(m.endswith((']', '"', "'")) for m in matches), matches
707 719
708 720 # - can complete on non-initial word of the string
709 721 _, matches = complete(line_buffer="d['a w")
710 722 nt.assert_in("word", matches)
711 723
712 724 # - understands quote escaping
713 725 _, matches = complete(line_buffer="d['a\\'")
714 726 nt.assert_in("b", matches)
715 727
716 728 # - default quoting should work like repr
717 729 _, matches = complete(line_buffer="d[")
718 730 nt.assert_in("\"a'b\"", matches)
719 731
720 732 # - when opening quote with ", possible to match with unescaped apostrophe
721 733 _, matches = complete(line_buffer="d[\"a'")
722 734 nt.assert_in("b", matches)
723 735
724 736 # need to not split at delims that readline won't split at
725 737 if '-' not in ip.Completer.splitter.delims:
726 738 ip.user_ns['d'] = {'before-after': None}
727 739 _, matches = complete(line_buffer="d['before-af")
728 740 nt.assert_in('before-after', matches)
729 741
730 742 def test_dict_key_completion_contexts():
731 743 """Test expression contexts in which dict key completion occurs"""
732 744 ip = get_ipython()
733 745 complete = ip.Completer.complete
734 746 d = {'abc': None}
735 747 ip.user_ns['d'] = d
736 748
737 749 class C:
738 750 data = d
739 751 ip.user_ns['C'] = C
740 752 ip.user_ns['get'] = lambda: d
741 753
742 754 def assert_no_completion(**kwargs):
743 755 _, matches = complete(**kwargs)
744 756 nt.assert_not_in('abc', matches)
745 757 nt.assert_not_in('abc\'', matches)
746 758 nt.assert_not_in('abc\']', matches)
747 759 nt.assert_not_in('\'abc\'', matches)
748 760 nt.assert_not_in('\'abc\']', matches)
749 761
750 762 def assert_completion(**kwargs):
751 763 _, matches = complete(**kwargs)
752 764 nt.assert_in("'abc'", matches)
753 765 nt.assert_not_in("'abc']", matches)
754 766
755 767 # no completion after string closed, even if reopened
756 768 assert_no_completion(line_buffer="d['a'")
757 769 assert_no_completion(line_buffer="d[\"a\"")
758 770 assert_no_completion(line_buffer="d['a' + ")
759 771 assert_no_completion(line_buffer="d['a' + '")
760 772
761 773 # completion in non-trivial expressions
762 774 assert_completion(line_buffer="+ d[")
763 775 assert_completion(line_buffer="(d[")
764 776 assert_completion(line_buffer="C.data[")
765 777
766 778 # greedy flag
767 779 def assert_completion(**kwargs):
768 780 _, matches = complete(**kwargs)
769 781 nt.assert_in("get()['abc']", matches)
770 782
771 783 assert_no_completion(line_buffer="get()[")
772 784 with greedy_completion():
773 785 assert_completion(line_buffer="get()[")
774 786 assert_completion(line_buffer="get()['")
775 787 assert_completion(line_buffer="get()['a")
776 788 assert_completion(line_buffer="get()['ab")
777 789 assert_completion(line_buffer="get()['abc")
778 790
779 791
780 792
781 793 def test_dict_key_completion_bytes():
782 794 """Test handling of bytes in dict key completion"""
783 795 ip = get_ipython()
784 796 complete = ip.Completer.complete
785 797
786 798 ip.user_ns['d'] = {'abc': None, b'abd': None}
787 799
788 800 _, matches = complete(line_buffer="d[")
789 801 nt.assert_in("'abc'", matches)
790 802 nt.assert_in("b'abd'", matches)
791 803
792 804 if False: # not currently implemented
793 805 _, matches = complete(line_buffer="d[b")
794 806 nt.assert_in("b'abd'", matches)
795 807 nt.assert_not_in("b'abc'", matches)
796 808
797 809 _, matches = complete(line_buffer="d[b'")
798 810 nt.assert_in("abd", matches)
799 811 nt.assert_not_in("abc", matches)
800 812
801 813 _, matches = complete(line_buffer="d[B'")
802 814 nt.assert_in("abd", matches)
803 815 nt.assert_not_in("abc", matches)
804 816
805 817 _, matches = complete(line_buffer="d['")
806 818 nt.assert_in("abc", matches)
807 819 nt.assert_not_in("abd", matches)
808 820
809 821
810 822 def test_dict_key_completion_unicode_py3():
811 823 """Test handling of unicode in dict key completion"""
812 824 ip = get_ipython()
813 825 complete = ip.Completer.complete
814 826
815 827 ip.user_ns['d'] = {u'a\u05d0': None}
816 828
817 829 # query using escape
818 830 if sys.platform != 'win32':
819 831 # Known failure on Windows
820 832 _, matches = complete(line_buffer="d['a\\u05d0")
821 833 nt.assert_in("u05d0", matches) # tokenized after \\
822 834
823 835 # query using character
824 836 _, matches = complete(line_buffer="d['a\u05d0")
825 837 nt.assert_in(u"a\u05d0", matches)
826 838
827 839 with greedy_completion():
828 840 # query using escape
829 841 _, matches = complete(line_buffer="d['a\\u05d0")
830 842 nt.assert_in("d['a\\u05d0']", matches) # tokenized after \\
831 843
832 844 # query using character
833 845 _, matches = complete(line_buffer="d['a\u05d0")
834 846 nt.assert_in(u"d['a\u05d0']", matches)
835 847
836 848
837 849
838 850 @dec.skip_without('numpy')
839 851 def test_struct_array_key_completion():
840 852 """Test dict key completion applies to numpy struct arrays"""
841 853 import numpy
842 854 ip = get_ipython()
843 855 complete = ip.Completer.complete
844 856 ip.user_ns['d'] = numpy.array([], dtype=[('hello', 'f'), ('world', 'f')])
845 857 _, matches = complete(line_buffer="d['")
846 858 nt.assert_in("hello", matches)
847 859 nt.assert_in("world", matches)
848 860 # complete on the numpy struct itself
849 861 dt = numpy.dtype([('my_head', [('my_dt', '>u4'), ('my_df', '>u4')]),
850 862 ('my_data', '>f4', 5)])
851 863 x = numpy.zeros(2, dtype=dt)
852 864 ip.user_ns['d'] = x[1]
853 865 _, matches = complete(line_buffer="d['")
854 866 nt.assert_in("my_head", matches)
855 867 nt.assert_in("my_data", matches)
856 868 # complete on a nested level
857 869 with greedy_completion():
858 870 ip.user_ns['d'] = numpy.zeros(2, dtype=dt)
859 871 _, matches = complete(line_buffer="d[1]['my_head']['")
860 872 nt.assert_true(any(["my_dt" in m for m in matches]))
861 873 nt.assert_true(any(["my_df" in m for m in matches]))
862 874
863 875
864 876 @dec.skip_without('pandas')
865 877 def test_dataframe_key_completion():
866 878 """Test dict key completion applies to pandas DataFrames"""
867 879 import pandas
868 880 ip = get_ipython()
869 881 complete = ip.Completer.complete
870 882 ip.user_ns['d'] = pandas.DataFrame({'hello': [1], 'world': [2]})
871 883 _, matches = complete(line_buffer="d['")
872 884 nt.assert_in("hello", matches)
873 885 nt.assert_in("world", matches)
874 886
875 887
876 888 def test_dict_key_completion_invalids():
877 889 """Smoke test cases dict key completion can't handle"""
878 890 ip = get_ipython()
879 891 complete = ip.Completer.complete
880 892
881 893 ip.user_ns['no_getitem'] = None
882 894 ip.user_ns['no_keys'] = []
883 895 ip.user_ns['cant_call_keys'] = dict
884 896 ip.user_ns['empty'] = {}
885 897 ip.user_ns['d'] = {'abc': 5}
886 898
887 899 _, matches = complete(line_buffer="no_getitem['")
888 900 _, matches = complete(line_buffer="no_keys['")
889 901 _, matches = complete(line_buffer="cant_call_keys['")
890 902 _, matches = complete(line_buffer="empty['")
891 903 _, matches = complete(line_buffer="name_error['")
892 904 _, matches = complete(line_buffer="d['\\") # incomplete escape
893 905
894 906 class KeyCompletable(object):
895 907 def __init__(self, things=()):
896 908 self.things = things
897 909
898 910 def _ipython_key_completions_(self):
899 911 return list(self.things)
900 912
901 913 def test_object_key_completion():
902 914 ip = get_ipython()
903 915 ip.user_ns['key_completable'] = KeyCompletable(['qwerty', 'qwick'])
904 916
905 917 _, matches = ip.Completer.complete(line_buffer="key_completable['qw")
906 918 nt.assert_in('qwerty', matches)
907 919 nt.assert_in('qwick', matches)
908 920
909 921
910 922 def test_tryimport():
911 923 """
912 924 Test that try-import don't crash on trailing dot, and import modules before
913 925 """
914 926 from IPython.core.completerlib import try_import
915 927 assert(try_import("IPython."))
916 928
917 929
918 930 def test_aimport_module_completer():
919 931 ip = get_ipython()
920 932 _, matches = ip.complete('i', '%aimport i')
921 933 nt.assert_in('io', matches)
922 934 nt.assert_not_in('int', matches)
923 935
924 936 def test_nested_import_module_completer():
925 937 ip = get_ipython()
926 938 _, matches = ip.complete(None, 'import IPython.co', 17)
927 939 nt.assert_in('IPython.core', matches)
928 940 nt.assert_not_in('import IPython.core', matches)
929 941 nt.assert_not_in('IPython.display', matches)
930 942
931 943 def test_import_module_completer():
932 944 ip = get_ipython()
933 945 _, matches = ip.complete('i', 'import i')
934 946 nt.assert_in('io', matches)
935 947 nt.assert_not_in('int', matches)
936 948
937 949 def test_from_module_completer():
938 950 ip = get_ipython()
939 951 _, matches = ip.complete('B', 'from io import B', 16)
940 952 nt.assert_in('BytesIO', matches)
941 953 nt.assert_not_in('BaseException', matches)
942 954
943 955 def test_snake_case_completion():
944 956 ip = get_ipython()
945 957 ip.user_ns['some_three'] = 3
946 958 ip.user_ns['some_four'] = 4
947 959 _, matches = ip.complete("s_", "print(s_f")
948 960 nt.assert_in('some_three', matches)
949 nt.assert_in('some_four', matches) No newline at end of file
961 nt.assert_in('some_four', matches)
@@ -1,160 +1,160 b''
1 1 """prompt-toolkit utilities
2 2
3 3 Everything in this module is a private API,
4 4 not to be used outside IPython.
5 5 """
6 6
7 7 # Copyright (c) IPython Development Team.
8 8 # Distributed under the terms of the Modified BSD License.
9 9
10 10 import unicodedata
11 11 from wcwidth import wcwidth
12 12
13 13 from IPython.core.completer import (
14 14 provisionalcompleter, cursor_to_position,
15 15 _deduplicate_completions)
16 16 from prompt_toolkit.completion import Completer, Completion
17 17 from prompt_toolkit.layout.lexers import Lexer
18 18 from prompt_toolkit.layout.lexers import PygmentsLexer
19 19
20 20 import pygments.lexers as pygments_lexers
21 21
22 22 _completion_sentinel = object()
23 23
24 24 def _elide(string, *, min_elide=30):
25 25 """
26 26 If a string is long enough, and has at least 2 dots,
27 27 replace the middle part with ellipses.
28 28
29 29 If three consecutive dots, or two consecutive dots are encountered these are
30 30 replaced by the equivalents HORIZONTAL ELLIPSIS or TWO DOT LEADER unicode
31 31 equivalents
32 32 """
33 33 string = string.replace('...','\N{HORIZONTAL ELLIPSIS}')
34 34 string = string.replace('..','\N{TWO DOT LEADER}')
35 35 if len(string) < min_elide:
36 36 return string
37 37
38 38 parts = string.split('.')
39 39
40 40 if len(parts) <= 3:
41 41 return string
42 42
43 43 return '{}.{}\N{HORIZONTAL ELLIPSIS}{}.{}'.format(parts[0], parts[1][0], parts[-2][-1], parts[-1])
44 44
45 45
46 46 def _adjust_completion_text_based_on_context(text, body, offset):
47 47 if text.endswith('=') and len(body) > offset and body[offset] is '=':
48 48 return text[:-1]
49 49 else:
50 50 return text
51 51
52 52
53 53 class IPythonPTCompleter(Completer):
54 54 """Adaptor to provide IPython completions to prompt_toolkit"""
55 55 def __init__(self, ipy_completer=None, shell=None, patch_stdout=None):
56 56 if shell is None and ipy_completer is None:
57 57 raise TypeError("Please pass shell=an InteractiveShell instance.")
58 58 self._ipy_completer = ipy_completer
59 59 self.shell = shell
60 60 if patch_stdout is None:
61 61 raise TypeError("Please pass patch_stdout")
62 62 self.patch_stdout = patch_stdout
63 63
64 64 @property
65 65 def ipy_completer(self):
66 66 if self._ipy_completer:
67 67 return self._ipy_completer
68 68 else:
69 69 return self.shell.Completer
70 70
71 71 def get_completions(self, document, complete_event):
72 72 if not document.current_line.strip():
73 73 return
74 74 # Some bits of our completion system may print stuff (e.g. if a module
75 75 # is imported). This context manager ensures that doesn't interfere with
76 76 # the prompt.
77 77
78 78 with self.patch_stdout(), provisionalcompleter():
79 79 body = document.text
80 80 cursor_row = document.cursor_position_row
81 81 cursor_col = document.cursor_position_col
82 82 cursor_position = document.cursor_position
83 83 offset = cursor_to_position(body, cursor_row, cursor_col)
84 84 yield from self._get_completions(body, offset, cursor_position, self.ipy_completer)
85 85
86 86 @staticmethod
87 87 def _get_completions(body, offset, cursor_position, ipyc):
88 88 """
89 89 Private equivalent of get_completions() use only for unit_testing.
90 90 """
91 91 debug = getattr(ipyc, 'debug', False)
92 92 completions = _deduplicate_completions(
93 93 body, ipyc.completions(body, offset))
94 94 for c in completions:
95 95 if not c.text:
96 96 # Guard against completion machinery giving us an empty string.
97 97 continue
98 98 text = unicodedata.normalize('NFC', c.text)
99 99 # When the first character of the completion has a zero length,
100 100 # then it's probably a decomposed unicode character. E.g. caused by
101 101 # the "\dot" completion. Try to compose again with the previous
102 102 # character.
103 103 if wcwidth(text[0]) == 0:
104 104 if cursor_position + c.start > 0:
105 105 char_before = body[c.start - 1]
106 106 fixed_text = unicodedata.normalize(
107 107 'NFC', char_before + text)
108 108
109 109 # Yield the modified completion instead, if this worked.
110 110 if wcwidth(text[0:1]) == 1:
111 111 yield Completion(fixed_text, start_position=c.start - offset - 1)
112 112 continue
113 113
114 114 # TODO: Use Jedi to determine meta_text
115 115 # (Jedi currently has a bug that results in incorrect information.)
116 116 # meta_text = ''
117 117 # yield Completion(m, start_position=start_pos,
118 118 # display_meta=meta_text)
119 119 display_text = c.text
120 120
121 121 adjusted_text = _adjust_completion_text_based_on_context(c.text, body, offset)
122 122 if c.type == 'function':
123 display_text = display_text + '()'
124
125 yield Completion(adjusted_text, start_position=c.start - offset, display=_elide(display_text), display_meta=c.type)
123 yield Completion(adjusted_text, start_position=c.start - offset, display=_elide(display_text+'()'), display_meta=c.type+c.signature)
124 else:
125 yield Completion(adjusted_text, start_position=c.start - offset, display=_elide(display_text), display_meta=c.type)
126 126
127 127 class IPythonPTLexer(Lexer):
128 128 """
129 129 Wrapper around PythonLexer and BashLexer.
130 130 """
131 131 def __init__(self):
132 132 l = pygments_lexers
133 133 self.python_lexer = PygmentsLexer(l.Python3Lexer)
134 134 self.shell_lexer = PygmentsLexer(l.BashLexer)
135 135
136 136 self.magic_lexers = {
137 137 'HTML': PygmentsLexer(l.HtmlLexer),
138 138 'html': PygmentsLexer(l.HtmlLexer),
139 139 'javascript': PygmentsLexer(l.JavascriptLexer),
140 140 'js': PygmentsLexer(l.JavascriptLexer),
141 141 'perl': PygmentsLexer(l.PerlLexer),
142 142 'ruby': PygmentsLexer(l.RubyLexer),
143 143 'latex': PygmentsLexer(l.TexLexer),
144 144 }
145 145
146 146 def lex_document(self, cli, document):
147 147 text = document.text.lstrip()
148 148
149 149 lexer = self.python_lexer
150 150
151 151 if text.startswith('!') or text.startswith('%%bash'):
152 152 lexer = self.shell_lexer
153 153
154 154 elif text.startswith('%%'):
155 155 for magic, l in self.magic_lexers.items():
156 156 if text.startswith('%%' + magic):
157 157 lexer = l
158 158 break
159 159
160 160 return lexer.lex_document(cli, document)
@@ -1,280 +1,282 b''
1 1 .. _tutorial:
2 2
3 3 ======================
4 4 Introducing IPython
5 5 ======================
6 6
7 7 You don't need to know anything beyond Python to start using IPython – just type
8 8 commands as you would at the standard Python prompt. But IPython can do much
9 9 more than the standard prompt. Some key features are described here. For more
10 10 information, check the :ref:`tips page <tips>`, or look at examples in the
11 11 `IPython cookbook <https://github.com/ipython/ipython/wiki/Cookbook%3A-Index>`_.
12 12
13 13 If you haven't done that yet see `how to install ipython <install>`_ .
14 14
15 15 If you've never used Python before, you might want to look at `the official
16 16 tutorial <http://docs.python.org/tutorial/>`_ or an alternative, `Dive into
17 17 Python <http://diveintopython.net/toc/index.html>`_.
18 18
19 19 Start IPython by issuing the ``ipython`` command from your shell, you should be
20 20 greeted by the following::
21 21
22 22 Python 3.6.0
23 23 Type 'copyright', 'credits' or 'license' for more information
24 24 IPython 6.0.0.dev -- An enhanced Interactive Python. Type '?' for help.
25 25
26 26 In [1]:
27 27
28 28
29 29 Unlike the Python REPL, you will see that the input prompt is ``In [N]:``
30 30 instead of ``>>>``. The number ``N`` in the prompt will be used later in this
31 31 tutorial but should usually not impact the computation.
32 32
33 33 You should be able to type single line expressions and press enter to evaluate
34 34 them. If an expression is incomplete, IPython will automatically detect this and
35 35 add a new line when you press :kbd:`Enter` instead of executing right away.
36 36
37 37 Feel free to explore multi-line text input. Unlike many other REPLs, with
38 38 IPython you can use the up and down arrow keys when editing multi-line
39 39 code blocks.
40 40
41 41 Here is an example of a longer interaction with the IPython REPL,
42 42 which we often refer to as an IPython *session* ::
43 43
44 44 In [1]: print('Hello IPython')
45 45 Hello IPython
46 46
47 47 In [2]: 21 * 2
48 48 Out[2]: 42
49 49
50 50 In [3]: def say_hello(name):
51 51 ...: print('Hello {name}'.format(name=name))
52 52 ...:
53 53
54 54 We won't get into details right now, but you may notice a few differences to
55 55 the standard Python REPL. First, your code should be syntax-highlighted as you
56 56 type. Second, you will see that some results will have an ``Out[N]:`` prompt,
57 57 while some other do not. We'll come to this later.
58 58
59 59 Depending on the exact command you are typing you might realize that sometimes
60 60 :kbd:`Enter` will add a new line, and sometimes it will execute the current
61 61 statement. IPython tries to guess what you are doing, so most of the time you
62 62 should not have to care. Though if by any chance IPython does not the right
63 63 thing you can force execution of the current code block by pressing in sequence
64 64 :kbd:`Esc` and :kbd:`Enter`. You can also force the insertion of a new line at
65 65 the position of the cursor by using :kbd:`Ctrl-o`.
66 66
67 67 The four most helpful commands
68 68 ==============================
69 69
70 70 The four most helpful commands, as well as their brief description, is shown
71 71 to you in a banner, every time you start IPython:
72 72
73 73 ========== =========================================================
74 74 command description
75 75 ========== =========================================================
76 76 ? Introduction and overview of IPython's features.
77 77 %quickref Quick reference.
78 78 help Python's own help system.
79 79 object? Details about 'object', use 'object??' for extra details.
80 80 ========== =========================================================
81 81
82 82 Tab completion
83 83 ==============
84 84
85 85 Tab completion, especially for attributes, is a convenient way to explore the
86 86 structure of any object you're dealing with. Simply type ``object_name.<TAB>``
87 87 to view the object's attributes. Besides Python objects and keywords, tab
88 88 completion also works on file and directory names.
89 89
90 90 Starting with IPython 6.0, if ``jedi`` is installed, IPython will try to pull
91 91 completions from Jedi as well. This allows to not only inspect currently
92 92 existing objects, but also to infer completion statically without executing
93 93 code. There is nothing particular need to get this to work, simply use tab
94 94 completion on more complex expressions like the following::
95 95
96 96 >>> data = ['Number of users', 123_456]
97 97 ... data[0].<tab>
98 98
99 99 IPython and Jedi will be able to infer that ``data[0]`` is actually a string
100 100 and should show relevant completions like ``upper()``, ``lower()`` and other
101 101 string methods. You can use the :kbd:`Tab` key to cycle through completions,
102 102 and while a completion is highlighted, its type will be shown as well.
103 When the type of the completion is a function, the completer will also show the
104 signature of the function when highlighted.
103 105
104 106 Exploring your objects
105 107 ======================
106 108
107 109 Typing ``object_name?`` will print all sorts of details about any object,
108 110 including docstrings, function definition lines (for call arguments) and
109 111 constructor details for classes. To get specific information on an object, you
110 112 can use the magic commands ``%pdoc``, ``%pdef``, ``%psource`` and ``%pfile``
111 113
112 114 .. _magics_explained:
113 115
114 116 Magic functions
115 117 ===============
116 118
117 119 IPython has a set of predefined 'magic functions' that you can call with a
118 120 command line style syntax. There are two kinds of magics, line-oriented and
119 121 cell-oriented. **Line magics** are prefixed with the ``%`` character and work
120 122 much like OS command-line calls: they get as an argument the rest of the line,
121 123 where arguments are passed without parentheses or quotes. **Lines magics** can
122 124 return results and can be used in the right hand side of an assignment. **Cell
123 125 magics** are prefixed with a double ``%%``, and they are functions that get as
124 126 an argument not only the rest of the line, but also the lines below it in a
125 127 separate argument.
126 128
127 129 Magics are useful as convenient functions where Python syntax is not the most
128 130 natural one, or when one want to embed invalid python syntax in their work flow.
129 131
130 132 The following examples show how to call the built-in :magic:`timeit` magic, both
131 133 in line and cell mode::
132 134
133 135 In [1]: %timeit range(1000)
134 136 100000 loops, best of 3: 7.76 us per loop
135 137
136 138 In [2]: %%timeit x = range(10000)
137 139 ...: max(x)
138 140 ...:
139 141 1000 loops, best of 3: 223 us per loop
140 142
141 143 The built-in magics include:
142 144
143 145 - Functions that work with code: :magic:`run`, :magic:`edit`, :magic:`save`,
144 146 :magic:`macro`, :magic:`recall`, etc.
145 147
146 148 - Functions which affect the shell: :magic:`colors`, :magic:`xmode`,
147 149 :magic:`autoindent`, :magic:`automagic`, etc.
148 150
149 151 - Other functions such as :magic:`reset`, :magic:`timeit`,
150 152 :cellmagic:`writefile`, :magic:`load`, or :magic:`paste`.
151 153
152 154 You can always call magics using the ``%`` prefix, and if you're calling a line
153 155 magic on a line by itself, as long as the identifier is not defined in your
154 156 namespace, you can omit even that::
155 157
156 158 run thescript.py
157 159
158 160 You can toggle this behavior by running the :magic:`automagic` magic. Cell
159 161 magics must always have the ``%%`` prefix.
160 162
161 163 A more detailed explanation of the magic system can be obtained by calling
162 164 ``%magic``, and for more details on any magic function, call ``%somemagic?`` to
163 165 read its docstring. To see all the available magic functions, call
164 166 ``%lsmagic``.
165 167
166 168 .. seealso::
167 169
168 170 The :ref:`magic` section of the documentation goes more in depth into how
169 171 the magics works and how to define your own, and :doc:`magics` for a list of
170 172 built-in magics.
171 173
172 174 `Cell magics`_ example notebook
173 175
174 176 Running and Editing
175 177 -------------------
176 178
177 179 The :magic:`run` magic command allows you to run any python script and load all
178 180 of its data directly into the interactive namespace. Since the file is re-read
179 181 from disk each time, changes you make to it are reflected immediately (unlike
180 182 imported modules, which have to be specifically reloaded). IPython also includes
181 183 :ref:`dreload <dreload>`, a recursive reload function.
182 184
183 185 ``%run`` has special flags for timing the execution of your scripts (-t), or
184 186 for running them under the control of either Python's pdb debugger (-d) or
185 187 profiler (-p).
186 188
187 189 The :magic:`edit` command gives a reasonable approximation of multi-line editing,
188 190 by invoking your favorite editor on the spot. IPython will execute the
189 191 code you type in there as if it were typed interactively. Note that for
190 192 :magic:`edit` to work, the call to startup your editor has to be a blocking
191 193 call. In a GUI environment, your editor likely will have such an option.
192 194
193 195 Debugging
194 196 ---------
195 197
196 198 After an exception occurs, you can call :magic:`debug` to jump into the Python
197 199 debugger (pdb) and examine the problem. Alternatively, if you call :magic:`pdb`,
198 200 IPython will automatically start the debugger on any uncaught exception. You can
199 201 print variables, see code, execute statements and even walk up and down the call
200 202 stack to track down the true source of the problem. This can be an efficient way
201 203 to develop and debug code, in many cases eliminating the need for print
202 204 statements or external debugging tools.
203 205
204 206 You can also step through a program from the beginning by calling
205 207 ``%run -d theprogram.py``.
206 208
207 209 History
208 210 =======
209 211
210 212 IPython stores both the commands you enter, and the results it produces. You
211 213 can easily go through previous commands with the up- and down-arrow keys, or
212 214 access your history in more sophisticated ways.
213 215
214 216 Input and output history are kept in variables called ``In`` and ``Out``, keyed
215 217 by the prompt numbers, e.g. ``In[4]``. The last three objects in output history
216 218 are also kept in variables named ``_``, ``__`` and ``___``.
217 219
218 220 You can use the ``%history`` magic function to examine past input and output.
219 221 Input history from previous sessions is saved in a database, and IPython can be
220 222 configured to save output history.
221 223
222 224 Several other magic functions can use your input history, including ``%edit``,
223 225 ``%rerun``, ``%recall``, ``%macro``, ``%save`` and ``%pastebin``. You can use a
224 226 standard format to refer to lines::
225 227
226 228 %pastebin 3 18-20 ~1/1-5
227 229
228 230 This will take line 3 and lines 18 to 20 from the current session, and lines
229 231 1-5 from the previous session.
230 232
231 233 System shell commands
232 234 =====================
233 235
234 236 To run any command at the system shell, simply prefix it with ``!``, e.g.::
235 237
236 238 !ping www.bbc.co.uk
237 239
238 240 You can capture the output into a Python list, e.g.: ``files = !ls``. To pass
239 241 the values of Python variables or expressions to system commands, prefix them
240 242 with $: ``!grep -rF $pattern ipython/*``. See :ref:`our shell section
241 243 <system_shell_access>` for more details.
242 244
243 245 Define your own system aliases
244 246 ------------------------------
245 247
246 248 It's convenient to have aliases to the system commands you use most often. This
247 249 allows you to work seamlessly from inside IPython with the same commands you are
248 250 used to in your system shell. IPython comes with some pre-defined aliases and a
249 251 complete system for changing directories, both via a stack (see :magic:`pushd`,
250 252 :magic:`popd` and :magic:`dhist`) and via direct :magic:`cd`. The latter keeps a
251 253 history of visited directories and allows you to go to any previously visited
252 254 one.
253 255
254 256
255 257 Configuration
256 258 =============
257 259
258 260 Much of IPython can be tweaked through :doc:`configuration </config/intro>`.
259 261 To get started, use the command ``ipython profile create`` to produce the
260 262 default config files. These will be placed in
261 263 :file:`~/.ipython/profile_default`, and contain comments explaining
262 264 what the various options do.
263 265
264 266 Profiles allow you to use IPython for different tasks, keeping separate config
265 267 files and history for each one. More details in :ref:`the profiles section
266 268 <profiles>`.
267 269
268 270 .. _startup_files:
269 271
270 272 Startup Files
271 273 -------------
272 274
273 275 If you want some code to be run at the beginning of every IPython session, the
274 276 easiest way is to add Python (.py) or IPython (.ipy) scripts to your
275 277 :file:`profile_default/startup/` directory. Files here will be executed as soon
276 278 as the IPython shell is constructed, before any other code or scripts you have
277 279 specified. The files will be run in order of their names, so you can control the
278 280 ordering with prefixes, like ``10-myimports.py``.
279 281
280 282 .. include:: ../links.txt
General Comments 0
You need to be logged in to leave comments. Login now