##// END OF EJS Templates
Fix file completion of commands with spaces in them.
Fernando Perez -
Show More
@@ -1,792 +1,789 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 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 #print 'Completer->file_matches: <%s>' % text # dbg
435 #io.rprint('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
442 441 if text.startswith('!'):
443 442 text = text[1:]
444 443 text_prefix = '!'
445 444 else:
446 445 text_prefix = ''
447 446
448 447 lbuf = self.lbuf
449 448 open_quotes = 0 # track strings with open quotes
450 449 try:
451 450 lsplit = shlex.split(lbuf)[-1]
452 451 except ValueError:
453 452 # typically an unmatched ", or backslash without escaped char.
454 453 if lbuf.count('"')==1:
455 454 open_quotes = 1
456 455 lsplit = lbuf.split('"')[-1]
457 456 elif lbuf.count("'")==1:
458 457 open_quotes = 1
459 458 lsplit = lbuf.split("'")[-1]
460 459 else:
461 460 return []
462 461 except IndexError:
463 462 # tab pressed on empty line
464 463 lsplit = ""
465 464
466 if lsplit != protect_filename(lsplit):
465 if not open_quotes and lsplit != protect_filename(lsplit):
467 466 # if protectables are found, do matching on the whole escaped
468 467 # name
469 468 has_protectables = 1
470 469 text0,text = text,lsplit
471 470 else:
472 471 has_protectables = 0
473 472 text = os.path.expanduser(text)
474 473
475 474 if text == "":
476 475 return [text_prefix + protect_filename(f) for f in self.glob("*")]
477 476
478 477 m0 = self.clean_glob(text.replace('\\',''))
479 478 if has_protectables:
480 479 # If we had protectables, we need to revert our changes to the
481 480 # beginning of filename so that we don't double-write the part
482 481 # of the filename we have so far
483 482 len_lsplit = len(lsplit)
484 483 matches = [text_prefix + text0 +
485 484 protect_filename(f[len_lsplit:]) for f in m0]
486 485 else:
487 486 if open_quotes:
488 487 # if we have a string with an open quote, we don't need to
489 488 # protect the names at all (and we _shouldn't_, as it
490 489 # would cause bugs when the filesystem call is made).
491 490 matches = m0
492 491 else:
493 492 matches = [text_prefix +
494 493 protect_filename(f) for f in m0]
495 494
496 #print 'mm',matches # dbg
497 #return single_dir_expand(matches)
495 #io.rprint('mm', matches) # dbg
498 496 return mark_dirs(matches)
499 497
500 498 def magic_matches(self, text):
501 499 """Match magics"""
502 500 #print 'Completer->magic_matches:',text,'lb',self.lbuf # dbg
503 501 # Get all shell magics now rather than statically, so magics loaded at
504 502 # runtime show up too
505 503 magics = self.shell.lsmagic()
506 504 pre = self.magic_escape
507 505 baretext = text.lstrip(pre)
508 506 return [ pre+m for m in magics if m.startswith(baretext)]
509 507
510 508 def alias_matches(self, text):
511 509 """Match internal system aliases"""
512 510 #print 'Completer->alias_matches:',text,'lb',self.lbuf # dbg
513 511
514 512 # if we are not in the first 'item', alias matching
515 513 # doesn't make sense - unless we are starting with 'sudo' command.
516 514 if ' ' in self.lbuf.lstrip() and \
517 515 not self.lbuf.lstrip().startswith('sudo'):
518 516 return []
519 517 text = os.path.expanduser(text)
520 518 aliases = self.alias_table.keys()
521 519 if text == "":
522 520 return aliases
523 521 else:
524 522 return [alias for alias in aliases if alias.startswith(text)]
525 523
526 524 def python_matches(self,text):
527 525 """Match attributes or global python names"""
528 526
529 527 #print 'Completer->python_matches, txt=%r' % text # dbg
530 528 if "." in text:
531 529 try:
532 530 matches = self.attr_matches(text)
533 531 if text.endswith('.') and self.omit__names:
534 532 if self.omit__names == 1:
535 533 # true if txt is _not_ a __ name, false otherwise:
536 534 no__name = (lambda txt:
537 535 re.match(r'.*\.__.*?__',txt) is None)
538 536 else:
539 537 # true if txt is _not_ a _ name, false otherwise:
540 538 no__name = (lambda txt:
541 539 re.match(r'.*\._.*?',txt) is None)
542 540 matches = filter(no__name, matches)
543 541 except NameError:
544 542 # catches <undefined attributes>.<tab>
545 543 matches = []
546 544 else:
547 545 matches = self.global_matches(text)
548 546
549 547 return matches
550 548
551 549 def _default_arguments(self, obj):
552 550 """Return the list of default arguments of obj if it is callable,
553 551 or empty list otherwise."""
554 552
555 553 if not (inspect.isfunction(obj) or inspect.ismethod(obj)):
556 554 # for classes, check for __init__,__new__
557 555 if inspect.isclass(obj):
558 556 obj = (getattr(obj,'__init__',None) or
559 557 getattr(obj,'__new__',None))
560 558 # for all others, check if they are __call__able
561 559 elif hasattr(obj, '__call__'):
562 560 obj = obj.__call__
563 561 # XXX: is there a way to handle the builtins ?
564 562 try:
565 563 args,_,_1,defaults = inspect.getargspec(obj)
566 564 if defaults:
567 565 return args[-len(defaults):]
568 566 except TypeError: pass
569 567 return []
570 568
571 569 def python_func_kw_matches(self,text):
572 570 """Match named parameters (kwargs) of the last open function"""
573 571
574 572 if "." in text: # a parameter cannot be dotted
575 573 return []
576 574 try: regexp = self.__funcParamsRegex
577 575 except AttributeError:
578 576 regexp = self.__funcParamsRegex = re.compile(r'''
579 577 '.*?' | # single quoted strings or
580 578 ".*?" | # double quoted strings or
581 579 \w+ | # identifier
582 580 \S # other characters
583 581 ''', re.VERBOSE | re.DOTALL)
584 582 # 1. find the nearest identifier that comes before an unclosed
585 583 # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo"
586 584 tokens = regexp.findall(self.get_line_buffer())
587 585 tokens.reverse()
588 586 iterTokens = iter(tokens); openPar = 0
589 587 for token in iterTokens:
590 588 if token == ')':
591 589 openPar -= 1
592 590 elif token == '(':
593 591 openPar += 1
594 592 if openPar > 0:
595 593 # found the last unclosed parenthesis
596 594 break
597 595 else:
598 596 return []
599 597 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
600 598 ids = []
601 599 isId = re.compile(r'\w+$').match
602 600 while True:
603 601 try:
604 602 ids.append(iterTokens.next())
605 603 if not isId(ids[-1]):
606 604 ids.pop(); break
607 605 if not iterTokens.next() == '.':
608 606 break
609 607 except StopIteration:
610 608 break
611 609 # lookup the candidate callable matches either using global_matches
612 610 # or attr_matches for dotted names
613 611 if len(ids) == 1:
614 612 callableMatches = self.global_matches(ids[0])
615 613 else:
616 614 callableMatches = self.attr_matches('.'.join(ids[::-1]))
617 615 argMatches = []
618 616 for callableMatch in callableMatches:
619 617 try:
620 618 namedArgs = self._default_arguments(eval(callableMatch,
621 619 self.namespace))
622 620 except:
623 621 continue
624 622 for namedArg in namedArgs:
625 623 if namedArg.startswith(text):
626 624 argMatches.append("%s=" %namedArg)
627 625 return argMatches
628 626
629 627 def dispatch_custom_completer(self,text):
630 628 #print "Custom! '%s' %s" % (text, self.custom_completers) # dbg
631 629 line = self.full_lbuf
632 630 if not line.strip():
633 631 return None
634 632
635 633 event = Bunch()
636 634 event.line = line
637 635 event.symbol = text
638 636 cmd = line.split(None,1)[0]
639 637 event.command = cmd
640 638 #print "\ncustom:{%s]\n" % event # dbg
641 639
642 640 # for foo etc, try also to find completer for %foo
643 641 if not cmd.startswith(self.magic_escape):
644 642 try_magic = self.custom_completers.s_matches(
645 643 self.magic_escape + cmd)
646 644 else:
647 645 try_magic = []
648 646
649 647 for c in itertools.chain(self.custom_completers.s_matches(cmd),
650 648 try_magic,
651 649 self.custom_completers.flat_matches(self.lbuf)):
652 650 #print "try",c # dbg
653 651 try:
654 652 res = c(event)
655 653 # first, try case sensitive match
656 654 withcase = [r for r in res if r.startswith(text)]
657 655 if withcase:
658 656 return withcase
659 657 # if none, then case insensitive ones are ok too
660 658 text_low = text.lower()
661 659 return [r for r in res if r.lower().startswith(text_low)]
662 660 except TryNext:
663 661 pass
664 662
665 663 return None
666 664
667 665 def complete(self, text=None, line_buffer=None, cursor_pos=None):
668 666 """Return the state-th possible completion for 'text'.
669 667
670 668 This is called successively with state == 0, 1, 2, ... until it
671 669 returns None. The completion should begin with 'text'.
672 670
673 671 Note that both the text and the line_buffer are optional, but at least
674 672 one of them must be given.
675 673
676 674 Parameters
677 675 ----------
678 676 text : string, optional
679 677 Text to perform the completion on. If not given, the line buffer
680 678 is split using the instance's CompletionSplitter object.
681 679
682 680 line_buffer : string, optional
683 681 If not given, the completer attempts to obtain the current line
684 682 buffer via readline. This keyword allows clients which are
685 683 requesting for text completions in non-readline contexts to inform
686 684 the completer of the entire text.
687 685
688 686 cursor_pos : int, optional
689 687 Index of the cursor in the full line buffer. Should be provided by
690 688 remote frontends where kernel has no access to frontend state.
691 689 """
692 #io.rprint('COMP1 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg
690 #io.rprint('\nCOMP1 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg
693 691
694 692 # if the cursor position isn't given, the only sane assumption we can
695 693 # make is that it's at the end of the line (the common case)
696 694 if cursor_pos is None:
697 695 cursor_pos = len(line_buffer) if text is None else len(text)
698 696
699 697 # if text is either None or an empty string, rely on the line buffer
700 698 if not text:
701 699 text = self.splitter.split_line(line_buffer, cursor_pos)
702 700
703 701 # If no line buffer is given, assume the input text is all there was
704 702 if line_buffer is None:
705 703 line_buffer = text
706 704
707 705 magic_escape = self.magic_escape
708 706 self.full_lbuf = line_buffer
709 707 self.lbuf = self.full_lbuf[:cursor_pos]
710
711 #io.rprint('COMP2 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg
708 #io.rprint('\nCOMP2 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg
712 709
713 710 # Start with a clean slate of completions
714 711 self.matches[:] = []
715 712 custom_res = self.dispatch_custom_completer(text)
716 713 if custom_res is not None:
717 714 # did custom completers produce something?
718 715 self.matches = custom_res
719 716 else:
720 717 # Extend the list of completions with the results of each
721 718 # matcher, so we return results to the user from all
722 719 # namespaces.
723 720 if self.merge_completions:
724 721 self.matches = []
725 722 for matcher in self.matchers:
726 723 self.matches.extend(matcher(text))
727 724 else:
728 725 for matcher in self.matchers:
729 726 self.matches = matcher(text)
730 727 if self.matches:
731 728 break
732 729 # FIXME: we should extend our api to return a dict with completions for
733 730 # different types of objects. The rlcomplete() method could then
734 731 # simply collapse the dict into a list for readline, but we'd have
735 732 # richer completion semantics in other evironments.
736 733 self.matches = sorted(set(self.matches))
737 734 #io.rprint('COMP TEXT, MATCHES: %r, %r' % (text, self.matches)) # dbg
738 735 return text, self.matches
739 736
740 737 def rlcomplete(self, text, state):
741 738 """Return the state-th possible completion for 'text'.
742 739
743 740 This is called successively with state == 0, 1, 2, ... until it
744 741 returns None. The completion should begin with 'text'.
745 742
746 743 Parameters
747 744 ----------
748 745 text : string
749 746 Text to perform the completion on.
750 747
751 748 state : int
752 749 Counter used by readline.
753 750 """
754 751 if state==0:
755 752
756 753 self.full_lbuf = line_buffer = self.get_line_buffer()
757 754 cursor_pos = self.get_endidx()
758 755
759 756 #io.rprint("\nRLCOMPLETE: %r %r %r" %
760 757 # (text, line_buffer, cursor_pos) ) # dbg
761 758
762 759 # if there is only a tab on a line with only whitespace, instead of
763 760 # the mostly useless 'do you want to see all million completions'
764 761 # message, just do the right thing and give the user his tab!
765 762 # Incidentally, this enables pasting of tabbed text from an editor
766 763 # (as long as autoindent is off).
767 764
768 765 # It should be noted that at least pyreadline still shows file
769 766 # completions - is there a way around it?
770 767
771 768 # don't apply this on 'dumb' terminals, such as emacs buffers, so
772 769 # we don't interfere with their own tab-completion mechanism.
773 770 if not (self.dumb_terminal or line_buffer.strip()):
774 771 self.readline.insert_text('\t')
775 772 sys.stdout.flush()
776 773 return None
777 774
778 775 # This method computes the self.matches array
779 776 self.complete(text, line_buffer, cursor_pos)
780 777
781 778 # Debug version, since readline silences all exceptions making it
782 779 # impossible to debug any problem in the above code
783 780
784 781 ## try:
785 782 ## self.complete(text, line_buffer, cursor_pos)
786 783 ## except:
787 784 ## import traceback; traceback.print_exc()
788 785
789 786 try:
790 787 return self.matches[state]
791 788 except IndexError:
792 789 return None
General Comments 0
You need to be logged in to leave comments. Login now