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