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