##// END OF EJS Templates
special case 'sudo' in alias_completer
vivainio -
Show More
@@ -1,627 +1,627 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 ---------------------------------------------------------------------------
9 ---------------------------------------------------------------------------
10 Original rlcompleter documentation:
10 Original rlcompleter documentation:
11
11
12 This requires the latest extension to the readline module (the
12 This requires the latest extension to the readline module (the
13 completes keywords, built-ins and globals in __main__; when completing
13 completes keywords, built-ins and globals in __main__; when completing
14 NAME.NAME..., it evaluates (!) the expression up to the last dot and
14 NAME.NAME..., it evaluates (!) the expression up to the last dot and
15 completes its attributes.
15 completes its attributes.
16
16
17 It's very cool to do "import string" type "string.", hit the
17 It's very cool to do "import string" type "string.", hit the
18 completion key (twice), and see the list of names defined by the
18 completion key (twice), and see the list of names defined by the
19 string module!
19 string module!
20
20
21 Tip: to use the tab key as the completion key, call
21 Tip: to use the tab key as the completion key, call
22
22
23 readline.parse_and_bind("tab: complete")
23 readline.parse_and_bind("tab: complete")
24
24
25 Notes:
25 Notes:
26
26
27 - Exceptions raised by the completer function are *ignored* (and
27 - Exceptions raised by the completer function are *ignored* (and
28 generally cause the completion to fail). This is a feature -- since
28 generally cause the completion to fail). This is a feature -- since
29 readline sets the tty device in raw (or cbreak) mode, printing a
29 readline sets the tty device in raw (or cbreak) mode, printing a
30 traceback wouldn't work well without some complicated hoopla to save,
30 traceback wouldn't work well without some complicated hoopla to save,
31 reset and restore the tty state.
31 reset and restore the tty state.
32
32
33 - The evaluation of the NAME.NAME... form may cause arbitrary
33 - The evaluation of the NAME.NAME... form may cause arbitrary
34 application defined code to be executed if an object with a
34 application defined code to be executed if an object with a
35 __getattr__ hook is found. Since it is the responsibility of the
35 __getattr__ hook is found. Since it is the responsibility of the
36 application (or the user) to enable this feature, I consider this an
36 application (or the user) to enable this feature, I consider this an
37 acceptable risk. More complicated expressions (e.g. function calls or
37 acceptable risk. More complicated expressions (e.g. function calls or
38 indexing operations) are *not* evaluated.
38 indexing operations) are *not* evaluated.
39
39
40 - GNU readline is also used by the built-in functions input() and
40 - GNU readline is also used by the built-in functions input() and
41 raw_input(), and thus these also benefit/suffer from the completer
41 raw_input(), and thus these also benefit/suffer from the completer
42 features. Clearly an interactive application can benefit by
42 features. Clearly an interactive application can benefit by
43 specifying its own completer function and using raw_input() for all
43 specifying its own completer function and using raw_input() for all
44 its input.
44 its input.
45
45
46 - When the original stdin is not a tty device, GNU readline is never
46 - When the original stdin is not a tty device, GNU readline is never
47 used, and this module (and the readline module) are silently inactive.
47 used, and this module (and the readline module) are silently inactive.
48
48
49 """
49 """
50
50
51 #*****************************************************************************
51 #*****************************************************************************
52 #
52 #
53 # Since this file is essentially a minimally modified copy of the rlcompleter
53 # Since this file is essentially a minimally modified copy of the rlcompleter
54 # module which is part of the standard Python distribution, I assume that the
54 # module which is part of the standard Python distribution, I assume that the
55 # proper procedure is to maintain its copyright as belonging to the Python
55 # proper procedure is to maintain its copyright as belonging to the Python
56 # Software Foundation (in addition to my own, for all new code).
56 # Software Foundation (in addition to my own, for all new code).
57 #
57 #
58 # Copyright (C) 2001 Python Software Foundation, www.python.org
58 # Copyright (C) 2001 Python Software Foundation, www.python.org
59 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
59 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
60 #
60 #
61 # Distributed under the terms of the BSD License. The full license is in
61 # Distributed under the terms of the BSD License. The full license is in
62 # the file COPYING, distributed as part of this software.
62 # the file COPYING, distributed as part of this software.
63 #
63 #
64 #*****************************************************************************
64 #*****************************************************************************
65
65
66 import __builtin__
66 import __builtin__
67 import __main__
67 import __main__
68 import glob
68 import glob
69 import keyword
69 import keyword
70 import os
70 import os
71 import re
71 import re
72 import shlex
72 import shlex
73 import sys
73 import sys
74 import IPython.rlineimpl as readline
74 import IPython.rlineimpl as readline
75 import itertools
75 import itertools
76 from IPython.ipstruct import Struct
76 from IPython.ipstruct import Struct
77 from IPython import ipapi
77 from IPython import ipapi
78
78
79 import types
79 import types
80
80
81 # Python 2.4 offers sets as a builtin
81 # Python 2.4 offers sets as a builtin
82 try:
82 try:
83 set([1,2])
83 set([1,2])
84 except NameError:
84 except NameError:
85 from sets import Set as set
85 from sets import Set as set
86
86
87 from IPython.genutils import debugx, dir2
87 from IPython.genutils import debugx, dir2
88
88
89 __all__ = ['Completer','IPCompleter']
89 __all__ = ['Completer','IPCompleter']
90
90
91 class Completer:
91 class Completer:
92 def __init__(self,namespace=None,global_namespace=None):
92 def __init__(self,namespace=None,global_namespace=None):
93 """Create a new completer for the command line.
93 """Create a new completer for the command line.
94
94
95 Completer([namespace,global_namespace]) -> completer instance.
95 Completer([namespace,global_namespace]) -> completer instance.
96
96
97 If unspecified, the default namespace where completions are performed
97 If unspecified, the default namespace where completions are performed
98 is __main__ (technically, __main__.__dict__). Namespaces should be
98 is __main__ (technically, __main__.__dict__). Namespaces should be
99 given as dictionaries.
99 given as dictionaries.
100
100
101 An optional second namespace can be given. This allows the completer
101 An optional second namespace can be given. This allows the completer
102 to handle cases where both the local and global scopes need to be
102 to handle cases where both the local and global scopes need to be
103 distinguished.
103 distinguished.
104
104
105 Completer instances should be used as the completion mechanism of
105 Completer instances should be used as the completion mechanism of
106 readline via the set_completer() call:
106 readline via the set_completer() call:
107
107
108 readline.set_completer(Completer(my_namespace).complete)
108 readline.set_completer(Completer(my_namespace).complete)
109 """
109 """
110
110
111 # some minimal strict typechecks. For some core data structures, I
111 # some minimal strict typechecks. For some core data structures, I
112 # want actual basic python types, not just anything that looks like
112 # want actual basic python types, not just anything that looks like
113 # one. This is especially true for namespaces.
113 # one. This is especially true for namespaces.
114 for ns in (namespace,global_namespace):
114 for ns in (namespace,global_namespace):
115 if ns is not None and type(ns) != types.DictType:
115 if ns is not None and type(ns) != types.DictType:
116 raise TypeError,'namespace must be a dictionary'
116 raise TypeError,'namespace must be a dictionary'
117
117
118 # Don't bind to namespace quite yet, but flag whether the user wants a
118 # Don't bind to namespace quite yet, but flag whether the user wants a
119 # specific namespace or to use __main__.__dict__. This will allow us
119 # specific namespace or to use __main__.__dict__. This will allow us
120 # to bind to __main__.__dict__ at completion time, not now.
120 # to bind to __main__.__dict__ at completion time, not now.
121 if namespace is None:
121 if namespace is None:
122 self.use_main_ns = 1
122 self.use_main_ns = 1
123 else:
123 else:
124 self.use_main_ns = 0
124 self.use_main_ns = 0
125 self.namespace = namespace
125 self.namespace = namespace
126
126
127 # The global namespace, if given, can be bound directly
127 # The global namespace, if given, can be bound directly
128 if global_namespace is None:
128 if global_namespace is None:
129 self.global_namespace = {}
129 self.global_namespace = {}
130 else:
130 else:
131 self.global_namespace = global_namespace
131 self.global_namespace = global_namespace
132
132
133 def complete(self, text, state):
133 def complete(self, text, state):
134 """Return the next possible completion for 'text'.
134 """Return the next possible completion for 'text'.
135
135
136 This is called successively with state == 0, 1, 2, ... until it
136 This is called successively with state == 0, 1, 2, ... until it
137 returns None. The completion should begin with 'text'.
137 returns None. The completion should begin with 'text'.
138
138
139 """
139 """
140 if self.use_main_ns:
140 if self.use_main_ns:
141 self.namespace = __main__.__dict__
141 self.namespace = __main__.__dict__
142
142
143 if state == 0:
143 if state == 0:
144 if "." in text:
144 if "." in text:
145 self.matches = self.attr_matches(text)
145 self.matches = self.attr_matches(text)
146 else:
146 else:
147 self.matches = self.global_matches(text)
147 self.matches = self.global_matches(text)
148 try:
148 try:
149 return self.matches[state]
149 return self.matches[state]
150 except IndexError:
150 except IndexError:
151 return None
151 return None
152
152
153 def global_matches(self, text):
153 def global_matches(self, text):
154 """Compute matches when text is a simple name.
154 """Compute matches when text is a simple name.
155
155
156 Return a list of all keywords, built-in functions and names currently
156 Return a list of all keywords, built-in functions and names currently
157 defined in self.namespace or self.global_namespace that match.
157 defined in self.namespace or self.global_namespace that match.
158
158
159 """
159 """
160 matches = []
160 matches = []
161 match_append = matches.append
161 match_append = matches.append
162 n = len(text)
162 n = len(text)
163 for lst in [keyword.kwlist,
163 for lst in [keyword.kwlist,
164 __builtin__.__dict__.keys(),
164 __builtin__.__dict__.keys(),
165 self.namespace.keys(),
165 self.namespace.keys(),
166 self.global_namespace.keys()]:
166 self.global_namespace.keys()]:
167 for word in lst:
167 for word in lst:
168 if word[:n] == text and word != "__builtins__":
168 if word[:n] == text and word != "__builtins__":
169 match_append(word)
169 match_append(word)
170 return matches
170 return matches
171
171
172 def attr_matches(self, text):
172 def attr_matches(self, text):
173 """Compute matches when text contains a dot.
173 """Compute matches when text contains a dot.
174
174
175 Assuming the text is of the form NAME.NAME....[NAME], and is
175 Assuming the text is of the form NAME.NAME....[NAME], and is
176 evaluatable in self.namespace or self.global_namespace, it will be
176 evaluatable in self.namespace or self.global_namespace, it will be
177 evaluated and its attributes (as revealed by dir()) are used as
177 evaluated and its attributes (as revealed by dir()) are used as
178 possible completions. (For class instances, class members are are
178 possible completions. (For class instances, class members are are
179 also considered.)
179 also considered.)
180
180
181 WARNING: this can still invoke arbitrary C code, if an object
181 WARNING: this can still invoke arbitrary C code, if an object
182 with a __getattr__ hook is evaluated.
182 with a __getattr__ hook is evaluated.
183
183
184 """
184 """
185 import re
185 import re
186
186
187 # Another option, seems to work great. Catches things like ''.<tab>
187 # Another option, seems to work great. Catches things like ''.<tab>
188 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
188 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
189
189
190 if not m:
190 if not m:
191 return []
191 return []
192
192
193 expr, attr = m.group(1, 3)
193 expr, attr = m.group(1, 3)
194 try:
194 try:
195 obj = eval(expr, self.namespace)
195 obj = eval(expr, self.namespace)
196 except:
196 except:
197 try:
197 try:
198 obj = eval(expr, self.global_namespace)
198 obj = eval(expr, self.global_namespace)
199 except:
199 except:
200 return []
200 return []
201
201
202 words = dir2(obj)
202 words = dir2(obj)
203
203
204 # Build match list to return
204 # Build match list to return
205 n = len(attr)
205 n = len(attr)
206 return ["%s.%s" % (expr, w) for w in words if w[:n] == attr ]
206 return ["%s.%s" % (expr, w) for w in words if w[:n] == attr ]
207
207
208 class IPCompleter(Completer):
208 class IPCompleter(Completer):
209 """Extension of the completer class with IPython-specific features"""
209 """Extension of the completer class with IPython-specific features"""
210
210
211 def __init__(self,shell,namespace=None,global_namespace=None,
211 def __init__(self,shell,namespace=None,global_namespace=None,
212 omit__names=0,alias_table=None):
212 omit__names=0,alias_table=None):
213 """IPCompleter() -> completer
213 """IPCompleter() -> completer
214
214
215 Return a completer object suitable for use by the readline library
215 Return a completer object suitable for use by the readline library
216 via readline.set_completer().
216 via readline.set_completer().
217
217
218 Inputs:
218 Inputs:
219
219
220 - shell: a pointer to the ipython shell itself. This is needed
220 - shell: a pointer to the ipython shell itself. This is needed
221 because this completer knows about magic functions, and those can
221 because this completer knows about magic functions, and those can
222 only be accessed via the ipython instance.
222 only be accessed via the ipython instance.
223
223
224 - namespace: an optional dict where completions are performed.
224 - namespace: an optional dict where completions are performed.
225
225
226 - global_namespace: secondary optional dict for completions, to
226 - global_namespace: secondary optional dict for completions, to
227 handle cases (such as IPython embedded inside functions) where
227 handle cases (such as IPython embedded inside functions) where
228 both Python scopes are visible.
228 both Python scopes are visible.
229
229
230 - The optional omit__names parameter sets the completer to omit the
230 - The optional omit__names parameter sets the completer to omit the
231 'magic' names (__magicname__) for python objects unless the text
231 'magic' names (__magicname__) for python objects unless the text
232 to be completed explicitly starts with one or more underscores.
232 to be completed explicitly starts with one or more underscores.
233
233
234 - If alias_table is supplied, it should be a dictionary of aliases
234 - If alias_table is supplied, it should be a dictionary of aliases
235 to complete. """
235 to complete. """
236
236
237 Completer.__init__(self,namespace,global_namespace)
237 Completer.__init__(self,namespace,global_namespace)
238 self.magic_prefix = shell.name+'.magic_'
238 self.magic_prefix = shell.name+'.magic_'
239 self.magic_escape = shell.ESC_MAGIC
239 self.magic_escape = shell.ESC_MAGIC
240 self.readline = readline
240 self.readline = readline
241 delims = self.readline.get_completer_delims()
241 delims = self.readline.get_completer_delims()
242 delims = delims.replace(self.magic_escape,'')
242 delims = delims.replace(self.magic_escape,'')
243 self.readline.set_completer_delims(delims)
243 self.readline.set_completer_delims(delims)
244 self.get_line_buffer = self.readline.get_line_buffer
244 self.get_line_buffer = self.readline.get_line_buffer
245 self.omit__names = omit__names
245 self.omit__names = omit__names
246 self.merge_completions = shell.rc.readline_merge_completions
246 self.merge_completions = shell.rc.readline_merge_completions
247
247
248 if alias_table is None:
248 if alias_table is None:
249 alias_table = {}
249 alias_table = {}
250 self.alias_table = alias_table
250 self.alias_table = alias_table
251 # Regexp to split filenames with spaces in them
251 # Regexp to split filenames with spaces in them
252 self.space_name_re = re.compile(r'([^\\] )')
252 self.space_name_re = re.compile(r'([^\\] )')
253 # Hold a local ref. to glob.glob for speed
253 # Hold a local ref. to glob.glob for speed
254 self.glob = glob.glob
254 self.glob = glob.glob
255
255
256 # Determine if we are running on 'dumb' terminals, like (X)Emacs
256 # Determine if we are running on 'dumb' terminals, like (X)Emacs
257 # buffers, to avoid completion problems.
257 # buffers, to avoid completion problems.
258 term = os.environ.get('TERM','xterm')
258 term = os.environ.get('TERM','xterm')
259 self.dumb_terminal = term in ['dumb','emacs']
259 self.dumb_terminal = term in ['dumb','emacs']
260
260
261 # Special handling of backslashes needed in win32 platforms
261 # Special handling of backslashes needed in win32 platforms
262 if sys.platform == "win32":
262 if sys.platform == "win32":
263 self.clean_glob = self._clean_glob_win32
263 self.clean_glob = self._clean_glob_win32
264 else:
264 else:
265 self.clean_glob = self._clean_glob
265 self.clean_glob = self._clean_glob
266 self.matchers = [self.python_matches,
266 self.matchers = [self.python_matches,
267 self.file_matches,
267 self.file_matches,
268 self.alias_matches,
268 self.alias_matches,
269 self.python_func_kw_matches]
269 self.python_func_kw_matches]
270
270
271 # Code contributed by Alex Schmolck, for ipython/emacs integration
271 # Code contributed by Alex Schmolck, for ipython/emacs integration
272 def all_completions(self, text):
272 def all_completions(self, text):
273 """Return all possible completions for the benefit of emacs."""
273 """Return all possible completions for the benefit of emacs."""
274
274
275 completions = []
275 completions = []
276 comp_append = completions.append
276 comp_append = completions.append
277 try:
277 try:
278 for i in xrange(sys.maxint):
278 for i in xrange(sys.maxint):
279 res = self.complete(text, i)
279 res = self.complete(text, i)
280
280
281 if not res: break
281 if not res: break
282
282
283 comp_append(res)
283 comp_append(res)
284 #XXX workaround for ``notDefined.<tab>``
284 #XXX workaround for ``notDefined.<tab>``
285 except NameError:
285 except NameError:
286 pass
286 pass
287 return completions
287 return completions
288 # /end Alex Schmolck code.
288 # /end Alex Schmolck code.
289
289
290 def _clean_glob(self,text):
290 def _clean_glob(self,text):
291 return self.glob("%s*" % text)
291 return self.glob("%s*" % text)
292
292
293 def _clean_glob_win32(self,text):
293 def _clean_glob_win32(self,text):
294 return [f.replace("\\","/")
294 return [f.replace("\\","/")
295 for f in self.glob("%s*" % text)]
295 for f in self.glob("%s*" % text)]
296
296
297 def file_matches(self, text):
297 def file_matches(self, text):
298 """Match filenames, expanding ~USER type strings.
298 """Match filenames, expanding ~USER type strings.
299
299
300 Most of the seemingly convoluted logic in this completer is an
300 Most of the seemingly convoluted logic in this completer is an
301 attempt to handle filenames with spaces in them. And yet it's not
301 attempt to handle filenames with spaces in them. And yet it's not
302 quite perfect, because Python's readline doesn't expose all of the
302 quite perfect, because Python's readline doesn't expose all of the
303 GNU readline details needed for this to be done correctly.
303 GNU readline details needed for this to be done correctly.
304
304
305 For a filename with a space in it, the printed completions will be
305 For a filename with a space in it, the printed completions will be
306 only the parts after what's already been typed (instead of the
306 only the parts after what's already been typed (instead of the
307 full completions, as is normally done). I don't think with the
307 full completions, as is normally done). I don't think with the
308 current (as of Python 2.3) Python readline it's possible to do
308 current (as of Python 2.3) Python readline it's possible to do
309 better."""
309 better."""
310
310
311 #print 'Completer->file_matches: <%s>' % text # dbg
311 #print 'Completer->file_matches: <%s>' % text # dbg
312
312
313 # chars that require escaping with backslash - i.e. chars
313 # chars that require escaping with backslash - i.e. chars
314 # that readline treats incorrectly as delimiters, but we
314 # that readline treats incorrectly as delimiters, but we
315 # don't want to treat as delimiters in filename matching
315 # don't want to treat as delimiters in filename matching
316 # when escaped with backslash
316 # when escaped with backslash
317
317
318 protectables = ' ()[]{}'
318 protectables = ' ()[]{}'
319
319
320 if text.startswith('!'):
320 if text.startswith('!'):
321 text = text[1:]
321 text = text[1:]
322 text_prefix = '!'
322 text_prefix = '!'
323 else:
323 else:
324 text_prefix = ''
324 text_prefix = ''
325
325
326 def protect_filename(s):
326 def protect_filename(s):
327 return "".join([(ch in protectables and '\\' + ch or ch)
327 return "".join([(ch in protectables and '\\' + ch or ch)
328 for ch in s])
328 for ch in s])
329
329
330 def single_dir_expand(matches):
330 def single_dir_expand(matches):
331 "Recursively expand match lists containing a single dir."
331 "Recursively expand match lists containing a single dir."
332
332
333 if len(matches) == 1 and os.path.isdir(matches[0]):
333 if len(matches) == 1 and os.path.isdir(matches[0]):
334 # Takes care of links to directories also. Use '/'
334 # Takes care of links to directories also. Use '/'
335 # explicitly, even under Windows, so that name completions
335 # explicitly, even under Windows, so that name completions
336 # don't end up escaped.
336 # don't end up escaped.
337 d = matches[0]
337 d = matches[0]
338 if d[-1] in ['/','\\']:
338 if d[-1] in ['/','\\']:
339 d = d[:-1]
339 d = d[:-1]
340
340
341 subdirs = os.listdir(d)
341 subdirs = os.listdir(d)
342 if subdirs:
342 if subdirs:
343 matches = [ (d + '/' + p) for p in subdirs]
343 matches = [ (d + '/' + p) for p in subdirs]
344 return single_dir_expand(matches)
344 return single_dir_expand(matches)
345 else:
345 else:
346 return matches
346 return matches
347 else:
347 else:
348 return matches
348 return matches
349
349
350 lbuf = self.lbuf
350 lbuf = self.lbuf
351 open_quotes = 0 # track strings with open quotes
351 open_quotes = 0 # track strings with open quotes
352 try:
352 try:
353 lsplit = shlex.split(lbuf)[-1]
353 lsplit = shlex.split(lbuf)[-1]
354 except ValueError:
354 except ValueError:
355 # typically an unmatched ", or backslash without escaped char.
355 # typically an unmatched ", or backslash without escaped char.
356 if lbuf.count('"')==1:
356 if lbuf.count('"')==1:
357 open_quotes = 1
357 open_quotes = 1
358 lsplit = lbuf.split('"')[-1]
358 lsplit = lbuf.split('"')[-1]
359 elif lbuf.count("'")==1:
359 elif lbuf.count("'")==1:
360 open_quotes = 1
360 open_quotes = 1
361 lsplit = lbuf.split("'")[-1]
361 lsplit = lbuf.split("'")[-1]
362 else:
362 else:
363 return []
363 return []
364 except IndexError:
364 except IndexError:
365 # tab pressed on empty line
365 # tab pressed on empty line
366 lsplit = ""
366 lsplit = ""
367
367
368 if lsplit != protect_filename(lsplit):
368 if lsplit != protect_filename(lsplit):
369 # if protectables are found, do matching on the whole escaped
369 # if protectables are found, do matching on the whole escaped
370 # name
370 # name
371 has_protectables = 1
371 has_protectables = 1
372 text0,text = text,lsplit
372 text0,text = text,lsplit
373 else:
373 else:
374 has_protectables = 0
374 has_protectables = 0
375 text = os.path.expanduser(text)
375 text = os.path.expanduser(text)
376
376
377 if text == "":
377 if text == "":
378 return [text_prefix + protect_filename(f) for f in self.glob("*")]
378 return [text_prefix + protect_filename(f) for f in self.glob("*")]
379
379
380 m0 = self.clean_glob(text.replace('\\',''))
380 m0 = self.clean_glob(text.replace('\\',''))
381 if has_protectables:
381 if has_protectables:
382 # If we had protectables, we need to revert our changes to the
382 # If we had protectables, we need to revert our changes to the
383 # beginning of filename so that we don't double-write the part
383 # beginning of filename so that we don't double-write the part
384 # of the filename we have so far
384 # of the filename we have so far
385 len_lsplit = len(lsplit)
385 len_lsplit = len(lsplit)
386 matches = [text_prefix + text0 +
386 matches = [text_prefix + text0 +
387 protect_filename(f[len_lsplit:]) for f in m0]
387 protect_filename(f[len_lsplit:]) for f in m0]
388 else:
388 else:
389 if open_quotes:
389 if open_quotes:
390 # if we have a string with an open quote, we don't need to
390 # if we have a string with an open quote, we don't need to
391 # protect the names at all (and we _shouldn't_, as it
391 # protect the names at all (and we _shouldn't_, as it
392 # would cause bugs when the filesystem call is made).
392 # would cause bugs when the filesystem call is made).
393 matches = m0
393 matches = m0
394 else:
394 else:
395 matches = [text_prefix +
395 matches = [text_prefix +
396 protect_filename(f) for f in m0]
396 protect_filename(f) for f in m0]
397
397
398 #print 'mm',matches # dbg
398 #print 'mm',matches # dbg
399 return single_dir_expand(matches)
399 return single_dir_expand(matches)
400
400
401 def alias_matches(self, text):
401 def alias_matches(self, text):
402 """Match internal system aliases"""
402 """Match internal system aliases"""
403 #print 'Completer->alias_matches:',text,'lb',self.lbuf # dbg
403 #print 'Completer->alias_matches:',text,'lb',self.lbuf # dbg
404
404
405 # if we are not in the first 'item', alias matching
405 # if we are not in the first 'item', alias matching
406 # doesn't make sense
406 # doesn't make sense - unless we are starting with 'sudo' command.
407 if ' ' in self.lbuf.lstrip():
407 if ' ' in self.lbuf.lstrip() and not self.lbuf.lstrip().startswith('sudo'):
408 return []
408 return []
409 text = os.path.expanduser(text)
409 text = os.path.expanduser(text)
410 aliases = self.alias_table.keys()
410 aliases = self.alias_table.keys()
411 if text == "":
411 if text == "":
412 return aliases
412 return aliases
413 else:
413 else:
414 return [alias for alias in aliases if alias.startswith(text)]
414 return [alias for alias in aliases if alias.startswith(text)]
415
415
416 def python_matches(self,text):
416 def python_matches(self,text):
417 """Match attributes or global python names"""
417 """Match attributes or global python names"""
418
418
419 #print 'Completer->python_matches, txt=<%s>' % text # dbg
419 #print 'Completer->python_matches, txt=<%s>' % text # dbg
420 if "." in text:
420 if "." in text:
421 try:
421 try:
422 matches = self.attr_matches(text)
422 matches = self.attr_matches(text)
423 if text.endswith('.') and self.omit__names:
423 if text.endswith('.') and self.omit__names:
424 if self.omit__names == 1:
424 if self.omit__names == 1:
425 # true if txt is _not_ a __ name, false otherwise:
425 # true if txt is _not_ a __ name, false otherwise:
426 no__name = (lambda txt:
426 no__name = (lambda txt:
427 re.match(r'.*\.__.*?__',txt) is None)
427 re.match(r'.*\.__.*?__',txt) is None)
428 else:
428 else:
429 # true if txt is _not_ a _ name, false otherwise:
429 # true if txt is _not_ a _ name, false otherwise:
430 no__name = (lambda txt:
430 no__name = (lambda txt:
431 re.match(r'.*\._.*?',txt) is None)
431 re.match(r'.*\._.*?',txt) is None)
432 matches = filter(no__name, matches)
432 matches = filter(no__name, matches)
433 except NameError:
433 except NameError:
434 # catches <undefined attributes>.<tab>
434 # catches <undefined attributes>.<tab>
435 matches = []
435 matches = []
436 else:
436 else:
437 matches = self.global_matches(text)
437 matches = self.global_matches(text)
438 # this is so completion finds magics when automagic is on:
438 # this is so completion finds magics when automagic is on:
439 if (matches == [] and
439 if (matches == [] and
440 not text.startswith(os.sep) and
440 not text.startswith(os.sep) and
441 not ' ' in self.lbuf):
441 not ' ' in self.lbuf):
442 matches = self.attr_matches(self.magic_prefix+text)
442 matches = self.attr_matches(self.magic_prefix+text)
443 return matches
443 return matches
444
444
445 def _default_arguments(self, obj):
445 def _default_arguments(self, obj):
446 """Return the list of default arguments of obj if it is callable,
446 """Return the list of default arguments of obj if it is callable,
447 or empty list otherwise."""
447 or empty list otherwise."""
448
448
449 if not (inspect.isfunction(obj) or inspect.ismethod(obj)):
449 if not (inspect.isfunction(obj) or inspect.ismethod(obj)):
450 # for classes, check for __init__,__new__
450 # for classes, check for __init__,__new__
451 if inspect.isclass(obj):
451 if inspect.isclass(obj):
452 obj = (getattr(obj,'__init__',None) or
452 obj = (getattr(obj,'__init__',None) or
453 getattr(obj,'__new__',None))
453 getattr(obj,'__new__',None))
454 # for all others, check if they are __call__able
454 # for all others, check if they are __call__able
455 elif hasattr(obj, '__call__'):
455 elif hasattr(obj, '__call__'):
456 obj = obj.__call__
456 obj = obj.__call__
457 # XXX: is there a way to handle the builtins ?
457 # XXX: is there a way to handle the builtins ?
458 try:
458 try:
459 args,_,_1,defaults = inspect.getargspec(obj)
459 args,_,_1,defaults = inspect.getargspec(obj)
460 if defaults:
460 if defaults:
461 return args[-len(defaults):]
461 return args[-len(defaults):]
462 except TypeError: pass
462 except TypeError: pass
463 return []
463 return []
464
464
465 def python_func_kw_matches(self,text):
465 def python_func_kw_matches(self,text):
466 """Match named parameters (kwargs) of the last open function"""
466 """Match named parameters (kwargs) of the last open function"""
467
467
468 if "." in text: # a parameter cannot be dotted
468 if "." in text: # a parameter cannot be dotted
469 return []
469 return []
470 try: regexp = self.__funcParamsRegex
470 try: regexp = self.__funcParamsRegex
471 except AttributeError:
471 except AttributeError:
472 regexp = self.__funcParamsRegex = re.compile(r'''
472 regexp = self.__funcParamsRegex = re.compile(r'''
473 '.*?' | # single quoted strings or
473 '.*?' | # single quoted strings or
474 ".*?" | # double quoted strings or
474 ".*?" | # double quoted strings or
475 \w+ | # identifier
475 \w+ | # identifier
476 \S # other characters
476 \S # other characters
477 ''', re.VERBOSE | re.DOTALL)
477 ''', re.VERBOSE | re.DOTALL)
478 # 1. find the nearest identifier that comes before an unclosed
478 # 1. find the nearest identifier that comes before an unclosed
479 # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo"
479 # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo"
480 tokens = regexp.findall(self.get_line_buffer())
480 tokens = regexp.findall(self.get_line_buffer())
481 tokens.reverse()
481 tokens.reverse()
482 iterTokens = iter(tokens); openPar = 0
482 iterTokens = iter(tokens); openPar = 0
483 for token in iterTokens:
483 for token in iterTokens:
484 if token == ')':
484 if token == ')':
485 openPar -= 1
485 openPar -= 1
486 elif token == '(':
486 elif token == '(':
487 openPar += 1
487 openPar += 1
488 if openPar > 0:
488 if openPar > 0:
489 # found the last unclosed parenthesis
489 # found the last unclosed parenthesis
490 break
490 break
491 else:
491 else:
492 return []
492 return []
493 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
493 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
494 ids = []
494 ids = []
495 isId = re.compile(r'\w+$').match
495 isId = re.compile(r'\w+$').match
496 while True:
496 while True:
497 try:
497 try:
498 ids.append(iterTokens.next())
498 ids.append(iterTokens.next())
499 if not isId(ids[-1]):
499 if not isId(ids[-1]):
500 ids.pop(); break
500 ids.pop(); break
501 if not iterTokens.next() == '.':
501 if not iterTokens.next() == '.':
502 break
502 break
503 except StopIteration:
503 except StopIteration:
504 break
504 break
505 # lookup the candidate callable matches either using global_matches
505 # lookup the candidate callable matches either using global_matches
506 # or attr_matches for dotted names
506 # or attr_matches for dotted names
507 if len(ids) == 1:
507 if len(ids) == 1:
508 callableMatches = self.global_matches(ids[0])
508 callableMatches = self.global_matches(ids[0])
509 else:
509 else:
510 callableMatches = self.attr_matches('.'.join(ids[::-1]))
510 callableMatches = self.attr_matches('.'.join(ids[::-1]))
511 argMatches = []
511 argMatches = []
512 for callableMatch in callableMatches:
512 for callableMatch in callableMatches:
513 try: namedArgs = self._default_arguments(eval(callableMatch,
513 try: namedArgs = self._default_arguments(eval(callableMatch,
514 self.namespace))
514 self.namespace))
515 except: continue
515 except: continue
516 for namedArg in namedArgs:
516 for namedArg in namedArgs:
517 if namedArg.startswith(text):
517 if namedArg.startswith(text):
518 argMatches.append("%s=" %namedArg)
518 argMatches.append("%s=" %namedArg)
519 return argMatches
519 return argMatches
520
520
521 def dispatch_custom_completer(self,text):
521 def dispatch_custom_completer(self,text):
522 #print "Custom! '%s' %s" % (text, self.custom_completers) # dbg
522 #print "Custom! '%s' %s" % (text, self.custom_completers) # dbg
523 line = self.full_lbuf
523 line = self.full_lbuf
524 if not line.strip():
524 if not line.strip():
525 return None
525 return None
526
526
527 event = Struct()
527 event = Struct()
528 event.line = line
528 event.line = line
529 event.symbol = text
529 event.symbol = text
530 cmd = line.split(None,1)[0]
530 cmd = line.split(None,1)[0]
531 event.command = cmd
531 event.command = cmd
532 #print "\ncustom:{%s]\n" % event # dbg
532 #print "\ncustom:{%s]\n" % event # dbg
533
533
534 # for foo etc, try also to find completer for %foo
534 # for foo etc, try also to find completer for %foo
535 if not cmd.startswith(self.magic_escape):
535 if not cmd.startswith(self.magic_escape):
536 try_magic = self.custom_completers.s_matches(
536 try_magic = self.custom_completers.s_matches(
537 self.magic_escape + cmd)
537 self.magic_escape + cmd)
538 else:
538 else:
539 try_magic = []
539 try_magic = []
540
540
541
541
542 for c in itertools.chain(
542 for c in itertools.chain(
543 self.custom_completers.s_matches(cmd),
543 self.custom_completers.s_matches(cmd),
544 try_magic,
544 try_magic,
545 self.custom_completers.flat_matches(self.lbuf)):
545 self.custom_completers.flat_matches(self.lbuf)):
546 #print "try",c # dbg
546 #print "try",c # dbg
547 try:
547 try:
548 res = c(event)
548 res = c(event)
549 return [r for r in res if r.lower().startswith(text.lower())]
549 return [r for r in res if r.lower().startswith(text.lower())]
550 except ipapi.TryNext:
550 except ipapi.TryNext:
551 pass
551 pass
552
552
553 return None
553 return None
554
554
555
555
556 def complete(self, text, state,line_buffer=None):
556 def complete(self, text, state,line_buffer=None):
557 """Return the next possible completion for 'text'.
557 """Return the next possible completion for 'text'.
558
558
559 This is called successively with state == 0, 1, 2, ... until it
559 This is called successively with state == 0, 1, 2, ... until it
560 returns None. The completion should begin with 'text'.
560 returns None. The completion should begin with 'text'.
561
561
562 :Keywords:
562 :Keywords:
563 - line_buffer: string
563 - line_buffer: string
564 If not given, the completer attempts to obtain the current line buffer
564 If not given, the completer attempts to obtain the current line buffer
565 via readline. This keyword allows clients which are requesting for
565 via readline. This keyword allows clients which are requesting for
566 text completions in non-readline contexts to inform the completer of
566 text completions in non-readline contexts to inform the completer of
567 the entire text.
567 the entire text.
568 """
568 """
569
569
570 #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg
570 #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg
571
571
572 # if there is only a tab on a line with only whitespace, instead
572 # if there is only a tab on a line with only whitespace, instead
573 # of the mostly useless 'do you want to see all million
573 # of the mostly useless 'do you want to see all million
574 # completions' message, just do the right thing and give the user
574 # completions' message, just do the right thing and give the user
575 # his tab! Incidentally, this enables pasting of tabbed text from
575 # his tab! Incidentally, this enables pasting of tabbed text from
576 # an editor (as long as autoindent is off).
576 # an editor (as long as autoindent is off).
577
577
578 # don't apply this on 'dumb' terminals, such as emacs buffers, so we
578 # don't apply this on 'dumb' terminals, such as emacs buffers, so we
579 # don't interfere with their own tab-completion mechanism.
579 # don't interfere with their own tab-completion mechanism.
580 if line_buffer is None:
580 if line_buffer is None:
581 self.full_lbuf = self.get_line_buffer()
581 self.full_lbuf = self.get_line_buffer()
582 else:
582 else:
583 self.full_lbuf = line_buffer
583 self.full_lbuf = line_buffer
584
584
585 if not (self.dumb_terminal or self.full_lbuf.strip()):
585 if not (self.dumb_terminal or self.full_lbuf.strip()):
586 self.readline.insert_text('\t')
586 self.readline.insert_text('\t')
587 return None
587 return None
588
588
589 magic_escape = self.magic_escape
589 magic_escape = self.magic_escape
590 magic_prefix = self.magic_prefix
590 magic_prefix = self.magic_prefix
591
591
592 self.lbuf = self.full_lbuf[:self.readline.get_endidx()]
592 self.lbuf = self.full_lbuf[:self.readline.get_endidx()]
593
593
594 try:
594 try:
595 if text.startswith(magic_escape):
595 if text.startswith(magic_escape):
596 text = text.replace(magic_escape,magic_prefix)
596 text = text.replace(magic_escape,magic_prefix)
597 elif text.startswith('~'):
597 elif text.startswith('~'):
598 text = os.path.expanduser(text)
598 text = os.path.expanduser(text)
599 if state == 0:
599 if state == 0:
600 custom_res = self.dispatch_custom_completer(text)
600 custom_res = self.dispatch_custom_completer(text)
601 if custom_res is not None:
601 if custom_res is not None:
602 # did custom completers produce something?
602 # did custom completers produce something?
603 self.matches = custom_res
603 self.matches = custom_res
604 else:
604 else:
605 # Extend the list of completions with the results of each
605 # Extend the list of completions with the results of each
606 # matcher, so we return results to the user from all
606 # matcher, so we return results to the user from all
607 # namespaces.
607 # namespaces.
608 if self.merge_completions:
608 if self.merge_completions:
609 self.matches = []
609 self.matches = []
610 for matcher in self.matchers:
610 for matcher in self.matchers:
611 self.matches.extend(matcher(text))
611 self.matches.extend(matcher(text))
612 else:
612 else:
613 for matcher in self.matchers:
613 for matcher in self.matchers:
614 self.matches = matcher(text)
614 self.matches = matcher(text)
615 if self.matches:
615 if self.matches:
616 break
616 break
617
617
618 try:
618 try:
619 return self.matches[state].replace(magic_prefix,magic_escape)
619 return self.matches[state].replace(magic_prefix,magic_escape)
620 except IndexError:
620 except IndexError:
621 return None
621 return None
622 except:
622 except:
623 #from IPython.ultraTB import AutoFormattedTB; # dbg
623 #from IPython.ultraTB import AutoFormattedTB; # dbg
624 #tb=AutoFormattedTB('Verbose');tb() #dbg
624 #tb=AutoFormattedTB('Verbose');tb() #dbg
625
625
626 # If completion fails, don't annoy the user.
626 # If completion fails, don't annoy the user.
627 return None
627 return None
General Comments 0
You need to be logged in to leave comments. Login now