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