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