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