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