##// END OF EJS Templates
Add completion support for cell magics and handling of line/cell magics....
Fernando Perez -
Show More
@@ -1,923 +1,933 b''
1 1 """Word completion for IPython.
2 2
3 3 This module is a fork of the rlcompleter module in the Python standard
4 4 library. The original enhancements made to rlcompleter have been sent
5 5 upstream and were accepted as of Python 2.3, but we need a lot more
6 6 functionality specific to IPython, so this module will continue to live as an
7 7 IPython-specific utility.
8 8
9 9 Original rlcompleter documentation:
10 10
11 11 This requires the latest extension to the readline module (the
12 12 completes keywords, built-ins and globals in __main__; when completing
13 13 NAME.NAME..., it evaluates (!) the expression up to the last dot and
14 14 completes its attributes.
15 15
16 16 It's very cool to do "import string" type "string.", hit the
17 17 completion key (twice), and see the list of names defined by the
18 18 string module!
19 19
20 20 Tip: to use the tab key as the completion key, call
21 21
22 22 readline.parse_and_bind("tab: complete")
23 23
24 24 Notes:
25 25
26 26 - Exceptions raised by the completer function are *ignored* (and
27 27 generally cause the completion to fail). This is a feature -- since
28 28 readline sets the tty device in raw (or cbreak) mode, printing a
29 29 traceback wouldn't work well without some complicated hoopla to save,
30 30 reset and restore the tty state.
31 31
32 32 - The evaluation of the NAME.NAME... form may cause arbitrary
33 33 application defined code to be executed if an object with a
34 34 __getattr__ hook is found. Since it is the responsibility of the
35 35 application (or the user) to enable this feature, I consider this an
36 36 acceptable risk. More complicated expressions (e.g. function calls or
37 37 indexing operations) are *not* evaluated.
38 38
39 39 - GNU readline is also used by the built-in functions input() and
40 40 raw_input(), and thus these also benefit/suffer from the completer
41 41 features. Clearly an interactive application can benefit by
42 42 specifying its own completer function and using raw_input() for all
43 43 its input.
44 44
45 45 - When the original stdin is not a tty device, GNU readline is never
46 46 used, and this module (and the readline module) are silently inactive.
47 47 """
48 48
49 49 #*****************************************************************************
50 50 #
51 51 # Since this file is essentially a minimally modified copy of the rlcompleter
52 52 # module which is part of the standard Python distribution, I assume that the
53 53 # proper procedure is to maintain its copyright as belonging to the Python
54 54 # Software Foundation (in addition to my own, for all new code).
55 55 #
56 # Copyright (C) 2008-2011 IPython Development Team
57 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
56 # Copyright (C) 2008 IPython Development Team
57 # Copyright (C) 2001 Fernando Perez. <fperez@colorado.edu>
58 58 # Copyright (C) 2001 Python Software Foundation, www.python.org
59 59 #
60 60 # Distributed under the terms of the BSD License. The full license is in
61 61 # the file COPYING, distributed as part of this software.
62 62 #
63 63 #*****************************************************************************
64 from __future__ import print_function
65 64
66 65 #-----------------------------------------------------------------------------
67 66 # Imports
68 67 #-----------------------------------------------------------------------------
69 68
70 69 import __builtin__
71 70 import __main__
72 71 import glob
73 72 import inspect
74 73 import itertools
75 74 import keyword
76 75 import os
77 76 import re
78 77 import shlex
79 78 import sys
80 79
81 80 from IPython.config.configurable import Configurable
82 81 from IPython.core.error import TryNext
83 82 from IPython.core.prefilter import ESC_MAGIC
84 83 from IPython.utils import generics
85 84 from IPython.utils import io
86 85 from IPython.utils.dir2 import dir2
87 86 from IPython.utils.process import arg_split
88 87 from IPython.utils.traitlets import CBool, Enum
89 88
90 89 #-----------------------------------------------------------------------------
91 90 # Globals
92 91 #-----------------------------------------------------------------------------
93 92
94 93 # Public API
95 94 __all__ = ['Completer','IPCompleter']
96 95
97 96 if sys.platform == 'win32':
98 97 PROTECTABLES = ' '
99 98 else:
100 99 PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&'
101 100
102 101 #-----------------------------------------------------------------------------
103 102 # Main functions and classes
104 103 #-----------------------------------------------------------------------------
105 104
106 105 def has_open_quotes(s):
107 106 """Return whether a string has open quotes.
108 107
109 108 This simply counts whether the number of quote characters of either type in
110 109 the string is odd.
111 110
112 111 Returns
113 112 -------
114 113 If there is an open quote, the quote character is returned. Else, return
115 114 False.
116 115 """
117 116 # We check " first, then ', so complex cases with nested quotes will get
118 117 # the " to take precedence.
119 118 if s.count('"') % 2:
120 119 return '"'
121 120 elif s.count("'") % 2:
122 121 return "'"
123 122 else:
124 123 return False
125 124
126 125
127 126 def protect_filename(s):
128 127 """Escape a string to protect certain characters."""
129 128
130 129 return "".join([(ch in PROTECTABLES and '\\' + ch or ch)
131 130 for ch in s])
132 131
133 132 def expand_user(path):
134 133 """Expand '~'-style usernames in strings.
135 134
136 135 This is similar to :func:`os.path.expanduser`, but it computes and returns
137 136 extra information that will be useful if the input was being used in
138 137 computing completions, and you wish to return the completions with the
139 138 original '~' instead of its expanded value.
140 139
141 140 Parameters
142 141 ----------
143 142 path : str
144 143 String to be expanded. If no ~ is present, the output is the same as the
145 144 input.
146 145
147 146 Returns
148 147 -------
149 148 newpath : str
150 149 Result of ~ expansion in the input path.
151 150 tilde_expand : bool
152 151 Whether any expansion was performed or not.
153 152 tilde_val : str
154 153 The value that ~ was replaced with.
155 154 """
156 155 # Default values
157 156 tilde_expand = False
158 157 tilde_val = ''
159 158 newpath = path
160 159
161 160 if path.startswith('~'):
162 161 tilde_expand = True
163 162 rest = len(path)-1
164 163 newpath = os.path.expanduser(path)
165 164 if rest:
166 165 tilde_val = newpath[:-rest]
167 166 else:
168 167 tilde_val = newpath
169 168
170 169 return newpath, tilde_expand, tilde_val
171 170
172 171
173 172 def compress_user(path, tilde_expand, tilde_val):
174 173 """Does the opposite of expand_user, with its outputs.
175 174 """
176 175 if tilde_expand:
177 176 return path.replace(tilde_val, '~')
178 177 else:
179 178 return path
180 179
181 180
182 181 class Bunch(object): pass
183 182
184 183
185 184 DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
186 185 GREEDY_DELIMS = ' \r\n'
187 186
188 187
189 188 class CompletionSplitter(object):
190 189 """An object to split an input line in a manner similar to readline.
191 190
192 191 By having our own implementation, we can expose readline-like completion in
193 192 a uniform manner to all frontends. This object only needs to be given the
194 193 line of text to be split and the cursor position on said line, and it
195 194 returns the 'word' to be completed on at the cursor after splitting the
196 195 entire line.
197 196
198 197 What characters are used as splitting delimiters can be controlled by
199 198 setting the `delims` attribute (this is a property that internally
200 199 automatically builds the necessary regular expression)"""
201 200
202 201 # Private interface
203 202
204 203 # A string of delimiter characters. The default value makes sense for
205 204 # IPython's most typical usage patterns.
206 205 _delims = DELIMS
207 206
208 207 # The expression (a normal string) to be compiled into a regular expression
209 208 # for actual splitting. We store it as an attribute mostly for ease of
210 209 # debugging, since this type of code can be so tricky to debug.
211 210 _delim_expr = None
212 211
213 212 # The regular expression that does the actual splitting
214 213 _delim_re = None
215 214
216 215 def __init__(self, delims=None):
217 216 delims = CompletionSplitter._delims if delims is None else delims
218 217 self.delims = delims
219 218
220 219 @property
221 220 def delims(self):
222 221 """Return the string of delimiter characters."""
223 222 return self._delims
224 223
225 224 @delims.setter
226 225 def delims(self, delims):
227 226 """Set the delimiters for line splitting."""
228 227 expr = '[' + ''.join('\\'+ c for c in delims) + ']'
229 228 self._delim_re = re.compile(expr)
230 229 self._delims = delims
231 230 self._delim_expr = expr
232 231
233 232 def split_line(self, line, cursor_pos=None):
234 233 """Split a line of text with a cursor at the given position.
235 234 """
236 235 l = line if cursor_pos is None else line[:cursor_pos]
237 236 return self._delim_re.split(l)[-1]
238 237
239 238
240 239 class Completer(Configurable):
241 240
242 241 greedy = CBool(False, config=True,
243 242 help="""Activate greedy completion
244 243
245 244 This will enable completion on elements of lists, results of function calls, etc.,
246 245 but can be unsafe because the code is actually evaluated on TAB.
247 246 """
248 247 )
249 248
250 249
251 250 def __init__(self, namespace=None, global_namespace=None, config=None, **kwargs):
252 251 """Create a new completer for the command line.
253 252
254 253 Completer(namespace=ns,global_namespace=ns2) -> completer instance.
255 254
256 255 If unspecified, the default namespace where completions are performed
257 256 is __main__ (technically, __main__.__dict__). Namespaces should be
258 257 given as dictionaries.
259 258
260 259 An optional second namespace can be given. This allows the completer
261 260 to handle cases where both the local and global scopes need to be
262 261 distinguished.
263 262
264 263 Completer instances should be used as the completion mechanism of
265 264 readline via the set_completer() call:
266 265
267 266 readline.set_completer(Completer(my_namespace).complete)
268 267 """
269 268
270 269 # Don't bind to namespace quite yet, but flag whether the user wants a
271 270 # specific namespace or to use __main__.__dict__. This will allow us
272 271 # to bind to __main__.__dict__ at completion time, not now.
273 272 if namespace is None:
274 273 self.use_main_ns = 1
275 274 else:
276 275 self.use_main_ns = 0
277 276 self.namespace = namespace
278 277
279 278 # The global namespace, if given, can be bound directly
280 279 if global_namespace is None:
281 280 self.global_namespace = {}
282 281 else:
283 282 self.global_namespace = global_namespace
284 283
285 284 super(Completer, self).__init__(config=config, **kwargs)
286 285
287 286 def complete(self, text, state):
288 287 """Return the next possible completion for 'text'.
289 288
290 289 This is called successively with state == 0, 1, 2, ... until it
291 290 returns None. The completion should begin with 'text'.
292 291
293 292 """
294 293 if self.use_main_ns:
295 294 self.namespace = __main__.__dict__
296 295
297 296 if state == 0:
298 297 if "." in text:
299 298 self.matches = self.attr_matches(text)
300 299 else:
301 300 self.matches = self.global_matches(text)
302 301 try:
303 302 return self.matches[state]
304 303 except IndexError:
305 304 return None
306 305
307 306 def global_matches(self, text):
308 307 """Compute matches when text is a simple name.
309 308
310 309 Return a list of all keywords, built-in functions and names currently
311 310 defined in self.namespace or self.global_namespace that match.
312 311
313 312 """
314 313 #print 'Completer->global_matches, txt=%r' % text # dbg
315 314 matches = []
316 315 match_append = matches.append
317 316 n = len(text)
318 317 for lst in [keyword.kwlist,
319 318 __builtin__.__dict__.keys(),
320 319 self.namespace.keys(),
321 320 self.global_namespace.keys()]:
322 321 for word in lst:
323 322 if word[:n] == text and word != "__builtins__":
324 323 match_append(word)
325 324 return matches
326 325
327 326 def attr_matches(self, text):
328 327 """Compute matches when text contains a dot.
329 328
330 329 Assuming the text is of the form NAME.NAME....[NAME], and is
331 330 evaluatable in self.namespace or self.global_namespace, it will be
332 331 evaluated and its attributes (as revealed by dir()) are used as
333 332 possible completions. (For class instances, class members are are
334 333 also considered.)
335 334
336 335 WARNING: this can still invoke arbitrary C code, if an object
337 336 with a __getattr__ hook is evaluated.
338 337
339 338 """
340 339
341 340 #io.rprint('Completer->attr_matches, txt=%r' % text) # dbg
342 341 # Another option, seems to work great. Catches things like ''.<tab>
343 342 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
344 343
345 344 if m:
346 345 expr, attr = m.group(1, 3)
347 346 elif self.greedy:
348 347 m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer)
349 348 if not m2:
350 349 return []
351 350 expr, attr = m2.group(1,2)
352 351 else:
353 352 return []
354 353
355 354 try:
356 355 obj = eval(expr, self.namespace)
357 356 except:
358 357 try:
359 358 obj = eval(expr, self.global_namespace)
360 359 except:
361 360 return []
362 361
363 362 if self.limit_to__all__ and hasattr(obj, '__all__'):
364 363 words = get__all__entries(obj)
365 364 else:
366 365 words = dir2(obj)
367 366
368 367 try:
369 368 words = generics.complete_object(obj, words)
370 369 except TryNext:
371 370 pass
372 371 except Exception:
373 372 # Silence errors from completion function
374 373 #raise # dbg
375 374 pass
376 375 # Build match list to return
377 376 n = len(attr)
378 377 res = ["%s.%s" % (expr, w) for w in words if w[:n] == attr ]
379 378 return res
380 379
381 380
382 381 def get__all__entries(obj):
383 382 """returns the strings in the __all__ attribute"""
384 383 try:
385 384 words = getattr(obj, '__all__')
386 385 except:
387 386 return []
388 387
389 388 return [w for w in words if isinstance(w, basestring)]
390 389
391 390
392 391 class IPCompleter(Completer):
393 392 """Extension of the completer class with IPython-specific features"""
394 393
395 394 def _greedy_changed(self, name, old, new):
396 395 """update the splitter and readline delims when greedy is changed"""
397 396 if new:
398 397 self.splitter.delims = GREEDY_DELIMS
399 398 else:
400 399 self.splitter.delims = DELIMS
401 400
402 401 if self.readline:
403 402 self.readline.set_completer_delims(self.splitter.delims)
404 403
405 404 merge_completions = CBool(True, config=True,
406 405 help="""Whether to merge completion results into a single list
407 406
408 407 If False, only the completion results from the first non-empty
409 408 completer will be returned.
410 409 """
411 410 )
412 411 omit__names = Enum((0,1,2), default_value=2, config=True,
413 412 help="""Instruct the completer to omit private method names
414 413
415 414 Specifically, when completing on ``object.<tab>``.
416 415
417 416 When 2 [default]: all names that start with '_' will be excluded.
418 417
419 418 When 1: all 'magic' names (``__foo__``) will be excluded.
420 419
421 420 When 0: nothing will be excluded.
422 421 """
423 422 )
424 423 limit_to__all__ = CBool(default_value=False, config=True,
425 424 help="""Instruct the completer to use __all__ for the completion
426 425
427 426 Specifically, when completing on ``object.<tab>``.
428 427
429 428 When True: only those names in obj.__all__ will be included.
430 429
431 430 When False [default]: the __all__ attribute is ignored
432 431 """
433 432 )
434 433
435 434 def __init__(self, shell=None, namespace=None, global_namespace=None,
436 435 alias_table=None, use_readline=True,
437 436 config=None, **kwargs):
438 437 """IPCompleter() -> completer
439 438
440 439 Return a completer object suitable for use by the readline library
441 440 via readline.set_completer().
442 441
443 442 Inputs:
444 443
445 444 - shell: a pointer to the ipython shell itself. This is needed
446 445 because this completer knows about magic functions, and those can
447 446 only be accessed via the ipython instance.
448 447
449 448 - namespace: an optional dict where completions are performed.
450 449
451 450 - global_namespace: secondary optional dict for completions, to
452 451 handle cases (such as IPython embedded inside functions) where
453 452 both Python scopes are visible.
454 453
455 454 - If alias_table is supplied, it should be a dictionary of aliases
456 455 to complete.
457 456
458 457 use_readline : bool, optional
459 458 If true, use the readline library. This completer can still function
460 459 without readline, though in that case callers must provide some extra
461 460 information on each call about the current line."""
462 461
463 462 self.magic_escape = ESC_MAGIC
464 463 self.splitter = CompletionSplitter()
465 464
466 465 # Readline configuration, only used by the rlcompleter method.
467 466 if use_readline:
468 467 # We store the right version of readline so that later code
469 468 import IPython.utils.rlineimpl as readline
470 469 self.readline = readline
471 470 else:
472 471 self.readline = None
473 472
474 473 # _greedy_changed() depends on splitter and readline being defined:
475 474 Completer.__init__(self, namespace=namespace, global_namespace=global_namespace,
476 475 config=config, **kwargs)
477 476
478 477 # List where completion matches will be stored
479 478 self.matches = []
480 479 self.shell = shell
481 480 if alias_table is None:
482 481 alias_table = {}
483 482 self.alias_table = alias_table
484 483 # Regexp to split filenames with spaces in them
485 484 self.space_name_re = re.compile(r'([^\\] )')
486 485 # Hold a local ref. to glob.glob for speed
487 486 self.glob = glob.glob
488 487
489 488 # Determine if we are running on 'dumb' terminals, like (X)Emacs
490 489 # buffers, to avoid completion problems.
491 490 term = os.environ.get('TERM','xterm')
492 491 self.dumb_terminal = term in ['dumb','emacs']
493 492
494 493 # Special handling of backslashes needed in win32 platforms
495 494 if sys.platform == "win32":
496 495 self.clean_glob = self._clean_glob_win32
497 496 else:
498 497 self.clean_glob = self._clean_glob
499 498
500 499 # All active matcher routines for completion
501 500 self.matchers = [self.python_matches,
502 501 self.file_matches,
503 502 self.magic_matches,
504 503 self.alias_matches,
505 504 self.python_func_kw_matches,
506 505 ]
507 506
508 507 def all_completions(self, text):
509 508 """
510 509 Wrapper around the complete method for the benefit of emacs
511 510 and pydb.
512 511 """
513 512 return self.complete(text)[1]
514 513
515 514 def _clean_glob(self,text):
516 515 return self.glob("%s*" % text)
517 516
518 517 def _clean_glob_win32(self,text):
519 518 return [f.replace("\\","/")
520 519 for f in self.glob("%s*" % text)]
521 520
522 521 def file_matches(self, text):
523 522 """Match filenames, expanding ~USER type strings.
524 523
525 524 Most of the seemingly convoluted logic in this completer is an
526 525 attempt to handle filenames with spaces in them. And yet it's not
527 526 quite perfect, because Python's readline doesn't expose all of the
528 527 GNU readline details needed for this to be done correctly.
529 528
530 529 For a filename with a space in it, the printed completions will be
531 530 only the parts after what's already been typed (instead of the
532 531 full completions, as is normally done). I don't think with the
533 532 current (as of Python 2.3) Python readline it's possible to do
534 533 better."""
535 534
536 535 #io.rprint('Completer->file_matches: <%r>' % text) # dbg
537 536
538 537 # chars that require escaping with backslash - i.e. chars
539 538 # that readline treats incorrectly as delimiters, but we
540 539 # don't want to treat as delimiters in filename matching
541 540 # when escaped with backslash
542 541 if text.startswith('!'):
543 542 text = text[1:]
544 543 text_prefix = '!'
545 544 else:
546 545 text_prefix = ''
547 546
548 547 text_until_cursor = self.text_until_cursor
549 548 # track strings with open quotes
550 549 open_quotes = has_open_quotes(text_until_cursor)
551 550
552 551 if '(' in text_until_cursor or '[' in text_until_cursor:
553 552 lsplit = text
554 553 else:
555 554 try:
556 555 # arg_split ~ shlex.split, but with unicode bugs fixed by us
557 556 lsplit = arg_split(text_until_cursor)[-1]
558 557 except ValueError:
559 558 # typically an unmatched ", or backslash without escaped char.
560 559 if open_quotes:
561 560 lsplit = text_until_cursor.split(open_quotes)[-1]
562 561 else:
563 562 return []
564 563 except IndexError:
565 564 # tab pressed on empty line
566 565 lsplit = ""
567 566
568 567 if not open_quotes and lsplit != protect_filename(lsplit):
569 568 # if protectables are found, do matching on the whole escaped name
570 569 has_protectables = True
571 570 text0,text = text,lsplit
572 571 else:
573 572 has_protectables = False
574 573 text = os.path.expanduser(text)
575 574
576 575 if text == "":
577 576 return [text_prefix + protect_filename(f) for f in self.glob("*")]
578 577
579 578 # Compute the matches from the filesystem
580 579 m0 = self.clean_glob(text.replace('\\',''))
581 580
582 581 if has_protectables:
583 582 # If we had protectables, we need to revert our changes to the
584 583 # beginning of filename so that we don't double-write the part
585 584 # of the filename we have so far
586 585 len_lsplit = len(lsplit)
587 586 matches = [text_prefix + text0 +
588 587 protect_filename(f[len_lsplit:]) for f in m0]
589 588 else:
590 589 if open_quotes:
591 590 # if we have a string with an open quote, we don't need to
592 591 # protect the names at all (and we _shouldn't_, as it
593 592 # would cause bugs when the filesystem call is made).
594 593 matches = m0
595 594 else:
596 595 matches = [text_prefix +
597 596 protect_filename(f) for f in m0]
598 597
599 598 #io.rprint('mm', matches) # dbg
600 599
601 600 # Mark directories in input list by appending '/' to their names.
602 601 matches = [x+'/' if os.path.isdir(x) else x for x in matches]
603 602 return matches
604 603
605 604 def magic_matches(self, text):
606 605 """Match magics"""
607 606 #print 'Completer->magic_matches:',text,'lb',self.text_until_cursor # dbg
608 607 # Get all shell magics now rather than statically, so magics loaded at
609 # runtime show up too
610 # FIXME - cell magics not implemented here yet.
611 magics = self.shell.magics_manager.lsmagic()['line']
608 # runtime show up too.
609 lsm = self.shell.magics_manager.lsmagic()
610 line_magics = lsm['line']
611 cell_magics = lsm['cell']
612 612 pre = self.magic_escape
613 baretext = text.lstrip(pre)
614 return [ pre+m for m in magics if m.startswith(baretext)]
613 pre2 = pre+pre
614
615 # Completion logic:
616 # - user gives %%: only do cell magics
617 # - user gives %: do both line and cell magics
618 # - no prefix: do both
619 # In other words, line magics are skipped if the user gives %% explicitly
620 bare_text = text.lstrip(pre)
621 comp = [ pre2+m for m in cell_magics if m.startswith(bare_text)]
622 if not text.startswith(pre2):
623 comp += [ pre+m for m in line_magics if m.startswith(bare_text)]
624 return comp
615 625
616 626 def alias_matches(self, text):
617 627 """Match internal system aliases"""
618 628 #print 'Completer->alias_matches:',text,'lb',self.text_until_cursor # dbg
619 629
620 630 # if we are not in the first 'item', alias matching
621 631 # doesn't make sense - unless we are starting with 'sudo' command.
622 632 main_text = self.text_until_cursor.lstrip()
623 633 if ' ' in main_text and not main_text.startswith('sudo'):
624 634 return []
625 635 text = os.path.expanduser(text)
626 636 aliases = self.alias_table.keys()
627 637 if text == '':
628 638 return aliases
629 639 else:
630 640 return [a for a in aliases if a.startswith(text)]
631 641
632 642 def python_matches(self,text):
633 643 """Match attributes or global python names"""
634 644
635 645 #io.rprint('Completer->python_matches, txt=%r' % text) # dbg
636 646 if "." in text:
637 647 try:
638 648 matches = self.attr_matches(text)
639 649 if text.endswith('.') and self.omit__names:
640 650 if self.omit__names == 1:
641 651 # true if txt is _not_ a __ name, false otherwise:
642 652 no__name = (lambda txt:
643 653 re.match(r'.*\.__.*?__',txt) is None)
644 654 else:
645 655 # true if txt is _not_ a _ name, false otherwise:
646 656 no__name = (lambda txt:
647 657 re.match(r'.*\._.*?',txt) is None)
648 658 matches = filter(no__name, matches)
649 659 except NameError:
650 660 # catches <undefined attributes>.<tab>
651 661 matches = []
652 662 else:
653 663 matches = self.global_matches(text)
654 664
655 665 return matches
656 666
657 667 def _default_arguments(self, obj):
658 668 """Return the list of default arguments of obj if it is callable,
659 669 or empty list otherwise."""
660 670
661 671 if not (inspect.isfunction(obj) or inspect.ismethod(obj)):
662 672 # for classes, check for __init__,__new__
663 673 if inspect.isclass(obj):
664 674 obj = (getattr(obj,'__init__',None) or
665 675 getattr(obj,'__new__',None))
666 676 # for all others, check if they are __call__able
667 677 elif hasattr(obj, '__call__'):
668 678 obj = obj.__call__
669 679 # XXX: is there a way to handle the builtins ?
670 680 try:
671 681 args,_,_1,defaults = inspect.getargspec(obj)
672 682 if defaults:
673 683 return args[-len(defaults):]
674 684 except TypeError: pass
675 685 return []
676 686
677 687 def python_func_kw_matches(self,text):
678 688 """Match named parameters (kwargs) of the last open function"""
679 689
680 690 if "." in text: # a parameter cannot be dotted
681 691 return []
682 692 try: regexp = self.__funcParamsRegex
683 693 except AttributeError:
684 694 regexp = self.__funcParamsRegex = re.compile(r'''
685 695 '.*?' | # single quoted strings or
686 696 ".*?" | # double quoted strings or
687 697 \w+ | # identifier
688 698 \S # other characters
689 699 ''', re.VERBOSE | re.DOTALL)
690 700 # 1. find the nearest identifier that comes before an unclosed
691 701 # parenthesis before the cursor
692 702 # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo"
693 703 tokens = regexp.findall(self.text_until_cursor)
694 704 tokens.reverse()
695 705 iterTokens = iter(tokens); openPar = 0
696 706 for token in iterTokens:
697 707 if token == ')':
698 708 openPar -= 1
699 709 elif token == '(':
700 710 openPar += 1
701 711 if openPar > 0:
702 712 # found the last unclosed parenthesis
703 713 break
704 714 else:
705 715 return []
706 716 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
707 717 ids = []
708 718 isId = re.compile(r'\w+$').match
709 719 while True:
710 720 try:
711 721 ids.append(iterTokens.next())
712 722 if not isId(ids[-1]):
713 723 ids.pop(); break
714 724 if not iterTokens.next() == '.':
715 725 break
716 726 except StopIteration:
717 727 break
718 728 # lookup the candidate callable matches either using global_matches
719 729 # or attr_matches for dotted names
720 730 if len(ids) == 1:
721 731 callableMatches = self.global_matches(ids[0])
722 732 else:
723 733 callableMatches = self.attr_matches('.'.join(ids[::-1]))
724 734 argMatches = []
725 735 for callableMatch in callableMatches:
726 736 try:
727 737 namedArgs = self._default_arguments(eval(callableMatch,
728 738 self.namespace))
729 739 except:
730 740 continue
731 741 for namedArg in namedArgs:
732 742 if namedArg.startswith(text):
733 743 argMatches.append("%s=" %namedArg)
734 744 return argMatches
735 745
736 746 def dispatch_custom_completer(self, text):
737 747 #io.rprint("Custom! '%s' %s" % (text, self.custom_completers)) # dbg
738 748 line = self.line_buffer
739 749 if not line.strip():
740 750 return None
741 751
742 752 # Create a little structure to pass all the relevant information about
743 753 # the current completion to any custom completer.
744 754 event = Bunch()
745 755 event.line = line
746 756 event.symbol = text
747 757 cmd = line.split(None,1)[0]
748 758 event.command = cmd
749 759 event.text_until_cursor = self.text_until_cursor
750 760
751 761 #print "\ncustom:{%s]\n" % event # dbg
752 762
753 763 # for foo etc, try also to find completer for %foo
754 764 if not cmd.startswith(self.magic_escape):
755 765 try_magic = self.custom_completers.s_matches(
756 766 self.magic_escape + cmd)
757 767 else:
758 768 try_magic = []
759 769
760 770 for c in itertools.chain(self.custom_completers.s_matches(cmd),
761 771 try_magic,
762 772 self.custom_completers.flat_matches(self.text_until_cursor)):
763 773 #print "try",c # dbg
764 774 try:
765 775 res = c(event)
766 776 if res:
767 777 # first, try case sensitive match
768 778 withcase = [r for r in res if r.startswith(text)]
769 779 if withcase:
770 780 return withcase
771 781 # if none, then case insensitive ones are ok too
772 782 text_low = text.lower()
773 783 return [r for r in res if r.lower().startswith(text_low)]
774 784 except TryNext:
775 785 pass
776 786
777 787 return None
778 788
779 789 def complete(self, text=None, line_buffer=None, cursor_pos=None):
780 790 """Find completions for the given text and line context.
781 791
782 792 This is called successively with state == 0, 1, 2, ... until it
783 793 returns None. The completion should begin with 'text'.
784 794
785 795 Note that both the text and the line_buffer are optional, but at least
786 796 one of them must be given.
787 797
788 798 Parameters
789 799 ----------
790 800 text : string, optional
791 801 Text to perform the completion on. If not given, the line buffer
792 802 is split using the instance's CompletionSplitter object.
793 803
794 804 line_buffer : string, optional
795 805 If not given, the completer attempts to obtain the current line
796 806 buffer via readline. This keyword allows clients which are
797 807 requesting for text completions in non-readline contexts to inform
798 808 the completer of the entire text.
799 809
800 810 cursor_pos : int, optional
801 811 Index of the cursor in the full line buffer. Should be provided by
802 812 remote frontends where kernel has no access to frontend state.
803 813
804 814 Returns
805 815 -------
806 816 text : str
807 817 Text that was actually used in the completion.
808 818
809 819 matches : list
810 820 A list of completion matches.
811 821 """
812 822 #io.rprint('\nCOMP1 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg
813 823
814 824 # if the cursor position isn't given, the only sane assumption we can
815 825 # make is that it's at the end of the line (the common case)
816 826 if cursor_pos is None:
817 827 cursor_pos = len(line_buffer) if text is None else len(text)
818 828
819 829 # if text is either None or an empty string, rely on the line buffer
820 830 if not text:
821 831 text = self.splitter.split_line(line_buffer, cursor_pos)
822 832
823 833 # If no line buffer is given, assume the input text is all there was
824 834 if line_buffer is None:
825 835 line_buffer = text
826 836
827 837 self.line_buffer = line_buffer
828 838 self.text_until_cursor = self.line_buffer[:cursor_pos]
829 839 #io.rprint('COMP2 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg
830 840
831 841 # Start with a clean slate of completions
832 842 self.matches[:] = []
833 843 custom_res = self.dispatch_custom_completer(text)
834 844 if custom_res is not None:
835 845 # did custom completers produce something?
836 846 self.matches = custom_res
837 847 else:
838 848 # Extend the list of completions with the results of each
839 849 # matcher, so we return results to the user from all
840 850 # namespaces.
841 851 if self.merge_completions:
842 852 self.matches = []
843 853 for matcher in self.matchers:
844 854 try:
845 855 self.matches.extend(matcher(text))
846 856 except:
847 857 # Show the ugly traceback if the matcher causes an
848 858 # exception, but do NOT crash the kernel!
849 859 sys.excepthook(*sys.exc_info())
850 860 else:
851 861 for matcher in self.matchers:
852 862 self.matches = matcher(text)
853 863 if self.matches:
854 864 break
855 865 # FIXME: we should extend our api to return a dict with completions for
856 866 # different types of objects. The rlcomplete() method could then
857 867 # simply collapse the dict into a list for readline, but we'd have
858 868 # richer completion semantics in other evironments.
859 869 self.matches = sorted(set(self.matches))
860 870 #io.rprint('COMP TEXT, MATCHES: %r, %r' % (text, self.matches)) # dbg
861 871 return text, self.matches
862 872
863 873 def rlcomplete(self, text, state):
864 874 """Return the state-th possible completion for 'text'.
865 875
866 876 This is called successively with state == 0, 1, 2, ... until it
867 877 returns None. The completion should begin with 'text'.
868 878
869 879 Parameters
870 880 ----------
871 881 text : string
872 882 Text to perform the completion on.
873 883
874 884 state : int
875 885 Counter used by readline.
876 886 """
877 887 if state==0:
878 888
879 889 self.line_buffer = line_buffer = self.readline.get_line_buffer()
880 890 cursor_pos = self.readline.get_endidx()
881 891
882 892 #io.rprint("\nRLCOMPLETE: %r %r %r" %
883 893 # (text, line_buffer, cursor_pos) ) # dbg
884 894
885 895 # if there is only a tab on a line with only whitespace, instead of
886 896 # the mostly useless 'do you want to see all million completions'
887 897 # message, just do the right thing and give the user his tab!
888 898 # Incidentally, this enables pasting of tabbed text from an editor
889 899 # (as long as autoindent is off).
890 900
891 901 # It should be noted that at least pyreadline still shows file
892 902 # completions - is there a way around it?
893 903
894 904 # don't apply this on 'dumb' terminals, such as emacs buffers, so
895 905 # we don't interfere with their own tab-completion mechanism.
896 906 if not (self.dumb_terminal or line_buffer.strip()):
897 907 self.readline.insert_text('\t')
898 908 sys.stdout.flush()
899 909 return None
900 910
901 911 # Note: debugging exceptions that may occur in completion is very
902 912 # tricky, because readline unconditionally silences them. So if
903 913 # during development you suspect a bug in the completion code, turn
904 914 # this flag on temporarily by uncommenting the second form (don't
905 915 # flip the value in the first line, as the '# dbg' marker can be
906 916 # automatically detected and is used elsewhere).
907 917 DEBUG = False
908 918 #DEBUG = True # dbg
909 919 if DEBUG:
910 920 try:
911 921 self.complete(text, line_buffer, cursor_pos)
912 922 except:
913 923 import traceback; traceback.print_exc()
914 924 else:
915 925 # The normal production version is here
916 926
917 927 # This method computes the self.matches array
918 928 self.complete(text, line_buffer, cursor_pos)
919 929
920 930 try:
921 931 return self.matches[state]
922 932 except IndexError:
923 933 return None
@@ -1,292 +1,343 b''
1 1 """Tests for the IPython tab-completion machinery.
2 2 """
3 3 #-----------------------------------------------------------------------------
4 4 # Module imports
5 5 #-----------------------------------------------------------------------------
6 6
7 7 # stdlib
8 8 import os
9 9 import sys
10 10 import unittest
11 11
12 12 # third party
13 13 import nose.tools as nt
14 14
15 15 # our own packages
16 16 from IPython.config.loader import Config
17 17 from IPython.core import completer
18 18 from IPython.external.decorators import knownfailureif
19 19 from IPython.utils.tempdir import TemporaryDirectory
20 20 from IPython.utils.generics import complete_object
21 21
22 22 #-----------------------------------------------------------------------------
23 23 # Test functions
24 24 #-----------------------------------------------------------------------------
25 25 def test_protect_filename():
26 26 pairs = [ ('abc','abc'),
27 27 (' abc',r'\ abc'),
28 28 ('a bc',r'a\ bc'),
29 29 ('a bc',r'a\ \ bc'),
30 30 (' bc',r'\ \ bc'),
31 31 ]
32 32 # On posix, we also protect parens and other special characters
33 33 if sys.platform != 'win32':
34 34 pairs.extend( [('a(bc',r'a\(bc'),
35 35 ('a)bc',r'a\)bc'),
36 36 ('a( )bc',r'a\(\ \)bc'),
37 37 ('a[1]bc', r'a\[1\]bc'),
38 38 ('a{1}bc', r'a\{1\}bc'),
39 39 ('a#bc', r'a\#bc'),
40 40 ('a?bc', r'a\?bc'),
41 41 ('a=bc', r'a\=bc'),
42 42 ('a\\bc', r'a\\bc'),
43 43 ('a|bc', r'a\|bc'),
44 44 ('a;bc', r'a\;bc'),
45 45 ('a:bc', r'a\:bc'),
46 46 ("a'bc", r"a\'bc"),
47 47 ('a*bc', r'a\*bc'),
48 48 ('a"bc', r'a\"bc'),
49 49 ('a^bc', r'a\^bc'),
50 50 ('a&bc', r'a\&bc'),
51 51 ] )
52 52 # run the actual tests
53 53 for s1, s2 in pairs:
54 54 s1p = completer.protect_filename(s1)
55 55 nt.assert_equals(s1p, s2)
56 56
57 57
58 58 def check_line_split(splitter, test_specs):
59 59 for part1, part2, split in test_specs:
60 60 cursor_pos = len(part1)
61 61 line = part1+part2
62 62 out = splitter.split_line(line, cursor_pos)
63 63 nt.assert_equal(out, split)
64 64
65 65
66 66 def test_line_split():
67 67 """Basice line splitter test with default specs."""
68 68 sp = completer.CompletionSplitter()
69 69 # The format of the test specs is: part1, part2, expected answer. Parts 1
70 70 # and 2 are joined into the 'line' sent to the splitter, as if the cursor
71 71 # was at the end of part1. So an empty part2 represents someone hitting
72 72 # tab at the end of the line, the most common case.
73 73 t = [('run some/scrip', '', 'some/scrip'),
74 74 ('run scripts/er', 'ror.py foo', 'scripts/er'),
75 75 ('echo $HOM', '', 'HOM'),
76 76 ('print sys.pa', '', 'sys.pa'),
77 77 ('print(sys.pa', '', 'sys.pa'),
78 78 ("execfile('scripts/er", '', 'scripts/er'),
79 79 ('a[x.', '', 'x.'),
80 80 ('a[x.', 'y', 'x.'),
81 81 ('cd "some_file/', '', 'some_file/'),
82 82 ]
83 83 check_line_split(sp, t)
84 84 # Ensure splitting works OK with unicode by re-running the tests with
85 85 # all inputs turned into unicode
86 86 check_line_split(sp, [ map(unicode, p) for p in t] )
87 87
88 88
89 89 def test_custom_completion_error():
90 90 """Test that errors from custom attribute completers are silenced."""
91 91 ip = get_ipython()
92 92 class A(object): pass
93 93 ip.user_ns['a'] = A()
94 94
95 95 @complete_object.when_type(A)
96 96 def complete_A(a, existing_completions):
97 97 raise TypeError("this should be silenced")
98 98
99 99 ip.complete("a.")
100 100
101 101
102 102 def test_unicode_completions():
103 103 ip = get_ipython()
104 104 # Some strings that trigger different types of completion. Check them both
105 105 # in str and unicode forms
106 106 s = ['ru', '%ru', 'cd /', 'floa', 'float(x)/']
107 107 for t in s + map(unicode, s):
108 108 # We don't need to check exact completion values (they may change
109 109 # depending on the state of the namespace, but at least no exceptions
110 110 # should be thrown and the return value should be a pair of text, list
111 111 # values.
112 112 text, matches = ip.complete(t)
113 113 nt.assert_true(isinstance(text, basestring))
114 114 nt.assert_true(isinstance(matches, list))
115 115
116 116
117 117 class CompletionSplitterTestCase(unittest.TestCase):
118 118 def setUp(self):
119 119 self.sp = completer.CompletionSplitter()
120 120
121 121 def test_delim_setting(self):
122 122 self.sp.delims = ' '
123 123 nt.assert_equal(self.sp.delims, ' ')
124 124 nt.assert_equal(self.sp._delim_expr, '[\ ]')
125 125
126 126 def test_spaces(self):
127 127 """Test with only spaces as split chars."""
128 128 self.sp.delims = ' '
129 129 t = [('foo', '', 'foo'),
130 130 ('run foo', '', 'foo'),
131 131 ('run foo', 'bar', 'foo'),
132 132 ]
133 133 check_line_split(self.sp, t)
134 134
135 135
136 136 def test_has_open_quotes1():
137 137 for s in ["'", "'''", "'hi' '"]:
138 138 nt.assert_equal(completer.has_open_quotes(s), "'")
139 139
140 140
141 141 def test_has_open_quotes2():
142 142 for s in ['"', '"""', '"hi" "']:
143 143 nt.assert_equal(completer.has_open_quotes(s), '"')
144 144
145 145
146 146 def test_has_open_quotes3():
147 147 for s in ["''", "''' '''", "'hi' 'ipython'"]:
148 148 nt.assert_false(completer.has_open_quotes(s))
149 149
150 150
151 151 def test_has_open_quotes4():
152 152 for s in ['""', '""" """', '"hi" "ipython"']:
153 153 nt.assert_false(completer.has_open_quotes(s))
154 154
155 155
156 156 @knownfailureif(sys.platform == 'win32', "abspath completions fail on Windows")
157 157 def test_abspath_file_completions():
158 158 ip = get_ipython()
159 159 with TemporaryDirectory() as tmpdir:
160 160 prefix = os.path.join(tmpdir, 'foo')
161 161 suffixes = map(str, [1,2])
162 162 names = [prefix+s for s in suffixes]
163 163 for n in names:
164 164 open(n, 'w').close()
165 165
166 166 # Check simple completion
167 167 c = ip.complete(prefix)[1]
168 168 nt.assert_equal(c, names)
169 169
170 170 # Now check with a function call
171 171 cmd = 'a = f("%s' % prefix
172 172 c = ip.complete(prefix, cmd)[1]
173 173 comp = [prefix+s for s in suffixes]
174 174 nt.assert_equal(c, comp)
175 175
176 176
177 177 def test_local_file_completions():
178 178 ip = get_ipython()
179 179 cwd = os.getcwdu()
180 180 try:
181 181 with TemporaryDirectory() as tmpdir:
182 182 os.chdir(tmpdir)
183 183 prefix = './foo'
184 184 suffixes = map(str, [1,2])
185 185 names = [prefix+s for s in suffixes]
186 186 for n in names:
187 187 open(n, 'w').close()
188 188
189 189 # Check simple completion
190 190 c = ip.complete(prefix)[1]
191 191 nt.assert_equal(c, names)
192 192
193 193 # Now check with a function call
194 194 cmd = 'a = f("%s' % prefix
195 195 c = ip.complete(prefix, cmd)[1]
196 196 comp = [prefix+s for s in suffixes]
197 197 nt.assert_equal(c, comp)
198 198 finally:
199 199 # prevent failures from making chdir stick
200 200 os.chdir(cwd)
201 201
202 202
203 203 def test_greedy_completions():
204 204 ip = get_ipython()
205 205 greedy_original = ip.Completer.greedy
206 206 try:
207 207 ip.Completer.greedy = False
208 208 ip.ex('a=range(5)')
209 209 _,c = ip.complete('.',line='a[0].')
210 210 nt.assert_false('a[0].real' in c,
211 211 "Shouldn't have completed on a[0]: %s"%c)
212 212 ip.Completer.greedy = True
213 213 _,c = ip.complete('.',line='a[0].')
214 214 nt.assert_true('a[0].real' in c, "Should have completed on a[0]: %s"%c)
215 215 finally:
216 216 ip.Completer.greedy = greedy_original
217 217
218 218
219 219 def test_omit__names():
220 220 # also happens to test IPCompleter as a configurable
221 221 ip = get_ipython()
222 222 ip._hidden_attr = 1
223 223 c = ip.Completer
224 224 ip.ex('ip=get_ipython()')
225 225 cfg = Config()
226 226 cfg.IPCompleter.omit__names = 0
227 227 c.update_config(cfg)
228 228 s,matches = c.complete('ip.')
229 229 nt.assert_true('ip.__str__' in matches)
230 230 nt.assert_true('ip._hidden_attr' in matches)
231 231 cfg.IPCompleter.omit__names = 1
232 232 c.update_config(cfg)
233 233 s,matches = c.complete('ip.')
234 234 nt.assert_false('ip.__str__' in matches)
235 235 nt.assert_true('ip._hidden_attr' in matches)
236 236 cfg.IPCompleter.omit__names = 2
237 237 c.update_config(cfg)
238 238 s,matches = c.complete('ip.')
239 239 nt.assert_false('ip.__str__' in matches)
240 240 nt.assert_false('ip._hidden_attr' in matches)
241 241 del ip._hidden_attr
242 242
243 243
244 244 def test_limit_to__all__False_ok():
245 245 ip = get_ipython()
246 246 c = ip.Completer
247 247 ip.ex('class D: x=24')
248 248 ip.ex('d=D()')
249 249 cfg = Config()
250 250 cfg.IPCompleter.limit_to__all__ = False
251 251 c.update_config(cfg)
252 252 s, matches = c.complete('d.')
253 253 nt.assert_true('d.x' in matches)
254 254
255 255
256 256 def test_limit_to__all__True_ok():
257 257 ip = get_ipython()
258 258 c = ip.Completer
259 259 ip.ex('class D: x=24')
260 260 ip.ex('d=D()')
261 261 ip.ex("d.__all__=['z']")
262 262 cfg = Config()
263 263 cfg.IPCompleter.limit_to__all__ = True
264 264 c.update_config(cfg)
265 265 s, matches = c.complete('d.')
266 266 nt.assert_true('d.z' in matches)
267 267 nt.assert_false('d.x' in matches)
268 268
269 269
270 270 def test_get__all__entries_ok():
271 271 class A(object):
272 272 __all__ = ['x', 1]
273 273 words = completer.get__all__entries(A())
274 274 nt.assert_equal(words, ['x'])
275 275
276 276
277 277 def test_get__all__entries_no__all__ok():
278 278 class A(object):
279 279 pass
280 280 words = completer.get__all__entries(A())
281 281 nt.assert_equal(words, [])
282 282
283 283
284 284 def test_func_kw_completions():
285 285 ip = get_ipython()
286 286 c = ip.Completer
287 287 ip.ex('def myfunc(a=1,b=2): return a+b')
288 288 s, matches = c.complete(None, 'myfunc(1,b')
289 289 nt.assert_in('b=', matches)
290 290 # Simulate completing with cursor right after b (pos==10):
291 291 s, matches = c.complete(None,'myfunc(1,b)', 10)
292 292 nt.assert_in('b=', matches)
293
294
295 def test_line_magics():
296 ip = get_ipython()
297 c = ip.Completer
298 s, matches = c.complete(None, 'lsmag')
299 nt.assert_in('%lsmagic', matches)
300 s, matches = c.complete(None, '%lsmag')
301 nt.assert_in('%lsmagic', matches)
302
303
304 def test_cell_magics():
305 from IPython.core.magic import register_cell_magic
306
307 @register_cell_magic
308 def _foo_cellm(line, cell):
309 pass
310
311 ip = get_ipython()
312 c = ip.Completer
313
314 s, matches = c.complete(None, '_foo_ce')
315 nt.assert_in('%%_foo_cellm', matches)
316 s, matches = c.complete(None, '%%_foo_ce')
317 nt.assert_in('%%_foo_cellm', matches)
318
319
320 def test_line_cell_magics():
321 from IPython.core.magic import register_line_cell_magic
322
323 @register_line_cell_magic
324 def _bar_cellm(line, cell):
325 pass
326
327 ip = get_ipython()
328 c = ip.Completer
329
330 # The policy here is trickier, see comments in completion code. The
331 # returned values depend on whether the user passes %% or not explicitly,
332 # and this will show a difference if the same name is both a line and cell
333 # magic.
334 s, matches = c.complete(None, '_bar_ce')
335 nt.assert_in('%_bar_cellm', matches)
336 nt.assert_in('%%_bar_cellm', matches)
337 s, matches = c.complete(None, '%_bar_ce')
338 nt.assert_in('%_bar_cellm', matches)
339 nt.assert_in('%%_bar_cellm', matches)
340 s, matches = c.complete(None, '%%_bar_ce')
341 nt.assert_not_in('%_bar_cellm', matches)
342 nt.assert_in('%%_bar_cellm', matches)
343
General Comments 0
You need to be logged in to leave comments. Login now