##// END OF EJS Templates
Use file completer when completable text starts with !
vivainio -
Show More
@@ -1,636 +1,644 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 ---------------------------------------------------------------------------
10 10 Original rlcompleter documentation:
11 11
12 12 This requires the latest extension to the readline module (the
13 13 completes keywords, built-ins and globals in __main__; when completing
14 14 NAME.NAME..., it evaluates (!) the expression up to the last dot and
15 15 completes its attributes.
16 16
17 17 It's very cool to do "import string" type "string.", hit the
18 18 completion key (twice), and see the list of names defined by the
19 19 string module!
20 20
21 21 Tip: to use the tab key as the completion key, call
22 22
23 23 readline.parse_and_bind("tab: complete")
24 24
25 25 Notes:
26 26
27 27 - Exceptions raised by the completer function are *ignored* (and
28 28 generally cause the completion to fail). This is a feature -- since
29 29 readline sets the tty device in raw (or cbreak) mode, printing a
30 30 traceback wouldn't work well without some complicated hoopla to save,
31 31 reset and restore the tty state.
32 32
33 33 - The evaluation of the NAME.NAME... form may cause arbitrary
34 34 application defined code to be executed if an object with a
35 35 __getattr__ hook is found. Since it is the responsibility of the
36 36 application (or the user) to enable this feature, I consider this an
37 37 acceptable risk. More complicated expressions (e.g. function calls or
38 38 indexing operations) are *not* evaluated.
39 39
40 40 - GNU readline is also used by the built-in functions input() and
41 41 raw_input(), and thus these also benefit/suffer from the completer
42 42 features. Clearly an interactive application can benefit by
43 43 specifying its own completer function and using raw_input() for all
44 44 its input.
45 45
46 46 - When the original stdin is not a tty device, GNU readline is never
47 47 used, and this module (and the readline module) are silently inactive.
48 48
49 49 """
50 50
51 51 #*****************************************************************************
52 52 #
53 53 # Since this file is essentially a minimally modified copy of the rlcompleter
54 54 # module which is part of the standard Python distribution, I assume that the
55 55 # proper procedure is to maintain its copyright as belonging to the Python
56 56 # Software Foundation (in addition to my own, for all new code).
57 57 #
58 58 # Copyright (C) 2001 Python Software Foundation, www.python.org
59 59 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
60 60 #
61 61 # Distributed under the terms of the BSD License. The full license is in
62 62 # the file COPYING, distributed as part of this software.
63 63 #
64 64 #*****************************************************************************
65 65
66 66 import __builtin__
67 67 import __main__
68 68 import glob
69 69 import keyword
70 70 import os
71 71 import re
72 72 import shlex
73 73 import sys
74 74 import IPython.rlineimpl as readline
75 75 import itertools
76 76 from IPython.ipstruct import Struct
77 77 from IPython import ipapi
78 78
79 79 import types
80 80
81 81 # Python 2.4 offers sets as a builtin
82 82 try:
83 83 set([1,2])
84 84 except NameError:
85 85 from sets import Set as set
86 86
87 87 from IPython.genutils import debugx
88 88
89 89 __all__ = ['Completer','IPCompleter']
90 90
91 91 def get_class_members(cls):
92 92 ret = dir(cls)
93 93 if hasattr(cls,'__bases__'):
94 94 for base in cls.__bases__:
95 95 ret.extend(get_class_members(base))
96 96 return ret
97 97
98 98 class Completer:
99 99 def __init__(self,namespace=None,global_namespace=None):
100 100 """Create a new completer for the command line.
101 101
102 102 Completer([namespace,global_namespace]) -> completer instance.
103 103
104 104 If unspecified, the default namespace where completions are performed
105 105 is __main__ (technically, __main__.__dict__). Namespaces should be
106 106 given as dictionaries.
107 107
108 108 An optional second namespace can be given. This allows the completer
109 109 to handle cases where both the local and global scopes need to be
110 110 distinguished.
111 111
112 112 Completer instances should be used as the completion mechanism of
113 113 readline via the set_completer() call:
114 114
115 115 readline.set_completer(Completer(my_namespace).complete)
116 116 """
117 117
118 118 # some minimal strict typechecks. For some core data structures, I
119 119 # want actual basic python types, not just anything that looks like
120 120 # one. This is especially true for namespaces.
121 121 for ns in (namespace,global_namespace):
122 122 if ns is not None and type(ns) != types.DictType:
123 123 raise TypeError,'namespace must be a dictionary'
124 124
125 125 # Don't bind to namespace quite yet, but flag whether the user wants a
126 126 # specific namespace or to use __main__.__dict__. This will allow us
127 127 # to bind to __main__.__dict__ at completion time, not now.
128 128 if namespace is None:
129 129 self.use_main_ns = 1
130 130 else:
131 131 self.use_main_ns = 0
132 132 self.namespace = namespace
133 133
134 134 # The global namespace, if given, can be bound directly
135 135 if global_namespace is None:
136 136 self.global_namespace = {}
137 137 else:
138 138 self.global_namespace = global_namespace
139 139
140 140 def complete(self, text, state):
141 141 """Return the next possible completion for 'text'.
142 142
143 143 This is called successively with state == 0, 1, 2, ... until it
144 144 returns None. The completion should begin with 'text'.
145 145
146 146 """
147 147 if self.use_main_ns:
148 148 self.namespace = __main__.__dict__
149 149
150 150 if state == 0:
151 151 if "." in text:
152 152 self.matches = self.attr_matches(text)
153 153 else:
154 154 self.matches = self.global_matches(text)
155 155 try:
156 156 return self.matches[state]
157 157 except IndexError:
158 158 return None
159 159
160 160 def global_matches(self, text):
161 161 """Compute matches when text is a simple name.
162 162
163 163 Return a list of all keywords, built-in functions and names currently
164 164 defined in self.namespace or self.global_namespace that match.
165 165
166 166 """
167 167 matches = []
168 168 match_append = matches.append
169 169 n = len(text)
170 170 for lst in [keyword.kwlist,
171 171 __builtin__.__dict__.keys(),
172 172 self.namespace.keys(),
173 173 self.global_namespace.keys()]:
174 174 for word in lst:
175 175 if word[:n] == text and word != "__builtins__":
176 176 match_append(word)
177 177 return matches
178 178
179 179 def attr_matches(self, text):
180 180 """Compute matches when text contains a dot.
181 181
182 182 Assuming the text is of the form NAME.NAME....[NAME], and is
183 183 evaluatable in self.namespace or self.global_namespace, it will be
184 184 evaluated and its attributes (as revealed by dir()) are used as
185 185 possible completions. (For class instances, class members are are
186 186 also considered.)
187 187
188 188 WARNING: this can still invoke arbitrary C code, if an object
189 189 with a __getattr__ hook is evaluated.
190 190
191 191 """
192 192 import re
193 193
194 194 # Another option, seems to work great. Catches things like ''.<tab>
195 195 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
196 196
197 197 if not m:
198 198 return []
199 199
200 200 expr, attr = m.group(1, 3)
201 201 try:
202 202 object = eval(expr, self.namespace)
203 203 except:
204 204 try:
205 205 object = eval(expr, self.global_namespace)
206 206 except:
207 207 return []
208 208
209 209
210 210 # Start building the attribute list via dir(), and then complete it
211 211 # with a few extra special-purpose calls.
212 212 words = dir(object)
213 213
214 214 if hasattr(object,'__class__'):
215 215 words.append('__class__')
216 216 words.extend(get_class_members(object.__class__))
217 217
218 218 # this is the 'dir' function for objects with Enthought's traits
219 219 if hasattr(object, 'trait_names'):
220 220 try:
221 221 words.extend(object.trait_names())
222 222 # eliminate possible duplicates, as some traits may also
223 223 # appear as normal attributes in the dir() call.
224 224 words = set(words)
225 225 except TypeError:
226 226 # This will happen if `object` is a class and not an instance.
227 227 pass
228 228
229 229 # Support for PyCrust-style _getAttributeNames magic method.
230 230 if hasattr(object, '_getAttributeNames'):
231 231 try:
232 232 words.extend(object._getAttributeNames())
233 233 # Eliminate duplicates.
234 234 words = set(words)
235 235 except TypeError:
236 236 # `object` is a class and not an instance. Ignore
237 237 # this error.
238 238 pass
239 239
240 240 # filter out non-string attributes which may be stuffed by dir() calls
241 241 # and poor coding in third-party modules
242 242 words = [w for w in words
243 243 if isinstance(w, basestring) and w != "__builtins__"]
244 244 # Build match list to return
245 245 n = len(attr)
246 246 return ["%s.%s" % (expr, w) for w in words if w[:n] == attr ]
247 247
248 248 class IPCompleter(Completer):
249 249 """Extension of the completer class with IPython-specific features"""
250 250
251 251 def __init__(self,shell,namespace=None,global_namespace=None,
252 252 omit__names=0,alias_table=None):
253 253 """IPCompleter() -> completer
254 254
255 255 Return a completer object suitable for use by the readline library
256 256 via readline.set_completer().
257 257
258 258 Inputs:
259 259
260 260 - shell: a pointer to the ipython shell itself. This is needed
261 261 because this completer knows about magic functions, and those can
262 262 only be accessed via the ipython instance.
263 263
264 264 - namespace: an optional dict where completions are performed.
265 265
266 266 - global_namespace: secondary optional dict for completions, to
267 267 handle cases (such as IPython embedded inside functions) where
268 268 both Python scopes are visible.
269 269
270 270 - The optional omit__names parameter sets the completer to omit the
271 271 'magic' names (__magicname__) for python objects unless the text
272 272 to be completed explicitly starts with one or more underscores.
273 273
274 274 - If alias_table is supplied, it should be a dictionary of aliases
275 275 to complete. """
276 276
277 277 Completer.__init__(self,namespace,global_namespace)
278 278 self.magic_prefix = shell.name+'.magic_'
279 279 self.magic_escape = shell.ESC_MAGIC
280 280 self.readline = readline
281 281 delims = self.readline.get_completer_delims()
282 282 delims = delims.replace(self.magic_escape,'')
283 283 self.readline.set_completer_delims(delims)
284 284 self.get_line_buffer = self.readline.get_line_buffer
285 285 self.omit__names = omit__names
286 286 self.merge_completions = shell.rc.readline_merge_completions
287 287
288 288 if alias_table is None:
289 289 alias_table = {}
290 290 self.alias_table = alias_table
291 291 # Regexp to split filenames with spaces in them
292 292 self.space_name_re = re.compile(r'([^\\] )')
293 293 # Hold a local ref. to glob.glob for speed
294 294 self.glob = glob.glob
295 295
296 296 # Determine if we are running on 'dumb' terminals, like (X)Emacs
297 297 # buffers, to avoid completion problems.
298 298 term = os.environ.get('TERM','xterm')
299 299 self.dumb_terminal = term in ['dumb','emacs']
300 300
301 301 # Special handling of backslashes needed in win32 platforms
302 302 if sys.platform == "win32":
303 303 self.clean_glob = self._clean_glob_win32
304 304 else:
305 305 self.clean_glob = self._clean_glob
306 306 self.matchers = [self.python_matches,
307 307 self.file_matches,
308 308 self.alias_matches,
309 309 self.python_func_kw_matches]
310 310
311 311 # Code contributed by Alex Schmolck, for ipython/emacs integration
312 312 def all_completions(self, text):
313 313 """Return all possible completions for the benefit of emacs."""
314 314
315 315 completions = []
316 316 comp_append = completions.append
317 317 try:
318 318 for i in xrange(sys.maxint):
319 319 res = self.complete(text, i)
320 320
321 321 if not res: break
322 322
323 323 comp_append(res)
324 324 #XXX workaround for ``notDefined.<tab>``
325 325 except NameError:
326 326 pass
327 327 return completions
328 328 # /end Alex Schmolck code.
329 329
330 330 def _clean_glob(self,text):
331 331 return self.glob("%s*" % text)
332 332
333 333 def _clean_glob_win32(self,text):
334 334 return [f.replace("\\","/")
335 335 for f in self.glob("%s*" % text)]
336 336
337 337 def file_matches(self, text):
338 338 """Match filneames, expanding ~USER type strings.
339 339
340 340 Most of the seemingly convoluted logic in this completer is an
341 341 attempt to handle filenames with spaces in them. And yet it's not
342 342 quite perfect, because Python's readline doesn't expose all of the
343 343 GNU readline details needed for this to be done correctly.
344 344
345 345 For a filename with a space in it, the printed completions will be
346 346 only the parts after what's already been typed (instead of the
347 347 full completions, as is normally done). I don't think with the
348 348 current (as of Python 2.3) Python readline it's possible to do
349 349 better."""
350 350
351 351 #print 'Completer->file_matches: <%s>' % text # dbg
352 352
353 353 # chars that require escaping with backslash - i.e. chars
354 354 # that readline treats incorrectly as delimiters, but we
355 355 # don't want to treat as delimiters in filename matching
356 356 # when escaped with backslash
357 357
358 358 protectables = ' ()[]{}'
359 359
360 if text.startswith('!'):
361 text = text[1:]
362 text_prefix = '!'
363 else:
364 text_prefix = ''
365
360 366 def protect_filename(s):
361 367 return "".join([(ch in protectables and '\\' + ch or ch)
362 368 for ch in s])
363 369
364 370 lbuf = self.lbuf
365 371 open_quotes = 0 # track strings with open quotes
366 372 try:
367 373 lsplit = shlex.split(lbuf)[-1]
368 374 except ValueError:
369 375 # typically an unmatched ", or backslash without escaped char.
370 376 if lbuf.count('"')==1:
371 377 open_quotes = 1
372 378 lsplit = lbuf.split('"')[-1]
373 379 elif lbuf.count("'")==1:
374 380 open_quotes = 1
375 381 lsplit = lbuf.split("'")[-1]
376 382 else:
377 383 return None
378 384 except IndexError:
379 385 # tab pressed on empty line
380 386 lsplit = ""
381 387
382 388 if lsplit != protect_filename(lsplit):
383 389 # if protectables are found, do matching on the whole escaped
384 390 # name
385 391 has_protectables = 1
386 392 text0,text = text,lsplit
387 393 else:
388 394 has_protectables = 0
389 395 text = os.path.expanduser(text)
390 396
391 397 if text == "":
392 return [protect_filename(f) for f in self.glob("*")]
398 return [text_prefix + protect_filename(f) for f in self.glob("*")]
393 399
394 400 m0 = self.clean_glob(text.replace('\\',''))
395 401 if has_protectables:
396 402 # If we had protectables, we need to revert our changes to the
397 403 # beginning of filename so that we don't double-write the part
398 404 # of the filename we have so far
399 405 len_lsplit = len(lsplit)
400 matches = [text0 + protect_filename(f[len_lsplit:]) for f in m0]
406 matches = [text_prefix + text0 +
407 protect_filename(f[len_lsplit:]) for f in m0]
401 408 else:
402 409 if open_quotes:
403 410 # if we have a string with an open quote, we don't need to
404 411 # protect the names at all (and we _shouldn't_, as it
405 412 # would cause bugs when the filesystem call is made).
406 413 matches = m0
407 414 else:
408 matches = [protect_filename(f) for f in m0]
415 matches = [text_prefix +
416 protect_filename(f) for f in m0]
409 417 if len(matches) == 1 and os.path.isdir(matches[0]):
410 418 # Takes care of links to directories also. Use '/'
411 419 # explicitly, even under Windows, so that name completions
412 420 # don't end up escaped.
413 421 d = matches[0]
414 422 if d[-1] in ['/','\\']:
415 423 d = d[:-1]
416 424
417 425 matches = [ (d + '/' + p) for p in os.listdir(d) ]
418 426
419 427 return matches
420 428
421 429 def alias_matches(self, text):
422 430 """Match internal system aliases"""
423 431 #print 'Completer->alias_matches:',text,'lb',self.lbuf # dbg
424 432
425 433 # if we are not in the first 'item', alias matching
426 434 # doesn't make sense
427 435 if ' ' in self.lbuf:
428 436 return []
429 437 text = os.path.expanduser(text)
430 438 aliases = self.alias_table.keys()
431 439 if text == "":
432 440 return aliases
433 441 else:
434 442 return [alias for alias in aliases if alias.startswith(text)]
435 443
436 444 def python_matches(self,text):
437 445 """Match attributes or global python names"""
438 446
439 447 #print 'Completer->python_matches, txt=<%s>' % text # dbg
440 448 if "." in text:
441 449 try:
442 450 matches = self.attr_matches(text)
443 451 if text.endswith('.') and self.omit__names:
444 452 if self.omit__names == 1:
445 453 # true if txt is _not_ a __ name, false otherwise:
446 454 no__name = (lambda txt:
447 455 re.match(r'.*\.__.*?__',txt) is None)
448 456 else:
449 457 # true if txt is _not_ a _ name, false otherwise:
450 458 no__name = (lambda txt:
451 459 re.match(r'.*\._.*?',txt) is None)
452 460 matches = filter(no__name, matches)
453 461 except NameError:
454 462 # catches <undefined attributes>.<tab>
455 463 matches = []
456 464 else:
457 465 matches = self.global_matches(text)
458 466 # this is so completion finds magics when automagic is on:
459 467 if (matches == [] and
460 468 not text.startswith(os.sep) and
461 469 not ' ' in self.lbuf):
462 470 matches = self.attr_matches(self.magic_prefix+text)
463 471 return matches
464 472
465 473 def _default_arguments(self, obj):
466 474 """Return the list of default arguments of obj if it is callable,
467 475 or empty list otherwise."""
468 476
469 477 if not (inspect.isfunction(obj) or inspect.ismethod(obj)):
470 478 # for classes, check for __init__,__new__
471 479 if inspect.isclass(obj):
472 480 obj = (getattr(obj,'__init__',None) or
473 481 getattr(obj,'__new__',None))
474 482 # for all others, check if they are __call__able
475 483 elif hasattr(obj, '__call__'):
476 484 obj = obj.__call__
477 485 # XXX: is there a way to handle the builtins ?
478 486 try:
479 487 args,_,_1,defaults = inspect.getargspec(obj)
480 488 if defaults:
481 489 return args[-len(defaults):]
482 490 except TypeError: pass
483 491 return []
484 492
485 493 def python_func_kw_matches(self,text):
486 494 """Match named parameters (kwargs) of the last open function"""
487 495
488 496 if "." in text: # a parameter cannot be dotted
489 497 return []
490 498 try: regexp = self.__funcParamsRegex
491 499 except AttributeError:
492 500 regexp = self.__funcParamsRegex = re.compile(r'''
493 501 '.*?' | # single quoted strings or
494 502 ".*?" | # double quoted strings or
495 503 \w+ | # identifier
496 504 \S # other characters
497 505 ''', re.VERBOSE | re.DOTALL)
498 506 # 1. find the nearest identifier that comes before an unclosed
499 507 # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo"
500 508 tokens = regexp.findall(self.get_line_buffer())
501 509 tokens.reverse()
502 510 iterTokens = iter(tokens); openPar = 0
503 511 for token in iterTokens:
504 512 if token == ')':
505 513 openPar -= 1
506 514 elif token == '(':
507 515 openPar += 1
508 516 if openPar > 0:
509 517 # found the last unclosed parenthesis
510 518 break
511 519 else:
512 520 return []
513 521 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
514 522 ids = []
515 523 isId = re.compile(r'\w+$').match
516 524 while True:
517 525 try:
518 526 ids.append(iterTokens.next())
519 527 if not isId(ids[-1]):
520 528 ids.pop(); break
521 529 if not iterTokens.next() == '.':
522 530 break
523 531 except StopIteration:
524 532 break
525 533 # lookup the candidate callable matches either using global_matches
526 534 # or attr_matches for dotted names
527 535 if len(ids) == 1:
528 536 callableMatches = self.global_matches(ids[0])
529 537 else:
530 538 callableMatches = self.attr_matches('.'.join(ids[::-1]))
531 539 argMatches = []
532 540 for callableMatch in callableMatches:
533 541 try: namedArgs = self._default_arguments(eval(callableMatch,
534 542 self.namespace))
535 543 except: continue
536 544 for namedArg in namedArgs:
537 545 if namedArg.startswith(text):
538 546 argMatches.append("%s=" %namedArg)
539 547 return argMatches
540 548
541 549 def dispatch_custom_completer(self,text):
542 550 # print "Custom! '%s' %s" % (text, self.custom_completers) # dbg
543 551 line = self.full_lbuf
544 552 if not line.strip():
545 553 return None
546 554
547 555 event = Struct()
548 556 event.line = line
549 557 event.symbol = text
550 558 cmd = line.split(None,1)[0]
551 559 event.command = cmd
552 560 #print "\ncustom:{%s]\n" % event # dbg
553 561
554 562 # for foo etc, try also to find completer for %foo
555 563 if not cmd.startswith(self.magic_escape):
556 564 try_magic = self.custom_completers.s_matches(
557 565 self.magic_escape + cmd)
558 566 else:
559 567 try_magic = []
560 568
561 569
562 570 for c in itertools.chain(
563 571 self.custom_completers.s_matches(cmd),
564 572 try_magic,
565 573 self.custom_completers.flat_matches(self.lbuf)):
566 574 # print "try",c # dbg
567 575 try:
568 576 res = c(event)
569 577 return [r for r in res if r.lower().startswith(text.lower())]
570 578 except ipapi.TryNext:
571 579 pass
572 580
573 581 return None
574 582
575 583
576 584
577 585 def complete(self, text, state):
578 586 """Return the next possible completion for 'text'.
579 587
580 588 This is called successively with state == 0, 1, 2, ... until it
581 589 returns None. The completion should begin with 'text'. """
582 590
583 591 #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg
584 592
585 593 # if there is only a tab on a line with only whitespace, instead
586 594 # of the mostly useless 'do you want to see all million
587 595 # completions' message, just do the right thing and give the user
588 596 # his tab! Incidentally, this enables pasting of tabbed text from
589 597 # an editor (as long as autoindent is off).
590 598
591 599 # don't apply this on 'dumb' terminals, such as emacs buffers, so we
592 600 # don't interfere with their own tab-completion mechanism.
593 601 self.full_lbuf = self.get_line_buffer()
594 602 self.lbuf = self.full_lbuf[:self.readline.get_endidx()]
595 603 if not (self.dumb_terminal or self.get_line_buffer().strip()):
596 604 self.readline.insert_text('\t')
597 605 return None
598 606
599 607
600 608 magic_escape = self.magic_escape
601 609 magic_prefix = self.magic_prefix
602 610
603 611 try:
604 612 if text.startswith(magic_escape):
605 613 text = text.replace(magic_escape,magic_prefix)
606 614 elif text.startswith('~'):
607 615 text = os.path.expanduser(text)
608 616 if state == 0:
609 617 custom_res = self.dispatch_custom_completer(text)
610 618 if custom_res is not None:
611 619 # did custom completers produce something?
612 620 self.matches = custom_res
613 621 else:
614 622 # Extend the list of completions with the results of each
615 623 # matcher, so we return results to the user from all
616 624 # namespaces.
617 625 if self.merge_completions:
618 626 self.matches = []
619 627 for matcher in self.matchers:
620 628 self.matches.extend(matcher(text))
621 629 else:
622 630 for matcher in self.matchers:
623 631 self.matches = matcher(text)
624 632 if self.matches:
625 633 break
626 634
627 635 try:
628 636 return self.matches[state].replace(magic_prefix,magic_escape)
629 637 except IndexError:
630 638 return None
631 639 except:
632 640 from IPython.ultraTB import AutoFormattedTB; # dbg
633 641 tb=AutoFormattedTB('Verbose');tb() #dbg
634 642
635 643 # If completion fails, don't annoy the user.
636 644 return None
General Comments 0
You need to be logged in to leave comments. Login now