##// END OF EJS Templates
Fix bugs with completions of paths that have ~ in them....
Fernando Perez -
Show More
@@ -1,795 +1,841 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-2010 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.core.error import TryNext
82 82 from IPython.core.prefilter import ESC_MAGIC
83 83 from IPython.utils import generics
84 84 from IPython.utils import io
85 85 from IPython.utils.dir2 import dir2
86 86
87 87 #-----------------------------------------------------------------------------
88 88 # Globals
89 89 #-----------------------------------------------------------------------------
90 90
91 91 # Public API
92 92 __all__ = ['Completer','IPCompleter']
93 93
94 94 if sys.platform == 'win32':
95 95 PROTECTABLES = ' '
96 96 else:
97 97 PROTECTABLES = ' ()'
98 98
99 99 #-----------------------------------------------------------------------------
100 100 # Main functions and classes
101 101 #-----------------------------------------------------------------------------
102 102
103 103 def protect_filename(s):
104 104 """Escape a string to protect certain characters."""
105 105
106 106 return "".join([(ch in PROTECTABLES and '\\' + ch or ch)
107 107 for ch in s])
108 108
109 109
110 110 def mark_dirs(matches):
111 111 """Mark directories in input list by appending '/' to their names."""
112 112 out = []
113 113 isdir = os.path.isdir
114 114 for x in matches:
115 115 if isdir(x):
116 116 out.append(x+'/')
117 117 else:
118 118 out.append(x)
119 119 return out
120 120
121 121
122 def expand_user(path):
123 """Expand '~'-style usernames in strings.
124
125 This is similar to :func:`os.path.expanduser`, but it computes and returns
126 extra information that will be useful if the input was being used in
127 computing completions, and you wish to return the completions with the
128 original '~' instead of its expanded value.
129
130 Parameters
131 ----------
132 path : str
133 String to be expanded. If no ~ is present, the output is the same as the
134 input.
135
136 Returns
137 -------
138 newpath : str
139 Result of ~ expansion in the input path.
140 tilde_expand : bool
141 Whether any expansion was performed or not.
142 tilde_val : str
143 The value that ~ was replaced with.
144 """
145 # Default values
146 tilde_expand = False
147 tilde_val = ''
148 newpath = path
149
150 if path.startswith('~'):
151 tilde_expand = True
152 rest = path[1:]
153 newpath = os.path.expanduser(path)
154 tilde_val = newpath.replace(rest, '')
155
156 return newpath, tilde_expand, tilde_val
157
158
159 def compress_user(path, tilde_expand, tilde_val):
160 """Does the opposite of expand_user, with its outputs.
161 """
162 if tilde_expand:
163 return path.replace(tilde_val, '~')
164 else:
165 return path
166
167
122 168 def single_dir_expand(matches):
123 169 "Recursively expand match lists containing a single dir."
124 170
125 171 if len(matches) == 1 and os.path.isdir(matches[0]):
126 172 # Takes care of links to directories also. Use '/'
127 173 # explicitly, even under Windows, so that name completions
128 174 # don't end up escaped.
129 175 d = matches[0]
130 176 if d[-1] in ['/','\\']:
131 177 d = d[:-1]
132 178
133 179 subdirs = os.listdir(d)
134 180 if subdirs:
135 181 matches = [ (d + '/' + p) for p in subdirs]
136 182 return single_dir_expand(matches)
137 183 else:
138 184 return matches
139 185 else:
140 186 return matches
141 187
142 188
143 189 class Bunch(object): pass
144 190
145 191
146 192 class CompletionSplitter(object):
147 193 """An object to split an input line in a manner similar to readline.
148 194
149 195 By having our own implementation, we can expose readline-like completion in
150 196 a uniform manner to all frontends. This object only needs to be given the
151 197 line of text to be split and the cursor position on said line, and it
152 198 returns the 'word' to be completed on at the cursor after splitting the
153 199 entire line.
154 200
155 201 What characters are used as splitting delimiters can be controlled by
156 202 setting the `delims` attribute (this is a property that internally
157 203 automatically builds the necessary """
158 204
159 205 # Private interface
160 206
161 207 # A string of delimiter characters. The default value makes sense for
162 208 # IPython's most typical usage patterns.
163 209 _delims = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
164 210
165 211 # The expression (a normal string) to be compiled into a regular expression
166 212 # for actual splitting. We store it as an attribute mostly for ease of
167 213 # debugging, since this type of code can be so tricky to debug.
168 214 _delim_expr = None
169 215
170 216 # The regular expression that does the actual splitting
171 217 _delim_re = None
172 218
173 219 def __init__(self, delims=None):
174 220 delims = CompletionSplitter._delims if delims is None else delims
175 221 self.set_delims(delims)
176 222
177 223 def set_delims(self, delims):
178 224 """Set the delimiters for line splitting."""
179 225 expr = '[' + ''.join('\\'+ c for c in delims) + ']'
180 226 self._delim_re = re.compile(expr)
181 227 self._delims = delims
182 228 self._delim_expr = expr
183 229
184 230 def get_delims(self):
185 231 """Return the string of delimiter characters."""
186 232 return self._delims
187 233
188 234 def split_line(self, line, cursor_pos=None):
189 235 """Split a line of text with a cursor at the given position.
190 236 """
191 237 l = line if cursor_pos is None else line[:cursor_pos]
192 238 return self._delim_re.split(l)[-1]
193 239
194 240
195 241 class Completer(object):
196 242 def __init__(self, namespace=None, global_namespace=None):
197 243 """Create a new completer for the command line.
198 244
199 245 Completer([namespace,global_namespace]) -> completer instance.
200 246
201 247 If unspecified, the default namespace where completions are performed
202 248 is __main__ (technically, __main__.__dict__). Namespaces should be
203 249 given as dictionaries.
204 250
205 251 An optional second namespace can be given. This allows the completer
206 252 to handle cases where both the local and global scopes need to be
207 253 distinguished.
208 254
209 255 Completer instances should be used as the completion mechanism of
210 256 readline via the set_completer() call:
211 257
212 258 readline.set_completer(Completer(my_namespace).complete)
213 259 """
214 260
215 261 # Don't bind to namespace quite yet, but flag whether the user wants a
216 262 # specific namespace or to use __main__.__dict__. This will allow us
217 263 # to bind to __main__.__dict__ at completion time, not now.
218 264 if namespace is None:
219 265 self.use_main_ns = 1
220 266 else:
221 267 self.use_main_ns = 0
222 268 self.namespace = namespace
223 269
224 270 # The global namespace, if given, can be bound directly
225 271 if global_namespace is None:
226 272 self.global_namespace = {}
227 273 else:
228 274 self.global_namespace = global_namespace
229 275
230 276 def complete(self, text, state):
231 277 """Return the next possible completion for 'text'.
232 278
233 279 This is called successively with state == 0, 1, 2, ... until it
234 280 returns None. The completion should begin with 'text'.
235 281
236 282 """
237 283 if self.use_main_ns:
238 284 self.namespace = __main__.__dict__
239 285
240 286 if state == 0:
241 287 if "." in text:
242 288 self.matches = self.attr_matches(text)
243 289 else:
244 290 self.matches = self.global_matches(text)
245 291 try:
246 292 return self.matches[state]
247 293 except IndexError:
248 294 return None
249 295
250 296 def global_matches(self, text):
251 297 """Compute matches when text is a simple name.
252 298
253 299 Return a list of all keywords, built-in functions and names currently
254 300 defined in self.namespace or self.global_namespace that match.
255 301
256 302 """
257 303 #print 'Completer->global_matches, txt=%r' % text # dbg
258 304 matches = []
259 305 match_append = matches.append
260 306 n = len(text)
261 307 for lst in [keyword.kwlist,
262 308 __builtin__.__dict__.keys(),
263 309 self.namespace.keys(),
264 310 self.global_namespace.keys()]:
265 311 for word in lst:
266 312 if word[:n] == text and word != "__builtins__":
267 313 match_append(word)
268 314 return matches
269 315
270 316 def attr_matches(self, text):
271 317 """Compute matches when text contains a dot.
272 318
273 319 Assuming the text is of the form NAME.NAME....[NAME], and is
274 320 evaluatable in self.namespace or self.global_namespace, it will be
275 321 evaluated and its attributes (as revealed by dir()) are used as
276 322 possible completions. (For class instances, class members are are
277 323 also considered.)
278 324
279 325 WARNING: this can still invoke arbitrary C code, if an object
280 326 with a __getattr__ hook is evaluated.
281 327
282 328 """
283 329
284 330 #print 'Completer->attr_matches, txt=%r' % text # dbg
285 331 # Another option, seems to work great. Catches things like ''.<tab>
286 332 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
287 333
288 334 if not m:
289 335 return []
290 336
291 337 expr, attr = m.group(1, 3)
292 338 try:
293 339 obj = eval(expr, self.namespace)
294 340 except:
295 341 try:
296 342 obj = eval(expr, self.global_namespace)
297 343 except:
298 344 return []
299 345
300 346 words = dir2(obj)
301 347
302 348 try:
303 349 words = generics.complete_object(obj, words)
304 350 except TryNext:
305 351 pass
306 352 # Build match list to return
307 353 n = len(attr)
308 354 res = ["%s.%s" % (expr, w) for w in words if w[:n] == attr ]
309 355 return res
310 356
311 357
312 358 class IPCompleter(Completer):
313 359 """Extension of the completer class with IPython-specific features"""
314 360
315 361 def __init__(self, shell, namespace=None, global_namespace=None,
316 362 omit__names=0, alias_table=None, use_readline=True):
317 363 """IPCompleter() -> completer
318 364
319 365 Return a completer object suitable for use by the readline library
320 366 via readline.set_completer().
321 367
322 368 Inputs:
323 369
324 370 - shell: a pointer to the ipython shell itself. This is needed
325 371 because this completer knows about magic functions, and those can
326 372 only be accessed via the ipython instance.
327 373
328 374 - namespace: an optional dict where completions are performed.
329 375
330 376 - global_namespace: secondary optional dict for completions, to
331 377 handle cases (such as IPython embedded inside functions) where
332 378 both Python scopes are visible.
333 379
334 380 - The optional omit__names parameter sets the completer to omit the
335 381 'magic' names (__magicname__) for python objects unless the text
336 382 to be completed explicitly starts with one or more underscores.
337 383
338 384 - If alias_table is supplied, it should be a dictionary of aliases
339 385 to complete.
340 386
341 387 use_readline : bool, optional
342 388 If true, use the readline library. This completer can still function
343 389 without readline, though in that case callers must provide some extra
344 390 information on each call about the current line."""
345 391
346 392 Completer.__init__(self, namespace, global_namespace)
347 393
348 394 self.magic_escape = ESC_MAGIC
349 395 self.splitter = CompletionSplitter()
350 396
351 397 # Readline configuration, only used by the rlcompleter method.
352 398 if use_readline:
353 399 # We store the right version of readline so that later code
354 400 import IPython.utils.rlineimpl as readline
355 401 self.readline = readline
356 402 else:
357 403 self.readline = None
358 404
359 405 # List where completion matches will be stored
360 406 self.matches = []
361 407 self.omit__names = omit__names
362 408 self.merge_completions = shell.readline_merge_completions
363 409 self.shell = shell.shell
364 410 if alias_table is None:
365 411 alias_table = {}
366 412 self.alias_table = alias_table
367 413 # Regexp to split filenames with spaces in them
368 414 self.space_name_re = re.compile(r'([^\\] )')
369 415 # Hold a local ref. to glob.glob for speed
370 416 self.glob = glob.glob
371 417
372 418 # Determine if we are running on 'dumb' terminals, like (X)Emacs
373 419 # buffers, to avoid completion problems.
374 420 term = os.environ.get('TERM','xterm')
375 421 self.dumb_terminal = term in ['dumb','emacs']
376 422
377 423 # Special handling of backslashes needed in win32 platforms
378 424 if sys.platform == "win32":
379 425 self.clean_glob = self._clean_glob_win32
380 426 else:
381 427 self.clean_glob = self._clean_glob
382 428
383 429 # All active matcher routines for completion
384 430 self.matchers = [self.python_matches,
385 431 self.file_matches,
386 432 self.magic_matches,
387 433 self.alias_matches,
388 434 self.python_func_kw_matches,
389 435 ]
390 436
391 437 # Code contributed by Alex Schmolck, for ipython/emacs integration
392 438 def all_completions(self, text):
393 439 """Return all possible completions for the benefit of emacs."""
394 440
395 441 completions = []
396 442 comp_append = completions.append
397 443 try:
398 444 for i in xrange(sys.maxint):
399 445 res = self.complete(text, i, text)
400 446 if not res:
401 447 break
402 448 comp_append(res)
403 449 #XXX workaround for ``notDefined.<tab>``
404 450 except NameError:
405 451 pass
406 452 return completions
407 453 # /end Alex Schmolck code.
408 454
409 455 def _clean_glob(self,text):
410 456 return self.glob("%s*" % text)
411 457
412 458 def _clean_glob_win32(self,text):
413 459 return [f.replace("\\","/")
414 460 for f in self.glob("%s*" % text)]
415 461
416 462 def file_matches(self, text):
417 463 """Match filenames, expanding ~USER type strings.
418 464
419 465 Most of the seemingly convoluted logic in this completer is an
420 466 attempt to handle filenames with spaces in them. And yet it's not
421 467 quite perfect, because Python's readline doesn't expose all of the
422 468 GNU readline details needed for this to be done correctly.
423 469
424 470 For a filename with a space in it, the printed completions will be
425 471 only the parts after what's already been typed (instead of the
426 472 full completions, as is normally done). I don't think with the
427 473 current (as of Python 2.3) Python readline it's possible to do
428 474 better."""
429 475
430 476 #io.rprint('Completer->file_matches: <%s>' % text) # dbg
431 477
432 478 # chars that require escaping with backslash - i.e. chars
433 479 # that readline treats incorrectly as delimiters, but we
434 480 # don't want to treat as delimiters in filename matching
435 481 # when escaped with backslash
436 482 if text.startswith('!'):
437 483 text = text[1:]
438 484 text_prefix = '!'
439 485 else:
440 486 text_prefix = ''
441 487
442 488 text_until_cursor = self.text_until_cursor
443 489 open_quotes = 0 # track strings with open quotes
444 490 try:
445 491 lsplit = shlex.split(text_until_cursor)[-1]
446 492 except ValueError:
447 493 # typically an unmatched ", or backslash without escaped char.
448 494 if text_until_cursor.count('"')==1:
449 495 open_quotes = 1
450 496 lsplit = text_until_cursor.split('"')[-1]
451 497 elif text_until_cursor.count("'")==1:
452 498 open_quotes = 1
453 499 lsplit = text_until_cursor.split("'")[-1]
454 500 else:
455 501 return []
456 502 except IndexError:
457 503 # tab pressed on empty line
458 504 lsplit = ""
459 505
460 506 if not open_quotes and lsplit != protect_filename(lsplit):
461 507 # if protectables are found, do matching on the whole escaped
462 508 # name
463 509 has_protectables = 1
464 510 text0,text = text,lsplit
465 511 else:
466 512 has_protectables = 0
467 513 text = os.path.expanduser(text)
468 514
469 515 if text == "":
470 516 return [text_prefix + protect_filename(f) for f in self.glob("*")]
471 517
472 518 m0 = self.clean_glob(text.replace('\\',''))
473 519 if has_protectables:
474 520 # If we had protectables, we need to revert our changes to the
475 521 # beginning of filename so that we don't double-write the part
476 522 # of the filename we have so far
477 523 len_lsplit = len(lsplit)
478 524 matches = [text_prefix + text0 +
479 525 protect_filename(f[len_lsplit:]) for f in m0]
480 526 else:
481 527 if open_quotes:
482 528 # if we have a string with an open quote, we don't need to
483 529 # protect the names at all (and we _shouldn't_, as it
484 530 # would cause bugs when the filesystem call is made).
485 531 matches = m0
486 532 else:
487 533 matches = [text_prefix +
488 534 protect_filename(f) for f in m0]
489 535
490 536 #io.rprint('mm', matches) # dbg
491 537 return mark_dirs(matches)
492 538
493 539 def magic_matches(self, text):
494 540 """Match magics"""
495 541 #print 'Completer->magic_matches:',text,'lb',self.text_until_cursor # dbg
496 542 # Get all shell magics now rather than statically, so magics loaded at
497 543 # runtime show up too
498 544 magics = self.shell.lsmagic()
499 545 pre = self.magic_escape
500 546 baretext = text.lstrip(pre)
501 547 return [ pre+m for m in magics if m.startswith(baretext)]
502 548
503 549 def alias_matches(self, text):
504 550 """Match internal system aliases"""
505 551 #print 'Completer->alias_matches:',text,'lb',self.text_until_cursor # dbg
506 552
507 553 # if we are not in the first 'item', alias matching
508 554 # doesn't make sense - unless we are starting with 'sudo' command.
509 555 main_text = self.text_until_cursor.lstrip()
510 556 if ' ' in main_text and not main_text.startswith('sudo'):
511 557 return []
512 558 text = os.path.expanduser(text)
513 559 aliases = self.alias_table.keys()
514 560 if text == '':
515 561 return aliases
516 562 else:
517 563 return [a for a in aliases if a.startswith(text)]
518 564
519 565 def python_matches(self,text):
520 566 """Match attributes or global python names"""
521 567
522 568 #print 'Completer->python_matches, txt=%r' % text # dbg
523 569 if "." in text:
524 570 try:
525 571 matches = self.attr_matches(text)
526 572 if text.endswith('.') and self.omit__names:
527 573 if self.omit__names == 1:
528 574 # true if txt is _not_ a __ name, false otherwise:
529 575 no__name = (lambda txt:
530 576 re.match(r'.*\.__.*?__',txt) is None)
531 577 else:
532 578 # true if txt is _not_ a _ name, false otherwise:
533 579 no__name = (lambda txt:
534 580 re.match(r'.*\._.*?',txt) is None)
535 581 matches = filter(no__name, matches)
536 582 except NameError:
537 583 # catches <undefined attributes>.<tab>
538 584 matches = []
539 585 else:
540 586 matches = self.global_matches(text)
541 587
542 588 return matches
543 589
544 590 def _default_arguments(self, obj):
545 591 """Return the list of default arguments of obj if it is callable,
546 592 or empty list otherwise."""
547 593
548 594 if not (inspect.isfunction(obj) or inspect.ismethod(obj)):
549 595 # for classes, check for __init__,__new__
550 596 if inspect.isclass(obj):
551 597 obj = (getattr(obj,'__init__',None) or
552 598 getattr(obj,'__new__',None))
553 599 # for all others, check if they are __call__able
554 600 elif hasattr(obj, '__call__'):
555 601 obj = obj.__call__
556 602 # XXX: is there a way to handle the builtins ?
557 603 try:
558 604 args,_,_1,defaults = inspect.getargspec(obj)
559 605 if defaults:
560 606 return args[-len(defaults):]
561 607 except TypeError: pass
562 608 return []
563 609
564 610 def python_func_kw_matches(self,text):
565 611 """Match named parameters (kwargs) of the last open function"""
566 612
567 613 if "." in text: # a parameter cannot be dotted
568 614 return []
569 615 try: regexp = self.__funcParamsRegex
570 616 except AttributeError:
571 617 regexp = self.__funcParamsRegex = re.compile(r'''
572 618 '.*?' | # single quoted strings or
573 619 ".*?" | # double quoted strings or
574 620 \w+ | # identifier
575 621 \S # other characters
576 622 ''', re.VERBOSE | re.DOTALL)
577 623 # 1. find the nearest identifier that comes before an unclosed
578 624 # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo"
579 625 tokens = regexp.findall(self.line_buffer)
580 626 tokens.reverse()
581 627 iterTokens = iter(tokens); openPar = 0
582 628 for token in iterTokens:
583 629 if token == ')':
584 630 openPar -= 1
585 631 elif token == '(':
586 632 openPar += 1
587 633 if openPar > 0:
588 634 # found the last unclosed parenthesis
589 635 break
590 636 else:
591 637 return []
592 638 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
593 639 ids = []
594 640 isId = re.compile(r'\w+$').match
595 641 while True:
596 642 try:
597 643 ids.append(iterTokens.next())
598 644 if not isId(ids[-1]):
599 645 ids.pop(); break
600 646 if not iterTokens.next() == '.':
601 647 break
602 648 except StopIteration:
603 649 break
604 650 # lookup the candidate callable matches either using global_matches
605 651 # or attr_matches for dotted names
606 652 if len(ids) == 1:
607 653 callableMatches = self.global_matches(ids[0])
608 654 else:
609 655 callableMatches = self.attr_matches('.'.join(ids[::-1]))
610 656 argMatches = []
611 657 for callableMatch in callableMatches:
612 658 try:
613 659 namedArgs = self._default_arguments(eval(callableMatch,
614 660 self.namespace))
615 661 except:
616 662 continue
617 663 for namedArg in namedArgs:
618 664 if namedArg.startswith(text):
619 665 argMatches.append("%s=" %namedArg)
620 666 return argMatches
621 667
622 668 def dispatch_custom_completer(self, text):
623 669 #print "Custom! '%s' %s" % (text, self.custom_completers) # dbg
624 670 line = self.line_buffer
625 671 if not line.strip():
626 672 return None
627 673
628 674 # Create a little structure to pass all the relevant information about
629 675 # the current completion to any custom completer.
630 676 event = Bunch()
631 677 event.line = line
632 678 event.symbol = text
633 679 cmd = line.split(None,1)[0]
634 680 event.command = cmd
635 681 event.text_until_cursor = self.text_until_cursor
636 682
637 683 #print "\ncustom:{%s]\n" % event # dbg
638 684
639 685 # for foo etc, try also to find completer for %foo
640 686 if not cmd.startswith(self.magic_escape):
641 687 try_magic = self.custom_completers.s_matches(
642 688 self.magic_escape + cmd)
643 689 else:
644 690 try_magic = []
645 691
646 692 for c in itertools.chain(self.custom_completers.s_matches(cmd),
647 693 try_magic,
648 694 self.custom_completers.flat_matches(self.text_until_cursor)):
649 695 #print "try",c # dbg
650 696 try:
651 697 res = c(event)
652 698 # first, try case sensitive match
653 699 withcase = [r for r in res if r.startswith(text)]
654 700 if withcase:
655 701 return withcase
656 702 # if none, then case insensitive ones are ok too
657 703 text_low = text.lower()
658 704 return [r for r in res if r.lower().startswith(text_low)]
659 705 except TryNext:
660 706 pass
661 707
662 708 return None
663 709
664 710 def complete(self, text=None, line_buffer=None, cursor_pos=None):
665 711 """Return the state-th possible completion for 'text'.
666 712
667 713 This is called successively with state == 0, 1, 2, ... until it
668 714 returns None. The completion should begin with 'text'.
669 715
670 716 Note that both the text and the line_buffer are optional, but at least
671 717 one of them must be given.
672 718
673 719 Parameters
674 720 ----------
675 721 text : string, optional
676 722 Text to perform the completion on. If not given, the line buffer
677 723 is split using the instance's CompletionSplitter object.
678 724
679 725 line_buffer : string, optional
680 726 If not given, the completer attempts to obtain the current line
681 727 buffer via readline. This keyword allows clients which are
682 728 requesting for text completions in non-readline contexts to inform
683 729 the completer of the entire text.
684 730
685 731 cursor_pos : int, optional
686 732 Index of the cursor in the full line buffer. Should be provided by
687 733 remote frontends where kernel has no access to frontend state.
688 734 """
689 735 #io.rprint('\nCOMP1 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg
690 736
691 737 # if the cursor position isn't given, the only sane assumption we can
692 738 # make is that it's at the end of the line (the common case)
693 739 if cursor_pos is None:
694 740 cursor_pos = len(line_buffer) if text is None else len(text)
695 741
696 742 # if text is either None or an empty string, rely on the line buffer
697 743 if not text:
698 744 text = self.splitter.split_line(line_buffer, cursor_pos)
699 745
700 746 # If no line buffer is given, assume the input text is all there was
701 747 if line_buffer is None:
702 748 line_buffer = text
703 749
704 750 self.line_buffer = line_buffer
705 751 self.text_until_cursor = self.line_buffer[:cursor_pos]
706 752 #io.rprint('\nCOMP2 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg
707 753
708 754 # Start with a clean slate of completions
709 755 self.matches[:] = []
710 756 custom_res = self.dispatch_custom_completer(text)
711 757 if custom_res is not None:
712 758 # did custom completers produce something?
713 759 self.matches = custom_res
714 760 else:
715 761 # Extend the list of completions with the results of each
716 762 # matcher, so we return results to the user from all
717 763 # namespaces.
718 764 if self.merge_completions:
719 765 self.matches = []
720 766 for matcher in self.matchers:
721 767 self.matches.extend(matcher(text))
722 768 else:
723 769 for matcher in self.matchers:
724 770 self.matches = matcher(text)
725 771 if self.matches:
726 772 break
727 773 # FIXME: we should extend our api to return a dict with completions for
728 774 # different types of objects. The rlcomplete() method could then
729 775 # simply collapse the dict into a list for readline, but we'd have
730 776 # richer completion semantics in other evironments.
731 777 self.matches = sorted(set(self.matches))
732 778 #io.rprint('COMP TEXT, MATCHES: %r, %r' % (text, self.matches)) # dbg
733 779 return text, self.matches
734 780
735 781 def rlcomplete(self, text, state):
736 782 """Return the state-th possible completion for 'text'.
737 783
738 784 This is called successively with state == 0, 1, 2, ... until it
739 785 returns None. The completion should begin with 'text'.
740 786
741 787 Parameters
742 788 ----------
743 789 text : string
744 790 Text to perform the completion on.
745 791
746 792 state : int
747 793 Counter used by readline.
748 794 """
749 795 if state==0:
750 796
751 797 self.line_buffer = line_buffer = self.readline.get_line_buffer()
752 798 cursor_pos = self.readline.get_endidx()
753 799
754 800 #io.rprint("\nRLCOMPLETE: %r %r %r" %
755 801 # (text, line_buffer, cursor_pos) ) # dbg
756 802
757 803 # if there is only a tab on a line with only whitespace, instead of
758 804 # the mostly useless 'do you want to see all million completions'
759 805 # message, just do the right thing and give the user his tab!
760 806 # Incidentally, this enables pasting of tabbed text from an editor
761 807 # (as long as autoindent is off).
762 808
763 809 # It should be noted that at least pyreadline still shows file
764 810 # completions - is there a way around it?
765 811
766 812 # don't apply this on 'dumb' terminals, such as emacs buffers, so
767 813 # we don't interfere with their own tab-completion mechanism.
768 814 if not (self.dumb_terminal or line_buffer.strip()):
769 815 self.readline.insert_text('\t')
770 816 sys.stdout.flush()
771 817 return None
772 818
773 819 # Note: debugging exceptions that may occur in completion is very
774 820 # tricky, because readline unconditionally silences them. So if
775 821 # during development you suspect a bug in the completion code, turn
776 822 # this flag on temporarily by uncommenting the second form (don't
777 823 # flip the value in the first line, as the '# dbg' marker can be
778 824 # automatically detected and is used elsewhere).
779 825 DEBUG = False
780 826 #DEBUG = True # dbg
781 827 if DEBUG:
782 828 try:
783 829 self.complete(text, line_buffer, cursor_pos)
784 830 except:
785 831 import traceback; traceback.print_exc()
786 832 else:
787 833 # The normal production version is here
788 834
789 835 # This method computes the self.matches array
790 836 self.complete(text, line_buffer, cursor_pos)
791 837
792 838 try:
793 839 return self.matches[state]
794 840 except IndexError:
795 841 return None
@@ -1,337 +1,346 b''
1 1 """Implementations for various useful completers.
2 2
3 3 These are all loaded by default by IPython.
4 4 """
5 5 #-----------------------------------------------------------------------------
6 6 # Copyright (C) 2010 The IPython Development Team.
7 7 #
8 8 # Distributed under the terms of the BSD License.
9 9 #
10 10 # The full license is in the file COPYING.txt, distributed with this software.
11 11 #-----------------------------------------------------------------------------
12 12
13 13 #-----------------------------------------------------------------------------
14 14 # Imports
15 15 #-----------------------------------------------------------------------------
16 16 from __future__ import print_function
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 shlex
24 24 import sys
25 25
26 26 # Third-party imports
27 27 from time import time
28 28 from zipimport import zipimporter
29 29
30 30 # Our own imports
31 from IPython.core.completer import expand_user, compress_user
31 32 from IPython.core.error import TryNext
32 33
33 34 # FIXME: this should be pulled in with the right call via the component system
34 35 from IPython.core.ipapi import get as get_ipython
35 36
36 37 #-----------------------------------------------------------------------------
37 38 # Globals and constants
38 39 #-----------------------------------------------------------------------------
39 40
40 41 # Time in seconds after which the rootmodules will be stored permanently in the
41 42 # ipython ip.db database (kept in the user's .ipython dir).
42 43 TIMEOUT_STORAGE = 2
43 44
44 45 # Time in seconds after which we give up
45 46 TIMEOUT_GIVEUP = 20
46 47
47 48 # Regular expression for the python import statement
48 49 import_re = re.compile(r'.*(\.so|\.py[cod]?)$')
49 50
50 51 # RE for the ipython %run command (python + ipython scripts)
51 52 magic_run_re = re.compile(r'.*(\.ipy|\.py[w]?)$')
52 53
53 54 #-----------------------------------------------------------------------------
54 55 # Local utilities
55 56 #-----------------------------------------------------------------------------
56 57
57 58 def shlex_split(x):
58 59 """Helper function to split lines into segments.
59 60 """
60 61 # shlex.split raises an exception if there is a syntax error in sh syntax
61 62 # for example if no closing " is found. This function keeps dropping the
62 63 # last character of the line until shlex.split does not raise
63 64 # an exception. It adds end of the line to the result of shlex.split
64 65 #
65 66 # Example:
66 67 # %run "c:/python -> ['%run','"c:/python']
67
68
69 # shlex.split has unicode bugs, so encode first to str
70 if isinstance(x, unicode):
71 x = x.encode(sys.stdin.encoding)
72
68 73 endofline = []
69 74 while x != '':
70 75 try:
71 76 comps = shlex.split(x)
72 77 if len(endofline) >= 1:
73 78 comps.append(''.join(endofline))
74 79 return comps
75 80
76 81 except ValueError:
77 82 endofline = [x[-1:]]+endofline
78 83 x = x[:-1]
79 84
80 85 return [''.join(endofline)]
81 86
82 87 def module_list(path):
83 88 """
84 89 Return the list containing the names of the modules available in the given
85 90 folder.
86 91 """
87 92
88 93 if os.path.isdir(path):
89 94 folder_list = os.listdir(path)
90 95 elif path.endswith('.egg'):
91 96 try:
92 97 folder_list = [f for f in zipimporter(path)._files]
93 98 except:
94 99 folder_list = []
95 100 else:
96 101 folder_list = []
97 102
98 103 if not folder_list:
99 104 return []
100 105
101 106 # A few local constants to be used in loops below
102 107 isfile = os.path.isfile
103 108 pjoin = os.path.join
104 109 basename = os.path.basename
105 110
106 111 # Now find actual path matches for packages or modules
107 112 folder_list = [p for p in folder_list
108 113 if isfile(pjoin(path, p,'__init__.py'))
109 114 or import_re.match(p) ]
110 115
111 116 return [basename(p).split('.')[0] for p in folder_list]
112 117
113 118 def get_root_modules():
114 119 """
115 120 Returns a list containing the names of all the modules available in the
116 121 folders of the pythonpath.
117 122 """
118 123 ip = get_ipython()
119 124
120 125 if 'rootmodules' in ip.db:
121 126 return ip.db['rootmodules']
122 127
123 128 t = time()
124 129 store = False
125 130 modules = list(sys.builtin_module_names)
126 131 for path in sys.path:
127 132 modules += module_list(path)
128 133 if time() - t >= TIMEOUT_STORAGE and not store:
129 134 store = True
130 135 print("\nCaching the list of root modules, please wait!")
131 136 print("(This will only be done once - type '%rehashx' to "
132 137 "reset cache!)\n")
133 138 sys.stdout.flush()
134 139 if time() - t > TIMEOUT_GIVEUP:
135 140 print("This is taking too long, we give up.\n")
136 141 ip.db['rootmodules'] = []
137 142 return []
138 143
139 144 modules = set(modules)
140 145 if '__init__' in modules:
141 146 modules.remove('__init__')
142 147 modules = list(modules)
143 148 if store:
144 149 ip.db['rootmodules'] = modules
145 150 return modules
146 151
147 152
148 153 def is_importable(module, attr, only_modules):
149 154 if only_modules:
150 155 return inspect.ismodule(getattr(module, attr))
151 156 else:
152 157 return not(attr[:2] == '__' and attr[-2:] == '__')
153 158
154 159
155 160 def try_import(mod, only_modules=False):
156 161 try:
157 162 m = __import__(mod)
158 163 except:
159 164 return []
160 165 mods = mod.split('.')
161 166 for module in mods[1:]:
162 167 m = getattr(m, module)
163 168
164 169 m_is_init = hasattr(m, '__file__') and '__init__' in m.__file__
165 170
166 171 completions = []
167 172 if (not hasattr(m, '__file__')) or (not only_modules) or m_is_init:
168 173 completions.extend( [attr for attr in dir(m) if
169 174 is_importable(m, attr, only_modules)])
170 175
171 176 completions.extend(getattr(m, '__all__', []))
172 177 if m_is_init:
173 178 completions.extend(module_list(os.path.dirname(m.__file__)))
174 179 completions = set(completions)
175 180 if '__init__' in completions:
176 181 completions.remove('__init__')
177 182 return list(completions)
178 183
179 184
180 185 #-----------------------------------------------------------------------------
181 186 # Completion-related functions.
182 187 #-----------------------------------------------------------------------------
183 188
184 189 def quick_completer(cmd, completions):
185 190 """ Easily create a trivial completer for a command.
186 191
187 192 Takes either a list of completions, or all completions in string (that will
188 193 be split on whitespace).
189 194
190 195 Example::
191 196
192 197 [d:\ipython]|1> import ipy_completers
193 198 [d:\ipython]|2> ipy_completers.quick_completer('foo', ['bar','baz'])
194 199 [d:\ipython]|3> foo b<TAB>
195 200 bar baz
196 201 [d:\ipython]|3> foo ba
197 202 """
198 203
199 204 if isinstance(completions, basestring):
200 205 completions = completions.split()
201 206
202 207 def do_complete(self, event):
203 208 return completions
204 209
205 210 get_ipython().set_hook('complete_command',do_complete, str_key = cmd)
206 211
207 212
208 213 def module_completion(line):
209 214 """
210 215 Returns a list containing the completion possibilities for an import line.
211 216
212 217 The line looks like this :
213 218 'import xml.d'
214 219 'from xml.dom import'
215 220 """
216 221
217 222 words = line.split(' ')
218 223 nwords = len(words)
219 224
220 225 # from whatever <tab> -> 'import '
221 226 if nwords == 3 and words[0] == 'from':
222 227 return ['import ']
223 228
224 229 # 'from xy<tab>' or 'import xy<tab>'
225 230 if nwords < 3 and (words[0] in ['import','from']) :
226 231 if nwords == 1:
227 232 return get_root_modules()
228 233 mod = words[1].split('.')
229 234 if len(mod) < 2:
230 235 return get_root_modules()
231 236 completion_list = try_import('.'.join(mod[:-1]), True)
232 237 return ['.'.join(mod[:-1] + [el]) for el in completion_list]
233 238
234 239 # 'from xyz import abc<tab>'
235 240 if nwords >= 3 and words[0] == 'from':
236 241 mod = words[1]
237 242 return try_import(mod)
238 243
239 244 #-----------------------------------------------------------------------------
240 245 # Completers
241 246 #-----------------------------------------------------------------------------
242 247 # These all have the func(self, event) signature to be used as custom
243 248 # completers
244 249
245 250 def module_completer(self,event):
246 251 """Give completions after user has typed 'import ...' or 'from ...'"""
247 252
248 253 # This works in all versions of python. While 2.5 has
249 254 # pkgutil.walk_packages(), that particular routine is fairly dangerous,
250 255 # since it imports *EVERYTHING* on sys.path. That is: a) very slow b) full
251 256 # of possibly problematic side effects.
252 257 # This search the folders in the sys.path for available modules.
253 258
254 259 return module_completion(event.line)
255 260
261 # FIXME: there's a lot of logic common to the run, cd and builtin file
262 # completers, that is currently reimplemented in each.
256 263
257 264 def magic_run_completer(self, event):
258 265 """Complete files that end in .py or .ipy for the %run command.
259 266 """
260 267 comps = shlex_split(event.line)
261 268 relpath = (len(comps) > 1 and comps[-1] or '').strip("'\"")
262 269
263 #print "\nev=",event # dbg
264 #print "rp=",relpath # dbg
265 #print 'comps=',comps # dbg
270 #print("\nev=", event) # dbg
271 #print("rp=", relpath) # dbg
272 #print('comps=', comps) # dbg
266 273
267 274 lglob = glob.glob
268 275 isdir = os.path.isdir
269 if relpath.startswith('~'):
270 relpath = os.path.expanduser(relpath)
276 relpath, tilde_expand, tilde_val = expand_user(relpath)
277
271 278 dirs = [f.replace('\\','/') + "/" for f in lglob(relpath+'*') if isdir(f)]
272 279
273 280 # Find if the user has already typed the first filename, after which we
274 281 # should complete on all files, since after the first one other files may
275 282 # be arguments to the input script.
276 283
277 284 if filter(magic_run_re.match, comps):
278 285 pys = [f.replace('\\','/') for f in lglob('*')]
279 286 else:
280 287 pys = [f.replace('\\','/')
281 288 for f in lglob(relpath+'*.py') + lglob(relpath+'*.ipy') +
282 289 lglob(relpath + '*.pyw')]
283 return dirs + pys
290 #print('run comp:', dirs+pys) # dbg
291 return [compress_user(p, tilde_expand, tilde_val) for p in dirs+pys]
284 292
285 293
286 294 def cd_completer(self, event):
287 295 """Completer function for cd, which only returns directories."""
288 296 ip = get_ipython()
289 297 relpath = event.symbol
290 298
291 299 #print(event) # dbg
292 300 if event.line.endswith('-b') or ' -b ' in event.line:
293 301 # return only bookmark completions
294 302 bkms = self.db.get('bookmarks', None)
295 303 if bkms:
296 304 return bkms.keys()
297 305 else:
298 306 return []
299 307
300 308 if event.symbol == '-':
301 309 width_dh = str(len(str(len(ip.user_ns['_dh']) + 1)))
302 310 # jump in directory history by number
303 311 fmt = '-%0' + width_dh +'d [%s]'
304 312 ents = [ fmt % (i,s) for i,s in enumerate(ip.user_ns['_dh'])]
305 313 if len(ents) > 1:
306 314 return ents
307 315 return []
308 316
309 317 if event.symbol.startswith('--'):
310 318 return ["--" + os.path.basename(d) for d in ip.user_ns['_dh']]
311
312 if relpath.startswith('~'):
313 relpath = os.path.expanduser(relpath).replace('\\','/')
319
320 # Expand ~ in path and normalize directory separators.
321 relpath, tilde_expand, tilde_val = expand_user(relpath)
322 relpath = relpath.replace('\\','/')
314 323
315 324 found = []
316 325 for d in [f.replace('\\','/') + '/' for f in glob.glob(relpath+'*')
317 326 if os.path.isdir(f)]:
318 327 if ' ' in d:
319 328 # we don't want to deal with any of that, complex code
320 329 # for this is elsewhere
321 330 raise TryNext
322 331
323 found.append( d )
332 found.append(d)
324 333
325 334 if not found:
326 335 if os.path.isdir(relpath):
327 return [relpath]
336 return [compress_user(relpath, tilde_expand, tilde_val)]
328 337
329 338 # if no completions so far, try bookmarks
330 339 bks = self.db.get('bookmarks',{}).keys()
331 340 bkmatches = [s for s in bks if s.startswith(event.symbol)]
332 341 if bkmatches:
333 342 return bkmatches
334 343
335 344 raise TryNext
336 345
337 return found
346 return [compress_user(p, tilde_expand, tilde_val) for p in found]
General Comments 0
You need to be logged in to leave comments. Login now