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