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