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