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