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