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