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