##// END OF EJS Templates
Fix bugs in completer.py with incompletely-implemented property....
Fernando Perez -
Show More
@@ -1,918 +1,923 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-2011 IPython Development Team
56 # Copyright (C) 2008-2011 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.config.configurable import Configurable
81 from IPython.config.configurable import Configurable
82 from IPython.core.error import TryNext
82 from IPython.core.error import TryNext
83 from IPython.core.prefilter import ESC_MAGIC
83 from IPython.core.prefilter import ESC_MAGIC
84 from IPython.utils import generics
84 from IPython.utils import generics
85 from IPython.utils import io
85 from IPython.utils import io
86 from IPython.utils.dir2 import dir2
86 from IPython.utils.dir2 import dir2
87 from IPython.utils.process import arg_split
87 from IPython.utils.process import arg_split
88 from IPython.utils.traitlets import CBool, Enum
88 from IPython.utils.traitlets import CBool, Enum
89
89
90 #-----------------------------------------------------------------------------
90 #-----------------------------------------------------------------------------
91 # Globals
91 # Globals
92 #-----------------------------------------------------------------------------
92 #-----------------------------------------------------------------------------
93
93
94 # Public API
94 # Public API
95 __all__ = ['Completer','IPCompleter']
95 __all__ = ['Completer','IPCompleter']
96
96
97 if sys.platform == 'win32':
97 if sys.platform == 'win32':
98 PROTECTABLES = ' '
98 PROTECTABLES = ' '
99 else:
99 else:
100 PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&'
100 PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&'
101
101
102 #-----------------------------------------------------------------------------
102 #-----------------------------------------------------------------------------
103 # Main functions and classes
103 # Main functions and classes
104 #-----------------------------------------------------------------------------
104 #-----------------------------------------------------------------------------
105
105
106 def has_open_quotes(s):
106 def has_open_quotes(s):
107 """Return whether a string has open quotes.
107 """Return whether a string has open quotes.
108
108
109 This simply counts whether the number of quote characters of either type in
109 This simply counts whether the number of quote characters of either type in
110 the string is odd.
110 the string is odd.
111
111
112 Returns
112 Returns
113 -------
113 -------
114 If there is an open quote, the quote character is returned. Else, return
114 If there is an open quote, the quote character is returned. Else, return
115 False.
115 False.
116 """
116 """
117 # We check " first, then ', so complex cases with nested quotes will get
117 # We check " first, then ', so complex cases with nested quotes will get
118 # the " to take precedence.
118 # the " to take precedence.
119 if s.count('"') % 2:
119 if s.count('"') % 2:
120 return '"'
120 return '"'
121 elif s.count("'") % 2:
121 elif s.count("'") % 2:
122 return "'"
122 return "'"
123 else:
123 else:
124 return False
124 return False
125
125
126
126
127 def protect_filename(s):
127 def protect_filename(s):
128 """Escape a string to protect certain characters."""
128 """Escape a string to protect certain characters."""
129
129
130 return "".join([(ch in PROTECTABLES and '\\' + ch or ch)
130 return "".join([(ch in PROTECTABLES and '\\' + ch or ch)
131 for ch in s])
131 for ch in s])
132
132
133 def expand_user(path):
133 def expand_user(path):
134 """Expand '~'-style usernames in strings.
134 """Expand '~'-style usernames in strings.
135
135
136 This is similar to :func:`os.path.expanduser`, but it computes and returns
136 This is similar to :func:`os.path.expanduser`, but it computes and returns
137 extra information that will be useful if the input was being used in
137 extra information that will be useful if the input was being used in
138 computing completions, and you wish to return the completions with the
138 computing completions, and you wish to return the completions with the
139 original '~' instead of its expanded value.
139 original '~' instead of its expanded value.
140
140
141 Parameters
141 Parameters
142 ----------
142 ----------
143 path : str
143 path : str
144 String to be expanded. If no ~ is present, the output is the same as the
144 String to be expanded. If no ~ is present, the output is the same as the
145 input.
145 input.
146
146
147 Returns
147 Returns
148 -------
148 -------
149 newpath : str
149 newpath : str
150 Result of ~ expansion in the input path.
150 Result of ~ expansion in the input path.
151 tilde_expand : bool
151 tilde_expand : bool
152 Whether any expansion was performed or not.
152 Whether any expansion was performed or not.
153 tilde_val : str
153 tilde_val : str
154 The value that ~ was replaced with.
154 The value that ~ was replaced with.
155 """
155 """
156 # Default values
156 # Default values
157 tilde_expand = False
157 tilde_expand = False
158 tilde_val = ''
158 tilde_val = ''
159 newpath = path
159 newpath = path
160
160
161 if path.startswith('~'):
161 if path.startswith('~'):
162 tilde_expand = True
162 tilde_expand = True
163 rest = len(path)-1
163 rest = len(path)-1
164 newpath = os.path.expanduser(path)
164 newpath = os.path.expanduser(path)
165 if rest:
165 if rest:
166 tilde_val = newpath[:-rest]
166 tilde_val = newpath[:-rest]
167 else:
167 else:
168 tilde_val = newpath
168 tilde_val = newpath
169
169
170 return newpath, tilde_expand, tilde_val
170 return newpath, tilde_expand, tilde_val
171
171
172
172
173 def compress_user(path, tilde_expand, tilde_val):
173 def compress_user(path, tilde_expand, tilde_val):
174 """Does the opposite of expand_user, with its outputs.
174 """Does the opposite of expand_user, with its outputs.
175 """
175 """
176 if tilde_expand:
176 if tilde_expand:
177 return path.replace(tilde_val, '~')
177 return path.replace(tilde_val, '~')
178 else:
178 else:
179 return path
179 return path
180
180
181
181 class Bunch(object): pass
182 class Bunch(object): pass
182
183
184
183 DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
185 DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
184 GREEDY_DELIMS = ' \r\n'
186 GREEDY_DELIMS = ' \r\n'
185
187
188
186 class CompletionSplitter(object):
189 class CompletionSplitter(object):
187 """An object to split an input line in a manner similar to readline.
190 """An object to split an input line in a manner similar to readline.
188
191
189 By having our own implementation, we can expose readline-like completion in
192 By having our own implementation, we can expose readline-like completion in
190 a uniform manner to all frontends. This object only needs to be given the
193 a uniform manner to all frontends. This object only needs to be given the
191 line of text to be split and the cursor position on said line, and it
194 line of text to be split and the cursor position on said line, and it
192 returns the 'word' to be completed on at the cursor after splitting the
195 returns the 'word' to be completed on at the cursor after splitting the
193 entire line.
196 entire line.
194
197
195 What characters are used as splitting delimiters can be controlled by
198 What characters are used as splitting delimiters can be controlled by
196 setting the `delims` attribute (this is a property that internally
199 setting the `delims` attribute (this is a property that internally
197 automatically builds the necessary """
200 automatically builds the necessary regular expression)"""
198
201
199 # Private interface
202 # Private interface
200
203
201 # A string of delimiter characters. The default value makes sense for
204 # A string of delimiter characters. The default value makes sense for
202 # IPython's most typical usage patterns.
205 # IPython's most typical usage patterns.
203 _delims = DELIMS
206 _delims = DELIMS
204
207
205 # The expression (a normal string) to be compiled into a regular expression
208 # The expression (a normal string) to be compiled into a regular expression
206 # for actual splitting. We store it as an attribute mostly for ease of
209 # for actual splitting. We store it as an attribute mostly for ease of
207 # debugging, since this type of code can be so tricky to debug.
210 # debugging, since this type of code can be so tricky to debug.
208 _delim_expr = None
211 _delim_expr = None
209
212
210 # The regular expression that does the actual splitting
213 # The regular expression that does the actual splitting
211 _delim_re = None
214 _delim_re = None
212
215
213 def __init__(self, delims=None):
216 def __init__(self, delims=None):
214 delims = CompletionSplitter._delims if delims is None else delims
217 delims = CompletionSplitter._delims if delims is None else delims
215 self.set_delims(delims)
218 self.delims = delims
216
219
217 def set_delims(self, delims):
220 @property
221 def delims(self):
222 """Return the string of delimiter characters."""
223 return self._delims
224
225 @delims.setter
226 def delims(self, delims):
218 """Set the delimiters for line splitting."""
227 """Set the delimiters for line splitting."""
219 expr = '[' + ''.join('\\'+ c for c in delims) + ']'
228 expr = '[' + ''.join('\\'+ c for c in delims) + ']'
220 self._delim_re = re.compile(expr)
229 self._delim_re = re.compile(expr)
221 self._delims = delims
230 self._delims = delims
222 self._delim_expr = expr
231 self._delim_expr = expr
223
232
224 def get_delims(self):
225 """Return the string of delimiter characters."""
226 return self._delims
227
228 def split_line(self, line, cursor_pos=None):
233 def split_line(self, line, cursor_pos=None):
229 """Split a line of text with a cursor at the given position.
234 """Split a line of text with a cursor at the given position.
230 """
235 """
231 l = line if cursor_pos is None else line[:cursor_pos]
236 l = line if cursor_pos is None else line[:cursor_pos]
232 return self._delim_re.split(l)[-1]
237 return self._delim_re.split(l)[-1]
233
238
234
239
235 class Completer(Configurable):
240 class Completer(Configurable):
236
241
237 greedy = CBool(False, config=True,
242 greedy = CBool(False, config=True,
238 help="""Activate greedy completion
243 help="""Activate greedy completion
239
244
240 This will enable completion on elements of lists, results of function calls, etc.,
245 This will enable completion on elements of lists, results of function calls, etc.,
241 but can be unsafe because the code is actually evaluated on TAB.
246 but can be unsafe because the code is actually evaluated on TAB.
242 """
247 """
243 )
248 )
244
249
245
250
246 def __init__(self, namespace=None, global_namespace=None, config=None, **kwargs):
251 def __init__(self, namespace=None, global_namespace=None, config=None, **kwargs):
247 """Create a new completer for the command line.
252 """Create a new completer for the command line.
248
253
249 Completer(namespace=ns,global_namespace=ns2) -> completer instance.
254 Completer(namespace=ns,global_namespace=ns2) -> completer instance.
250
255
251 If unspecified, the default namespace where completions are performed
256 If unspecified, the default namespace where completions are performed
252 is __main__ (technically, __main__.__dict__). Namespaces should be
257 is __main__ (technically, __main__.__dict__). Namespaces should be
253 given as dictionaries.
258 given as dictionaries.
254
259
255 An optional second namespace can be given. This allows the completer
260 An optional second namespace can be given. This allows the completer
256 to handle cases where both the local and global scopes need to be
261 to handle cases where both the local and global scopes need to be
257 distinguished.
262 distinguished.
258
263
259 Completer instances should be used as the completion mechanism of
264 Completer instances should be used as the completion mechanism of
260 readline via the set_completer() call:
265 readline via the set_completer() call:
261
266
262 readline.set_completer(Completer(my_namespace).complete)
267 readline.set_completer(Completer(my_namespace).complete)
263 """
268 """
264
269
265 # Don't bind to namespace quite yet, but flag whether the user wants a
270 # Don't bind to namespace quite yet, but flag whether the user wants a
266 # specific namespace or to use __main__.__dict__. This will allow us
271 # specific namespace or to use __main__.__dict__. This will allow us
267 # to bind to __main__.__dict__ at completion time, not now.
272 # to bind to __main__.__dict__ at completion time, not now.
268 if namespace is None:
273 if namespace is None:
269 self.use_main_ns = 1
274 self.use_main_ns = 1
270 else:
275 else:
271 self.use_main_ns = 0
276 self.use_main_ns = 0
272 self.namespace = namespace
277 self.namespace = namespace
273
278
274 # The global namespace, if given, can be bound directly
279 # The global namespace, if given, can be bound directly
275 if global_namespace is None:
280 if global_namespace is None:
276 self.global_namespace = {}
281 self.global_namespace = {}
277 else:
282 else:
278 self.global_namespace = global_namespace
283 self.global_namespace = global_namespace
279
284
280 super(Completer, self).__init__(config=config, **kwargs)
285 super(Completer, self).__init__(config=config, **kwargs)
281
286
282 def complete(self, text, state):
287 def complete(self, text, state):
283 """Return the next possible completion for 'text'.
288 """Return the next possible completion for 'text'.
284
289
285 This is called successively with state == 0, 1, 2, ... until it
290 This is called successively with state == 0, 1, 2, ... until it
286 returns None. The completion should begin with 'text'.
291 returns None. The completion should begin with 'text'.
287
292
288 """
293 """
289 if self.use_main_ns:
294 if self.use_main_ns:
290 self.namespace = __main__.__dict__
295 self.namespace = __main__.__dict__
291
296
292 if state == 0:
297 if state == 0:
293 if "." in text:
298 if "." in text:
294 self.matches = self.attr_matches(text)
299 self.matches = self.attr_matches(text)
295 else:
300 else:
296 self.matches = self.global_matches(text)
301 self.matches = self.global_matches(text)
297 try:
302 try:
298 return self.matches[state]
303 return self.matches[state]
299 except IndexError:
304 except IndexError:
300 return None
305 return None
301
306
302 def global_matches(self, text):
307 def global_matches(self, text):
303 """Compute matches when text is a simple name.
308 """Compute matches when text is a simple name.
304
309
305 Return a list of all keywords, built-in functions and names currently
310 Return a list of all keywords, built-in functions and names currently
306 defined in self.namespace or self.global_namespace that match.
311 defined in self.namespace or self.global_namespace that match.
307
312
308 """
313 """
309 #print 'Completer->global_matches, txt=%r' % text # dbg
314 #print 'Completer->global_matches, txt=%r' % text # dbg
310 matches = []
315 matches = []
311 match_append = matches.append
316 match_append = matches.append
312 n = len(text)
317 n = len(text)
313 for lst in [keyword.kwlist,
318 for lst in [keyword.kwlist,
314 __builtin__.__dict__.keys(),
319 __builtin__.__dict__.keys(),
315 self.namespace.keys(),
320 self.namespace.keys(),
316 self.global_namespace.keys()]:
321 self.global_namespace.keys()]:
317 for word in lst:
322 for word in lst:
318 if word[:n] == text and word != "__builtins__":
323 if word[:n] == text and word != "__builtins__":
319 match_append(word)
324 match_append(word)
320 return matches
325 return matches
321
326
322 def attr_matches(self, text):
327 def attr_matches(self, text):
323 """Compute matches when text contains a dot.
328 """Compute matches when text contains a dot.
324
329
325 Assuming the text is of the form NAME.NAME....[NAME], and is
330 Assuming the text is of the form NAME.NAME....[NAME], and is
326 evaluatable in self.namespace or self.global_namespace, it will be
331 evaluatable in self.namespace or self.global_namespace, it will be
327 evaluated and its attributes (as revealed by dir()) are used as
332 evaluated and its attributes (as revealed by dir()) are used as
328 possible completions. (For class instances, class members are are
333 possible completions. (For class instances, class members are are
329 also considered.)
334 also considered.)
330
335
331 WARNING: this can still invoke arbitrary C code, if an object
336 WARNING: this can still invoke arbitrary C code, if an object
332 with a __getattr__ hook is evaluated.
337 with a __getattr__ hook is evaluated.
333
338
334 """
339 """
335
340
336 #io.rprint('Completer->attr_matches, txt=%r' % text) # dbg
341 #io.rprint('Completer->attr_matches, txt=%r' % text) # dbg
337 # Another option, seems to work great. Catches things like ''.<tab>
342 # Another option, seems to work great. Catches things like ''.<tab>
338 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
343 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
339
344
340 if m:
345 if m:
341 expr, attr = m.group(1, 3)
346 expr, attr = m.group(1, 3)
342 elif self.greedy:
347 elif self.greedy:
343 m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer)
348 m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer)
344 if not m2:
349 if not m2:
345 return []
350 return []
346 expr, attr = m2.group(1,2)
351 expr, attr = m2.group(1,2)
347 else:
352 else:
348 return []
353 return []
349
354
350 try:
355 try:
351 obj = eval(expr, self.namespace)
356 obj = eval(expr, self.namespace)
352 except:
357 except:
353 try:
358 try:
354 obj = eval(expr, self.global_namespace)
359 obj = eval(expr, self.global_namespace)
355 except:
360 except:
356 return []
361 return []
357
362
358 if self.limit_to__all__ and hasattr(obj, '__all__'):
363 if self.limit_to__all__ and hasattr(obj, '__all__'):
359 words = get__all__entries(obj)
364 words = get__all__entries(obj)
360 else:
365 else:
361 words = dir2(obj)
366 words = dir2(obj)
362
367
363 try:
368 try:
364 words = generics.complete_object(obj, words)
369 words = generics.complete_object(obj, words)
365 except TryNext:
370 except TryNext:
366 pass
371 pass
367 except Exception:
372 except Exception:
368 # Silence errors from completion function
373 # Silence errors from completion function
369 #raise # dbg
374 #raise # dbg
370 pass
375 pass
371 # Build match list to return
376 # Build match list to return
372 n = len(attr)
377 n = len(attr)
373 res = ["%s.%s" % (expr, w) for w in words if w[:n] == attr ]
378 res = ["%s.%s" % (expr, w) for w in words if w[:n] == attr ]
374 return res
379 return res
375
380
376
381
377 def get__all__entries(obj):
382 def get__all__entries(obj):
378 """returns the strings in the __all__ attribute"""
383 """returns the strings in the __all__ attribute"""
379 try:
384 try:
380 words = getattr(obj,'__all__')
385 words = getattr(obj, '__all__')
381 except:
386 except:
382 return []
387 return []
383
388
384 return [w for w in words if isinstance(w, basestring)]
389 return [w for w in words if isinstance(w, basestring)]
385
390
386
391
387 class IPCompleter(Completer):
392 class IPCompleter(Completer):
388 """Extension of the completer class with IPython-specific features"""
393 """Extension of the completer class with IPython-specific features"""
389
394
390 def _greedy_changed(self, name, old, new):
395 def _greedy_changed(self, name, old, new):
391 """update the splitter and readline delims when greedy is changed"""
396 """update the splitter and readline delims when greedy is changed"""
392 if new:
397 if new:
393 self.splitter.set_delims(GREEDY_DELIMS)
398 self.splitter.delims = GREEDY_DELIMS
394 else:
399 else:
395 self.splitter.set_delims(DELIMS)
400 self.splitter.delims = DELIMS
396
401
397 if self.readline:
402 if self.readline:
398 self.readline.set_completer_delims(self.splitter.get_delims())
403 self.readline.set_completer_delims(self.splitter.delims)
399
404
400 merge_completions = CBool(True, config=True,
405 merge_completions = CBool(True, config=True,
401 help="""Whether to merge completion results into a single list
406 help="""Whether to merge completion results into a single list
402
407
403 If False, only the completion results from the first non-empty
408 If False, only the completion results from the first non-empty
404 completer will be returned.
409 completer will be returned.
405 """
410 """
406 )
411 )
407 omit__names = Enum((0,1,2), default_value=2, config=True,
412 omit__names = Enum((0,1,2), default_value=2, config=True,
408 help="""Instruct the completer to omit private method names
413 help="""Instruct the completer to omit private method names
409
414
410 Specifically, when completing on ``object.<tab>``.
415 Specifically, when completing on ``object.<tab>``.
411
416
412 When 2 [default]: all names that start with '_' will be excluded.
417 When 2 [default]: all names that start with '_' will be excluded.
413
418
414 When 1: all 'magic' names (``__foo__``) will be excluded.
419 When 1: all 'magic' names (``__foo__``) will be excluded.
415
420
416 When 0: nothing will be excluded.
421 When 0: nothing will be excluded.
417 """
422 """
418 )
423 )
419 limit_to__all__ = CBool(default_value=False, config=True,
424 limit_to__all__ = CBool(default_value=False, config=True,
420 help="""Instruct the completer to use __all__ for the completion
425 help="""Instruct the completer to use __all__ for the completion
421
426
422 Specifically, when completing on ``object.<tab>``.
427 Specifically, when completing on ``object.<tab>``.
423
428
424 When True: only those names in obj.__all__ will be included.
429 When True: only those names in obj.__all__ will be included.
425
430
426 When False [default]: the __all__ attribute is ignored
431 When False [default]: the __all__ attribute is ignored
427 """
432 """
428 )
433 )
429
434
430 def __init__(self, shell=None, namespace=None, global_namespace=None,
435 def __init__(self, shell=None, namespace=None, global_namespace=None,
431 alias_table=None, use_readline=True,
436 alias_table=None, use_readline=True,
432 config=None, **kwargs):
437 config=None, **kwargs):
433 """IPCompleter() -> completer
438 """IPCompleter() -> completer
434
439
435 Return a completer object suitable for use by the readline library
440 Return a completer object suitable for use by the readline library
436 via readline.set_completer().
441 via readline.set_completer().
437
442
438 Inputs:
443 Inputs:
439
444
440 - shell: a pointer to the ipython shell itself. This is needed
445 - shell: a pointer to the ipython shell itself. This is needed
441 because this completer knows about magic functions, and those can
446 because this completer knows about magic functions, and those can
442 only be accessed via the ipython instance.
447 only be accessed via the ipython instance.
443
448
444 - namespace: an optional dict where completions are performed.
449 - namespace: an optional dict where completions are performed.
445
450
446 - global_namespace: secondary optional dict for completions, to
451 - global_namespace: secondary optional dict for completions, to
447 handle cases (such as IPython embedded inside functions) where
452 handle cases (such as IPython embedded inside functions) where
448 both Python scopes are visible.
453 both Python scopes are visible.
449
454
450 - If alias_table is supplied, it should be a dictionary of aliases
455 - If alias_table is supplied, it should be a dictionary of aliases
451 to complete.
456 to complete.
452
457
453 use_readline : bool, optional
458 use_readline : bool, optional
454 If true, use the readline library. This completer can still function
459 If true, use the readline library. This completer can still function
455 without readline, though in that case callers must provide some extra
460 without readline, though in that case callers must provide some extra
456 information on each call about the current line."""
461 information on each call about the current line."""
457
462
458 self.magic_escape = ESC_MAGIC
463 self.magic_escape = ESC_MAGIC
459 self.splitter = CompletionSplitter()
464 self.splitter = CompletionSplitter()
460
465
461 # Readline configuration, only used by the rlcompleter method.
466 # Readline configuration, only used by the rlcompleter method.
462 if use_readline:
467 if use_readline:
463 # We store the right version of readline so that later code
468 # We store the right version of readline so that later code
464 import IPython.utils.rlineimpl as readline
469 import IPython.utils.rlineimpl as readline
465 self.readline = readline
470 self.readline = readline
466 else:
471 else:
467 self.readline = None
472 self.readline = None
468
473
469 # _greedy_changed() depends on splitter and readline being defined:
474 # _greedy_changed() depends on splitter and readline being defined:
470 Completer.__init__(self, namespace=namespace, global_namespace=global_namespace,
475 Completer.__init__(self, namespace=namespace, global_namespace=global_namespace,
471 config=config, **kwargs)
476 config=config, **kwargs)
472
477
473 # List where completion matches will be stored
478 # List where completion matches will be stored
474 self.matches = []
479 self.matches = []
475 self.shell = shell
480 self.shell = shell
476 if alias_table is None:
481 if alias_table is None:
477 alias_table = {}
482 alias_table = {}
478 self.alias_table = alias_table
483 self.alias_table = alias_table
479 # Regexp to split filenames with spaces in them
484 # Regexp to split filenames with spaces in them
480 self.space_name_re = re.compile(r'([^\\] )')
485 self.space_name_re = re.compile(r'([^\\] )')
481 # Hold a local ref. to glob.glob for speed
486 # Hold a local ref. to glob.glob for speed
482 self.glob = glob.glob
487 self.glob = glob.glob
483
488
484 # Determine if we are running on 'dumb' terminals, like (X)Emacs
489 # Determine if we are running on 'dumb' terminals, like (X)Emacs
485 # buffers, to avoid completion problems.
490 # buffers, to avoid completion problems.
486 term = os.environ.get('TERM','xterm')
491 term = os.environ.get('TERM','xterm')
487 self.dumb_terminal = term in ['dumb','emacs']
492 self.dumb_terminal = term in ['dumb','emacs']
488
493
489 # Special handling of backslashes needed in win32 platforms
494 # Special handling of backslashes needed in win32 platforms
490 if sys.platform == "win32":
495 if sys.platform == "win32":
491 self.clean_glob = self._clean_glob_win32
496 self.clean_glob = self._clean_glob_win32
492 else:
497 else:
493 self.clean_glob = self._clean_glob
498 self.clean_glob = self._clean_glob
494
499
495 # All active matcher routines for completion
500 # All active matcher routines for completion
496 self.matchers = [self.python_matches,
501 self.matchers = [self.python_matches,
497 self.file_matches,
502 self.file_matches,
498 self.magic_matches,
503 self.magic_matches,
499 self.alias_matches,
504 self.alias_matches,
500 self.python_func_kw_matches,
505 self.python_func_kw_matches,
501 ]
506 ]
502
507
503 def all_completions(self, text):
508 def all_completions(self, text):
504 """
509 """
505 Wrapper around the complete method for the benefit of emacs
510 Wrapper around the complete method for the benefit of emacs
506 and pydb.
511 and pydb.
507 """
512 """
508 return self.complete(text)[1]
513 return self.complete(text)[1]
509
514
510 def _clean_glob(self,text):
515 def _clean_glob(self,text):
511 return self.glob("%s*" % text)
516 return self.glob("%s*" % text)
512
517
513 def _clean_glob_win32(self,text):
518 def _clean_glob_win32(self,text):
514 return [f.replace("\\","/")
519 return [f.replace("\\","/")
515 for f in self.glob("%s*" % text)]
520 for f in self.glob("%s*" % text)]
516
521
517 def file_matches(self, text):
522 def file_matches(self, text):
518 """Match filenames, expanding ~USER type strings.
523 """Match filenames, expanding ~USER type strings.
519
524
520 Most of the seemingly convoluted logic in this completer is an
525 Most of the seemingly convoluted logic in this completer is an
521 attempt to handle filenames with spaces in them. And yet it's not
526 attempt to handle filenames with spaces in them. And yet it's not
522 quite perfect, because Python's readline doesn't expose all of the
527 quite perfect, because Python's readline doesn't expose all of the
523 GNU readline details needed for this to be done correctly.
528 GNU readline details needed for this to be done correctly.
524
529
525 For a filename with a space in it, the printed completions will be
530 For a filename with a space in it, the printed completions will be
526 only the parts after what's already been typed (instead of the
531 only the parts after what's already been typed (instead of the
527 full completions, as is normally done). I don't think with the
532 full completions, as is normally done). I don't think with the
528 current (as of Python 2.3) Python readline it's possible to do
533 current (as of Python 2.3) Python readline it's possible to do
529 better."""
534 better."""
530
535
531 #io.rprint('Completer->file_matches: <%r>' % text) # dbg
536 #io.rprint('Completer->file_matches: <%r>' % text) # dbg
532
537
533 # chars that require escaping with backslash - i.e. chars
538 # chars that require escaping with backslash - i.e. chars
534 # that readline treats incorrectly as delimiters, but we
539 # that readline treats incorrectly as delimiters, but we
535 # don't want to treat as delimiters in filename matching
540 # don't want to treat as delimiters in filename matching
536 # when escaped with backslash
541 # when escaped with backslash
537 if text.startswith('!'):
542 if text.startswith('!'):
538 text = text[1:]
543 text = text[1:]
539 text_prefix = '!'
544 text_prefix = '!'
540 else:
545 else:
541 text_prefix = ''
546 text_prefix = ''
542
547
543 text_until_cursor = self.text_until_cursor
548 text_until_cursor = self.text_until_cursor
544 # track strings with open quotes
549 # track strings with open quotes
545 open_quotes = has_open_quotes(text_until_cursor)
550 open_quotes = has_open_quotes(text_until_cursor)
546
551
547 if '(' in text_until_cursor or '[' in text_until_cursor:
552 if '(' in text_until_cursor or '[' in text_until_cursor:
548 lsplit = text
553 lsplit = text
549 else:
554 else:
550 try:
555 try:
551 # arg_split ~ shlex.split, but with unicode bugs fixed by us
556 # arg_split ~ shlex.split, but with unicode bugs fixed by us
552 lsplit = arg_split(text_until_cursor)[-1]
557 lsplit = arg_split(text_until_cursor)[-1]
553 except ValueError:
558 except ValueError:
554 # typically an unmatched ", or backslash without escaped char.
559 # typically an unmatched ", or backslash without escaped char.
555 if open_quotes:
560 if open_quotes:
556 lsplit = text_until_cursor.split(open_quotes)[-1]
561 lsplit = text_until_cursor.split(open_quotes)[-1]
557 else:
562 else:
558 return []
563 return []
559 except IndexError:
564 except IndexError:
560 # tab pressed on empty line
565 # tab pressed on empty line
561 lsplit = ""
566 lsplit = ""
562
567
563 if not open_quotes and lsplit != protect_filename(lsplit):
568 if not open_quotes and lsplit != protect_filename(lsplit):
564 # if protectables are found, do matching on the whole escaped name
569 # if protectables are found, do matching on the whole escaped name
565 has_protectables = True
570 has_protectables = True
566 text0,text = text,lsplit
571 text0,text = text,lsplit
567 else:
572 else:
568 has_protectables = False
573 has_protectables = False
569 text = os.path.expanduser(text)
574 text = os.path.expanduser(text)
570
575
571 if text == "":
576 if text == "":
572 return [text_prefix + protect_filename(f) for f in self.glob("*")]
577 return [text_prefix + protect_filename(f) for f in self.glob("*")]
573
578
574 # Compute the matches from the filesystem
579 # Compute the matches from the filesystem
575 m0 = self.clean_glob(text.replace('\\',''))
580 m0 = self.clean_glob(text.replace('\\',''))
576
581
577 if has_protectables:
582 if has_protectables:
578 # If we had protectables, we need to revert our changes to the
583 # If we had protectables, we need to revert our changes to the
579 # beginning of filename so that we don't double-write the part
584 # beginning of filename so that we don't double-write the part
580 # of the filename we have so far
585 # of the filename we have so far
581 len_lsplit = len(lsplit)
586 len_lsplit = len(lsplit)
582 matches = [text_prefix + text0 +
587 matches = [text_prefix + text0 +
583 protect_filename(f[len_lsplit:]) for f in m0]
588 protect_filename(f[len_lsplit:]) for f in m0]
584 else:
589 else:
585 if open_quotes:
590 if open_quotes:
586 # if we have a string with an open quote, we don't need to
591 # if we have a string with an open quote, we don't need to
587 # protect the names at all (and we _shouldn't_, as it
592 # protect the names at all (and we _shouldn't_, as it
588 # would cause bugs when the filesystem call is made).
593 # would cause bugs when the filesystem call is made).
589 matches = m0
594 matches = m0
590 else:
595 else:
591 matches = [text_prefix +
596 matches = [text_prefix +
592 protect_filename(f) for f in m0]
597 protect_filename(f) for f in m0]
593
598
594 #io.rprint('mm', matches) # dbg
599 #io.rprint('mm', matches) # dbg
595
600
596 # Mark directories in input list by appending '/' to their names.
601 # Mark directories in input list by appending '/' to their names.
597 matches = [x+'/' if os.path.isdir(x) else x for x in matches]
602 matches = [x+'/' if os.path.isdir(x) else x for x in matches]
598 return matches
603 return matches
599
604
600 def magic_matches(self, text):
605 def magic_matches(self, text):
601 """Match magics"""
606 """Match magics"""
602 #print 'Completer->magic_matches:',text,'lb',self.text_until_cursor # dbg
607 #print 'Completer->magic_matches:',text,'lb',self.text_until_cursor # dbg
603 # Get all shell magics now rather than statically, so magics loaded at
608 # Get all shell magics now rather than statically, so magics loaded at
604 # runtime show up too
609 # runtime show up too
605 # FIXME - cell magics not implemented here yet.
610 # FIXME - cell magics not implemented here yet.
606 magics = self.shell.magics_manager.lsmagic()['line']
611 magics = self.shell.magics_manager.lsmagic()['line']
607 pre = self.magic_escape
612 pre = self.magic_escape
608 baretext = text.lstrip(pre)
613 baretext = text.lstrip(pre)
609 return [ pre+m for m in magics if m.startswith(baretext)]
614 return [ pre+m for m in magics if m.startswith(baretext)]
610
615
611 def alias_matches(self, text):
616 def alias_matches(self, text):
612 """Match internal system aliases"""
617 """Match internal system aliases"""
613 #print 'Completer->alias_matches:',text,'lb',self.text_until_cursor # dbg
618 #print 'Completer->alias_matches:',text,'lb',self.text_until_cursor # dbg
614
619
615 # if we are not in the first 'item', alias matching
620 # if we are not in the first 'item', alias matching
616 # doesn't make sense - unless we are starting with 'sudo' command.
621 # doesn't make sense - unless we are starting with 'sudo' command.
617 main_text = self.text_until_cursor.lstrip()
622 main_text = self.text_until_cursor.lstrip()
618 if ' ' in main_text and not main_text.startswith('sudo'):
623 if ' ' in main_text and not main_text.startswith('sudo'):
619 return []
624 return []
620 text = os.path.expanduser(text)
625 text = os.path.expanduser(text)
621 aliases = self.alias_table.keys()
626 aliases = self.alias_table.keys()
622 if text == '':
627 if text == '':
623 return aliases
628 return aliases
624 else:
629 else:
625 return [a for a in aliases if a.startswith(text)]
630 return [a for a in aliases if a.startswith(text)]
626
631
627 def python_matches(self,text):
632 def python_matches(self,text):
628 """Match attributes or global python names"""
633 """Match attributes or global python names"""
629
634
630 #io.rprint('Completer->python_matches, txt=%r' % text) # dbg
635 #io.rprint('Completer->python_matches, txt=%r' % text) # dbg
631 if "." in text:
636 if "." in text:
632 try:
637 try:
633 matches = self.attr_matches(text)
638 matches = self.attr_matches(text)
634 if text.endswith('.') and self.omit__names:
639 if text.endswith('.') and self.omit__names:
635 if self.omit__names == 1:
640 if self.omit__names == 1:
636 # true if txt is _not_ a __ name, false otherwise:
641 # true if txt is _not_ a __ name, false otherwise:
637 no__name = (lambda txt:
642 no__name = (lambda txt:
638 re.match(r'.*\.__.*?__',txt) is None)
643 re.match(r'.*\.__.*?__',txt) is None)
639 else:
644 else:
640 # true if txt is _not_ a _ name, false otherwise:
645 # true if txt is _not_ a _ name, false otherwise:
641 no__name = (lambda txt:
646 no__name = (lambda txt:
642 re.match(r'.*\._.*?',txt) is None)
647 re.match(r'.*\._.*?',txt) is None)
643 matches = filter(no__name, matches)
648 matches = filter(no__name, matches)
644 except NameError:
649 except NameError:
645 # catches <undefined attributes>.<tab>
650 # catches <undefined attributes>.<tab>
646 matches = []
651 matches = []
647 else:
652 else:
648 matches = self.global_matches(text)
653 matches = self.global_matches(text)
649
654
650 return matches
655 return matches
651
656
652 def _default_arguments(self, obj):
657 def _default_arguments(self, obj):
653 """Return the list of default arguments of obj if it is callable,
658 """Return the list of default arguments of obj if it is callable,
654 or empty list otherwise."""
659 or empty list otherwise."""
655
660
656 if not (inspect.isfunction(obj) or inspect.ismethod(obj)):
661 if not (inspect.isfunction(obj) or inspect.ismethod(obj)):
657 # for classes, check for __init__,__new__
662 # for classes, check for __init__,__new__
658 if inspect.isclass(obj):
663 if inspect.isclass(obj):
659 obj = (getattr(obj,'__init__',None) or
664 obj = (getattr(obj,'__init__',None) or
660 getattr(obj,'__new__',None))
665 getattr(obj,'__new__',None))
661 # for all others, check if they are __call__able
666 # for all others, check if they are __call__able
662 elif hasattr(obj, '__call__'):
667 elif hasattr(obj, '__call__'):
663 obj = obj.__call__
668 obj = obj.__call__
664 # XXX: is there a way to handle the builtins ?
669 # XXX: is there a way to handle the builtins ?
665 try:
670 try:
666 args,_,_1,defaults = inspect.getargspec(obj)
671 args,_,_1,defaults = inspect.getargspec(obj)
667 if defaults:
672 if defaults:
668 return args[-len(defaults):]
673 return args[-len(defaults):]
669 except TypeError: pass
674 except TypeError: pass
670 return []
675 return []
671
676
672 def python_func_kw_matches(self,text):
677 def python_func_kw_matches(self,text):
673 """Match named parameters (kwargs) of the last open function"""
678 """Match named parameters (kwargs) of the last open function"""
674
679
675 if "." in text: # a parameter cannot be dotted
680 if "." in text: # a parameter cannot be dotted
676 return []
681 return []
677 try: regexp = self.__funcParamsRegex
682 try: regexp = self.__funcParamsRegex
678 except AttributeError:
683 except AttributeError:
679 regexp = self.__funcParamsRegex = re.compile(r'''
684 regexp = self.__funcParamsRegex = re.compile(r'''
680 '.*?' | # single quoted strings or
685 '.*?' | # single quoted strings or
681 ".*?" | # double quoted strings or
686 ".*?" | # double quoted strings or
682 \w+ | # identifier
687 \w+ | # identifier
683 \S # other characters
688 \S # other characters
684 ''', re.VERBOSE | re.DOTALL)
689 ''', re.VERBOSE | re.DOTALL)
685 # 1. find the nearest identifier that comes before an unclosed
690 # 1. find the nearest identifier that comes before an unclosed
686 # parenthesis before the cursor
691 # parenthesis before the cursor
687 # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo"
692 # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo"
688 tokens = regexp.findall(self.text_until_cursor)
693 tokens = regexp.findall(self.text_until_cursor)
689 tokens.reverse()
694 tokens.reverse()
690 iterTokens = iter(tokens); openPar = 0
695 iterTokens = iter(tokens); openPar = 0
691 for token in iterTokens:
696 for token in iterTokens:
692 if token == ')':
697 if token == ')':
693 openPar -= 1
698 openPar -= 1
694 elif token == '(':
699 elif token == '(':
695 openPar += 1
700 openPar += 1
696 if openPar > 0:
701 if openPar > 0:
697 # found the last unclosed parenthesis
702 # found the last unclosed parenthesis
698 break
703 break
699 else:
704 else:
700 return []
705 return []
701 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
706 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
702 ids = []
707 ids = []
703 isId = re.compile(r'\w+$').match
708 isId = re.compile(r'\w+$').match
704 while True:
709 while True:
705 try:
710 try:
706 ids.append(iterTokens.next())
711 ids.append(iterTokens.next())
707 if not isId(ids[-1]):
712 if not isId(ids[-1]):
708 ids.pop(); break
713 ids.pop(); break
709 if not iterTokens.next() == '.':
714 if not iterTokens.next() == '.':
710 break
715 break
711 except StopIteration:
716 except StopIteration:
712 break
717 break
713 # lookup the candidate callable matches either using global_matches
718 # lookup the candidate callable matches either using global_matches
714 # or attr_matches for dotted names
719 # or attr_matches for dotted names
715 if len(ids) == 1:
720 if len(ids) == 1:
716 callableMatches = self.global_matches(ids[0])
721 callableMatches = self.global_matches(ids[0])
717 else:
722 else:
718 callableMatches = self.attr_matches('.'.join(ids[::-1]))
723 callableMatches = self.attr_matches('.'.join(ids[::-1]))
719 argMatches = []
724 argMatches = []
720 for callableMatch in callableMatches:
725 for callableMatch in callableMatches:
721 try:
726 try:
722 namedArgs = self._default_arguments(eval(callableMatch,
727 namedArgs = self._default_arguments(eval(callableMatch,
723 self.namespace))
728 self.namespace))
724 except:
729 except:
725 continue
730 continue
726 for namedArg in namedArgs:
731 for namedArg in namedArgs:
727 if namedArg.startswith(text):
732 if namedArg.startswith(text):
728 argMatches.append("%s=" %namedArg)
733 argMatches.append("%s=" %namedArg)
729 return argMatches
734 return argMatches
730
735
731 def dispatch_custom_completer(self, text):
736 def dispatch_custom_completer(self, text):
732 #io.rprint("Custom! '%s' %s" % (text, self.custom_completers)) # dbg
737 #io.rprint("Custom! '%s' %s" % (text, self.custom_completers)) # dbg
733 line = self.line_buffer
738 line = self.line_buffer
734 if not line.strip():
739 if not line.strip():
735 return None
740 return None
736
741
737 # Create a little structure to pass all the relevant information about
742 # Create a little structure to pass all the relevant information about
738 # the current completion to any custom completer.
743 # the current completion to any custom completer.
739 event = Bunch()
744 event = Bunch()
740 event.line = line
745 event.line = line
741 event.symbol = text
746 event.symbol = text
742 cmd = line.split(None,1)[0]
747 cmd = line.split(None,1)[0]
743 event.command = cmd
748 event.command = cmd
744 event.text_until_cursor = self.text_until_cursor
749 event.text_until_cursor = self.text_until_cursor
745
750
746 #print "\ncustom:{%s]\n" % event # dbg
751 #print "\ncustom:{%s]\n" % event # dbg
747
752
748 # for foo etc, try also to find completer for %foo
753 # for foo etc, try also to find completer for %foo
749 if not cmd.startswith(self.magic_escape):
754 if not cmd.startswith(self.magic_escape):
750 try_magic = self.custom_completers.s_matches(
755 try_magic = self.custom_completers.s_matches(
751 self.magic_escape + cmd)
756 self.magic_escape + cmd)
752 else:
757 else:
753 try_magic = []
758 try_magic = []
754
759
755 for c in itertools.chain(self.custom_completers.s_matches(cmd),
760 for c in itertools.chain(self.custom_completers.s_matches(cmd),
756 try_magic,
761 try_magic,
757 self.custom_completers.flat_matches(self.text_until_cursor)):
762 self.custom_completers.flat_matches(self.text_until_cursor)):
758 #print "try",c # dbg
763 #print "try",c # dbg
759 try:
764 try:
760 res = c(event)
765 res = c(event)
761 if res:
766 if res:
762 # first, try case sensitive match
767 # first, try case sensitive match
763 withcase = [r for r in res if r.startswith(text)]
768 withcase = [r for r in res if r.startswith(text)]
764 if withcase:
769 if withcase:
765 return withcase
770 return withcase
766 # if none, then case insensitive ones are ok too
771 # if none, then case insensitive ones are ok too
767 text_low = text.lower()
772 text_low = text.lower()
768 return [r for r in res if r.lower().startswith(text_low)]
773 return [r for r in res if r.lower().startswith(text_low)]
769 except TryNext:
774 except TryNext:
770 pass
775 pass
771
776
772 return None
777 return None
773
778
774 def complete(self, text=None, line_buffer=None, cursor_pos=None):
779 def complete(self, text=None, line_buffer=None, cursor_pos=None):
775 """Find completions for the given text and line context.
780 """Find completions for the given text and line context.
776
781
777 This is called successively with state == 0, 1, 2, ... until it
782 This is called successively with state == 0, 1, 2, ... until it
778 returns None. The completion should begin with 'text'.
783 returns None. The completion should begin with 'text'.
779
784
780 Note that both the text and the line_buffer are optional, but at least
785 Note that both the text and the line_buffer are optional, but at least
781 one of them must be given.
786 one of them must be given.
782
787
783 Parameters
788 Parameters
784 ----------
789 ----------
785 text : string, optional
790 text : string, optional
786 Text to perform the completion on. If not given, the line buffer
791 Text to perform the completion on. If not given, the line buffer
787 is split using the instance's CompletionSplitter object.
792 is split using the instance's CompletionSplitter object.
788
793
789 line_buffer : string, optional
794 line_buffer : string, optional
790 If not given, the completer attempts to obtain the current line
795 If not given, the completer attempts to obtain the current line
791 buffer via readline. This keyword allows clients which are
796 buffer via readline. This keyword allows clients which are
792 requesting for text completions in non-readline contexts to inform
797 requesting for text completions in non-readline contexts to inform
793 the completer of the entire text.
798 the completer of the entire text.
794
799
795 cursor_pos : int, optional
800 cursor_pos : int, optional
796 Index of the cursor in the full line buffer. Should be provided by
801 Index of the cursor in the full line buffer. Should be provided by
797 remote frontends where kernel has no access to frontend state.
802 remote frontends where kernel has no access to frontend state.
798
803
799 Returns
804 Returns
800 -------
805 -------
801 text : str
806 text : str
802 Text that was actually used in the completion.
807 Text that was actually used in the completion.
803
808
804 matches : list
809 matches : list
805 A list of completion matches.
810 A list of completion matches.
806 """
811 """
807 #io.rprint('\nCOMP1 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg
812 #io.rprint('\nCOMP1 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg
808
813
809 # if the cursor position isn't given, the only sane assumption we can
814 # if the cursor position isn't given, the only sane assumption we can
810 # make is that it's at the end of the line (the common case)
815 # make is that it's at the end of the line (the common case)
811 if cursor_pos is None:
816 if cursor_pos is None:
812 cursor_pos = len(line_buffer) if text is None else len(text)
817 cursor_pos = len(line_buffer) if text is None else len(text)
813
818
814 # if text is either None or an empty string, rely on the line buffer
819 # if text is either None or an empty string, rely on the line buffer
815 if not text:
820 if not text:
816 text = self.splitter.split_line(line_buffer, cursor_pos)
821 text = self.splitter.split_line(line_buffer, cursor_pos)
817
822
818 # If no line buffer is given, assume the input text is all there was
823 # If no line buffer is given, assume the input text is all there was
819 if line_buffer is None:
824 if line_buffer is None:
820 line_buffer = text
825 line_buffer = text
821
826
822 self.line_buffer = line_buffer
827 self.line_buffer = line_buffer
823 self.text_until_cursor = self.line_buffer[:cursor_pos]
828 self.text_until_cursor = self.line_buffer[:cursor_pos]
824 #io.rprint('\nCOMP2 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg
829 #io.rprint('COMP2 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg
825
830
826 # Start with a clean slate of completions
831 # Start with a clean slate of completions
827 self.matches[:] = []
832 self.matches[:] = []
828 custom_res = self.dispatch_custom_completer(text)
833 custom_res = self.dispatch_custom_completer(text)
829 if custom_res is not None:
834 if custom_res is not None:
830 # did custom completers produce something?
835 # did custom completers produce something?
831 self.matches = custom_res
836 self.matches = custom_res
832 else:
837 else:
833 # Extend the list of completions with the results of each
838 # Extend the list of completions with the results of each
834 # matcher, so we return results to the user from all
839 # matcher, so we return results to the user from all
835 # namespaces.
840 # namespaces.
836 if self.merge_completions:
841 if self.merge_completions:
837 self.matches = []
842 self.matches = []
838 for matcher in self.matchers:
843 for matcher in self.matchers:
839 try:
844 try:
840 self.matches.extend(matcher(text))
845 self.matches.extend(matcher(text))
841 except:
846 except:
842 # Show the ugly traceback if the matcher causes an
847 # Show the ugly traceback if the matcher causes an
843 # exception, but do NOT crash the kernel!
848 # exception, but do NOT crash the kernel!
844 sys.excepthook(*sys.exc_info())
849 sys.excepthook(*sys.exc_info())
845 else:
850 else:
846 for matcher in self.matchers:
851 for matcher in self.matchers:
847 self.matches = matcher(text)
852 self.matches = matcher(text)
848 if self.matches:
853 if self.matches:
849 break
854 break
850 # FIXME: we should extend our api to return a dict with completions for
855 # FIXME: we should extend our api to return a dict with completions for
851 # different types of objects. The rlcomplete() method could then
856 # different types of objects. The rlcomplete() method could then
852 # simply collapse the dict into a list for readline, but we'd have
857 # simply collapse the dict into a list for readline, but we'd have
853 # richer completion semantics in other evironments.
858 # richer completion semantics in other evironments.
854 self.matches = sorted(set(self.matches))
859 self.matches = sorted(set(self.matches))
855 #io.rprint('COMP TEXT, MATCHES: %r, %r' % (text, self.matches)) # dbg
860 #io.rprint('COMP TEXT, MATCHES: %r, %r' % (text, self.matches)) # dbg
856 return text, self.matches
861 return text, self.matches
857
862
858 def rlcomplete(self, text, state):
863 def rlcomplete(self, text, state):
859 """Return the state-th possible completion for 'text'.
864 """Return the state-th possible completion for 'text'.
860
865
861 This is called successively with state == 0, 1, 2, ... until it
866 This is called successively with state == 0, 1, 2, ... until it
862 returns None. The completion should begin with 'text'.
867 returns None. The completion should begin with 'text'.
863
868
864 Parameters
869 Parameters
865 ----------
870 ----------
866 text : string
871 text : string
867 Text to perform the completion on.
872 Text to perform the completion on.
868
873
869 state : int
874 state : int
870 Counter used by readline.
875 Counter used by readline.
871 """
876 """
872 if state==0:
877 if state==0:
873
878
874 self.line_buffer = line_buffer = self.readline.get_line_buffer()
879 self.line_buffer = line_buffer = self.readline.get_line_buffer()
875 cursor_pos = self.readline.get_endidx()
880 cursor_pos = self.readline.get_endidx()
876
881
877 #io.rprint("\nRLCOMPLETE: %r %r %r" %
882 #io.rprint("\nRLCOMPLETE: %r %r %r" %
878 # (text, line_buffer, cursor_pos) ) # dbg
883 # (text, line_buffer, cursor_pos) ) # dbg
879
884
880 # if there is only a tab on a line with only whitespace, instead of
885 # if there is only a tab on a line with only whitespace, instead of
881 # the mostly useless 'do you want to see all million completions'
886 # the mostly useless 'do you want to see all million completions'
882 # message, just do the right thing and give the user his tab!
887 # message, just do the right thing and give the user his tab!
883 # Incidentally, this enables pasting of tabbed text from an editor
888 # Incidentally, this enables pasting of tabbed text from an editor
884 # (as long as autoindent is off).
889 # (as long as autoindent is off).
885
890
886 # It should be noted that at least pyreadline still shows file
891 # It should be noted that at least pyreadline still shows file
887 # completions - is there a way around it?
892 # completions - is there a way around it?
888
893
889 # don't apply this on 'dumb' terminals, such as emacs buffers, so
894 # don't apply this on 'dumb' terminals, such as emacs buffers, so
890 # we don't interfere with their own tab-completion mechanism.
895 # we don't interfere with their own tab-completion mechanism.
891 if not (self.dumb_terminal or line_buffer.strip()):
896 if not (self.dumb_terminal or line_buffer.strip()):
892 self.readline.insert_text('\t')
897 self.readline.insert_text('\t')
893 sys.stdout.flush()
898 sys.stdout.flush()
894 return None
899 return None
895
900
896 # Note: debugging exceptions that may occur in completion is very
901 # Note: debugging exceptions that may occur in completion is very
897 # tricky, because readline unconditionally silences them. So if
902 # tricky, because readline unconditionally silences them. So if
898 # during development you suspect a bug in the completion code, turn
903 # during development you suspect a bug in the completion code, turn
899 # this flag on temporarily by uncommenting the second form (don't
904 # this flag on temporarily by uncommenting the second form (don't
900 # flip the value in the first line, as the '# dbg' marker can be
905 # flip the value in the first line, as the '# dbg' marker can be
901 # automatically detected and is used elsewhere).
906 # automatically detected and is used elsewhere).
902 DEBUG = False
907 DEBUG = False
903 #DEBUG = True # dbg
908 #DEBUG = True # dbg
904 if DEBUG:
909 if DEBUG:
905 try:
910 try:
906 self.complete(text, line_buffer, cursor_pos)
911 self.complete(text, line_buffer, cursor_pos)
907 except:
912 except:
908 import traceback; traceback.print_exc()
913 import traceback; traceback.print_exc()
909 else:
914 else:
910 # The normal production version is here
915 # The normal production version is here
911
916
912 # This method computes the self.matches array
917 # This method computes the self.matches array
913 self.complete(text, line_buffer, cursor_pos)
918 self.complete(text, line_buffer, cursor_pos)
914
919
915 try:
920 try:
916 return self.matches[state]
921 return self.matches[state]
917 except IndexError:
922 except IndexError:
918 return None
923 return None
@@ -1,286 +1,292 b''
1 """Tests for the IPython tab-completion machinery.
1 """Tests for the IPython tab-completion machinery.
2 """
2 """
3 #-----------------------------------------------------------------------------
3 #-----------------------------------------------------------------------------
4 # Module imports
4 # Module imports
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
6
6
7 # stdlib
7 # stdlib
8 import os
8 import os
9 import sys
9 import sys
10 import unittest
10 import unittest
11
11
12 # third party
12 # third party
13 import nose.tools as nt
13 import nose.tools as nt
14
14
15 # our own packages
15 # our own packages
16 from IPython.config.loader import Config
16 from IPython.config.loader import Config
17 from IPython.core import completer
17 from IPython.core import completer
18 from IPython.external.decorators import knownfailureif
18 from IPython.external.decorators import knownfailureif
19 from IPython.utils.tempdir import TemporaryDirectory
19 from IPython.utils.tempdir import TemporaryDirectory
20 from IPython.utils.generics import complete_object
20 from IPython.utils.generics import complete_object
21
21
22 #-----------------------------------------------------------------------------
22 #-----------------------------------------------------------------------------
23 # Test functions
23 # Test functions
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25 def test_protect_filename():
25 def test_protect_filename():
26 pairs = [ ('abc','abc'),
26 pairs = [ ('abc','abc'),
27 (' abc',r'\ abc'),
27 (' abc',r'\ abc'),
28 ('a bc',r'a\ bc'),
28 ('a bc',r'a\ bc'),
29 ('a bc',r'a\ \ bc'),
29 ('a bc',r'a\ \ bc'),
30 (' bc',r'\ \ bc'),
30 (' bc',r'\ \ bc'),
31 ]
31 ]
32 # On posix, we also protect parens and other special characters
32 # On posix, we also protect parens and other special characters
33 if sys.platform != 'win32':
33 if sys.platform != 'win32':
34 pairs.extend( [('a(bc',r'a\(bc'),
34 pairs.extend( [('a(bc',r'a\(bc'),
35 ('a)bc',r'a\)bc'),
35 ('a)bc',r'a\)bc'),
36 ('a( )bc',r'a\(\ \)bc'),
36 ('a( )bc',r'a\(\ \)bc'),
37 ('a[1]bc', r'a\[1\]bc'),
37 ('a[1]bc', r'a\[1\]bc'),
38 ('a{1}bc', r'a\{1\}bc'),
38 ('a{1}bc', r'a\{1\}bc'),
39 ('a#bc', r'a\#bc'),
39 ('a#bc', r'a\#bc'),
40 ('a?bc', r'a\?bc'),
40 ('a?bc', r'a\?bc'),
41 ('a=bc', r'a\=bc'),
41 ('a=bc', r'a\=bc'),
42 ('a\\bc', r'a\\bc'),
42 ('a\\bc', r'a\\bc'),
43 ('a|bc', r'a\|bc'),
43 ('a|bc', r'a\|bc'),
44 ('a;bc', r'a\;bc'),
44 ('a;bc', r'a\;bc'),
45 ('a:bc', r'a\:bc'),
45 ('a:bc', r'a\:bc'),
46 ("a'bc", r"a\'bc"),
46 ("a'bc", r"a\'bc"),
47 ('a*bc', r'a\*bc'),
47 ('a*bc', r'a\*bc'),
48 ('a"bc', r'a\"bc'),
48 ('a"bc', r'a\"bc'),
49 ('a^bc', r'a\^bc'),
49 ('a^bc', r'a\^bc'),
50 ('a&bc', r'a\&bc'),
50 ('a&bc', r'a\&bc'),
51 ] )
51 ] )
52 # run the actual tests
52 # run the actual tests
53 for s1, s2 in pairs:
53 for s1, s2 in pairs:
54 s1p = completer.protect_filename(s1)
54 s1p = completer.protect_filename(s1)
55 nt.assert_equals(s1p, s2)
55 nt.assert_equals(s1p, s2)
56
56
57
57
58 def check_line_split(splitter, test_specs):
58 def check_line_split(splitter, test_specs):
59 for part1, part2, split in test_specs:
59 for part1, part2, split in test_specs:
60 cursor_pos = len(part1)
60 cursor_pos = len(part1)
61 line = part1+part2
61 line = part1+part2
62 out = splitter.split_line(line, cursor_pos)
62 out = splitter.split_line(line, cursor_pos)
63 nt.assert_equal(out, split)
63 nt.assert_equal(out, split)
64
64
65
65
66 def test_line_split():
66 def test_line_split():
67 """Basice line splitter test with default specs."""
67 """Basice line splitter test with default specs."""
68 sp = completer.CompletionSplitter()
68 sp = completer.CompletionSplitter()
69 # The format of the test specs is: part1, part2, expected answer. Parts 1
69 # The format of the test specs is: part1, part2, expected answer. Parts 1
70 # and 2 are joined into the 'line' sent to the splitter, as if the cursor
70 # and 2 are joined into the 'line' sent to the splitter, as if the cursor
71 # was at the end of part1. So an empty part2 represents someone hitting
71 # was at the end of part1. So an empty part2 represents someone hitting
72 # tab at the end of the line, the most common case.
72 # tab at the end of the line, the most common case.
73 t = [('run some/scrip', '', 'some/scrip'),
73 t = [('run some/scrip', '', 'some/scrip'),
74 ('run scripts/er', 'ror.py foo', 'scripts/er'),
74 ('run scripts/er', 'ror.py foo', 'scripts/er'),
75 ('echo $HOM', '', 'HOM'),
75 ('echo $HOM', '', 'HOM'),
76 ('print sys.pa', '', 'sys.pa'),
76 ('print sys.pa', '', 'sys.pa'),
77 ('print(sys.pa', '', 'sys.pa'),
77 ('print(sys.pa', '', 'sys.pa'),
78 ("execfile('scripts/er", '', 'scripts/er'),
78 ("execfile('scripts/er", '', 'scripts/er'),
79 ('a[x.', '', 'x.'),
79 ('a[x.', '', 'x.'),
80 ('a[x.', 'y', 'x.'),
80 ('a[x.', 'y', 'x.'),
81 ('cd "some_file/', '', 'some_file/'),
81 ('cd "some_file/', '', 'some_file/'),
82 ]
82 ]
83 check_line_split(sp, t)
83 check_line_split(sp, t)
84 # Ensure splitting works OK with unicode by re-running the tests with
84 # Ensure splitting works OK with unicode by re-running the tests with
85 # all inputs turned into unicode
85 # all inputs turned into unicode
86 check_line_split(sp, [ map(unicode, p) for p in t] )
86 check_line_split(sp, [ map(unicode, p) for p in t] )
87
87
88
88
89 def test_custom_completion_error():
89 def test_custom_completion_error():
90 """Test that errors from custom attribute completers are silenced."""
90 """Test that errors from custom attribute completers are silenced."""
91 ip = get_ipython()
91 ip = get_ipython()
92 class A(object): pass
92 class A(object): pass
93 ip.user_ns['a'] = A()
93 ip.user_ns['a'] = A()
94
94
95 @complete_object.when_type(A)
95 @complete_object.when_type(A)
96 def complete_A(a, existing_completions):
96 def complete_A(a, existing_completions):
97 raise TypeError("this should be silenced")
97 raise TypeError("this should be silenced")
98
98
99 ip.complete("a.")
99 ip.complete("a.")
100
100
101
101
102 def test_unicode_completions():
102 def test_unicode_completions():
103 ip = get_ipython()
103 ip = get_ipython()
104 # Some strings that trigger different types of completion. Check them both
104 # Some strings that trigger different types of completion. Check them both
105 # in str and unicode forms
105 # in str and unicode forms
106 s = ['ru', '%ru', 'cd /', 'floa', 'float(x)/']
106 s = ['ru', '%ru', 'cd /', 'floa', 'float(x)/']
107 for t in s + map(unicode, s):
107 for t in s + map(unicode, s):
108 # We don't need to check exact completion values (they may change
108 # We don't need to check exact completion values (they may change
109 # depending on the state of the namespace, but at least no exceptions
109 # depending on the state of the namespace, but at least no exceptions
110 # should be thrown and the return value should be a pair of text, list
110 # should be thrown and the return value should be a pair of text, list
111 # values.
111 # values.
112 text, matches = ip.complete(t)
112 text, matches = ip.complete(t)
113 nt.assert_true(isinstance(text, basestring))
113 nt.assert_true(isinstance(text, basestring))
114 nt.assert_true(isinstance(matches, list))
114 nt.assert_true(isinstance(matches, list))
115
115
116
116
117 class CompletionSplitterTestCase(unittest.TestCase):
117 class CompletionSplitterTestCase(unittest.TestCase):
118 def setUp(self):
118 def setUp(self):
119 self.sp = completer.CompletionSplitter()
119 self.sp = completer.CompletionSplitter()
120
120
121 def test_delim_setting(self):
121 def test_delim_setting(self):
122 self.sp.set_delims(' ')
122 self.sp.delims = ' '
123 nt.assert_equal(self.sp.get_delims(), ' ')
123 nt.assert_equal(self.sp.delims, ' ')
124 nt.assert_equal(self.sp._delim_expr, '[\ ]')
124 nt.assert_equal(self.sp._delim_expr, '[\ ]')
125
125
126 def test_spaces(self):
126 def test_spaces(self):
127 """Test with only spaces as split chars."""
127 """Test with only spaces as split chars."""
128 self.sp.delims = ' '
128 self.sp.delims = ' '
129 t = [('foo', '', 'foo'),
129 t = [('foo', '', 'foo'),
130 ('run foo', '', 'foo'),
130 ('run foo', '', 'foo'),
131 ('run foo', 'bar', 'foo'),
131 ('run foo', 'bar', 'foo'),
132 ]
132 ]
133 check_line_split(self.sp, t)
133 check_line_split(self.sp, t)
134
134
135
135
136 def test_has_open_quotes1():
136 def test_has_open_quotes1():
137 for s in ["'", "'''", "'hi' '"]:
137 for s in ["'", "'''", "'hi' '"]:
138 nt.assert_equal(completer.has_open_quotes(s), "'")
138 nt.assert_equal(completer.has_open_quotes(s), "'")
139
139
140
140
141 def test_has_open_quotes2():
141 def test_has_open_quotes2():
142 for s in ['"', '"""', '"hi" "']:
142 for s in ['"', '"""', '"hi" "']:
143 nt.assert_equal(completer.has_open_quotes(s), '"')
143 nt.assert_equal(completer.has_open_quotes(s), '"')
144
144
145
145
146 def test_has_open_quotes3():
146 def test_has_open_quotes3():
147 for s in ["''", "''' '''", "'hi' 'ipython'"]:
147 for s in ["''", "''' '''", "'hi' 'ipython'"]:
148 nt.assert_false(completer.has_open_quotes(s))
148 nt.assert_false(completer.has_open_quotes(s))
149
149
150
150
151 def test_has_open_quotes4():
151 def test_has_open_quotes4():
152 for s in ['""', '""" """', '"hi" "ipython"']:
152 for s in ['""', '""" """', '"hi" "ipython"']:
153 nt.assert_false(completer.has_open_quotes(s))
153 nt.assert_false(completer.has_open_quotes(s))
154
154
155
155
156 @knownfailureif(sys.platform == 'win32', "abspath completions fail on Windows")
156 @knownfailureif(sys.platform == 'win32', "abspath completions fail on Windows")
157 def test_abspath_file_completions():
157 def test_abspath_file_completions():
158 ip = get_ipython()
158 ip = get_ipython()
159 with TemporaryDirectory() as tmpdir:
159 with TemporaryDirectory() as tmpdir:
160 prefix = os.path.join(tmpdir, 'foo')
160 prefix = os.path.join(tmpdir, 'foo')
161 suffixes = map(str, [1,2])
161 suffixes = map(str, [1,2])
162 names = [prefix+s for s in suffixes]
162 names = [prefix+s for s in suffixes]
163 for n in names:
163 for n in names:
164 open(n, 'w').close()
164 open(n, 'w').close()
165
165
166 # Check simple completion
166 # Check simple completion
167 c = ip.complete(prefix)[1]
167 c = ip.complete(prefix)[1]
168 nt.assert_equal(c, names)
168 nt.assert_equal(c, names)
169
169
170 # Now check with a function call
170 # Now check with a function call
171 cmd = 'a = f("%s' % prefix
171 cmd = 'a = f("%s' % prefix
172 c = ip.complete(prefix, cmd)[1]
172 c = ip.complete(prefix, cmd)[1]
173 comp = [prefix+s for s in suffixes]
173 comp = [prefix+s for s in suffixes]
174 nt.assert_equal(c, comp)
174 nt.assert_equal(c, comp)
175
175
176
176
177 def test_local_file_completions():
177 def test_local_file_completions():
178 ip = get_ipython()
178 ip = get_ipython()
179 cwd = os.getcwdu()
179 cwd = os.getcwdu()
180 try:
180 try:
181 with TemporaryDirectory() as tmpdir:
181 with TemporaryDirectory() as tmpdir:
182 os.chdir(tmpdir)
182 os.chdir(tmpdir)
183 prefix = './foo'
183 prefix = './foo'
184 suffixes = map(str, [1,2])
184 suffixes = map(str, [1,2])
185 names = [prefix+s for s in suffixes]
185 names = [prefix+s for s in suffixes]
186 for n in names:
186 for n in names:
187 open(n, 'w').close()
187 open(n, 'w').close()
188
188
189 # Check simple completion
189 # Check simple completion
190 c = ip.complete(prefix)[1]
190 c = ip.complete(prefix)[1]
191 nt.assert_equal(c, names)
191 nt.assert_equal(c, names)
192
192
193 # Now check with a function call
193 # Now check with a function call
194 cmd = 'a = f("%s' % prefix
194 cmd = 'a = f("%s' % prefix
195 c = ip.complete(prefix, cmd)[1]
195 c = ip.complete(prefix, cmd)[1]
196 comp = [prefix+s for s in suffixes]
196 comp = [prefix+s for s in suffixes]
197 nt.assert_equal(c, comp)
197 nt.assert_equal(c, comp)
198 finally:
198 finally:
199 # prevent failures from making chdir stick
199 # prevent failures from making chdir stick
200 os.chdir(cwd)
200 os.chdir(cwd)
201
201
202
202
203 def test_greedy_completions():
203 def test_greedy_completions():
204 ip = get_ipython()
204 ip = get_ipython()
205 ip.Completer.greedy = False
205 greedy_original = ip.Completer.greedy
206 ip.ex('a=range(5)')
206 try:
207 _,c = ip.complete('.',line='a[0].')
207 ip.Completer.greedy = False
208 nt.assert_false('a[0].real' in c, "Shouldn't have completed on a[0]: %s"%c)
208 ip.ex('a=range(5)')
209 ip.Completer.greedy = True
209 _,c = ip.complete('.',line='a[0].')
210 _,c = ip.complete('.',line='a[0].')
210 nt.assert_false('a[0].real' in c,
211 nt.assert_true('a[0].real' in c, "Should have completed on a[0]: %s"%c)
211 "Shouldn't have completed on a[0]: %s"%c)
212 ip.Completer.greedy = True
213 _,c = ip.complete('.',line='a[0].')
214 nt.assert_true('a[0].real' in c, "Should have completed on a[0]: %s"%c)
215 finally:
216 ip.Completer.greedy = greedy_original
212
217
213
218
214 def test_omit__names():
219 def test_omit__names():
215 # also happens to test IPCompleter as a configurable
220 # also happens to test IPCompleter as a configurable
216 ip = get_ipython()
221 ip = get_ipython()
217 ip._hidden_attr = 1
222 ip._hidden_attr = 1
218 c = ip.Completer
223 c = ip.Completer
219 ip.ex('ip=get_ipython()')
224 ip.ex('ip=get_ipython()')
220 cfg = Config()
225 cfg = Config()
221 cfg.IPCompleter.omit__names = 0
226 cfg.IPCompleter.omit__names = 0
222 c.update_config(cfg)
227 c.update_config(cfg)
223 s,matches = c.complete('ip.')
228 s,matches = c.complete('ip.')
224 nt.assert_true('ip.__str__' in matches)
229 nt.assert_true('ip.__str__' in matches)
225 nt.assert_true('ip._hidden_attr' in matches)
230 nt.assert_true('ip._hidden_attr' in matches)
226 cfg.IPCompleter.omit__names = 1
231 cfg.IPCompleter.omit__names = 1
227 c.update_config(cfg)
232 c.update_config(cfg)
228 s,matches = c.complete('ip.')
233 s,matches = c.complete('ip.')
229 nt.assert_false('ip.__str__' in matches)
234 nt.assert_false('ip.__str__' in matches)
230 nt.assert_true('ip._hidden_attr' in matches)
235 nt.assert_true('ip._hidden_attr' in matches)
231 cfg.IPCompleter.omit__names = 2
236 cfg.IPCompleter.omit__names = 2
232 c.update_config(cfg)
237 c.update_config(cfg)
233 s,matches = c.complete('ip.')
238 s,matches = c.complete('ip.')
234 nt.assert_false('ip.__str__' in matches)
239 nt.assert_false('ip.__str__' in matches)
235 nt.assert_false('ip._hidden_attr' in matches)
240 nt.assert_false('ip._hidden_attr' in matches)
236 del ip._hidden_attr
241 del ip._hidden_attr
237
242
238
243
239 def test_limit_to__all__False_ok():
244 def test_limit_to__all__False_ok():
240 ip = get_ipython()
245 ip = get_ipython()
241 c = ip.Completer
246 c = ip.Completer
242 ip.ex('class D: x=24')
247 ip.ex('class D: x=24')
243 ip.ex('d=D()')
248 ip.ex('d=D()')
244 cfg = Config()
249 cfg = Config()
245 cfg.IPCompleter.limit_to__all__ = False
250 cfg.IPCompleter.limit_to__all__ = False
246 c.update_config(cfg)
251 c.update_config(cfg)
247 s, matches = c.complete('d.')
252 s, matches = c.complete('d.')
248 nt.assert_true('d.x' in matches)
253 nt.assert_true('d.x' in matches)
249
254
250
255
251 def test_limit_to__all__True_ok():
256 def test_limit_to__all__True_ok():
252 ip = get_ipython()
257 ip = get_ipython()
253 c = ip.Completer
258 c = ip.Completer
254 ip.ex('class D: x=24')
259 ip.ex('class D: x=24')
255 ip.ex('d=D()')
260 ip.ex('d=D()')
256 ip.ex("d.__all__=['z']")
261 ip.ex("d.__all__=['z']")
257 cfg = Config()
262 cfg = Config()
258 cfg.IPCompleter.limit_to__all__ = True
263 cfg.IPCompleter.limit_to__all__ = True
259 c.update_config(cfg)
264 c.update_config(cfg)
260 s, matches = c.complete('d.')
265 s, matches = c.complete('d.')
261 nt.assert_true('d.z' in matches)
266 nt.assert_true('d.z' in matches)
262 nt.assert_false('d.x' in matches)
267 nt.assert_false('d.x' in matches)
263
268
264
269
265 def test_get__all__entries_ok():
270 def test_get__all__entries_ok():
266 class A(object):
271 class A(object):
267 __all__ = ['x', 1]
272 __all__ = ['x', 1]
268 words = completer.get__all__entries(A())
273 words = completer.get__all__entries(A())
269 nt.assert_equal(words, ['x'])
274 nt.assert_equal(words, ['x'])
270
275
271
276
272 def test_get__all__entries_no__all__ok():
277 def test_get__all__entries_no__all__ok():
273 class A(object):
278 class A(object):
274 pass
279 pass
275 words = completer.get__all__entries(A())
280 words = completer.get__all__entries(A())
276 nt.assert_equal(words, [])
281 nt.assert_equal(words, [])
277
282
278
283
279 def test_func_kw_completions():
284 def test_func_kw_completions():
280 ip = get_ipython()
285 ip = get_ipython()
281 c = ip.Completer
286 c = ip.Completer
282 ip.ex('def myfunc(a=1,b=2): return a+b')
287 ip.ex('def myfunc(a=1,b=2): return a+b')
283 s, matches = c.complete(None,'myfunc(1,b')
288 s, matches = c.complete(None, 'myfunc(1,b')
284 nt.assert_true('b=' in matches)
289 nt.assert_in('b=', matches)
285 s, matches = c.complete(None,'myfunc(1,b)',10)#cursor is right after b
290 # Simulate completing with cursor right after b (pos==10):
286 nt.assert_true('b=' in matches)
291 s, matches = c.complete(None,'myfunc(1,b)', 10)
292 nt.assert_in('b=', matches)
General Comments 0
You need to be logged in to leave comments. Login now