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