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