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