##// END OF EJS Templates
- Small dir. completion fix, problem reported by Stefan.
fperez -
Show More

The requested changes are too big and content was truncated. Show full diff

@@ -1,650 +1,657 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 # Some libraries (such as traits) may introduce duplicates, we want to
218 # Some libraries (such as traits) may introduce duplicates, we want to
219 # track and clean this up if it happens
219 # track and clean this up if it happens
220 may_have_dupes = False
220 may_have_dupes = False
221
221
222 # this is the 'dir' function for objects with Enthought's traits
222 # this is the 'dir' function for objects with Enthought's traits
223 if hasattr(object, 'trait_names'):
223 if hasattr(object, 'trait_names'):
224 try:
224 try:
225 words.extend(object.trait_names())
225 words.extend(object.trait_names())
226 may_have_dupes = True
226 may_have_dupes = True
227 except TypeError:
227 except TypeError:
228 # This will happen if `object` is a class and not an instance.
228 # This will happen if `object` is a class and not an instance.
229 pass
229 pass
230
230
231 # Support for PyCrust-style _getAttributeNames magic method.
231 # Support for PyCrust-style _getAttributeNames magic method.
232 if hasattr(object, '_getAttributeNames'):
232 if hasattr(object, '_getAttributeNames'):
233 try:
233 try:
234 words.extend(object._getAttributeNames())
234 words.extend(object._getAttributeNames())
235 may_have_dupes = True
235 may_have_dupes = True
236 except TypeError:
236 except TypeError:
237 # `object` is a class and not an instance. Ignore
237 # `object` is a class and not an instance. Ignore
238 # this error.
238 # this error.
239 pass
239 pass
240
240
241 if may_have_dupes:
241 if may_have_dupes:
242 # eliminate possible duplicates, as some traits may also
242 # eliminate possible duplicates, as some traits may also
243 # appear as normal attributes in the dir() call.
243 # appear as normal attributes in the dir() call.
244 words = set(words)
244 words = set(words)
245
245
246 # filter out non-string attributes which may be stuffed by dir() calls
246 # filter out non-string attributes which may be stuffed by dir() calls
247 # and poor coding in third-party modules
247 # and poor coding in third-party modules
248 words = [w for w in words
248 words = [w for w in words
249 if isinstance(w, basestring) and w != "__builtins__"]
249 if isinstance(w, basestring) and w != "__builtins__"]
250 # Build match list to return
250 # Build match list to return
251 n = len(attr)
251 n = len(attr)
252 return ["%s.%s" % (expr, w) for w in words if w[:n] == attr ]
252 return ["%s.%s" % (expr, w) for w in words if w[:n] == attr ]
253
253
254 class IPCompleter(Completer):
254 class IPCompleter(Completer):
255 """Extension of the completer class with IPython-specific features"""
255 """Extension of the completer class with IPython-specific features"""
256
256
257 def __init__(self,shell,namespace=None,global_namespace=None,
257 def __init__(self,shell,namespace=None,global_namespace=None,
258 omit__names=0,alias_table=None):
258 omit__names=0,alias_table=None):
259 """IPCompleter() -> completer
259 """IPCompleter() -> completer
260
260
261 Return a completer object suitable for use by the readline library
261 Return a completer object suitable for use by the readline library
262 via readline.set_completer().
262 via readline.set_completer().
263
263
264 Inputs:
264 Inputs:
265
265
266 - shell: a pointer to the ipython shell itself. This is needed
266 - shell: a pointer to the ipython shell itself. This is needed
267 because this completer knows about magic functions, and those can
267 because this completer knows about magic functions, and those can
268 only be accessed via the ipython instance.
268 only be accessed via the ipython instance.
269
269
270 - namespace: an optional dict where completions are performed.
270 - namespace: an optional dict where completions are performed.
271
271
272 - global_namespace: secondary optional dict for completions, to
272 - global_namespace: secondary optional dict for completions, to
273 handle cases (such as IPython embedded inside functions) where
273 handle cases (such as IPython embedded inside functions) where
274 both Python scopes are visible.
274 both Python scopes are visible.
275
275
276 - The optional omit__names parameter sets the completer to omit the
276 - The optional omit__names parameter sets the completer to omit the
277 'magic' names (__magicname__) for python objects unless the text
277 'magic' names (__magicname__) for python objects unless the text
278 to be completed explicitly starts with one or more underscores.
278 to be completed explicitly starts with one or more underscores.
279
279
280 - If alias_table is supplied, it should be a dictionary of aliases
280 - If alias_table is supplied, it should be a dictionary of aliases
281 to complete. """
281 to complete. """
282
282
283 Completer.__init__(self,namespace,global_namespace)
283 Completer.__init__(self,namespace,global_namespace)
284 self.magic_prefix = shell.name+'.magic_'
284 self.magic_prefix = shell.name+'.magic_'
285 self.magic_escape = shell.ESC_MAGIC
285 self.magic_escape = shell.ESC_MAGIC
286 self.readline = readline
286 self.readline = readline
287 delims = self.readline.get_completer_delims()
287 delims = self.readline.get_completer_delims()
288 delims = delims.replace(self.magic_escape,'')
288 delims = delims.replace(self.magic_escape,'')
289 self.readline.set_completer_delims(delims)
289 self.readline.set_completer_delims(delims)
290 self.get_line_buffer = self.readline.get_line_buffer
290 self.get_line_buffer = self.readline.get_line_buffer
291 self.omit__names = omit__names
291 self.omit__names = omit__names
292 self.merge_completions = shell.rc.readline_merge_completions
292 self.merge_completions = shell.rc.readline_merge_completions
293
293
294 if alias_table is None:
294 if alias_table is None:
295 alias_table = {}
295 alias_table = {}
296 self.alias_table = alias_table
296 self.alias_table = alias_table
297 # Regexp to split filenames with spaces in them
297 # Regexp to split filenames with spaces in them
298 self.space_name_re = re.compile(r'([^\\] )')
298 self.space_name_re = re.compile(r'([^\\] )')
299 # Hold a local ref. to glob.glob for speed
299 # Hold a local ref. to glob.glob for speed
300 self.glob = glob.glob
300 self.glob = glob.glob
301
301
302 # Determine if we are running on 'dumb' terminals, like (X)Emacs
302 # Determine if we are running on 'dumb' terminals, like (X)Emacs
303 # buffers, to avoid completion problems.
303 # buffers, to avoid completion problems.
304 term = os.environ.get('TERM','xterm')
304 term = os.environ.get('TERM','xterm')
305 self.dumb_terminal = term in ['dumb','emacs']
305 self.dumb_terminal = term in ['dumb','emacs']
306
306
307 # Special handling of backslashes needed in win32 platforms
307 # Special handling of backslashes needed in win32 platforms
308 if sys.platform == "win32":
308 if sys.platform == "win32":
309 self.clean_glob = self._clean_glob_win32
309 self.clean_glob = self._clean_glob_win32
310 else:
310 else:
311 self.clean_glob = self._clean_glob
311 self.clean_glob = self._clean_glob
312 self.matchers = [self.python_matches,
312 self.matchers = [self.python_matches,
313 self.file_matches,
313 self.file_matches,
314 self.alias_matches,
314 self.alias_matches,
315 self.python_func_kw_matches]
315 self.python_func_kw_matches]
316
316
317 # Code contributed by Alex Schmolck, for ipython/emacs integration
317 # Code contributed by Alex Schmolck, for ipython/emacs integration
318 def all_completions(self, text):
318 def all_completions(self, text):
319 """Return all possible completions for the benefit of emacs."""
319 """Return all possible completions for the benefit of emacs."""
320
320
321 completions = []
321 completions = []
322 comp_append = completions.append
322 comp_append = completions.append
323 try:
323 try:
324 for i in xrange(sys.maxint):
324 for i in xrange(sys.maxint):
325 res = self.complete(text, i)
325 res = self.complete(text, i)
326
326
327 if not res: break
327 if not res: break
328
328
329 comp_append(res)
329 comp_append(res)
330 #XXX workaround for ``notDefined.<tab>``
330 #XXX workaround for ``notDefined.<tab>``
331 except NameError:
331 except NameError:
332 pass
332 pass
333 return completions
333 return completions
334 # /end Alex Schmolck code.
334 # /end Alex Schmolck code.
335
335
336 def _clean_glob(self,text):
336 def _clean_glob(self,text):
337 return self.glob("%s*" % text)
337 return self.glob("%s*" % text)
338
338
339 def _clean_glob_win32(self,text):
339 def _clean_glob_win32(self,text):
340 return [f.replace("\\","/")
340 return [f.replace("\\","/")
341 for f in self.glob("%s*" % text)]
341 for f in self.glob("%s*" % text)]
342
342
343 def file_matches(self, text):
343 def file_matches(self, text):
344 """Match filenames, expanding ~USER type strings.
344 """Match filenames, expanding ~USER type strings.
345
345
346 Most of the seemingly convoluted logic in this completer is an
346 Most of the seemingly convoluted logic in this completer is an
347 attempt to handle filenames with spaces in them. And yet it's not
347 attempt to handle filenames with spaces in them. And yet it's not
348 quite perfect, because Python's readline doesn't expose all of the
348 quite perfect, because Python's readline doesn't expose all of the
349 GNU readline details needed for this to be done correctly.
349 GNU readline details needed for this to be done correctly.
350
350
351 For a filename with a space in it, the printed completions will be
351 For a filename with a space in it, the printed completions will be
352 only the parts after what's already been typed (instead of the
352 only the parts after what's already been typed (instead of the
353 full completions, as is normally done). I don't think with the
353 full completions, as is normally done). I don't think with the
354 current (as of Python 2.3) Python readline it's possible to do
354 current (as of Python 2.3) Python readline it's possible to do
355 better."""
355 better."""
356
356
357 #print 'Completer->file_matches: <%s>' % text # dbg
357 #print 'Completer->file_matches: <%s>' % text # dbg
358
358
359 # chars that require escaping with backslash - i.e. chars
359 # chars that require escaping with backslash - i.e. chars
360 # that readline treats incorrectly as delimiters, but we
360 # that readline treats incorrectly as delimiters, but we
361 # don't want to treat as delimiters in filename matching
361 # don't want to treat as delimiters in filename matching
362 # when escaped with backslash
362 # when escaped with backslash
363
363
364 protectables = ' ()[]{}'
364 protectables = ' ()[]{}'
365
365
366 if text.startswith('!'):
366 if text.startswith('!'):
367 text = text[1:]
367 text = text[1:]
368 text_prefix = '!'
368 text_prefix = '!'
369 else:
369 else:
370 text_prefix = ''
370 text_prefix = ''
371
371
372 def protect_filename(s):
372 def protect_filename(s):
373 return "".join([(ch in protectables and '\\' + ch or ch)
373 return "".join([(ch in protectables and '\\' + ch or ch)
374 for ch in s])
374 for ch in s])
375
376 def single_dir_expand(matches):
377 "Recursively expand match lists containing a single dir."
378
379 if len(matches) == 1 and os.path.isdir(matches[0]):
380 # Takes care of links to directories also. Use '/'
381 # explicitly, even under Windows, so that name completions
382 # don't end up escaped.
383 d = matches[0]
384 if d[-1] in ['/','\\']:
385 d = d[:-1]
386
387 matches = [ (d + '/' + p) for p in os.listdir(d) ]
388 return single_dir_expand(matches)
389 else:
390 return matches
375
391
376 lbuf = self.lbuf
392 lbuf = self.lbuf
377 open_quotes = 0 # track strings with open quotes
393 open_quotes = 0 # track strings with open quotes
378 try:
394 try:
379 lsplit = shlex.split(lbuf)[-1]
395 lsplit = shlex.split(lbuf)[-1]
380 except ValueError:
396 except ValueError:
381 # typically an unmatched ", or backslash without escaped char.
397 # typically an unmatched ", or backslash without escaped char.
382 if lbuf.count('"')==1:
398 if lbuf.count('"')==1:
383 open_quotes = 1
399 open_quotes = 1
384 lsplit = lbuf.split('"')[-1]
400 lsplit = lbuf.split('"')[-1]
385 elif lbuf.count("'")==1:
401 elif lbuf.count("'")==1:
386 open_quotes = 1
402 open_quotes = 1
387 lsplit = lbuf.split("'")[-1]
403 lsplit = lbuf.split("'")[-1]
388 else:
404 else:
389 return []
405 return []
390 except IndexError:
406 except IndexError:
391 # tab pressed on empty line
407 # tab pressed on empty line
392 lsplit = ""
408 lsplit = ""
393
409
394 if lsplit != protect_filename(lsplit):
410 if lsplit != protect_filename(lsplit):
395 # if protectables are found, do matching on the whole escaped
411 # if protectables are found, do matching on the whole escaped
396 # name
412 # name
397 has_protectables = 1
413 has_protectables = 1
398 text0,text = text,lsplit
414 text0,text = text,lsplit
399 else:
415 else:
400 has_protectables = 0
416 has_protectables = 0
401 text = os.path.expanduser(text)
417 text = os.path.expanduser(text)
402
418
403 if text == "":
419 if text == "":
404 return [text_prefix + protect_filename(f) for f in self.glob("*")]
420 return [text_prefix + protect_filename(f) for f in self.glob("*")]
405
421
406 m0 = self.clean_glob(text.replace('\\',''))
422 m0 = self.clean_glob(text.replace('\\',''))
407 if has_protectables:
423 if has_protectables:
408 # If we had protectables, we need to revert our changes to the
424 # If we had protectables, we need to revert our changes to the
409 # beginning of filename so that we don't double-write the part
425 # beginning of filename so that we don't double-write the part
410 # of the filename we have so far
426 # of the filename we have so far
411 len_lsplit = len(lsplit)
427 len_lsplit = len(lsplit)
412 matches = [text_prefix + text0 +
428 matches = [text_prefix + text0 +
413 protect_filename(f[len_lsplit:]) for f in m0]
429 protect_filename(f[len_lsplit:]) for f in m0]
414 else:
430 else:
415 if open_quotes:
431 if open_quotes:
416 # if we have a string with an open quote, we don't need to
432 # if we have a string with an open quote, we don't need to
417 # protect the names at all (and we _shouldn't_, as it
433 # protect the names at all (and we _shouldn't_, as it
418 # would cause bugs when the filesystem call is made).
434 # would cause bugs when the filesystem call is made).
419 matches = m0
435 matches = m0
420 else:
436 else:
421 matches = [text_prefix +
437 matches = [text_prefix +
422 protect_filename(f) for f in m0]
438 protect_filename(f) for f in m0]
423 if len(matches) == 1 and os.path.isdir(matches[0]):
439
424 # Takes care of links to directories also. Use '/'
440 return single_dir_expand(matches)
425 # explicitly, even under Windows, so that name completions
426 # don't end up escaped.
427 d = matches[0]
428 if d[-1] in ['/','\\']:
429 d = d[:-1]
430
431 matches = [ (d + '/' + p) for p in os.listdir(d) ]
432
433 return matches
434
441
435 def alias_matches(self, text):
442 def alias_matches(self, text):
436 """Match internal system aliases"""
443 """Match internal system aliases"""
437 #print 'Completer->alias_matches:',text,'lb',self.lbuf # dbg
444 #print 'Completer->alias_matches:',text,'lb',self.lbuf # dbg
438
445
439 # if we are not in the first 'item', alias matching
446 # if we are not in the first 'item', alias matching
440 # doesn't make sense
447 # doesn't make sense
441 if ' ' in self.lbuf:
448 if ' ' in self.lbuf:
442 return []
449 return []
443 text = os.path.expanduser(text)
450 text = os.path.expanduser(text)
444 aliases = self.alias_table.keys()
451 aliases = self.alias_table.keys()
445 if text == "":
452 if text == "":
446 return aliases
453 return aliases
447 else:
454 else:
448 return [alias for alias in aliases if alias.startswith(text)]
455 return [alias for alias in aliases if alias.startswith(text)]
449
456
450 def python_matches(self,text):
457 def python_matches(self,text):
451 """Match attributes or global python names"""
458 """Match attributes or global python names"""
452
459
453 #print 'Completer->python_matches, txt=<%s>' % text # dbg
460 #print 'Completer->python_matches, txt=<%s>' % text # dbg
454 if "." in text:
461 if "." in text:
455 try:
462 try:
456 matches = self.attr_matches(text)
463 matches = self.attr_matches(text)
457 if text.endswith('.') and self.omit__names:
464 if text.endswith('.') and self.omit__names:
458 if self.omit__names == 1:
465 if self.omit__names == 1:
459 # true if txt is _not_ a __ name, false otherwise:
466 # true if txt is _not_ a __ name, false otherwise:
460 no__name = (lambda txt:
467 no__name = (lambda txt:
461 re.match(r'.*\.__.*?__',txt) is None)
468 re.match(r'.*\.__.*?__',txt) is None)
462 else:
469 else:
463 # true if txt is _not_ a _ name, false otherwise:
470 # true if txt is _not_ a _ name, false otherwise:
464 no__name = (lambda txt:
471 no__name = (lambda txt:
465 re.match(r'.*\._.*?',txt) is None)
472 re.match(r'.*\._.*?',txt) is None)
466 matches = filter(no__name, matches)
473 matches = filter(no__name, matches)
467 except NameError:
474 except NameError:
468 # catches <undefined attributes>.<tab>
475 # catches <undefined attributes>.<tab>
469 matches = []
476 matches = []
470 else:
477 else:
471 matches = self.global_matches(text)
478 matches = self.global_matches(text)
472 # this is so completion finds magics when automagic is on:
479 # this is so completion finds magics when automagic is on:
473 if (matches == [] and
480 if (matches == [] and
474 not text.startswith(os.sep) and
481 not text.startswith(os.sep) and
475 not ' ' in self.lbuf):
482 not ' ' in self.lbuf):
476 matches = self.attr_matches(self.magic_prefix+text)
483 matches = self.attr_matches(self.magic_prefix+text)
477 return matches
484 return matches
478
485
479 def _default_arguments(self, obj):
486 def _default_arguments(self, obj):
480 """Return the list of default arguments of obj if it is callable,
487 """Return the list of default arguments of obj if it is callable,
481 or empty list otherwise."""
488 or empty list otherwise."""
482
489
483 if not (inspect.isfunction(obj) or inspect.ismethod(obj)):
490 if not (inspect.isfunction(obj) or inspect.ismethod(obj)):
484 # for classes, check for __init__,__new__
491 # for classes, check for __init__,__new__
485 if inspect.isclass(obj):
492 if inspect.isclass(obj):
486 obj = (getattr(obj,'__init__',None) or
493 obj = (getattr(obj,'__init__',None) or
487 getattr(obj,'__new__',None))
494 getattr(obj,'__new__',None))
488 # for all others, check if they are __call__able
495 # for all others, check if they are __call__able
489 elif hasattr(obj, '__call__'):
496 elif hasattr(obj, '__call__'):
490 obj = obj.__call__
497 obj = obj.__call__
491 # XXX: is there a way to handle the builtins ?
498 # XXX: is there a way to handle the builtins ?
492 try:
499 try:
493 args,_,_1,defaults = inspect.getargspec(obj)
500 args,_,_1,defaults = inspect.getargspec(obj)
494 if defaults:
501 if defaults:
495 return args[-len(defaults):]
502 return args[-len(defaults):]
496 except TypeError: pass
503 except TypeError: pass
497 return []
504 return []
498
505
499 def python_func_kw_matches(self,text):
506 def python_func_kw_matches(self,text):
500 """Match named parameters (kwargs) of the last open function"""
507 """Match named parameters (kwargs) of the last open function"""
501
508
502 if "." in text: # a parameter cannot be dotted
509 if "." in text: # a parameter cannot be dotted
503 return []
510 return []
504 try: regexp = self.__funcParamsRegex
511 try: regexp = self.__funcParamsRegex
505 except AttributeError:
512 except AttributeError:
506 regexp = self.__funcParamsRegex = re.compile(r'''
513 regexp = self.__funcParamsRegex = re.compile(r'''
507 '.*?' | # single quoted strings or
514 '.*?' | # single quoted strings or
508 ".*?" | # double quoted strings or
515 ".*?" | # double quoted strings or
509 \w+ | # identifier
516 \w+ | # identifier
510 \S # other characters
517 \S # other characters
511 ''', re.VERBOSE | re.DOTALL)
518 ''', re.VERBOSE | re.DOTALL)
512 # 1. find the nearest identifier that comes before an unclosed
519 # 1. find the nearest identifier that comes before an unclosed
513 # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo"
520 # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo"
514 tokens = regexp.findall(self.get_line_buffer())
521 tokens = regexp.findall(self.get_line_buffer())
515 tokens.reverse()
522 tokens.reverse()
516 iterTokens = iter(tokens); openPar = 0
523 iterTokens = iter(tokens); openPar = 0
517 for token in iterTokens:
524 for token in iterTokens:
518 if token == ')':
525 if token == ')':
519 openPar -= 1
526 openPar -= 1
520 elif token == '(':
527 elif token == '(':
521 openPar += 1
528 openPar += 1
522 if openPar > 0:
529 if openPar > 0:
523 # found the last unclosed parenthesis
530 # found the last unclosed parenthesis
524 break
531 break
525 else:
532 else:
526 return []
533 return []
527 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
534 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
528 ids = []
535 ids = []
529 isId = re.compile(r'\w+$').match
536 isId = re.compile(r'\w+$').match
530 while True:
537 while True:
531 try:
538 try:
532 ids.append(iterTokens.next())
539 ids.append(iterTokens.next())
533 if not isId(ids[-1]):
540 if not isId(ids[-1]):
534 ids.pop(); break
541 ids.pop(); break
535 if not iterTokens.next() == '.':
542 if not iterTokens.next() == '.':
536 break
543 break
537 except StopIteration:
544 except StopIteration:
538 break
545 break
539 # lookup the candidate callable matches either using global_matches
546 # lookup the candidate callable matches either using global_matches
540 # or attr_matches for dotted names
547 # or attr_matches for dotted names
541 if len(ids) == 1:
548 if len(ids) == 1:
542 callableMatches = self.global_matches(ids[0])
549 callableMatches = self.global_matches(ids[0])
543 else:
550 else:
544 callableMatches = self.attr_matches('.'.join(ids[::-1]))
551 callableMatches = self.attr_matches('.'.join(ids[::-1]))
545 argMatches = []
552 argMatches = []
546 for callableMatch in callableMatches:
553 for callableMatch in callableMatches:
547 try: namedArgs = self._default_arguments(eval(callableMatch,
554 try: namedArgs = self._default_arguments(eval(callableMatch,
548 self.namespace))
555 self.namespace))
549 except: continue
556 except: continue
550 for namedArg in namedArgs:
557 for namedArg in namedArgs:
551 if namedArg.startswith(text):
558 if namedArg.startswith(text):
552 argMatches.append("%s=" %namedArg)
559 argMatches.append("%s=" %namedArg)
553 return argMatches
560 return argMatches
554
561
555 def dispatch_custom_completer(self,text):
562 def dispatch_custom_completer(self,text):
556 # print "Custom! '%s' %s" % (text, self.custom_completers) # dbg
563 # print "Custom! '%s' %s" % (text, self.custom_completers) # dbg
557 line = self.full_lbuf
564 line = self.full_lbuf
558 if not line.strip():
565 if not line.strip():
559 return None
566 return None
560
567
561 event = Struct()
568 event = Struct()
562 event.line = line
569 event.line = line
563 event.symbol = text
570 event.symbol = text
564 cmd = line.split(None,1)[0]
571 cmd = line.split(None,1)[0]
565 event.command = cmd
572 event.command = cmd
566 #print "\ncustom:{%s]\n" % event # dbg
573 #print "\ncustom:{%s]\n" % event # dbg
567
574
568 # for foo etc, try also to find completer for %foo
575 # for foo etc, try also to find completer for %foo
569 if not cmd.startswith(self.magic_escape):
576 if not cmd.startswith(self.magic_escape):
570 try_magic = self.custom_completers.s_matches(
577 try_magic = self.custom_completers.s_matches(
571 self.magic_escape + cmd)
578 self.magic_escape + cmd)
572 else:
579 else:
573 try_magic = []
580 try_magic = []
574
581
575
582
576 for c in itertools.chain(
583 for c in itertools.chain(
577 self.custom_completers.s_matches(cmd),
584 self.custom_completers.s_matches(cmd),
578 try_magic,
585 try_magic,
579 self.custom_completers.flat_matches(self.lbuf)):
586 self.custom_completers.flat_matches(self.lbuf)):
580 # print "try",c # dbg
587 # print "try",c # dbg
581 try:
588 try:
582 res = c(event)
589 res = c(event)
583 return [r for r in res if r.lower().startswith(text.lower())]
590 return [r for r in res if r.lower().startswith(text.lower())]
584 except ipapi.TryNext:
591 except ipapi.TryNext:
585 pass
592 pass
586
593
587 return None
594 return None
588
595
589
596
590
597
591 def complete(self, text, state):
598 def complete(self, text, state):
592 """Return the next possible completion for 'text'.
599 """Return the next possible completion for 'text'.
593
600
594 This is called successively with state == 0, 1, 2, ... until it
601 This is called successively with state == 0, 1, 2, ... until it
595 returns None. The completion should begin with 'text'. """
602 returns None. The completion should begin with 'text'. """
596
603
597 #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg
604 #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg
598
605
599 # if there is only a tab on a line with only whitespace, instead
606 # if there is only a tab on a line with only whitespace, instead
600 # of the mostly useless 'do you want to see all million
607 # of the mostly useless 'do you want to see all million
601 # completions' message, just do the right thing and give the user
608 # completions' message, just do the right thing and give the user
602 # his tab! Incidentally, this enables pasting of tabbed text from
609 # his tab! Incidentally, this enables pasting of tabbed text from
603 # an editor (as long as autoindent is off).
610 # an editor (as long as autoindent is off).
604
611
605 # don't apply this on 'dumb' terminals, such as emacs buffers, so we
612 # don't apply this on 'dumb' terminals, such as emacs buffers, so we
606 # don't interfere with their own tab-completion mechanism.
613 # don't interfere with their own tab-completion mechanism.
607 self.full_lbuf = self.get_line_buffer()
614 self.full_lbuf = self.get_line_buffer()
608 self.lbuf = self.full_lbuf[:self.readline.get_endidx()]
615 self.lbuf = self.full_lbuf[:self.readline.get_endidx()]
609 if not (self.dumb_terminal or self.get_line_buffer().strip()):
616 if not (self.dumb_terminal or self.get_line_buffer().strip()):
610 self.readline.insert_text('\t')
617 self.readline.insert_text('\t')
611 return None
618 return None
612
619
613
620
614 magic_escape = self.magic_escape
621 magic_escape = self.magic_escape
615 magic_prefix = self.magic_prefix
622 magic_prefix = self.magic_prefix
616
623
617 try:
624 try:
618 if text.startswith(magic_escape):
625 if text.startswith(magic_escape):
619 text = text.replace(magic_escape,magic_prefix)
626 text = text.replace(magic_escape,magic_prefix)
620 elif text.startswith('~'):
627 elif text.startswith('~'):
621 text = os.path.expanduser(text)
628 text = os.path.expanduser(text)
622 if state == 0:
629 if state == 0:
623 custom_res = self.dispatch_custom_completer(text)
630 custom_res = self.dispatch_custom_completer(text)
624 if custom_res is not None:
631 if custom_res is not None:
625 # did custom completers produce something?
632 # did custom completers produce something?
626 self.matches = custom_res
633 self.matches = custom_res
627 else:
634 else:
628 # Extend the list of completions with the results of each
635 # Extend the list of completions with the results of each
629 # matcher, so we return results to the user from all
636 # matcher, so we return results to the user from all
630 # namespaces.
637 # namespaces.
631 if self.merge_completions:
638 if self.merge_completions:
632 self.matches = []
639 self.matches = []
633 for matcher in self.matchers:
640 for matcher in self.matchers:
634 self.matches.extend(matcher(text))
641 self.matches.extend(matcher(text))
635 else:
642 else:
636 for matcher in self.matchers:
643 for matcher in self.matchers:
637 self.matches = matcher(text)
644 self.matches = matcher(text)
638 if self.matches:
645 if self.matches:
639 break
646 break
640
647
641 try:
648 try:
642 return self.matches[state].replace(magic_prefix,magic_escape)
649 return self.matches[state].replace(magic_prefix,magic_escape)
643 except IndexError:
650 except IndexError:
644 return None
651 return None
645 except:
652 except:
646 from IPython.ultraTB import AutoFormattedTB; # dbg
653 from IPython.ultraTB import AutoFormattedTB; # dbg
647 tb=AutoFormattedTB('Verbose');tb() #dbg
654 tb=AutoFormattedTB('Verbose');tb() #dbg
648
655
649 # If completion fails, don't annoy the user.
656 # If completion fails, don't annoy the user.
650 return None
657 return None
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
General Comments 0
You need to be logged in to leave comments. Login now