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