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