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