##// END OF EJS Templates
fix for underscore completion
Paul Ivanov -
Show More
@@ -1,1156 +1,1139 b''
1 """Word completion for IPython.
1 """Word completion for IPython.
2
2
3 This module is a fork of the rlcompleter module in the Python standard
3 This module is a fork of the rlcompleter module in the Python standard
4 library. The original enhancements made to rlcompleter have been sent
4 library. The original enhancements made to rlcompleter have been sent
5 upstream and were accepted as of Python 2.3, but we need a lot more
5 upstream and were accepted as of Python 2.3, but we need a lot more
6 functionality specific to IPython, so this module will continue to live as an
6 functionality specific to IPython, so this module will continue to live as an
7 IPython-specific utility.
7 IPython-specific utility.
8
8
9 Original rlcompleter documentation:
9 Original rlcompleter documentation:
10
10
11 This requires the latest extension to the readline module (the
11 This requires the latest extension to the readline module (the
12 completes keywords, built-ins and globals in __main__; when completing
12 completes keywords, built-ins and globals in __main__; when completing
13 NAME.NAME..., it evaluates (!) the expression up to the last dot and
13 NAME.NAME..., it evaluates (!) the expression up to the last dot and
14 completes its attributes.
14 completes its attributes.
15
15
16 It's very cool to do "import string" type "string.", hit the
16 It's very cool to do "import string" type "string.", hit the
17 completion key (twice), and see the list of names defined by the
17 completion key (twice), and see the list of names defined by the
18 string module!
18 string module!
19
19
20 Tip: to use the tab key as the completion key, call
20 Tip: to use the tab key as the completion key, call
21
21
22 readline.parse_and_bind("tab: complete")
22 readline.parse_and_bind("tab: complete")
23
23
24 Notes:
24 Notes:
25
25
26 - Exceptions raised by the completer function are *ignored* (and
26 - Exceptions raised by the completer function are *ignored* (and
27 generally cause the completion to fail). This is a feature -- since
27 generally cause the completion to fail). This is a feature -- since
28 readline sets the tty device in raw (or cbreak) mode, printing a
28 readline sets the tty device in raw (or cbreak) mode, printing a
29 traceback wouldn't work well without some complicated hoopla to save,
29 traceback wouldn't work well without some complicated hoopla to save,
30 reset and restore the tty state.
30 reset and restore the tty state.
31
31
32 - The evaluation of the NAME.NAME... form may cause arbitrary
32 - The evaluation of the NAME.NAME... form may cause arbitrary
33 application defined code to be executed if an object with a
33 application defined code to be executed if an object with a
34 ``__getattr__`` hook is found. Since it is the responsibility of the
34 ``__getattr__`` hook is found. Since it is the responsibility of the
35 application (or the user) to enable this feature, I consider this an
35 application (or the user) to enable this feature, I consider this an
36 acceptable risk. More complicated expressions (e.g. function calls or
36 acceptable risk. More complicated expressions (e.g. function calls or
37 indexing operations) are *not* evaluated.
37 indexing operations) are *not* evaluated.
38
38
39 - GNU readline is also used by the built-in functions input() and
39 - GNU readline is also used by the built-in functions input() and
40 raw_input(), and thus these also benefit/suffer from the completer
40 raw_input(), and thus these also benefit/suffer from the completer
41 features. Clearly an interactive application can benefit by
41 features. Clearly an interactive application can benefit by
42 specifying its own completer function and using raw_input() for all
42 specifying its own completer function and using raw_input() for all
43 its input.
43 its input.
44
44
45 - When the original stdin is not a tty device, GNU readline is never
45 - When the original stdin is not a tty device, GNU readline is never
46 used, and this module (and the readline module) are silently inactive.
46 used, and this module (and the readline module) are silently inactive.
47 """
47 """
48
48
49 #*****************************************************************************
49 # Copyright (c) IPython Development Team.
50 #
50 # Distributed under the terms of the Modified BSD License.
51 # Since this file is essentially a minimally modified copy of the rlcompleter
52 # module which is part of the standard Python distribution, I assume that the
53 # proper procedure is to maintain its copyright as belonging to the Python
54 # Software Foundation (in addition to my own, for all new code).
55 #
56 # Copyright (C) 2008 IPython Development Team
57 # Copyright (C) 2001 Fernando Perez. <fperez@colorado.edu>
58 # Copyright (C) 2001 Python Software Foundation, www.python.org
59 #
60 # Distributed under the terms of the BSD License. The full license is in
61 # the file COPYING, distributed as part of this software.
62 #
63 #*****************************************************************************
64
65 #-----------------------------------------------------------------------------
66 # Imports
67 #-----------------------------------------------------------------------------
68
51
69 import __main__
52 import __main__
70 import glob
53 import glob
71 import inspect
54 import inspect
72 import itertools
55 import itertools
73 import keyword
56 import keyword
74 import os
57 import os
75 import re
58 import re
76 import sys
59 import sys
77
60
78 from IPython.config.configurable import Configurable
61 from IPython.config.configurable import Configurable
79 from IPython.core.error import TryNext
62 from IPython.core.error import TryNext
80 from IPython.core.inputsplitter import ESC_MAGIC
63 from IPython.core.inputsplitter import ESC_MAGIC
81 from IPython.utils import generics
64 from IPython.utils import generics
82 from IPython.utils import io
65 from IPython.utils import io
83 from IPython.utils.decorators import undoc
66 from IPython.utils.decorators import undoc
84 from IPython.utils.dir2 import dir2
67 from IPython.utils.dir2 import dir2
85 from IPython.utils.process import arg_split
68 from IPython.utils.process import arg_split
86 from IPython.utils.py3compat import builtin_mod, string_types
69 from IPython.utils.py3compat import builtin_mod, string_types
87 from IPython.utils.traitlets import CBool, Enum
70 from IPython.utils.traitlets import CBool, Enum
88
71
89 #-----------------------------------------------------------------------------
72 #-----------------------------------------------------------------------------
90 # Globals
73 # Globals
91 #-----------------------------------------------------------------------------
74 #-----------------------------------------------------------------------------
92
75
93 # Public API
76 # Public API
94 __all__ = ['Completer','IPCompleter']
77 __all__ = ['Completer','IPCompleter']
95
78
96 if sys.platform == 'win32':
79 if sys.platform == 'win32':
97 PROTECTABLES = ' '
80 PROTECTABLES = ' '
98 else:
81 else:
99 PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&'
82 PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&'
100
83
101
84
102 #-----------------------------------------------------------------------------
85 #-----------------------------------------------------------------------------
103 # Main functions and classes
86 # Main functions and classes
104 #-----------------------------------------------------------------------------
87 #-----------------------------------------------------------------------------
105
88
106 def has_open_quotes(s):
89 def has_open_quotes(s):
107 """Return whether a string has open quotes.
90 """Return whether a string has open quotes.
108
91
109 This simply counts whether the number of quote characters of either type in
92 This simply counts whether the number of quote characters of either type in
110 the string is odd.
93 the string is odd.
111
94
112 Returns
95 Returns
113 -------
96 -------
114 If there is an open quote, the quote character is returned. Else, return
97 If there is an open quote, the quote character is returned. Else, return
115 False.
98 False.
116 """
99 """
117 # We check " first, then ', so complex cases with nested quotes will get
100 # We check " first, then ', so complex cases with nested quotes will get
118 # the " to take precedence.
101 # the " to take precedence.
119 if s.count('"') % 2:
102 if s.count('"') % 2:
120 return '"'
103 return '"'
121 elif s.count("'") % 2:
104 elif s.count("'") % 2:
122 return "'"
105 return "'"
123 else:
106 else:
124 return False
107 return False
125
108
126
109
127 def protect_filename(s):
110 def protect_filename(s):
128 """Escape a string to protect certain characters."""
111 """Escape a string to protect certain characters."""
129
112
130 return "".join([(ch in PROTECTABLES and '\\' + ch or ch)
113 return "".join([(ch in PROTECTABLES and '\\' + ch or ch)
131 for ch in s])
114 for ch in s])
132
115
133 def expand_user(path):
116 def expand_user(path):
134 """Expand '~'-style usernames in strings.
117 """Expand '~'-style usernames in strings.
135
118
136 This is similar to :func:`os.path.expanduser`, but it computes and returns
119 This is similar to :func:`os.path.expanduser`, but it computes and returns
137 extra information that will be useful if the input was being used in
120 extra information that will be useful if the input was being used in
138 computing completions, and you wish to return the completions with the
121 computing completions, and you wish to return the completions with the
139 original '~' instead of its expanded value.
122 original '~' instead of its expanded value.
140
123
141 Parameters
124 Parameters
142 ----------
125 ----------
143 path : str
126 path : str
144 String to be expanded. If no ~ is present, the output is the same as the
127 String to be expanded. If no ~ is present, the output is the same as the
145 input.
128 input.
146
129
147 Returns
130 Returns
148 -------
131 -------
149 newpath : str
132 newpath : str
150 Result of ~ expansion in the input path.
133 Result of ~ expansion in the input path.
151 tilde_expand : bool
134 tilde_expand : bool
152 Whether any expansion was performed or not.
135 Whether any expansion was performed or not.
153 tilde_val : str
136 tilde_val : str
154 The value that ~ was replaced with.
137 The value that ~ was replaced with.
155 """
138 """
156 # Default values
139 # Default values
157 tilde_expand = False
140 tilde_expand = False
158 tilde_val = ''
141 tilde_val = ''
159 newpath = path
142 newpath = path
160
143
161 if path.startswith('~'):
144 if path.startswith('~'):
162 tilde_expand = True
145 tilde_expand = True
163 rest = len(path)-1
146 rest = len(path)-1
164 newpath = os.path.expanduser(path)
147 newpath = os.path.expanduser(path)
165 if rest:
148 if rest:
166 tilde_val = newpath[:-rest]
149 tilde_val = newpath[:-rest]
167 else:
150 else:
168 tilde_val = newpath
151 tilde_val = newpath
169
152
170 return newpath, tilde_expand, tilde_val
153 return newpath, tilde_expand, tilde_val
171
154
172
155
173 def compress_user(path, tilde_expand, tilde_val):
156 def compress_user(path, tilde_expand, tilde_val):
174 """Does the opposite of expand_user, with its outputs.
157 """Does the opposite of expand_user, with its outputs.
175 """
158 """
176 if tilde_expand:
159 if tilde_expand:
177 return path.replace(tilde_val, '~')
160 return path.replace(tilde_val, '~')
178 else:
161 else:
179 return path
162 return path
180
163
181
164
182
165
183 def penalize_magics_key(word):
166 def penalize_magics_key(word):
184 """key for sorting that penalizes magic commands in the ordering
167 """key for sorting that penalizes magic commands in the ordering
185
168
186 Normal words are left alone.
169 Normal words are left alone.
187
170
188 Magic commands have the initial % moved to the end, e.g.
171 Magic commands have the initial % moved to the end, e.g.
189 %matplotlib is transformed as follows:
172 %matplotlib is transformed as follows:
190
173
191 %matplotlib -> matplotlib%
174 %matplotlib -> matplotlib%
192
175
193 [The choice of the final % is arbitrary.]
176 [The choice of the final % is arbitrary.]
194
177
195 Since "matplotlib" < "matplotlib%" as strings,
178 Since "matplotlib" < "matplotlib%" as strings,
196 "timeit" will appear before the magic "%timeit" in the ordering
179 "timeit" will appear before the magic "%timeit" in the ordering
197
180
198 For consistency, move "%%" to the end, so cell magics appear *after*
181 For consistency, move "%%" to the end, so cell magics appear *after*
199 line magics with the same name.
182 line magics with the same name.
200
183
201 A check is performed that there are no other "%" in the string;
184 A check is performed that there are no other "%" in the string;
202 if there are, then the string is not a magic command and is left unchanged.
185 if there are, then the string is not a magic command and is left unchanged.
203
186
204 """
187 """
205
188
206 # Move any % signs from start to end of the key
189 # Move any % signs from start to end of the key
207 # provided there are no others elsewhere in the string
190 # provided there are no others elsewhere in the string
208
191
209 if word[:2] == "%%":
192 if word[:2] == "%%":
210 if not "%" in word[2:]:
193 if not "%" in word[2:]:
211 return word[2:] + "%%"
194 return word[2:] + "%%"
212
195
213 if word[:1] == "%":
196 if word[:1] == "%":
214 if not "%" in word[1:]:
197 if not "%" in word[1:]:
215 return word[1:] + "%"
198 return word[1:] + "%"
216
199
217 return word
200 return word
218
201
219
202
220 @undoc
203 @undoc
221 class Bunch(object): pass
204 class Bunch(object): pass
222
205
223
206
224 DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
207 DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
225 GREEDY_DELIMS = ' =\r\n'
208 GREEDY_DELIMS = ' =\r\n'
226
209
227
210
228 class CompletionSplitter(object):
211 class CompletionSplitter(object):
229 """An object to split an input line in a manner similar to readline.
212 """An object to split an input line in a manner similar to readline.
230
213
231 By having our own implementation, we can expose readline-like completion in
214 By having our own implementation, we can expose readline-like completion in
232 a uniform manner to all frontends. This object only needs to be given the
215 a uniform manner to all frontends. This object only needs to be given the
233 line of text to be split and the cursor position on said line, and it
216 line of text to be split and the cursor position on said line, and it
234 returns the 'word' to be completed on at the cursor after splitting the
217 returns the 'word' to be completed on at the cursor after splitting the
235 entire line.
218 entire line.
236
219
237 What characters are used as splitting delimiters can be controlled by
220 What characters are used as splitting delimiters can be controlled by
238 setting the `delims` attribute (this is a property that internally
221 setting the `delims` attribute (this is a property that internally
239 automatically builds the necessary regular expression)"""
222 automatically builds the necessary regular expression)"""
240
223
241 # Private interface
224 # Private interface
242
225
243 # A string of delimiter characters. The default value makes sense for
226 # A string of delimiter characters. The default value makes sense for
244 # IPython's most typical usage patterns.
227 # IPython's most typical usage patterns.
245 _delims = DELIMS
228 _delims = DELIMS
246
229
247 # The expression (a normal string) to be compiled into a regular expression
230 # The expression (a normal string) to be compiled into a regular expression
248 # for actual splitting. We store it as an attribute mostly for ease of
231 # for actual splitting. We store it as an attribute mostly for ease of
249 # debugging, since this type of code can be so tricky to debug.
232 # debugging, since this type of code can be so tricky to debug.
250 _delim_expr = None
233 _delim_expr = None
251
234
252 # The regular expression that does the actual splitting
235 # The regular expression that does the actual splitting
253 _delim_re = None
236 _delim_re = None
254
237
255 def __init__(self, delims=None):
238 def __init__(self, delims=None):
256 delims = CompletionSplitter._delims if delims is None else delims
239 delims = CompletionSplitter._delims if delims is None else delims
257 self.delims = delims
240 self.delims = delims
258
241
259 @property
242 @property
260 def delims(self):
243 def delims(self):
261 """Return the string of delimiter characters."""
244 """Return the string of delimiter characters."""
262 return self._delims
245 return self._delims
263
246
264 @delims.setter
247 @delims.setter
265 def delims(self, delims):
248 def delims(self, delims):
266 """Set the delimiters for line splitting."""
249 """Set the delimiters for line splitting."""
267 expr = '[' + ''.join('\\'+ c for c in delims) + ']'
250 expr = '[' + ''.join('\\'+ c for c in delims) + ']'
268 self._delim_re = re.compile(expr)
251 self._delim_re = re.compile(expr)
269 self._delims = delims
252 self._delims = delims
270 self._delim_expr = expr
253 self._delim_expr = expr
271
254
272 def split_line(self, line, cursor_pos=None):
255 def split_line(self, line, cursor_pos=None):
273 """Split a line of text with a cursor at the given position.
256 """Split a line of text with a cursor at the given position.
274 """
257 """
275 l = line if cursor_pos is None else line[:cursor_pos]
258 l = line if cursor_pos is None else line[:cursor_pos]
276 return self._delim_re.split(l)[-1]
259 return self._delim_re.split(l)[-1]
277
260
278
261
279 class Completer(Configurable):
262 class Completer(Configurable):
280
263
281 greedy = CBool(False, config=True,
264 greedy = CBool(False, config=True,
282 help="""Activate greedy completion
265 help="""Activate greedy completion
283
266
284 This will enable completion on elements of lists, results of function calls, etc.,
267 This will enable completion on elements of lists, results of function calls, etc.,
285 but can be unsafe because the code is actually evaluated on TAB.
268 but can be unsafe because the code is actually evaluated on TAB.
286 """
269 """
287 )
270 )
288
271
289
272
290 def __init__(self, namespace=None, global_namespace=None, **kwargs):
273 def __init__(self, namespace=None, global_namespace=None, **kwargs):
291 """Create a new completer for the command line.
274 """Create a new completer for the command line.
292
275
293 Completer(namespace=ns,global_namespace=ns2) -> completer instance.
276 Completer(namespace=ns,global_namespace=ns2) -> completer instance.
294
277
295 If unspecified, the default namespace where completions are performed
278 If unspecified, the default namespace where completions are performed
296 is __main__ (technically, __main__.__dict__). Namespaces should be
279 is __main__ (technically, __main__.__dict__). Namespaces should be
297 given as dictionaries.
280 given as dictionaries.
298
281
299 An optional second namespace can be given. This allows the completer
282 An optional second namespace can be given. This allows the completer
300 to handle cases where both the local and global scopes need to be
283 to handle cases where both the local and global scopes need to be
301 distinguished.
284 distinguished.
302
285
303 Completer instances should be used as the completion mechanism of
286 Completer instances should be used as the completion mechanism of
304 readline via the set_completer() call:
287 readline via the set_completer() call:
305
288
306 readline.set_completer(Completer(my_namespace).complete)
289 readline.set_completer(Completer(my_namespace).complete)
307 """
290 """
308
291
309 # Don't bind to namespace quite yet, but flag whether the user wants a
292 # Don't bind to namespace quite yet, but flag whether the user wants a
310 # specific namespace or to use __main__.__dict__. This will allow us
293 # specific namespace or to use __main__.__dict__. This will allow us
311 # to bind to __main__.__dict__ at completion time, not now.
294 # to bind to __main__.__dict__ at completion time, not now.
312 if namespace is None:
295 if namespace is None:
313 self.use_main_ns = 1
296 self.use_main_ns = 1
314 else:
297 else:
315 self.use_main_ns = 0
298 self.use_main_ns = 0
316 self.namespace = namespace
299 self.namespace = namespace
317
300
318 # The global namespace, if given, can be bound directly
301 # The global namespace, if given, can be bound directly
319 if global_namespace is None:
302 if global_namespace is None:
320 self.global_namespace = {}
303 self.global_namespace = {}
321 else:
304 else:
322 self.global_namespace = global_namespace
305 self.global_namespace = global_namespace
323
306
324 super(Completer, self).__init__(**kwargs)
307 super(Completer, self).__init__(**kwargs)
325
308
326 def complete(self, text, state):
309 def complete(self, text, state):
327 """Return the next possible completion for 'text'.
310 """Return the next possible completion for 'text'.
328
311
329 This is called successively with state == 0, 1, 2, ... until it
312 This is called successively with state == 0, 1, 2, ... until it
330 returns None. The completion should begin with 'text'.
313 returns None. The completion should begin with 'text'.
331
314
332 """
315 """
333 if self.use_main_ns:
316 if self.use_main_ns:
334 self.namespace = __main__.__dict__
317 self.namespace = __main__.__dict__
335
318
336 if state == 0:
319 if state == 0:
337 if "." in text:
320 if "." in text:
338 self.matches = self.attr_matches(text)
321 self.matches = self.attr_matches(text)
339 else:
322 else:
340 self.matches = self.global_matches(text)
323 self.matches = self.global_matches(text)
341 try:
324 try:
342 return self.matches[state]
325 return self.matches[state]
343 except IndexError:
326 except IndexError:
344 return None
327 return None
345
328
346 def global_matches(self, text):
329 def global_matches(self, text):
347 """Compute matches when text is a simple name.
330 """Compute matches when text is a simple name.
348
331
349 Return a list of all keywords, built-in functions and names currently
332 Return a list of all keywords, built-in functions and names currently
350 defined in self.namespace or self.global_namespace that match.
333 defined in self.namespace or self.global_namespace that match.
351
334
352 """
335 """
353 #print 'Completer->global_matches, txt=%r' % text # dbg
336 #print 'Completer->global_matches, txt=%r' % text # dbg
354 matches = []
337 matches = []
355 match_append = matches.append
338 match_append = matches.append
356 n = len(text)
339 n = len(text)
357 for lst in [keyword.kwlist,
340 for lst in [keyword.kwlist,
358 builtin_mod.__dict__.keys(),
341 builtin_mod.__dict__.keys(),
359 self.namespace.keys(),
342 self.namespace.keys(),
360 self.global_namespace.keys()]:
343 self.global_namespace.keys()]:
361 for word in lst:
344 for word in lst:
362 if word[:n] == text and word != "__builtins__":
345 if word[:n] == text and word != "__builtins__":
363 match_append(word)
346 match_append(word)
364 return matches
347 return matches
365
348
366 def attr_matches(self, text):
349 def attr_matches(self, text):
367 """Compute matches when text contains a dot.
350 """Compute matches when text contains a dot.
368
351
369 Assuming the text is of the form NAME.NAME....[NAME], and is
352 Assuming the text is of the form NAME.NAME....[NAME], and is
370 evaluatable in self.namespace or self.global_namespace, it will be
353 evaluatable in self.namespace or self.global_namespace, it will be
371 evaluated and its attributes (as revealed by dir()) are used as
354 evaluated and its attributes (as revealed by dir()) are used as
372 possible completions. (For class instances, class members are are
355 possible completions. (For class instances, class members are are
373 also considered.)
356 also considered.)
374
357
375 WARNING: this can still invoke arbitrary C code, if an object
358 WARNING: this can still invoke arbitrary C code, if an object
376 with a __getattr__ hook is evaluated.
359 with a __getattr__ hook is evaluated.
377
360
378 """
361 """
379
362
380 #io.rprint('Completer->attr_matches, txt=%r' % text) # dbg
363 #io.rprint('Completer->attr_matches, txt=%r' % text) # dbg
381 # Another option, seems to work great. Catches things like ''.<tab>
364 # Another option, seems to work great. Catches things like ''.<tab>
382 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
365 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
383
366
384 if m:
367 if m:
385 expr, attr = m.group(1, 3)
368 expr, attr = m.group(1, 3)
386 elif self.greedy:
369 elif self.greedy:
387 m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer)
370 m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer)
388 if not m2:
371 if not m2:
389 return []
372 return []
390 expr, attr = m2.group(1,2)
373 expr, attr = m2.group(1,2)
391 else:
374 else:
392 return []
375 return []
393
376
394 try:
377 try:
395 obj = eval(expr, self.namespace)
378 obj = eval(expr, self.namespace)
396 except:
379 except:
397 try:
380 try:
398 obj = eval(expr, self.global_namespace)
381 obj = eval(expr, self.global_namespace)
399 except:
382 except:
400 return []
383 return []
401
384
402 if self.limit_to__all__ and hasattr(obj, '__all__'):
385 if self.limit_to__all__ and hasattr(obj, '__all__'):
403 words = get__all__entries(obj)
386 words = get__all__entries(obj)
404 else:
387 else:
405 words = dir2(obj)
388 words = dir2(obj)
406
389
407 try:
390 try:
408 words = generics.complete_object(obj, words)
391 words = generics.complete_object(obj, words)
409 except TryNext:
392 except TryNext:
410 pass
393 pass
411 except Exception:
394 except Exception:
412 # Silence errors from completion function
395 # Silence errors from completion function
413 #raise # dbg
396 #raise # dbg
414 pass
397 pass
415 # Build match list to return
398 # Build match list to return
416 n = len(attr)
399 n = len(attr)
417 res = ["%s.%s" % (expr, w) for w in words if w[:n] == attr ]
400 res = ["%s.%s" % (expr, w) for w in words if w[:n] == attr ]
418 return res
401 return res
419
402
420
403
421 def get__all__entries(obj):
404 def get__all__entries(obj):
422 """returns the strings in the __all__ attribute"""
405 """returns the strings in the __all__ attribute"""
423 try:
406 try:
424 words = getattr(obj, '__all__')
407 words = getattr(obj, '__all__')
425 except:
408 except:
426 return []
409 return []
427
410
428 return [w for w in words if isinstance(w, string_types)]
411 return [w for w in words if isinstance(w, string_types)]
429
412
430
413
431 def match_dict_keys(keys, prefix):
414 def match_dict_keys(keys, prefix):
432 """Used by dict_key_matches, matching the prefix to a list of keys"""
415 """Used by dict_key_matches, matching the prefix to a list of keys"""
433 if not prefix:
416 if not prefix:
434 return None, 0, [repr(k) for k in keys
417 return None, 0, [repr(k) for k in keys
435 if isinstance(k, (string_types, bytes))]
418 if isinstance(k, (string_types, bytes))]
436 quote_match = re.search('["\']', prefix)
419 quote_match = re.search('["\']', prefix)
437 quote = quote_match.group()
420 quote = quote_match.group()
438 try:
421 try:
439 prefix_str = eval(prefix + quote, {})
422 prefix_str = eval(prefix + quote, {})
440 except Exception:
423 except Exception:
441 return None, 0, []
424 return None, 0, []
442
425
443 token_match = re.search(r'\w*$', prefix, re.UNICODE)
426 token_match = re.search(r'\w*$', prefix, re.UNICODE)
444 token_start = token_match.start()
427 token_start = token_match.start()
445 token_prefix = token_match.group()
428 token_prefix = token_match.group()
446
429
447 # TODO: support bytes in Py3k
430 # TODO: support bytes in Py3k
448 matched = []
431 matched = []
449 for key in keys:
432 for key in keys:
450 try:
433 try:
451 if not key.startswith(prefix_str):
434 if not key.startswith(prefix_str):
452 continue
435 continue
453 except (AttributeError, TypeError, UnicodeError):
436 except (AttributeError, TypeError, UnicodeError):
454 # Python 3+ TypeError on b'a'.startswith('a') or vice-versa
437 # Python 3+ TypeError on b'a'.startswith('a') or vice-versa
455 continue
438 continue
456
439
457 # reformat remainder of key to begin with prefix
440 # reformat remainder of key to begin with prefix
458 rem = key[len(prefix_str):]
441 rem = key[len(prefix_str):]
459 # force repr wrapped in '
442 # force repr wrapped in '
460 rem_repr = repr(rem + '"')
443 rem_repr = repr(rem + '"')
461 if rem_repr.startswith('u') and prefix[0] not in 'uU':
444 if rem_repr.startswith('u') and prefix[0] not in 'uU':
462 # Found key is unicode, but prefix is Py2 string.
445 # Found key is unicode, but prefix is Py2 string.
463 # Therefore attempt to interpret key as string.
446 # Therefore attempt to interpret key as string.
464 try:
447 try:
465 rem_repr = repr(rem.encode('ascii') + '"')
448 rem_repr = repr(rem.encode('ascii') + '"')
466 except UnicodeEncodeError:
449 except UnicodeEncodeError:
467 continue
450 continue
468
451
469 rem_repr = rem_repr[1 + rem_repr.index("'"):-2]
452 rem_repr = rem_repr[1 + rem_repr.index("'"):-2]
470 if quote == '"':
453 if quote == '"':
471 # The entered prefix is quoted with ",
454 # The entered prefix is quoted with ",
472 # but the match is quoted with '.
455 # but the match is quoted with '.
473 # A contained " hence needs escaping for comparison:
456 # A contained " hence needs escaping for comparison:
474 rem_repr = rem_repr.replace('"', '\\"')
457 rem_repr = rem_repr.replace('"', '\\"')
475
458
476 # then reinsert prefix from start of token
459 # then reinsert prefix from start of token
477 matched.append('%s%s' % (token_prefix, rem_repr))
460 matched.append('%s%s' % (token_prefix, rem_repr))
478 return quote, token_start, matched
461 return quote, token_start, matched
479
462
480
463
481 def _safe_isinstance(obj, module, class_name):
464 def _safe_isinstance(obj, module, class_name):
482 """Checks if obj is an instance of module.class_name if loaded
465 """Checks if obj is an instance of module.class_name if loaded
483 """
466 """
484 return (module in sys.modules and
467 return (module in sys.modules and
485 isinstance(obj, getattr(__import__(module), class_name)))
468 isinstance(obj, getattr(__import__(module), class_name)))
486
469
487
470
488
471
489 class IPCompleter(Completer):
472 class IPCompleter(Completer):
490 """Extension of the completer class with IPython-specific features"""
473 """Extension of the completer class with IPython-specific features"""
491
474
492 def _greedy_changed(self, name, old, new):
475 def _greedy_changed(self, name, old, new):
493 """update the splitter and readline delims when greedy is changed"""
476 """update the splitter and readline delims when greedy is changed"""
494 if new:
477 if new:
495 self.splitter.delims = GREEDY_DELIMS
478 self.splitter.delims = GREEDY_DELIMS
496 else:
479 else:
497 self.splitter.delims = DELIMS
480 self.splitter.delims = DELIMS
498
481
499 if self.readline:
482 if self.readline:
500 self.readline.set_completer_delims(self.splitter.delims)
483 self.readline.set_completer_delims(self.splitter.delims)
501
484
502 merge_completions = CBool(True, config=True,
485 merge_completions = CBool(True, config=True,
503 help="""Whether to merge completion results into a single list
486 help="""Whether to merge completion results into a single list
504
487
505 If False, only the completion results from the first non-empty
488 If False, only the completion results from the first non-empty
506 completer will be returned.
489 completer will be returned.
507 """
490 """
508 )
491 )
509 omit__names = Enum((0,1,2), default_value=2, config=True,
492 omit__names = Enum((0,1,2), default_value=2, config=True,
510 help="""Instruct the completer to omit private method names
493 help="""Instruct the completer to omit private method names
511
494
512 Specifically, when completing on ``object.<tab>``.
495 Specifically, when completing on ``object.<tab>``.
513
496
514 When 2 [default]: all names that start with '_' will be excluded.
497 When 2 [default]: all names that start with '_' will be excluded.
515
498
516 When 1: all 'magic' names (``__foo__``) will be excluded.
499 When 1: all 'magic' names (``__foo__``) will be excluded.
517
500
518 When 0: nothing will be excluded.
501 When 0: nothing will be excluded.
519 """
502 """
520 )
503 )
521 limit_to__all__ = CBool(default_value=False, config=True,
504 limit_to__all__ = CBool(default_value=False, config=True,
522 help="""Instruct the completer to use __all__ for the completion
505 help="""Instruct the completer to use __all__ for the completion
523
506
524 Specifically, when completing on ``object.<tab>``.
507 Specifically, when completing on ``object.<tab>``.
525
508
526 When True: only those names in obj.__all__ will be included.
509 When True: only those names in obj.__all__ will be included.
527
510
528 When False [default]: the __all__ attribute is ignored
511 When False [default]: the __all__ attribute is ignored
529 """
512 """
530 )
513 )
531
514
532 def __init__(self, shell=None, namespace=None, global_namespace=None,
515 def __init__(self, shell=None, namespace=None, global_namespace=None,
533 use_readline=True, config=None, **kwargs):
516 use_readline=True, config=None, **kwargs):
534 """IPCompleter() -> completer
517 """IPCompleter() -> completer
535
518
536 Return a completer object suitable for use by the readline library
519 Return a completer object suitable for use by the readline library
537 via readline.set_completer().
520 via readline.set_completer().
538
521
539 Inputs:
522 Inputs:
540
523
541 - shell: a pointer to the ipython shell itself. This is needed
524 - shell: a pointer to the ipython shell itself. This is needed
542 because this completer knows about magic functions, and those can
525 because this completer knows about magic functions, and those can
543 only be accessed via the ipython instance.
526 only be accessed via the ipython instance.
544
527
545 - namespace: an optional dict where completions are performed.
528 - namespace: an optional dict where completions are performed.
546
529
547 - global_namespace: secondary optional dict for completions, to
530 - global_namespace: secondary optional dict for completions, to
548 handle cases (such as IPython embedded inside functions) where
531 handle cases (such as IPython embedded inside functions) where
549 both Python scopes are visible.
532 both Python scopes are visible.
550
533
551 use_readline : bool, optional
534 use_readline : bool, optional
552 If true, use the readline library. This completer can still function
535 If true, use the readline library. This completer can still function
553 without readline, though in that case callers must provide some extra
536 without readline, though in that case callers must provide some extra
554 information on each call about the current line."""
537 information on each call about the current line."""
555
538
556 self.magic_escape = ESC_MAGIC
539 self.magic_escape = ESC_MAGIC
557 self.splitter = CompletionSplitter()
540 self.splitter = CompletionSplitter()
558
541
559 # Readline configuration, only used by the rlcompleter method.
542 # Readline configuration, only used by the rlcompleter method.
560 if use_readline:
543 if use_readline:
561 # We store the right version of readline so that later code
544 # We store the right version of readline so that later code
562 import IPython.utils.rlineimpl as readline
545 import IPython.utils.rlineimpl as readline
563 self.readline = readline
546 self.readline = readline
564 else:
547 else:
565 self.readline = None
548 self.readline = None
566
549
567 # _greedy_changed() depends on splitter and readline being defined:
550 # _greedy_changed() depends on splitter and readline being defined:
568 Completer.__init__(self, namespace=namespace, global_namespace=global_namespace,
551 Completer.__init__(self, namespace=namespace, global_namespace=global_namespace,
569 config=config, **kwargs)
552 config=config, **kwargs)
570
553
571 # List where completion matches will be stored
554 # List where completion matches will be stored
572 self.matches = []
555 self.matches = []
573 self.shell = shell
556 self.shell = shell
574 # Regexp to split filenames with spaces in them
557 # Regexp to split filenames with spaces in them
575 self.space_name_re = re.compile(r'([^\\] )')
558 self.space_name_re = re.compile(r'([^\\] )')
576 # Hold a local ref. to glob.glob for speed
559 # Hold a local ref. to glob.glob for speed
577 self.glob = glob.glob
560 self.glob = glob.glob
578
561
579 # Determine if we are running on 'dumb' terminals, like (X)Emacs
562 # Determine if we are running on 'dumb' terminals, like (X)Emacs
580 # buffers, to avoid completion problems.
563 # buffers, to avoid completion problems.
581 term = os.environ.get('TERM','xterm')
564 term = os.environ.get('TERM','xterm')
582 self.dumb_terminal = term in ['dumb','emacs']
565 self.dumb_terminal = term in ['dumb','emacs']
583
566
584 # Special handling of backslashes needed in win32 platforms
567 # Special handling of backslashes needed in win32 platforms
585 if sys.platform == "win32":
568 if sys.platform == "win32":
586 self.clean_glob = self._clean_glob_win32
569 self.clean_glob = self._clean_glob_win32
587 else:
570 else:
588 self.clean_glob = self._clean_glob
571 self.clean_glob = self._clean_glob
589
572
590 #regexp to parse docstring for function signature
573 #regexp to parse docstring for function signature
591 self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
574 self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
592 self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
575 self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
593 #use this if positional argument name is also needed
576 #use this if positional argument name is also needed
594 #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)')
577 #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)')
595
578
596 # All active matcher routines for completion
579 # All active matcher routines for completion
597 self.matchers = [self.python_matches,
580 self.matchers = [self.python_matches,
598 self.file_matches,
581 self.file_matches,
599 self.magic_matches,
582 self.magic_matches,
600 self.python_func_kw_matches,
583 self.python_func_kw_matches,
601 self.dict_key_matches,
584 self.dict_key_matches,
602 ]
585 ]
603
586
604 def all_completions(self, text):
587 def all_completions(self, text):
605 """
588 """
606 Wrapper around the complete method for the benefit of emacs
589 Wrapper around the complete method for the benefit of emacs
607 and pydb.
590 and pydb.
608 """
591 """
609 return self.complete(text)[1]
592 return self.complete(text)[1]
610
593
611 def _clean_glob(self,text):
594 def _clean_glob(self,text):
612 return self.glob("%s*" % text)
595 return self.glob("%s*" % text)
613
596
614 def _clean_glob_win32(self,text):
597 def _clean_glob_win32(self,text):
615 return [f.replace("\\","/")
598 return [f.replace("\\","/")
616 for f in self.glob("%s*" % text)]
599 for f in self.glob("%s*" % text)]
617
600
618 def file_matches(self, text):
601 def file_matches(self, text):
619 """Match filenames, expanding ~USER type strings.
602 """Match filenames, expanding ~USER type strings.
620
603
621 Most of the seemingly convoluted logic in this completer is an
604 Most of the seemingly convoluted logic in this completer is an
622 attempt to handle filenames with spaces in them. And yet it's not
605 attempt to handle filenames with spaces in them. And yet it's not
623 quite perfect, because Python's readline doesn't expose all of the
606 quite perfect, because Python's readline doesn't expose all of the
624 GNU readline details needed for this to be done correctly.
607 GNU readline details needed for this to be done correctly.
625
608
626 For a filename with a space in it, the printed completions will be
609 For a filename with a space in it, the printed completions will be
627 only the parts after what's already been typed (instead of the
610 only the parts after what's already been typed (instead of the
628 full completions, as is normally done). I don't think with the
611 full completions, as is normally done). I don't think with the
629 current (as of Python 2.3) Python readline it's possible to do
612 current (as of Python 2.3) Python readline it's possible to do
630 better."""
613 better."""
631
614
632 #io.rprint('Completer->file_matches: <%r>' % text) # dbg
615 #io.rprint('Completer->file_matches: <%r>' % text) # dbg
633
616
634 # chars that require escaping with backslash - i.e. chars
617 # chars that require escaping with backslash - i.e. chars
635 # that readline treats incorrectly as delimiters, but we
618 # that readline treats incorrectly as delimiters, but we
636 # don't want to treat as delimiters in filename matching
619 # don't want to treat as delimiters in filename matching
637 # when escaped with backslash
620 # when escaped with backslash
638 if text.startswith('!'):
621 if text.startswith('!'):
639 text = text[1:]
622 text = text[1:]
640 text_prefix = '!'
623 text_prefix = '!'
641 else:
624 else:
642 text_prefix = ''
625 text_prefix = ''
643
626
644 text_until_cursor = self.text_until_cursor
627 text_until_cursor = self.text_until_cursor
645 # track strings with open quotes
628 # track strings with open quotes
646 open_quotes = has_open_quotes(text_until_cursor)
629 open_quotes = has_open_quotes(text_until_cursor)
647
630
648 if '(' in text_until_cursor or '[' in text_until_cursor:
631 if '(' in text_until_cursor or '[' in text_until_cursor:
649 lsplit = text
632 lsplit = text
650 else:
633 else:
651 try:
634 try:
652 # arg_split ~ shlex.split, but with unicode bugs fixed by us
635 # arg_split ~ shlex.split, but with unicode bugs fixed by us
653 lsplit = arg_split(text_until_cursor)[-1]
636 lsplit = arg_split(text_until_cursor)[-1]
654 except ValueError:
637 except ValueError:
655 # typically an unmatched ", or backslash without escaped char.
638 # typically an unmatched ", or backslash without escaped char.
656 if open_quotes:
639 if open_quotes:
657 lsplit = text_until_cursor.split(open_quotes)[-1]
640 lsplit = text_until_cursor.split(open_quotes)[-1]
658 else:
641 else:
659 return []
642 return []
660 except IndexError:
643 except IndexError:
661 # tab pressed on empty line
644 # tab pressed on empty line
662 lsplit = ""
645 lsplit = ""
663
646
664 if not open_quotes and lsplit != protect_filename(lsplit):
647 if not open_quotes and lsplit != protect_filename(lsplit):
665 # if protectables are found, do matching on the whole escaped name
648 # if protectables are found, do matching on the whole escaped name
666 has_protectables = True
649 has_protectables = True
667 text0,text = text,lsplit
650 text0,text = text,lsplit
668 else:
651 else:
669 has_protectables = False
652 has_protectables = False
670 text = os.path.expanduser(text)
653 text = os.path.expanduser(text)
671
654
672 if text == "":
655 if text == "":
673 return [text_prefix + protect_filename(f) for f in self.glob("*")]
656 return [text_prefix + protect_filename(f) for f in self.glob("*")]
674
657
675 # Compute the matches from the filesystem
658 # Compute the matches from the filesystem
676 m0 = self.clean_glob(text.replace('\\',''))
659 m0 = self.clean_glob(text.replace('\\',''))
677
660
678 if has_protectables:
661 if has_protectables:
679 # If we had protectables, we need to revert our changes to the
662 # If we had protectables, we need to revert our changes to the
680 # beginning of filename so that we don't double-write the part
663 # beginning of filename so that we don't double-write the part
681 # of the filename we have so far
664 # of the filename we have so far
682 len_lsplit = len(lsplit)
665 len_lsplit = len(lsplit)
683 matches = [text_prefix + text0 +
666 matches = [text_prefix + text0 +
684 protect_filename(f[len_lsplit:]) for f in m0]
667 protect_filename(f[len_lsplit:]) for f in m0]
685 else:
668 else:
686 if open_quotes:
669 if open_quotes:
687 # if we have a string with an open quote, we don't need to
670 # if we have a string with an open quote, we don't need to
688 # protect the names at all (and we _shouldn't_, as it
671 # protect the names at all (and we _shouldn't_, as it
689 # would cause bugs when the filesystem call is made).
672 # would cause bugs when the filesystem call is made).
690 matches = m0
673 matches = m0
691 else:
674 else:
692 matches = [text_prefix +
675 matches = [text_prefix +
693 protect_filename(f) for f in m0]
676 protect_filename(f) for f in m0]
694
677
695 #io.rprint('mm', matches) # dbg
678 #io.rprint('mm', matches) # dbg
696
679
697 # Mark directories in input list by appending '/' to their names.
680 # Mark directories in input list by appending '/' to their names.
698 matches = [x+'/' if os.path.isdir(x) else x for x in matches]
681 matches = [x+'/' if os.path.isdir(x) else x for x in matches]
699 return matches
682 return matches
700
683
701 def magic_matches(self, text):
684 def magic_matches(self, text):
702 """Match magics"""
685 """Match magics"""
703 #print 'Completer->magic_matches:',text,'lb',self.text_until_cursor # dbg
686 #print 'Completer->magic_matches:',text,'lb',self.text_until_cursor # dbg
704 # Get all shell magics now rather than statically, so magics loaded at
687 # Get all shell magics now rather than statically, so magics loaded at
705 # runtime show up too.
688 # runtime show up too.
706 lsm = self.shell.magics_manager.lsmagic()
689 lsm = self.shell.magics_manager.lsmagic()
707 line_magics = lsm['line']
690 line_magics = lsm['line']
708 cell_magics = lsm['cell']
691 cell_magics = lsm['cell']
709 pre = self.magic_escape
692 pre = self.magic_escape
710 pre2 = pre+pre
693 pre2 = pre+pre
711
694
712 # Completion logic:
695 # Completion logic:
713 # - user gives %%: only do cell magics
696 # - user gives %%: only do cell magics
714 # - user gives %: do both line and cell magics
697 # - user gives %: do both line and cell magics
715 # - no prefix: do both
698 # - no prefix: do both
716 # In other words, line magics are skipped if the user gives %% explicitly
699 # In other words, line magics are skipped if the user gives %% explicitly
717 bare_text = text.lstrip(pre)
700 bare_text = text.lstrip(pre)
718 comp = [ pre2+m for m in cell_magics if m.startswith(bare_text)]
701 comp = [ pre2+m for m in cell_magics if m.startswith(bare_text)]
719 if not text.startswith(pre2):
702 if not text.startswith(pre2):
720 comp += [ pre+m for m in line_magics if m.startswith(bare_text)]
703 comp += [ pre+m for m in line_magics if m.startswith(bare_text)]
721 return comp
704 return comp
722
705
723 def python_matches(self,text):
706 def python_matches(self,text):
724 """Match attributes or global python names"""
707 """Match attributes or global python names"""
725
708
726 #io.rprint('Completer->python_matches, txt=%r' % text) # dbg
709 #io.rprint('Completer->python_matches, txt=%r' % text) # dbg
727 if "." in text:
710 if "." in text:
728 try:
711 try:
729 matches = self.attr_matches(text)
712 matches = self.attr_matches(text)
730 if text.endswith('.') and self.omit__names:
713 if text.endswith('.') and self.omit__names:
731 if self.omit__names == 1:
714 if self.omit__names == 1:
732 # true if txt is _not_ a __ name, false otherwise:
715 # true if txt is _not_ a __ name, false otherwise:
733 no__name = (lambda txt:
716 no__name = (lambda txt:
734 re.match(r'.*\.__.*?__',txt) is None)
717 re.match(r'.*\.__.*?__',txt) is None)
735 else:
718 else:
736 # true if txt is _not_ a _ name, false otherwise:
719 # true if txt is _not_ a _ name, false otherwise:
737 no__name = (lambda txt:
720 no__name = (lambda txt:
738 re.match(r'.*\._.*?',txt) is None)
721 re.match(r'.*\._.*?',txt[txt.rindex('.'):]) is None)
739 matches = filter(no__name, matches)
722 matches = filter(no__name, matches)
740 except NameError:
723 except NameError:
741 # catches <undefined attributes>.<tab>
724 # catches <undefined attributes>.<tab>
742 matches = []
725 matches = []
743 else:
726 else:
744 matches = self.global_matches(text)
727 matches = self.global_matches(text)
745
728
746 return matches
729 return matches
747
730
748 def _default_arguments_from_docstring(self, doc):
731 def _default_arguments_from_docstring(self, doc):
749 """Parse the first line of docstring for call signature.
732 """Parse the first line of docstring for call signature.
750
733
751 Docstring should be of the form 'min(iterable[, key=func])\n'.
734 Docstring should be of the form 'min(iterable[, key=func])\n'.
752 It can also parse cython docstring of the form
735 It can also parse cython docstring of the form
753 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'.
736 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'.
754 """
737 """
755 if doc is None:
738 if doc is None:
756 return []
739 return []
757
740
758 #care only the firstline
741 #care only the firstline
759 line = doc.lstrip().splitlines()[0]
742 line = doc.lstrip().splitlines()[0]
760
743
761 #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
744 #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
762 #'min(iterable[, key=func])\n' -> 'iterable[, key=func]'
745 #'min(iterable[, key=func])\n' -> 'iterable[, key=func]'
763 sig = self.docstring_sig_re.search(line)
746 sig = self.docstring_sig_re.search(line)
764 if sig is None:
747 if sig is None:
765 return []
748 return []
766 # iterable[, key=func]' -> ['iterable[' ,' key=func]']
749 # iterable[, key=func]' -> ['iterable[' ,' key=func]']
767 sig = sig.groups()[0].split(',')
750 sig = sig.groups()[0].split(',')
768 ret = []
751 ret = []
769 for s in sig:
752 for s in sig:
770 #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
753 #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
771 ret += self.docstring_kwd_re.findall(s)
754 ret += self.docstring_kwd_re.findall(s)
772 return ret
755 return ret
773
756
774 def _default_arguments(self, obj):
757 def _default_arguments(self, obj):
775 """Return the list of default arguments of obj if it is callable,
758 """Return the list of default arguments of obj if it is callable,
776 or empty list otherwise."""
759 or empty list otherwise."""
777 call_obj = obj
760 call_obj = obj
778 ret = []
761 ret = []
779 if inspect.isbuiltin(obj):
762 if inspect.isbuiltin(obj):
780 pass
763 pass
781 elif not (inspect.isfunction(obj) or inspect.ismethod(obj)):
764 elif not (inspect.isfunction(obj) or inspect.ismethod(obj)):
782 if inspect.isclass(obj):
765 if inspect.isclass(obj):
783 #for cython embededsignature=True the constructor docstring
766 #for cython embededsignature=True the constructor docstring
784 #belongs to the object itself not __init__
767 #belongs to the object itself not __init__
785 ret += self._default_arguments_from_docstring(
768 ret += self._default_arguments_from_docstring(
786 getattr(obj, '__doc__', ''))
769 getattr(obj, '__doc__', ''))
787 # for classes, check for __init__,__new__
770 # for classes, check for __init__,__new__
788 call_obj = (getattr(obj, '__init__', None) or
771 call_obj = (getattr(obj, '__init__', None) or
789 getattr(obj, '__new__', None))
772 getattr(obj, '__new__', None))
790 # for all others, check if they are __call__able
773 # for all others, check if they are __call__able
791 elif hasattr(obj, '__call__'):
774 elif hasattr(obj, '__call__'):
792 call_obj = obj.__call__
775 call_obj = obj.__call__
793
776
794 ret += self._default_arguments_from_docstring(
777 ret += self._default_arguments_from_docstring(
795 getattr(call_obj, '__doc__', ''))
778 getattr(call_obj, '__doc__', ''))
796
779
797 try:
780 try:
798 args,_,_1,defaults = inspect.getargspec(call_obj)
781 args,_,_1,defaults = inspect.getargspec(call_obj)
799 if defaults:
782 if defaults:
800 ret+=args[-len(defaults):]
783 ret+=args[-len(defaults):]
801 except TypeError:
784 except TypeError:
802 pass
785 pass
803
786
804 return list(set(ret))
787 return list(set(ret))
805
788
806 def python_func_kw_matches(self,text):
789 def python_func_kw_matches(self,text):
807 """Match named parameters (kwargs) of the last open function"""
790 """Match named parameters (kwargs) of the last open function"""
808
791
809 if "." in text: # a parameter cannot be dotted
792 if "." in text: # a parameter cannot be dotted
810 return []
793 return []
811 try: regexp = self.__funcParamsRegex
794 try: regexp = self.__funcParamsRegex
812 except AttributeError:
795 except AttributeError:
813 regexp = self.__funcParamsRegex = re.compile(r'''
796 regexp = self.__funcParamsRegex = re.compile(r'''
814 '.*?(?<!\\)' | # single quoted strings or
797 '.*?(?<!\\)' | # single quoted strings or
815 ".*?(?<!\\)" | # double quoted strings or
798 ".*?(?<!\\)" | # double quoted strings or
816 \w+ | # identifier
799 \w+ | # identifier
817 \S # other characters
800 \S # other characters
818 ''', re.VERBOSE | re.DOTALL)
801 ''', re.VERBOSE | re.DOTALL)
819 # 1. find the nearest identifier that comes before an unclosed
802 # 1. find the nearest identifier that comes before an unclosed
820 # parenthesis before the cursor
803 # parenthesis before the cursor
821 # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo"
804 # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo"
822 tokens = regexp.findall(self.text_until_cursor)
805 tokens = regexp.findall(self.text_until_cursor)
823 tokens.reverse()
806 tokens.reverse()
824 iterTokens = iter(tokens); openPar = 0
807 iterTokens = iter(tokens); openPar = 0
825
808
826 for token in iterTokens:
809 for token in iterTokens:
827 if token == ')':
810 if token == ')':
828 openPar -= 1
811 openPar -= 1
829 elif token == '(':
812 elif token == '(':
830 openPar += 1
813 openPar += 1
831 if openPar > 0:
814 if openPar > 0:
832 # found the last unclosed parenthesis
815 # found the last unclosed parenthesis
833 break
816 break
834 else:
817 else:
835 return []
818 return []
836 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
819 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
837 ids = []
820 ids = []
838 isId = re.compile(r'\w+$').match
821 isId = re.compile(r'\w+$').match
839
822
840 while True:
823 while True:
841 try:
824 try:
842 ids.append(next(iterTokens))
825 ids.append(next(iterTokens))
843 if not isId(ids[-1]):
826 if not isId(ids[-1]):
844 ids.pop(); break
827 ids.pop(); break
845 if not next(iterTokens) == '.':
828 if not next(iterTokens) == '.':
846 break
829 break
847 except StopIteration:
830 except StopIteration:
848 break
831 break
849 # lookup the candidate callable matches either using global_matches
832 # lookup the candidate callable matches either using global_matches
850 # or attr_matches for dotted names
833 # or attr_matches for dotted names
851 if len(ids) == 1:
834 if len(ids) == 1:
852 callableMatches = self.global_matches(ids[0])
835 callableMatches = self.global_matches(ids[0])
853 else:
836 else:
854 callableMatches = self.attr_matches('.'.join(ids[::-1]))
837 callableMatches = self.attr_matches('.'.join(ids[::-1]))
855 argMatches = []
838 argMatches = []
856 for callableMatch in callableMatches:
839 for callableMatch in callableMatches:
857 try:
840 try:
858 namedArgs = self._default_arguments(eval(callableMatch,
841 namedArgs = self._default_arguments(eval(callableMatch,
859 self.namespace))
842 self.namespace))
860 except:
843 except:
861 continue
844 continue
862
845
863 for namedArg in namedArgs:
846 for namedArg in namedArgs:
864 if namedArg.startswith(text):
847 if namedArg.startswith(text):
865 argMatches.append("%s=" %namedArg)
848 argMatches.append("%s=" %namedArg)
866 return argMatches
849 return argMatches
867
850
868 def dict_key_matches(self, text):
851 def dict_key_matches(self, text):
869 "Match string keys in a dictionary, after e.g. 'foo[' "
852 "Match string keys in a dictionary, after e.g. 'foo[' "
870 def get_keys(obj):
853 def get_keys(obj):
871 # Only allow completion for known in-memory dict-like types
854 # Only allow completion for known in-memory dict-like types
872 if isinstance(obj, dict) or\
855 if isinstance(obj, dict) or\
873 _safe_isinstance(obj, 'pandas', 'DataFrame'):
856 _safe_isinstance(obj, 'pandas', 'DataFrame'):
874 try:
857 try:
875 return list(obj.keys())
858 return list(obj.keys())
876 except Exception:
859 except Exception:
877 return []
860 return []
878 elif _safe_isinstance(obj, 'numpy', 'ndarray'):
861 elif _safe_isinstance(obj, 'numpy', 'ndarray'):
879 return obj.dtype.names or []
862 return obj.dtype.names or []
880 return []
863 return []
881
864
882 try:
865 try:
883 regexps = self.__dict_key_regexps
866 regexps = self.__dict_key_regexps
884 except AttributeError:
867 except AttributeError:
885 dict_key_re_fmt = r'''(?x)
868 dict_key_re_fmt = r'''(?x)
886 ( # match dict-referring expression wrt greedy setting
869 ( # match dict-referring expression wrt greedy setting
887 %s
870 %s
888 )
871 )
889 \[ # open bracket
872 \[ # open bracket
890 \s* # and optional whitespace
873 \s* # and optional whitespace
891 ([uUbB]? # string prefix (r not handled)
874 ([uUbB]? # string prefix (r not handled)
892 (?: # unclosed string
875 (?: # unclosed string
893 '(?:[^']|(?<!\\)\\')*
876 '(?:[^']|(?<!\\)\\')*
894 |
877 |
895 "(?:[^"]|(?<!\\)\\")*
878 "(?:[^"]|(?<!\\)\\")*
896 )
879 )
897 )?
880 )?
898 $
881 $
899 '''
882 '''
900 regexps = self.__dict_key_regexps = {
883 regexps = self.__dict_key_regexps = {
901 False: re.compile(dict_key_re_fmt % '''
884 False: re.compile(dict_key_re_fmt % '''
902 # identifiers separated by .
885 # identifiers separated by .
903 (?!\d)\w+
886 (?!\d)\w+
904 (?:\.(?!\d)\w+)*
887 (?:\.(?!\d)\w+)*
905 '''),
888 '''),
906 True: re.compile(dict_key_re_fmt % '''
889 True: re.compile(dict_key_re_fmt % '''
907 .+
890 .+
908 ''')
891 ''')
909 }
892 }
910
893
911 match = regexps[self.greedy].search(self.text_until_cursor)
894 match = regexps[self.greedy].search(self.text_until_cursor)
912 if match is None:
895 if match is None:
913 return []
896 return []
914
897
915 expr, prefix = match.groups()
898 expr, prefix = match.groups()
916 try:
899 try:
917 obj = eval(expr, self.namespace)
900 obj = eval(expr, self.namespace)
918 except Exception:
901 except Exception:
919 try:
902 try:
920 obj = eval(expr, self.global_namespace)
903 obj = eval(expr, self.global_namespace)
921 except Exception:
904 except Exception:
922 return []
905 return []
923
906
924 keys = get_keys(obj)
907 keys = get_keys(obj)
925 if not keys:
908 if not keys:
926 return keys
909 return keys
927 closing_quote, token_offset, matches = match_dict_keys(keys, prefix)
910 closing_quote, token_offset, matches = match_dict_keys(keys, prefix)
928 if not matches:
911 if not matches:
929 return matches
912 return matches
930
913
931 # get the cursor position of
914 # get the cursor position of
932 # - the text being completed
915 # - the text being completed
933 # - the start of the key text
916 # - the start of the key text
934 # - the start of the completion
917 # - the start of the completion
935 text_start = len(self.text_until_cursor) - len(text)
918 text_start = len(self.text_until_cursor) - len(text)
936 if prefix:
919 if prefix:
937 key_start = match.start(2)
920 key_start = match.start(2)
938 completion_start = key_start + token_offset
921 completion_start = key_start + token_offset
939 else:
922 else:
940 key_start = completion_start = match.end()
923 key_start = completion_start = match.end()
941
924
942 # grab the leading prefix, to make sure all completions start with `text`
925 # grab the leading prefix, to make sure all completions start with `text`
943 if text_start > key_start:
926 if text_start > key_start:
944 leading = ''
927 leading = ''
945 else:
928 else:
946 leading = text[text_start:completion_start]
929 leading = text[text_start:completion_start]
947
930
948 # the index of the `[` character
931 # the index of the `[` character
949 bracket_idx = match.end(1)
932 bracket_idx = match.end(1)
950
933
951 # append closing quote and bracket as appropriate
934 # append closing quote and bracket as appropriate
952 # this is *not* appropriate if the opening quote or bracket is outside
935 # this is *not* appropriate if the opening quote or bracket is outside
953 # the text given to this method
936 # the text given to this method
954 suf = ''
937 suf = ''
955 continuation = self.line_buffer[len(self.text_until_cursor):]
938 continuation = self.line_buffer[len(self.text_until_cursor):]
956 if key_start > text_start and closing_quote:
939 if key_start > text_start and closing_quote:
957 # quotes were opened inside text, maybe close them
940 # quotes were opened inside text, maybe close them
958 if continuation.startswith(closing_quote):
941 if continuation.startswith(closing_quote):
959 continuation = continuation[len(closing_quote):]
942 continuation = continuation[len(closing_quote):]
960 else:
943 else:
961 suf += closing_quote
944 suf += closing_quote
962 if bracket_idx > text_start:
945 if bracket_idx > text_start:
963 # brackets were opened inside text, maybe close them
946 # brackets were opened inside text, maybe close them
964 if not continuation.startswith(']'):
947 if not continuation.startswith(']'):
965 suf += ']'
948 suf += ']'
966
949
967 return [leading + k + suf for k in matches]
950 return [leading + k + suf for k in matches]
968
951
969 def dispatch_custom_completer(self, text):
952 def dispatch_custom_completer(self, text):
970 #io.rprint("Custom! '%s' %s" % (text, self.custom_completers)) # dbg
953 #io.rprint("Custom! '%s' %s" % (text, self.custom_completers)) # dbg
971 line = self.line_buffer
954 line = self.line_buffer
972 if not line.strip():
955 if not line.strip():
973 return None
956 return None
974
957
975 # Create a little structure to pass all the relevant information about
958 # Create a little structure to pass all the relevant information about
976 # the current completion to any custom completer.
959 # the current completion to any custom completer.
977 event = Bunch()
960 event = Bunch()
978 event.line = line
961 event.line = line
979 event.symbol = text
962 event.symbol = text
980 cmd = line.split(None,1)[0]
963 cmd = line.split(None,1)[0]
981 event.command = cmd
964 event.command = cmd
982 event.text_until_cursor = self.text_until_cursor
965 event.text_until_cursor = self.text_until_cursor
983
966
984 #print "\ncustom:{%s]\n" % event # dbg
967 #print "\ncustom:{%s]\n" % event # dbg
985
968
986 # for foo etc, try also to find completer for %foo
969 # for foo etc, try also to find completer for %foo
987 if not cmd.startswith(self.magic_escape):
970 if not cmd.startswith(self.magic_escape):
988 try_magic = self.custom_completers.s_matches(
971 try_magic = self.custom_completers.s_matches(
989 self.magic_escape + cmd)
972 self.magic_escape + cmd)
990 else:
973 else:
991 try_magic = []
974 try_magic = []
992
975
993 for c in itertools.chain(self.custom_completers.s_matches(cmd),
976 for c in itertools.chain(self.custom_completers.s_matches(cmd),
994 try_magic,
977 try_magic,
995 self.custom_completers.flat_matches(self.text_until_cursor)):
978 self.custom_completers.flat_matches(self.text_until_cursor)):
996 #print "try",c # dbg
979 #print "try",c # dbg
997 try:
980 try:
998 res = c(event)
981 res = c(event)
999 if res:
982 if res:
1000 # first, try case sensitive match
983 # first, try case sensitive match
1001 withcase = [r for r in res if r.startswith(text)]
984 withcase = [r for r in res if r.startswith(text)]
1002 if withcase:
985 if withcase:
1003 return withcase
986 return withcase
1004 # if none, then case insensitive ones are ok too
987 # if none, then case insensitive ones are ok too
1005 text_low = text.lower()
988 text_low = text.lower()
1006 return [r for r in res if r.lower().startswith(text_low)]
989 return [r for r in res if r.lower().startswith(text_low)]
1007 except TryNext:
990 except TryNext:
1008 pass
991 pass
1009
992
1010 return None
993 return None
1011
994
1012 def complete(self, text=None, line_buffer=None, cursor_pos=None):
995 def complete(self, text=None, line_buffer=None, cursor_pos=None):
1013 """Find completions for the given text and line context.
996 """Find completions for the given text and line context.
1014
997
1015 Note that both the text and the line_buffer are optional, but at least
998 Note that both the text and the line_buffer are optional, but at least
1016 one of them must be given.
999 one of them must be given.
1017
1000
1018 Parameters
1001 Parameters
1019 ----------
1002 ----------
1020 text : string, optional
1003 text : string, optional
1021 Text to perform the completion on. If not given, the line buffer
1004 Text to perform the completion on. If not given, the line buffer
1022 is split using the instance's CompletionSplitter object.
1005 is split using the instance's CompletionSplitter object.
1023
1006
1024 line_buffer : string, optional
1007 line_buffer : string, optional
1025 If not given, the completer attempts to obtain the current line
1008 If not given, the completer attempts to obtain the current line
1026 buffer via readline. This keyword allows clients which are
1009 buffer via readline. This keyword allows clients which are
1027 requesting for text completions in non-readline contexts to inform
1010 requesting for text completions in non-readline contexts to inform
1028 the completer of the entire text.
1011 the completer of the entire text.
1029
1012
1030 cursor_pos : int, optional
1013 cursor_pos : int, optional
1031 Index of the cursor in the full line buffer. Should be provided by
1014 Index of the cursor in the full line buffer. Should be provided by
1032 remote frontends where kernel has no access to frontend state.
1015 remote frontends where kernel has no access to frontend state.
1033
1016
1034 Returns
1017 Returns
1035 -------
1018 -------
1036 text : str
1019 text : str
1037 Text that was actually used in the completion.
1020 Text that was actually used in the completion.
1038
1021
1039 matches : list
1022 matches : list
1040 A list of completion matches.
1023 A list of completion matches.
1041 """
1024 """
1042 #io.rprint('\nCOMP1 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg
1025 #io.rprint('\nCOMP1 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg
1043
1026
1044 # if the cursor position isn't given, the only sane assumption we can
1027 # if the cursor position isn't given, the only sane assumption we can
1045 # make is that it's at the end of the line (the common case)
1028 # make is that it's at the end of the line (the common case)
1046 if cursor_pos is None:
1029 if cursor_pos is None:
1047 cursor_pos = len(line_buffer) if text is None else len(text)
1030 cursor_pos = len(line_buffer) if text is None else len(text)
1048
1031
1049 # if text is either None or an empty string, rely on the line buffer
1032 # if text is either None or an empty string, rely on the line buffer
1050 if not text:
1033 if not text:
1051 text = self.splitter.split_line(line_buffer, cursor_pos)
1034 text = self.splitter.split_line(line_buffer, cursor_pos)
1052
1035
1053 # If no line buffer is given, assume the input text is all there was
1036 # If no line buffer is given, assume the input text is all there was
1054 if line_buffer is None:
1037 if line_buffer is None:
1055 line_buffer = text
1038 line_buffer = text
1056
1039
1057 self.line_buffer = line_buffer
1040 self.line_buffer = line_buffer
1058 self.text_until_cursor = self.line_buffer[:cursor_pos]
1041 self.text_until_cursor = self.line_buffer[:cursor_pos]
1059 #io.rprint('COMP2 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg
1042 #io.rprint('COMP2 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg
1060
1043
1061 # Start with a clean slate of completions
1044 # Start with a clean slate of completions
1062 self.matches[:] = []
1045 self.matches[:] = []
1063 custom_res = self.dispatch_custom_completer(text)
1046 custom_res = self.dispatch_custom_completer(text)
1064 if custom_res is not None:
1047 if custom_res is not None:
1065 # did custom completers produce something?
1048 # did custom completers produce something?
1066 self.matches = custom_res
1049 self.matches = custom_res
1067 else:
1050 else:
1068 # Extend the list of completions with the results of each
1051 # Extend the list of completions with the results of each
1069 # matcher, so we return results to the user from all
1052 # matcher, so we return results to the user from all
1070 # namespaces.
1053 # namespaces.
1071 if self.merge_completions:
1054 if self.merge_completions:
1072 self.matches = []
1055 self.matches = []
1073 for matcher in self.matchers:
1056 for matcher in self.matchers:
1074 try:
1057 try:
1075 self.matches.extend(matcher(text))
1058 self.matches.extend(matcher(text))
1076 except:
1059 except:
1077 # Show the ugly traceback if the matcher causes an
1060 # Show the ugly traceback if the matcher causes an
1078 # exception, but do NOT crash the kernel!
1061 # exception, but do NOT crash the kernel!
1079 sys.excepthook(*sys.exc_info())
1062 sys.excepthook(*sys.exc_info())
1080 else:
1063 else:
1081 for matcher in self.matchers:
1064 for matcher in self.matchers:
1082 self.matches = matcher(text)
1065 self.matches = matcher(text)
1083 if self.matches:
1066 if self.matches:
1084 break
1067 break
1085 # FIXME: we should extend our api to return a dict with completions for
1068 # FIXME: we should extend our api to return a dict with completions for
1086 # different types of objects. The rlcomplete() method could then
1069 # different types of objects. The rlcomplete() method could then
1087 # simply collapse the dict into a list for readline, but we'd have
1070 # simply collapse the dict into a list for readline, but we'd have
1088 # richer completion semantics in other evironments.
1071 # richer completion semantics in other evironments.
1089
1072
1090 # use penalize_magics_key to put magics after variables with same name
1073 # use penalize_magics_key to put magics after variables with same name
1091 self.matches = sorted(set(self.matches), key=penalize_magics_key)
1074 self.matches = sorted(set(self.matches), key=penalize_magics_key)
1092
1075
1093 #io.rprint('COMP TEXT, MATCHES: %r, %r' % (text, self.matches)) # dbg
1076 #io.rprint('COMP TEXT, MATCHES: %r, %r' % (text, self.matches)) # dbg
1094 return text, self.matches
1077 return text, self.matches
1095
1078
1096 def rlcomplete(self, text, state):
1079 def rlcomplete(self, text, state):
1097 """Return the state-th possible completion for 'text'.
1080 """Return the state-th possible completion for 'text'.
1098
1081
1099 This is called successively with state == 0, 1, 2, ... until it
1082 This is called successively with state == 0, 1, 2, ... until it
1100 returns None. The completion should begin with 'text'.
1083 returns None. The completion should begin with 'text'.
1101
1084
1102 Parameters
1085 Parameters
1103 ----------
1086 ----------
1104 text : string
1087 text : string
1105 Text to perform the completion on.
1088 Text to perform the completion on.
1106
1089
1107 state : int
1090 state : int
1108 Counter used by readline.
1091 Counter used by readline.
1109 """
1092 """
1110 if state==0:
1093 if state==0:
1111
1094
1112 self.line_buffer = line_buffer = self.readline.get_line_buffer()
1095 self.line_buffer = line_buffer = self.readline.get_line_buffer()
1113 cursor_pos = self.readline.get_endidx()
1096 cursor_pos = self.readline.get_endidx()
1114
1097
1115 #io.rprint("\nRLCOMPLETE: %r %r %r" %
1098 #io.rprint("\nRLCOMPLETE: %r %r %r" %
1116 # (text, line_buffer, cursor_pos) ) # dbg
1099 # (text, line_buffer, cursor_pos) ) # dbg
1117
1100
1118 # if there is only a tab on a line with only whitespace, instead of
1101 # if there is only a tab on a line with only whitespace, instead of
1119 # the mostly useless 'do you want to see all million completions'
1102 # the mostly useless 'do you want to see all million completions'
1120 # message, just do the right thing and give the user his tab!
1103 # message, just do the right thing and give the user his tab!
1121 # Incidentally, this enables pasting of tabbed text from an editor
1104 # Incidentally, this enables pasting of tabbed text from an editor
1122 # (as long as autoindent is off).
1105 # (as long as autoindent is off).
1123
1106
1124 # It should be noted that at least pyreadline still shows file
1107 # It should be noted that at least pyreadline still shows file
1125 # completions - is there a way around it?
1108 # completions - is there a way around it?
1126
1109
1127 # don't apply this on 'dumb' terminals, such as emacs buffers, so
1110 # don't apply this on 'dumb' terminals, such as emacs buffers, so
1128 # we don't interfere with their own tab-completion mechanism.
1111 # we don't interfere with their own tab-completion mechanism.
1129 if not (self.dumb_terminal or line_buffer.strip()):
1112 if not (self.dumb_terminal or line_buffer.strip()):
1130 self.readline.insert_text('\t')
1113 self.readline.insert_text('\t')
1131 sys.stdout.flush()
1114 sys.stdout.flush()
1132 return None
1115 return None
1133
1116
1134 # Note: debugging exceptions that may occur in completion is very
1117 # Note: debugging exceptions that may occur in completion is very
1135 # tricky, because readline unconditionally silences them. So if
1118 # tricky, because readline unconditionally silences them. So if
1136 # during development you suspect a bug in the completion code, turn
1119 # during development you suspect a bug in the completion code, turn
1137 # this flag on temporarily by uncommenting the second form (don't
1120 # this flag on temporarily by uncommenting the second form (don't
1138 # flip the value in the first line, as the '# dbg' marker can be
1121 # flip the value in the first line, as the '# dbg' marker can be
1139 # automatically detected and is used elsewhere).
1122 # automatically detected and is used elsewhere).
1140 DEBUG = False
1123 DEBUG = False
1141 #DEBUG = True # dbg
1124 #DEBUG = True # dbg
1142 if DEBUG:
1125 if DEBUG:
1143 try:
1126 try:
1144 self.complete(text, line_buffer, cursor_pos)
1127 self.complete(text, line_buffer, cursor_pos)
1145 except:
1128 except:
1146 import traceback; traceback.print_exc()
1129 import traceback; traceback.print_exc()
1147 else:
1130 else:
1148 # The normal production version is here
1131 # The normal production version is here
1149
1132
1150 # This method computes the self.matches array
1133 # This method computes the self.matches array
1151 self.complete(text, line_buffer, cursor_pos)
1134 self.complete(text, line_buffer, cursor_pos)
1152
1135
1153 try:
1136 try:
1154 return self.matches[state]
1137 return self.matches[state]
1155 except IndexError:
1138 except IndexError:
1156 return None
1139 return None
General Comments 0
You need to be logged in to leave comments. Login now