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