##// END OF EJS Templates
Add docstring for latex_matches method
Thomas Kluyver -
Show More
@@ -1,1179 +1,1185 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """Word completion for IPython.
2 """Word completion for IPython.
3
3
4 This module is a fork of the rlcompleter module in the Python standard
4 This module is a fork of the rlcompleter module in the Python standard
5 library. The original enhancements made to rlcompleter have been sent
5 library. The original enhancements made to rlcompleter have been sent
6 upstream and were accepted as of Python 2.3, but we need a lot more
6 upstream and were accepted as of Python 2.3, but we need a lot more
7 functionality specific to IPython, so this module will continue to live as an
7 functionality specific to IPython, so this module will continue to live as an
8 IPython-specific utility.
8 IPython-specific utility.
9
9
10 Original rlcompleter documentation:
10 Original rlcompleter documentation:
11
11
12 This requires the latest extension to the readline module (the
12 This requires the latest extension to the readline module (the
13 completes keywords, built-ins and globals in __main__; when completing
13 completes keywords, built-ins and globals in __main__; when completing
14 NAME.NAME..., it evaluates (!) the expression up to the last dot and
14 NAME.NAME..., it evaluates (!) the expression up to the last dot and
15 completes its attributes.
15 completes its attributes.
16
16
17 It's very cool to do "import string" type "string.", hit the
17 It's very cool to do "import string" type "string.", hit the
18 completion key (twice), and see the list of names defined by the
18 completion key (twice), and see the list of names defined by the
19 string module!
19 string module!
20
20
21 Tip: to use the tab key as the completion key, call
21 Tip: to use the tab key as the completion key, call
22
22
23 readline.parse_and_bind("tab: complete")
23 readline.parse_and_bind("tab: complete")
24
24
25 Notes:
25 Notes:
26
26
27 - Exceptions raised by the completer function are *ignored* (and
27 - Exceptions raised by the completer function are *ignored* (and
28 generally cause the completion to fail). This is a feature -- since
28 generally cause the completion to fail). This is a feature -- since
29 readline sets the tty device in raw (or cbreak) mode, printing a
29 readline sets the tty device in raw (or cbreak) mode, printing a
30 traceback wouldn't work well without some complicated hoopla to save,
30 traceback wouldn't work well without some complicated hoopla to save,
31 reset and restore the tty state.
31 reset and restore the tty state.
32
32
33 - The evaluation of the NAME.NAME... form may cause arbitrary
33 - The evaluation of the NAME.NAME... form may cause arbitrary
34 application defined code to be executed if an object with a
34 application defined code to be executed if an object with a
35 ``__getattr__`` hook is found. Since it is the responsibility of the
35 ``__getattr__`` hook is found. Since it is the responsibility of the
36 application (or the user) to enable this feature, I consider this an
36 application (or the user) to enable this feature, I consider this an
37 acceptable risk. More complicated expressions (e.g. function calls or
37 acceptable risk. More complicated expressions (e.g. function calls or
38 indexing operations) are *not* evaluated.
38 indexing operations) are *not* evaluated.
39
39
40 - GNU readline is also used by the built-in functions input() and
40 - GNU readline is also used by the built-in functions input() and
41 raw_input(), and thus these also benefit/suffer from the completer
41 raw_input(), and thus these also benefit/suffer from the completer
42 features. Clearly an interactive application can benefit by
42 features. Clearly an interactive application can benefit by
43 specifying its own completer function and using raw_input() for all
43 specifying its own completer function and using raw_input() for all
44 its input.
44 its input.
45
45
46 - When the original stdin is not a tty device, GNU readline is never
46 - When the original stdin is not a tty device, GNU readline is never
47 used, and this module (and the readline module) are silently inactive.
47 used, and this module (and the readline module) are silently inactive.
48 """
48 """
49
49
50 #*****************************************************************************
50 #*****************************************************************************
51 #
51 #
52 # Since this file is essentially a minimally modified copy of the rlcompleter
52 # Since this file is essentially a minimally modified copy of the rlcompleter
53 # module which is part of the standard Python distribution, I assume that the
53 # module which is part of the standard Python distribution, I assume that the
54 # proper procedure is to maintain its copyright as belonging to the Python
54 # proper procedure is to maintain its copyright as belonging to the Python
55 # Software Foundation (in addition to my own, for all new code).
55 # Software Foundation (in addition to my own, for all new code).
56 #
56 #
57 # Copyright (C) 2008 IPython Development Team
57 # Copyright (C) 2008 IPython Development Team
58 # Copyright (C) 2001 Fernando Perez. <fperez@colorado.edu>
58 # Copyright (C) 2001 Fernando Perez. <fperez@colorado.edu>
59 # Copyright (C) 2001 Python Software Foundation, www.python.org
59 # Copyright (C) 2001 Python Software Foundation, www.python.org
60 #
60 #
61 # Distributed under the terms of the BSD License. The full license is in
61 # Distributed under the terms of the BSD License. The full license is in
62 # the file COPYING, distributed as part of this software.
62 # the file COPYING, distributed as part of this software.
63 #
63 #
64 #*****************************************************************************
64 #*****************************************************************************
65
65
66 #-----------------------------------------------------------------------------
66 #-----------------------------------------------------------------------------
67 # Imports
67 # Imports
68 #-----------------------------------------------------------------------------
68 #-----------------------------------------------------------------------------
69
69
70 import __main__
70 import __main__
71 import glob
71 import glob
72 import inspect
72 import inspect
73 import itertools
73 import itertools
74 import keyword
74 import keyword
75 import os
75 import os
76 import re
76 import re
77 import sys
77 import sys
78
78
79 from IPython.config.configurable import Configurable
79 from IPython.config.configurable import Configurable
80 from IPython.core.error import TryNext
80 from IPython.core.error import TryNext
81 from IPython.core.inputsplitter import ESC_MAGIC
81 from IPython.core.inputsplitter import ESC_MAGIC
82 from IPython.core.latex_symbols import latex_symbols
82 from IPython.core.latex_symbols import latex_symbols
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.decorators import undoc
85 from IPython.utils.decorators import undoc
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.py3compat import builtin_mod, string_types, PY3
88 from IPython.utils.py3compat import builtin_mod, string_types, PY3
89 from IPython.utils.traitlets import CBool, Enum
89 from IPython.utils.traitlets import CBool, Enum
90
90
91 #-----------------------------------------------------------------------------
91 #-----------------------------------------------------------------------------
92 # Globals
92 # Globals
93 #-----------------------------------------------------------------------------
93 #-----------------------------------------------------------------------------
94
94
95 # Public API
95 # Public API
96 __all__ = ['Completer','IPCompleter']
96 __all__ = ['Completer','IPCompleter']
97
97
98 if sys.platform == 'win32':
98 if sys.platform == 'win32':
99 PROTECTABLES = ' '
99 PROTECTABLES = ' '
100 else:
100 else:
101 PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&'
101 PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&'
102
102
103
103
104 #-----------------------------------------------------------------------------
104 #-----------------------------------------------------------------------------
105 # Main functions and classes
105 # Main functions and classes
106 #-----------------------------------------------------------------------------
106 #-----------------------------------------------------------------------------
107
107
108 def has_open_quotes(s):
108 def has_open_quotes(s):
109 """Return whether a string has open quotes.
109 """Return whether a string has open quotes.
110
110
111 This simply counts whether the number of quote characters of either type in
111 This simply counts whether the number of quote characters of either type in
112 the string is odd.
112 the string is odd.
113
113
114 Returns
114 Returns
115 -------
115 -------
116 If there is an open quote, the quote character is returned. Else, return
116 If there is an open quote, the quote character is returned. Else, return
117 False.
117 False.
118 """
118 """
119 # We check " first, then ', so complex cases with nested quotes will get
119 # We check " first, then ', so complex cases with nested quotes will get
120 # the " to take precedence.
120 # the " to take precedence.
121 if s.count('"') % 2:
121 if s.count('"') % 2:
122 return '"'
122 return '"'
123 elif s.count("'") % 2:
123 elif s.count("'") % 2:
124 return "'"
124 return "'"
125 else:
125 else:
126 return False
126 return False
127
127
128
128
129 def protect_filename(s):
129 def protect_filename(s):
130 """Escape a string to protect certain characters."""
130 """Escape a string to protect certain characters."""
131
131
132 return "".join([(ch in PROTECTABLES and '\\' + ch or ch)
132 return "".join([(ch in PROTECTABLES and '\\' + ch or ch)
133 for ch in s])
133 for ch in s])
134
134
135 def expand_user(path):
135 def expand_user(path):
136 """Expand '~'-style usernames in strings.
136 """Expand '~'-style usernames in strings.
137
137
138 This is similar to :func:`os.path.expanduser`, but it computes and returns
138 This is similar to :func:`os.path.expanduser`, but it computes and returns
139 extra information that will be useful if the input was being used in
139 extra information that will be useful if the input was being used in
140 computing completions, and you wish to return the completions with the
140 computing completions, and you wish to return the completions with the
141 original '~' instead of its expanded value.
141 original '~' instead of its expanded value.
142
142
143 Parameters
143 Parameters
144 ----------
144 ----------
145 path : str
145 path : str
146 String to be expanded. If no ~ is present, the output is the same as the
146 String to be expanded. If no ~ is present, the output is the same as the
147 input.
147 input.
148
148
149 Returns
149 Returns
150 -------
150 -------
151 newpath : str
151 newpath : str
152 Result of ~ expansion in the input path.
152 Result of ~ expansion in the input path.
153 tilde_expand : bool
153 tilde_expand : bool
154 Whether any expansion was performed or not.
154 Whether any expansion was performed or not.
155 tilde_val : str
155 tilde_val : str
156 The value that ~ was replaced with.
156 The value that ~ was replaced with.
157 """
157 """
158 # Default values
158 # Default values
159 tilde_expand = False
159 tilde_expand = False
160 tilde_val = ''
160 tilde_val = ''
161 newpath = path
161 newpath = path
162
162
163 if path.startswith('~'):
163 if path.startswith('~'):
164 tilde_expand = True
164 tilde_expand = True
165 rest = len(path)-1
165 rest = len(path)-1
166 newpath = os.path.expanduser(path)
166 newpath = os.path.expanduser(path)
167 if rest:
167 if rest:
168 tilde_val = newpath[:-rest]
168 tilde_val = newpath[:-rest]
169 else:
169 else:
170 tilde_val = newpath
170 tilde_val = newpath
171
171
172 return newpath, tilde_expand, tilde_val
172 return newpath, tilde_expand, tilde_val
173
173
174
174
175 def compress_user(path, tilde_expand, tilde_val):
175 def compress_user(path, tilde_expand, tilde_val):
176 """Does the opposite of expand_user, with its outputs.
176 """Does the opposite of expand_user, with its outputs.
177 """
177 """
178 if tilde_expand:
178 if tilde_expand:
179 return path.replace(tilde_val, '~')
179 return path.replace(tilde_val, '~')
180 else:
180 else:
181 return path
181 return path
182
182
183
183
184
184
185 def penalize_magics_key(word):
185 def penalize_magics_key(word):
186 """key for sorting that penalizes magic commands in the ordering
186 """key for sorting that penalizes magic commands in the ordering
187
187
188 Normal words are left alone.
188 Normal words are left alone.
189
189
190 Magic commands have the initial % moved to the end, e.g.
190 Magic commands have the initial % moved to the end, e.g.
191 %matplotlib is transformed as follows:
191 %matplotlib is transformed as follows:
192
192
193 %matplotlib -> matplotlib%
193 %matplotlib -> matplotlib%
194
194
195 [The choice of the final % is arbitrary.]
195 [The choice of the final % is arbitrary.]
196
196
197 Since "matplotlib" < "matplotlib%" as strings,
197 Since "matplotlib" < "matplotlib%" as strings,
198 "timeit" will appear before the magic "%timeit" in the ordering
198 "timeit" will appear before the magic "%timeit" in the ordering
199
199
200 For consistency, move "%%" to the end, so cell magics appear *after*
200 For consistency, move "%%" to the end, so cell magics appear *after*
201 line magics with the same name.
201 line magics with the same name.
202
202
203 A check is performed that there are no other "%" in the string;
203 A check is performed that there are no other "%" in the string;
204 if there are, then the string is not a magic command and is left unchanged.
204 if there are, then the string is not a magic command and is left unchanged.
205
205
206 """
206 """
207
207
208 # Move any % signs from start to end of the key
208 # Move any % signs from start to end of the key
209 # provided there are no others elsewhere in the string
209 # provided there are no others elsewhere in the string
210
210
211 if word[:2] == "%%":
211 if word[:2] == "%%":
212 if not "%" in word[2:]:
212 if not "%" in word[2:]:
213 return word[2:] + "%%"
213 return word[2:] + "%%"
214
214
215 if word[:1] == "%":
215 if word[:1] == "%":
216 if not "%" in word[1:]:
216 if not "%" in word[1:]:
217 return word[1:] + "%"
217 return word[1:] + "%"
218
218
219 return word
219 return word
220
220
221
221
222 @undoc
222 @undoc
223 class Bunch(object): pass
223 class Bunch(object): pass
224
224
225
225
226 DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
226 DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
227 GREEDY_DELIMS = ' =\r\n'
227 GREEDY_DELIMS = ' =\r\n'
228
228
229
229
230 class CompletionSplitter(object):
230 class CompletionSplitter(object):
231 """An object to split an input line in a manner similar to readline.
231 """An object to split an input line in a manner similar to readline.
232
232
233 By having our own implementation, we can expose readline-like completion in
233 By having our own implementation, we can expose readline-like completion in
234 a uniform manner to all frontends. This object only needs to be given the
234 a uniform manner to all frontends. This object only needs to be given the
235 line of text to be split and the cursor position on said line, and it
235 line of text to be split and the cursor position on said line, and it
236 returns the 'word' to be completed on at the cursor after splitting the
236 returns the 'word' to be completed on at the cursor after splitting the
237 entire line.
237 entire line.
238
238
239 What characters are used as splitting delimiters can be controlled by
239 What characters are used as splitting delimiters can be controlled by
240 setting the `delims` attribute (this is a property that internally
240 setting the `delims` attribute (this is a property that internally
241 automatically builds the necessary regular expression)"""
241 automatically builds the necessary regular expression)"""
242
242
243 # Private interface
243 # Private interface
244
244
245 # A string of delimiter characters. The default value makes sense for
245 # A string of delimiter characters. The default value makes sense for
246 # IPython's most typical usage patterns.
246 # IPython's most typical usage patterns.
247 _delims = DELIMS
247 _delims = DELIMS
248
248
249 # The expression (a normal string) to be compiled into a regular expression
249 # The expression (a normal string) to be compiled into a regular expression
250 # for actual splitting. We store it as an attribute mostly for ease of
250 # for actual splitting. We store it as an attribute mostly for ease of
251 # debugging, since this type of code can be so tricky to debug.
251 # debugging, since this type of code can be so tricky to debug.
252 _delim_expr = None
252 _delim_expr = None
253
253
254 # The regular expression that does the actual splitting
254 # The regular expression that does the actual splitting
255 _delim_re = None
255 _delim_re = None
256
256
257 def __init__(self, delims=None):
257 def __init__(self, delims=None):
258 delims = CompletionSplitter._delims if delims is None else delims
258 delims = CompletionSplitter._delims if delims is None else delims
259 self.delims = delims
259 self.delims = delims
260
260
261 @property
261 @property
262 def delims(self):
262 def delims(self):
263 """Return the string of delimiter characters."""
263 """Return the string of delimiter characters."""
264 return self._delims
264 return self._delims
265
265
266 @delims.setter
266 @delims.setter
267 def delims(self, delims):
267 def delims(self, delims):
268 """Set the delimiters for line splitting."""
268 """Set the delimiters for line splitting."""
269 expr = '[' + ''.join('\\'+ c for c in delims) + ']'
269 expr = '[' + ''.join('\\'+ c for c in delims) + ']'
270 self._delim_re = re.compile(expr)
270 self._delim_re = re.compile(expr)
271 self._delims = delims
271 self._delims = delims
272 self._delim_expr = expr
272 self._delim_expr = expr
273
273
274 def split_line(self, line, cursor_pos=None):
274 def split_line(self, line, cursor_pos=None):
275 """Split a line of text with a cursor at the given position.
275 """Split a line of text with a cursor at the given position.
276 """
276 """
277 l = line if cursor_pos is None else line[:cursor_pos]
277 l = line if cursor_pos is None else line[:cursor_pos]
278 return self._delim_re.split(l)[-1]
278 return self._delim_re.split(l)[-1]
279
279
280
280
281 class Completer(Configurable):
281 class Completer(Configurable):
282
282
283 greedy = CBool(False, config=True,
283 greedy = CBool(False, config=True,
284 help="""Activate greedy completion
284 help="""Activate greedy completion
285
285
286 This will enable completion on elements of lists, results of function calls, etc.,
286 This will enable completion on elements of lists, results of function calls, etc.,
287 but can be unsafe because the code is actually evaluated on TAB.
287 but can be unsafe because the code is actually evaluated on TAB.
288 """
288 """
289 )
289 )
290
290
291
291
292 def __init__(self, namespace=None, global_namespace=None, **kwargs):
292 def __init__(self, namespace=None, global_namespace=None, **kwargs):
293 """Create a new completer for the command line.
293 """Create a new completer for the command line.
294
294
295 Completer(namespace=ns,global_namespace=ns2) -> completer instance.
295 Completer(namespace=ns,global_namespace=ns2) -> completer instance.
296
296
297 If unspecified, the default namespace where completions are performed
297 If unspecified, the default namespace where completions are performed
298 is __main__ (technically, __main__.__dict__). Namespaces should be
298 is __main__ (technically, __main__.__dict__). Namespaces should be
299 given as dictionaries.
299 given as dictionaries.
300
300
301 An optional second namespace can be given. This allows the completer
301 An optional second namespace can be given. This allows the completer
302 to handle cases where both the local and global scopes need to be
302 to handle cases where both the local and global scopes need to be
303 distinguished.
303 distinguished.
304
304
305 Completer instances should be used as the completion mechanism of
305 Completer instances should be used as the completion mechanism of
306 readline via the set_completer() call:
306 readline via the set_completer() call:
307
307
308 readline.set_completer(Completer(my_namespace).complete)
308 readline.set_completer(Completer(my_namespace).complete)
309 """
309 """
310
310
311 # Don't bind to namespace quite yet, but flag whether the user wants a
311 # Don't bind to namespace quite yet, but flag whether the user wants a
312 # specific namespace or to use __main__.__dict__. This will allow us
312 # specific namespace or to use __main__.__dict__. This will allow us
313 # to bind to __main__.__dict__ at completion time, not now.
313 # to bind to __main__.__dict__ at completion time, not now.
314 if namespace is None:
314 if namespace is None:
315 self.use_main_ns = 1
315 self.use_main_ns = 1
316 else:
316 else:
317 self.use_main_ns = 0
317 self.use_main_ns = 0
318 self.namespace = namespace
318 self.namespace = namespace
319
319
320 # The global namespace, if given, can be bound directly
320 # The global namespace, if given, can be bound directly
321 if global_namespace is None:
321 if global_namespace is None:
322 self.global_namespace = {}
322 self.global_namespace = {}
323 else:
323 else:
324 self.global_namespace = global_namespace
324 self.global_namespace = global_namespace
325
325
326 super(Completer, self).__init__(**kwargs)
326 super(Completer, self).__init__(**kwargs)
327
327
328 def complete(self, text, state):
328 def complete(self, text, state):
329 """Return the next possible completion for 'text'.
329 """Return the next possible completion for 'text'.
330
330
331 This is called successively with state == 0, 1, 2, ... until it
331 This is called successively with state == 0, 1, 2, ... until it
332 returns None. The completion should begin with 'text'.
332 returns None. The completion should begin with 'text'.
333
333
334 """
334 """
335 if self.use_main_ns:
335 if self.use_main_ns:
336 self.namespace = __main__.__dict__
336 self.namespace = __main__.__dict__
337
337
338 if state == 0:
338 if state == 0:
339 if "." in text:
339 if "." in text:
340 self.matches = self.attr_matches(text)
340 self.matches = self.attr_matches(text)
341 else:
341 else:
342 self.matches = self.global_matches(text)
342 self.matches = self.global_matches(text)
343 try:
343 try:
344 return self.matches[state]
344 return self.matches[state]
345 except IndexError:
345 except IndexError:
346 return None
346 return None
347
347
348 def global_matches(self, text):
348 def global_matches(self, text):
349 """Compute matches when text is a simple name.
349 """Compute matches when text is a simple name.
350
350
351 Return a list of all keywords, built-in functions and names currently
351 Return a list of all keywords, built-in functions and names currently
352 defined in self.namespace or self.global_namespace that match.
352 defined in self.namespace or self.global_namespace that match.
353
353
354 """
354 """
355 #print 'Completer->global_matches, txt=%r' % text # dbg
355 #print 'Completer->global_matches, txt=%r' % text # dbg
356 matches = []
356 matches = []
357 match_append = matches.append
357 match_append = matches.append
358 n = len(text)
358 n = len(text)
359 for lst in [keyword.kwlist,
359 for lst in [keyword.kwlist,
360 builtin_mod.__dict__.keys(),
360 builtin_mod.__dict__.keys(),
361 self.namespace.keys(),
361 self.namespace.keys(),
362 self.global_namespace.keys()]:
362 self.global_namespace.keys()]:
363 for word in lst:
363 for word in lst:
364 if word[:n] == text and word != "__builtins__":
364 if word[:n] == text and word != "__builtins__":
365 match_append(word)
365 match_append(word)
366 return matches
366 return matches
367
367
368 def attr_matches(self, text):
368 def attr_matches(self, text):
369 """Compute matches when text contains a dot.
369 """Compute matches when text contains a dot.
370
370
371 Assuming the text is of the form NAME.NAME....[NAME], and is
371 Assuming the text is of the form NAME.NAME....[NAME], and is
372 evaluatable in self.namespace or self.global_namespace, it will be
372 evaluatable in self.namespace or self.global_namespace, it will be
373 evaluated and its attributes (as revealed by dir()) are used as
373 evaluated and its attributes (as revealed by dir()) are used as
374 possible completions. (For class instances, class members are are
374 possible completions. (For class instances, class members are are
375 also considered.)
375 also considered.)
376
376
377 WARNING: this can still invoke arbitrary C code, if an object
377 WARNING: this can still invoke arbitrary C code, if an object
378 with a __getattr__ hook is evaluated.
378 with a __getattr__ hook is evaluated.
379
379
380 """
380 """
381
381
382 #io.rprint('Completer->attr_matches, txt=%r' % text) # dbg
382 #io.rprint('Completer->attr_matches, txt=%r' % text) # dbg
383 # Another option, seems to work great. Catches things like ''.<tab>
383 # Another option, seems to work great. Catches things like ''.<tab>
384 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
384 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
385
385
386 if m:
386 if m:
387 expr, attr = m.group(1, 3)
387 expr, attr = m.group(1, 3)
388 elif self.greedy:
388 elif self.greedy:
389 m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer)
389 m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer)
390 if not m2:
390 if not m2:
391 return []
391 return []
392 expr, attr = m2.group(1,2)
392 expr, attr = m2.group(1,2)
393 else:
393 else:
394 return []
394 return []
395
395
396 try:
396 try:
397 obj = eval(expr, self.namespace)
397 obj = eval(expr, self.namespace)
398 except:
398 except:
399 try:
399 try:
400 obj = eval(expr, self.global_namespace)
400 obj = eval(expr, self.global_namespace)
401 except:
401 except:
402 return []
402 return []
403
403
404 if self.limit_to__all__ and hasattr(obj, '__all__'):
404 if self.limit_to__all__ and hasattr(obj, '__all__'):
405 words = get__all__entries(obj)
405 words = get__all__entries(obj)
406 else:
406 else:
407 words = dir2(obj)
407 words = dir2(obj)
408
408
409 try:
409 try:
410 words = generics.complete_object(obj, words)
410 words = generics.complete_object(obj, words)
411 except TryNext:
411 except TryNext:
412 pass
412 pass
413 except Exception:
413 except Exception:
414 # Silence errors from completion function
414 # Silence errors from completion function
415 #raise # dbg
415 #raise # dbg
416 pass
416 pass
417 # Build match list to return
417 # Build match list to return
418 n = len(attr)
418 n = len(attr)
419 res = ["%s.%s" % (expr, w) for w in words if w[:n] == attr ]
419 res = ["%s.%s" % (expr, w) for w in words if w[:n] == attr ]
420 return res
420 return res
421
421
422
422
423 def get__all__entries(obj):
423 def get__all__entries(obj):
424 """returns the strings in the __all__ attribute"""
424 """returns the strings in the __all__ attribute"""
425 try:
425 try:
426 words = getattr(obj, '__all__')
426 words = getattr(obj, '__all__')
427 except:
427 except:
428 return []
428 return []
429
429
430 return [w for w in words if isinstance(w, string_types)]
430 return [w for w in words if isinstance(w, string_types)]
431
431
432
432
433 def match_dict_keys(keys, prefix):
433 def match_dict_keys(keys, prefix):
434 """Used by dict_key_matches, matching the prefix to a list of keys"""
434 """Used by dict_key_matches, matching the prefix to a list of keys"""
435 if not prefix:
435 if not prefix:
436 return None, 0, [repr(k) for k in keys
436 return None, 0, [repr(k) for k in keys
437 if isinstance(k, (string_types, bytes))]
437 if isinstance(k, (string_types, bytes))]
438 quote_match = re.search('["\']', prefix)
438 quote_match = re.search('["\']', prefix)
439 quote = quote_match.group()
439 quote = quote_match.group()
440 try:
440 try:
441 prefix_str = eval(prefix + quote, {})
441 prefix_str = eval(prefix + quote, {})
442 except Exception:
442 except Exception:
443 return None, 0, []
443 return None, 0, []
444
444
445 token_match = re.search(r'\w*$', prefix, re.UNICODE)
445 token_match = re.search(r'\w*$', prefix, re.UNICODE)
446 token_start = token_match.start()
446 token_start = token_match.start()
447 token_prefix = token_match.group()
447 token_prefix = token_match.group()
448
448
449 # TODO: support bytes in Py3k
449 # TODO: support bytes in Py3k
450 matched = []
450 matched = []
451 for key in keys:
451 for key in keys:
452 try:
452 try:
453 if not key.startswith(prefix_str):
453 if not key.startswith(prefix_str):
454 continue
454 continue
455 except (AttributeError, TypeError, UnicodeError):
455 except (AttributeError, TypeError, UnicodeError):
456 # Python 3+ TypeError on b'a'.startswith('a') or vice-versa
456 # Python 3+ TypeError on b'a'.startswith('a') or vice-versa
457 continue
457 continue
458
458
459 # reformat remainder of key to begin with prefix
459 # reformat remainder of key to begin with prefix
460 rem = key[len(prefix_str):]
460 rem = key[len(prefix_str):]
461 # force repr wrapped in '
461 # force repr wrapped in '
462 rem_repr = repr(rem + '"')
462 rem_repr = repr(rem + '"')
463 if rem_repr.startswith('u') and prefix[0] not in 'uU':
463 if rem_repr.startswith('u') and prefix[0] not in 'uU':
464 # Found key is unicode, but prefix is Py2 string.
464 # Found key is unicode, but prefix is Py2 string.
465 # Therefore attempt to interpret key as string.
465 # Therefore attempt to interpret key as string.
466 try:
466 try:
467 rem_repr = repr(rem.encode('ascii') + '"')
467 rem_repr = repr(rem.encode('ascii') + '"')
468 except UnicodeEncodeError:
468 except UnicodeEncodeError:
469 continue
469 continue
470
470
471 rem_repr = rem_repr[1 + rem_repr.index("'"):-2]
471 rem_repr = rem_repr[1 + rem_repr.index("'"):-2]
472 if quote == '"':
472 if quote == '"':
473 # The entered prefix is quoted with ",
473 # The entered prefix is quoted with ",
474 # but the match is quoted with '.
474 # but the match is quoted with '.
475 # A contained " hence needs escaping for comparison:
475 # A contained " hence needs escaping for comparison:
476 rem_repr = rem_repr.replace('"', '\\"')
476 rem_repr = rem_repr.replace('"', '\\"')
477
477
478 # then reinsert prefix from start of token
478 # then reinsert prefix from start of token
479 matched.append('%s%s' % (token_prefix, rem_repr))
479 matched.append('%s%s' % (token_prefix, rem_repr))
480 return quote, token_start, matched
480 return quote, token_start, matched
481
481
482
482
483 def _safe_isinstance(obj, module, class_name):
483 def _safe_isinstance(obj, module, class_name):
484 """Checks if obj is an instance of module.class_name if loaded
484 """Checks if obj is an instance of module.class_name if loaded
485 """
485 """
486 return (module in sys.modules and
486 return (module in sys.modules and
487 isinstance(obj, getattr(__import__(module), class_name)))
487 isinstance(obj, getattr(__import__(module), class_name)))
488
488
489
489
490
490
491 class IPCompleter(Completer):
491 class IPCompleter(Completer):
492 """Extension of the completer class with IPython-specific features"""
492 """Extension of the completer class with IPython-specific features"""
493
493
494 def _greedy_changed(self, name, old, new):
494 def _greedy_changed(self, name, old, new):
495 """update the splitter and readline delims when greedy is changed"""
495 """update the splitter and readline delims when greedy is changed"""
496 if new:
496 if new:
497 self.splitter.delims = GREEDY_DELIMS
497 self.splitter.delims = GREEDY_DELIMS
498 else:
498 else:
499 self.splitter.delims = DELIMS
499 self.splitter.delims = DELIMS
500
500
501 if self.readline:
501 if self.readline:
502 self.readline.set_completer_delims(self.splitter.delims)
502 self.readline.set_completer_delims(self.splitter.delims)
503
503
504 merge_completions = CBool(True, config=True,
504 merge_completions = CBool(True, config=True,
505 help="""Whether to merge completion results into a single list
505 help="""Whether to merge completion results into a single list
506
506
507 If False, only the completion results from the first non-empty
507 If False, only the completion results from the first non-empty
508 completer will be returned.
508 completer will be returned.
509 """
509 """
510 )
510 )
511 omit__names = Enum((0,1,2), default_value=2, config=True,
511 omit__names = Enum((0,1,2), default_value=2, config=True,
512 help="""Instruct the completer to omit private method names
512 help="""Instruct the completer to omit private method names
513
513
514 Specifically, when completing on ``object.<tab>``.
514 Specifically, when completing on ``object.<tab>``.
515
515
516 When 2 [default]: all names that start with '_' will be excluded.
516 When 2 [default]: all names that start with '_' will be excluded.
517
517
518 When 1: all 'magic' names (``__foo__``) will be excluded.
518 When 1: all 'magic' names (``__foo__``) will be excluded.
519
519
520 When 0: nothing will be excluded.
520 When 0: nothing will be excluded.
521 """
521 """
522 )
522 )
523 limit_to__all__ = CBool(default_value=False, config=True,
523 limit_to__all__ = CBool(default_value=False, config=True,
524 help="""Instruct the completer to use __all__ for the completion
524 help="""Instruct the completer to use __all__ for the completion
525
525
526 Specifically, when completing on ``object.<tab>``.
526 Specifically, when completing on ``object.<tab>``.
527
527
528 When True: only those names in obj.__all__ will be included.
528 When True: only those names in obj.__all__ will be included.
529
529
530 When False [default]: the __all__ attribute is ignored
530 When False [default]: the __all__ attribute is ignored
531 """
531 """
532 )
532 )
533
533
534 def __init__(self, shell=None, namespace=None, global_namespace=None,
534 def __init__(self, shell=None, namespace=None, global_namespace=None,
535 use_readline=True, config=None, **kwargs):
535 use_readline=True, config=None, **kwargs):
536 """IPCompleter() -> completer
536 """IPCompleter() -> completer
537
537
538 Return a completer object suitable for use by the readline library
538 Return a completer object suitable for use by the readline library
539 via readline.set_completer().
539 via readline.set_completer().
540
540
541 Inputs:
541 Inputs:
542
542
543 - shell: a pointer to the ipython shell itself. This is needed
543 - shell: a pointer to the ipython shell itself. This is needed
544 because this completer knows about magic functions, and those can
544 because this completer knows about magic functions, and those can
545 only be accessed via the ipython instance.
545 only be accessed via the ipython instance.
546
546
547 - namespace: an optional dict where completions are performed.
547 - namespace: an optional dict where completions are performed.
548
548
549 - global_namespace: secondary optional dict for completions, to
549 - global_namespace: secondary optional dict for completions, to
550 handle cases (such as IPython embedded inside functions) where
550 handle cases (such as IPython embedded inside functions) where
551 both Python scopes are visible.
551 both Python scopes are visible.
552
552
553 use_readline : bool, optional
553 use_readline : bool, optional
554 If true, use the readline library. This completer can still function
554 If true, use the readline library. This completer can still function
555 without readline, though in that case callers must provide some extra
555 without readline, though in that case callers must provide some extra
556 information on each call about the current line."""
556 information on each call about the current line."""
557
557
558 self.magic_escape = ESC_MAGIC
558 self.magic_escape = ESC_MAGIC
559 self.splitter = CompletionSplitter()
559 self.splitter = CompletionSplitter()
560
560
561 # Readline configuration, only used by the rlcompleter method.
561 # Readline configuration, only used by the rlcompleter method.
562 if use_readline:
562 if use_readline:
563 # We store the right version of readline so that later code
563 # We store the right version of readline so that later code
564 import IPython.utils.rlineimpl as readline
564 import IPython.utils.rlineimpl as readline
565 self.readline = readline
565 self.readline = readline
566 else:
566 else:
567 self.readline = None
567 self.readline = None
568
568
569 # _greedy_changed() depends on splitter and readline being defined:
569 # _greedy_changed() depends on splitter and readline being defined:
570 Completer.__init__(self, namespace=namespace, global_namespace=global_namespace,
570 Completer.__init__(self, namespace=namespace, global_namespace=global_namespace,
571 config=config, **kwargs)
571 config=config, **kwargs)
572
572
573 # List where completion matches will be stored
573 # List where completion matches will be stored
574 self.matches = []
574 self.matches = []
575 self.shell = shell
575 self.shell = shell
576 # Regexp to split filenames with spaces in them
576 # Regexp to split filenames with spaces in them
577 self.space_name_re = re.compile(r'([^\\] )')
577 self.space_name_re = re.compile(r'([^\\] )')
578 # Hold a local ref. to glob.glob for speed
578 # Hold a local ref. to glob.glob for speed
579 self.glob = glob.glob
579 self.glob = glob.glob
580
580
581 # Determine if we are running on 'dumb' terminals, like (X)Emacs
581 # Determine if we are running on 'dumb' terminals, like (X)Emacs
582 # buffers, to avoid completion problems.
582 # buffers, to avoid completion problems.
583 term = os.environ.get('TERM','xterm')
583 term = os.environ.get('TERM','xterm')
584 self.dumb_terminal = term in ['dumb','emacs']
584 self.dumb_terminal = term in ['dumb','emacs']
585
585
586 # Special handling of backslashes needed in win32 platforms
586 # Special handling of backslashes needed in win32 platforms
587 if sys.platform == "win32":
587 if sys.platform == "win32":
588 self.clean_glob = self._clean_glob_win32
588 self.clean_glob = self._clean_glob_win32
589 else:
589 else:
590 self.clean_glob = self._clean_glob
590 self.clean_glob = self._clean_glob
591
591
592 #regexp to parse docstring for function signature
592 #regexp to parse docstring for function signature
593 self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
593 self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
594 self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
594 self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
595 #use this if positional argument name is also needed
595 #use this if positional argument name is also needed
596 #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)')
596 #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)')
597
597
598 # All active matcher routines for completion
598 # All active matcher routines for completion
599 self.matchers = [self.python_matches,
599 self.matchers = [self.python_matches,
600 self.file_matches,
600 self.file_matches,
601 self.magic_matches,
601 self.magic_matches,
602 self.python_func_kw_matches,
602 self.python_func_kw_matches,
603 self.dict_key_matches,
603 self.dict_key_matches,
604 ]
604 ]
605
605
606 def all_completions(self, text):
606 def all_completions(self, text):
607 """
607 """
608 Wrapper around the complete method for the benefit of emacs
608 Wrapper around the complete method for the benefit of emacs
609 and pydb.
609 and pydb.
610 """
610 """
611 return self.complete(text)[1]
611 return self.complete(text)[1]
612
612
613 def _clean_glob(self,text):
613 def _clean_glob(self,text):
614 return self.glob("%s*" % text)
614 return self.glob("%s*" % text)
615
615
616 def _clean_glob_win32(self,text):
616 def _clean_glob_win32(self,text):
617 return [f.replace("\\","/")
617 return [f.replace("\\","/")
618 for f in self.glob("%s*" % text)]
618 for f in self.glob("%s*" % text)]
619
619
620 def file_matches(self, text):
620 def file_matches(self, text):
621 """Match filenames, expanding ~USER type strings.
621 """Match filenames, expanding ~USER type strings.
622
622
623 Most of the seemingly convoluted logic in this completer is an
623 Most of the seemingly convoluted logic in this completer is an
624 attempt to handle filenames with spaces in them. And yet it's not
624 attempt to handle filenames with spaces in them. And yet it's not
625 quite perfect, because Python's readline doesn't expose all of the
625 quite perfect, because Python's readline doesn't expose all of the
626 GNU readline details needed for this to be done correctly.
626 GNU readline details needed for this to be done correctly.
627
627
628 For a filename with a space in it, the printed completions will be
628 For a filename with a space in it, the printed completions will be
629 only the parts after what's already been typed (instead of the
629 only the parts after what's already been typed (instead of the
630 full completions, as is normally done). I don't think with the
630 full completions, as is normally done). I don't think with the
631 current (as of Python 2.3) Python readline it's possible to do
631 current (as of Python 2.3) Python readline it's possible to do
632 better."""
632 better."""
633
633
634 #io.rprint('Completer->file_matches: <%r>' % text) # dbg
634 #io.rprint('Completer->file_matches: <%r>' % text) # dbg
635
635
636 # chars that require escaping with backslash - i.e. chars
636 # chars that require escaping with backslash - i.e. chars
637 # that readline treats incorrectly as delimiters, but we
637 # that readline treats incorrectly as delimiters, but we
638 # don't want to treat as delimiters in filename matching
638 # don't want to treat as delimiters in filename matching
639 # when escaped with backslash
639 # when escaped with backslash
640 if text.startswith('!'):
640 if text.startswith('!'):
641 text = text[1:]
641 text = text[1:]
642 text_prefix = '!'
642 text_prefix = '!'
643 else:
643 else:
644 text_prefix = ''
644 text_prefix = ''
645
645
646 text_until_cursor = self.text_until_cursor
646 text_until_cursor = self.text_until_cursor
647 # track strings with open quotes
647 # track strings with open quotes
648 open_quotes = has_open_quotes(text_until_cursor)
648 open_quotes = has_open_quotes(text_until_cursor)
649
649
650 if '(' in text_until_cursor or '[' in text_until_cursor:
650 if '(' in text_until_cursor or '[' in text_until_cursor:
651 lsplit = text
651 lsplit = text
652 else:
652 else:
653 try:
653 try:
654 # arg_split ~ shlex.split, but with unicode bugs fixed by us
654 # arg_split ~ shlex.split, but with unicode bugs fixed by us
655 lsplit = arg_split(text_until_cursor)[-1]
655 lsplit = arg_split(text_until_cursor)[-1]
656 except ValueError:
656 except ValueError:
657 # typically an unmatched ", or backslash without escaped char.
657 # typically an unmatched ", or backslash without escaped char.
658 if open_quotes:
658 if open_quotes:
659 lsplit = text_until_cursor.split(open_quotes)[-1]
659 lsplit = text_until_cursor.split(open_quotes)[-1]
660 else:
660 else:
661 return []
661 return []
662 except IndexError:
662 except IndexError:
663 # tab pressed on empty line
663 # tab pressed on empty line
664 lsplit = ""
664 lsplit = ""
665
665
666 if not open_quotes and lsplit != protect_filename(lsplit):
666 if not open_quotes and lsplit != protect_filename(lsplit):
667 # if protectables are found, do matching on the whole escaped name
667 # if protectables are found, do matching on the whole escaped name
668 has_protectables = True
668 has_protectables = True
669 text0,text = text,lsplit
669 text0,text = text,lsplit
670 else:
670 else:
671 has_protectables = False
671 has_protectables = False
672 text = os.path.expanduser(text)
672 text = os.path.expanduser(text)
673
673
674 if text == "":
674 if text == "":
675 return [text_prefix + protect_filename(f) for f in self.glob("*")]
675 return [text_prefix + protect_filename(f) for f in self.glob("*")]
676
676
677 # Compute the matches from the filesystem
677 # Compute the matches from the filesystem
678 m0 = self.clean_glob(text.replace('\\',''))
678 m0 = self.clean_glob(text.replace('\\',''))
679
679
680 if has_protectables:
680 if has_protectables:
681 # If we had protectables, we need to revert our changes to the
681 # If we had protectables, we need to revert our changes to the
682 # beginning of filename so that we don't double-write the part
682 # beginning of filename so that we don't double-write the part
683 # of the filename we have so far
683 # of the filename we have so far
684 len_lsplit = len(lsplit)
684 len_lsplit = len(lsplit)
685 matches = [text_prefix + text0 +
685 matches = [text_prefix + text0 +
686 protect_filename(f[len_lsplit:]) for f in m0]
686 protect_filename(f[len_lsplit:]) for f in m0]
687 else:
687 else:
688 if open_quotes:
688 if open_quotes:
689 # if we have a string with an open quote, we don't need to
689 # if we have a string with an open quote, we don't need to
690 # protect the names at all (and we _shouldn't_, as it
690 # protect the names at all (and we _shouldn't_, as it
691 # would cause bugs when the filesystem call is made).
691 # would cause bugs when the filesystem call is made).
692 matches = m0
692 matches = m0
693 else:
693 else:
694 matches = [text_prefix +
694 matches = [text_prefix +
695 protect_filename(f) for f in m0]
695 protect_filename(f) for f in m0]
696
696
697 #io.rprint('mm', matches) # dbg
697 #io.rprint('mm', matches) # dbg
698
698
699 # Mark directories in input list by appending '/' to their names.
699 # Mark directories in input list by appending '/' to their names.
700 matches = [x+'/' if os.path.isdir(x) else x for x in matches]
700 matches = [x+'/' if os.path.isdir(x) else x for x in matches]
701 return matches
701 return matches
702
702
703 def magic_matches(self, text):
703 def magic_matches(self, text):
704 """Match magics"""
704 """Match magics"""
705 #print 'Completer->magic_matches:',text,'lb',self.text_until_cursor # dbg
705 #print 'Completer->magic_matches:',text,'lb',self.text_until_cursor # dbg
706 # Get all shell magics now rather than statically, so magics loaded at
706 # Get all shell magics now rather than statically, so magics loaded at
707 # runtime show up too.
707 # runtime show up too.
708 lsm = self.shell.magics_manager.lsmagic()
708 lsm = self.shell.magics_manager.lsmagic()
709 line_magics = lsm['line']
709 line_magics = lsm['line']
710 cell_magics = lsm['cell']
710 cell_magics = lsm['cell']
711 pre = self.magic_escape
711 pre = self.magic_escape
712 pre2 = pre+pre
712 pre2 = pre+pre
713
713
714 # Completion logic:
714 # Completion logic:
715 # - user gives %%: only do cell magics
715 # - user gives %%: only do cell magics
716 # - user gives %: do both line and cell magics
716 # - user gives %: do both line and cell magics
717 # - no prefix: do both
717 # - no prefix: do both
718 # In other words, line magics are skipped if the user gives %% explicitly
718 # In other words, line magics are skipped if the user gives %% explicitly
719 bare_text = text.lstrip(pre)
719 bare_text = text.lstrip(pre)
720 comp = [ pre2+m for m in cell_magics if m.startswith(bare_text)]
720 comp = [ pre2+m for m in cell_magics if m.startswith(bare_text)]
721 if not text.startswith(pre2):
721 if not text.startswith(pre2):
722 comp += [ pre+m for m in line_magics if m.startswith(bare_text)]
722 comp += [ pre+m for m in line_magics if m.startswith(bare_text)]
723 return comp
723 return comp
724
724
725 def python_matches(self,text):
725 def python_matches(self,text):
726 """Match attributes or global python names"""
726 """Match attributes or global python names"""
727
727
728 #io.rprint('Completer->python_matches, txt=%r' % text) # dbg
728 #io.rprint('Completer->python_matches, txt=%r' % text) # dbg
729 if "." in text:
729 if "." in text:
730 try:
730 try:
731 matches = self.attr_matches(text)
731 matches = self.attr_matches(text)
732 if text.endswith('.') and self.omit__names:
732 if text.endswith('.') and self.omit__names:
733 if self.omit__names == 1:
733 if self.omit__names == 1:
734 # true if txt is _not_ a __ name, false otherwise:
734 # true if txt is _not_ a __ name, false otherwise:
735 no__name = (lambda txt:
735 no__name = (lambda txt:
736 re.match(r'.*\.__.*?__',txt) is None)
736 re.match(r'.*\.__.*?__',txt) is None)
737 else:
737 else:
738 # true if txt is _not_ a _ name, false otherwise:
738 # true if txt is _not_ a _ name, false otherwise:
739 no__name = (lambda txt:
739 no__name = (lambda txt:
740 re.match(r'.*\._.*?',txt) is None)
740 re.match(r'.*\._.*?',txt) is None)
741 matches = filter(no__name, matches)
741 matches = filter(no__name, matches)
742 except NameError:
742 except NameError:
743 # catches <undefined attributes>.<tab>
743 # catches <undefined attributes>.<tab>
744 matches = []
744 matches = []
745 else:
745 else:
746 matches = self.global_matches(text)
746 matches = self.global_matches(text)
747
747
748 return matches
748 return matches
749
749
750 def _default_arguments_from_docstring(self, doc):
750 def _default_arguments_from_docstring(self, doc):
751 """Parse the first line of docstring for call signature.
751 """Parse the first line of docstring for call signature.
752
752
753 Docstring should be of the form 'min(iterable[, key=func])\n'.
753 Docstring should be of the form 'min(iterable[, key=func])\n'.
754 It can also parse cython docstring of the form
754 It can also parse cython docstring of the form
755 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'.
755 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'.
756 """
756 """
757 if doc is None:
757 if doc is None:
758 return []
758 return []
759
759
760 #care only the firstline
760 #care only the firstline
761 line = doc.lstrip().splitlines()[0]
761 line = doc.lstrip().splitlines()[0]
762
762
763 #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
763 #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
764 #'min(iterable[, key=func])\n' -> 'iterable[, key=func]'
764 #'min(iterable[, key=func])\n' -> 'iterable[, key=func]'
765 sig = self.docstring_sig_re.search(line)
765 sig = self.docstring_sig_re.search(line)
766 if sig is None:
766 if sig is None:
767 return []
767 return []
768 # iterable[, key=func]' -> ['iterable[' ,' key=func]']
768 # iterable[, key=func]' -> ['iterable[' ,' key=func]']
769 sig = sig.groups()[0].split(',')
769 sig = sig.groups()[0].split(',')
770 ret = []
770 ret = []
771 for s in sig:
771 for s in sig:
772 #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
772 #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
773 ret += self.docstring_kwd_re.findall(s)
773 ret += self.docstring_kwd_re.findall(s)
774 return ret
774 return ret
775
775
776 def _default_arguments(self, obj):
776 def _default_arguments(self, obj):
777 """Return the list of default arguments of obj if it is callable,
777 """Return the list of default arguments of obj if it is callable,
778 or empty list otherwise."""
778 or empty list otherwise."""
779 call_obj = obj
779 call_obj = obj
780 ret = []
780 ret = []
781 if inspect.isbuiltin(obj):
781 if inspect.isbuiltin(obj):
782 pass
782 pass
783 elif not (inspect.isfunction(obj) or inspect.ismethod(obj)):
783 elif not (inspect.isfunction(obj) or inspect.ismethod(obj)):
784 if inspect.isclass(obj):
784 if inspect.isclass(obj):
785 #for cython embededsignature=True the constructor docstring
785 #for cython embededsignature=True the constructor docstring
786 #belongs to the object itself not __init__
786 #belongs to the object itself not __init__
787 ret += self._default_arguments_from_docstring(
787 ret += self._default_arguments_from_docstring(
788 getattr(obj, '__doc__', ''))
788 getattr(obj, '__doc__', ''))
789 # for classes, check for __init__,__new__
789 # for classes, check for __init__,__new__
790 call_obj = (getattr(obj, '__init__', None) or
790 call_obj = (getattr(obj, '__init__', None) or
791 getattr(obj, '__new__', None))
791 getattr(obj, '__new__', None))
792 # for all others, check if they are __call__able
792 # for all others, check if they are __call__able
793 elif hasattr(obj, '__call__'):
793 elif hasattr(obj, '__call__'):
794 call_obj = obj.__call__
794 call_obj = obj.__call__
795
795
796 ret += self._default_arguments_from_docstring(
796 ret += self._default_arguments_from_docstring(
797 getattr(call_obj, '__doc__', ''))
797 getattr(call_obj, '__doc__', ''))
798
798
799 try:
799 try:
800 args,_,_1,defaults = inspect.getargspec(call_obj)
800 args,_,_1,defaults = inspect.getargspec(call_obj)
801 if defaults:
801 if defaults:
802 ret+=args[-len(defaults):]
802 ret+=args[-len(defaults):]
803 except TypeError:
803 except TypeError:
804 pass
804 pass
805
805
806 return list(set(ret))
806 return list(set(ret))
807
807
808 def python_func_kw_matches(self,text):
808 def python_func_kw_matches(self,text):
809 """Match named parameters (kwargs) of the last open function"""
809 """Match named parameters (kwargs) of the last open function"""
810
810
811 if "." in text: # a parameter cannot be dotted
811 if "." in text: # a parameter cannot be dotted
812 return []
812 return []
813 try: regexp = self.__funcParamsRegex
813 try: regexp = self.__funcParamsRegex
814 except AttributeError:
814 except AttributeError:
815 regexp = self.__funcParamsRegex = re.compile(r'''
815 regexp = self.__funcParamsRegex = re.compile(r'''
816 '.*?(?<!\\)' | # single quoted strings or
816 '.*?(?<!\\)' | # single quoted strings or
817 ".*?(?<!\\)" | # double quoted strings or
817 ".*?(?<!\\)" | # double quoted strings or
818 \w+ | # identifier
818 \w+ | # identifier
819 \S # other characters
819 \S # other characters
820 ''', re.VERBOSE | re.DOTALL)
820 ''', re.VERBOSE | re.DOTALL)
821 # 1. find the nearest identifier that comes before an unclosed
821 # 1. find the nearest identifier that comes before an unclosed
822 # parenthesis before the cursor
822 # parenthesis before the cursor
823 # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo"
823 # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo"
824 tokens = regexp.findall(self.text_until_cursor)
824 tokens = regexp.findall(self.text_until_cursor)
825 tokens.reverse()
825 tokens.reverse()
826 iterTokens = iter(tokens); openPar = 0
826 iterTokens = iter(tokens); openPar = 0
827
827
828 for token in iterTokens:
828 for token in iterTokens:
829 if token == ')':
829 if token == ')':
830 openPar -= 1
830 openPar -= 1
831 elif token == '(':
831 elif token == '(':
832 openPar += 1
832 openPar += 1
833 if openPar > 0:
833 if openPar > 0:
834 # found the last unclosed parenthesis
834 # found the last unclosed parenthesis
835 break
835 break
836 else:
836 else:
837 return []
837 return []
838 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
838 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
839 ids = []
839 ids = []
840 isId = re.compile(r'\w+$').match
840 isId = re.compile(r'\w+$').match
841
841
842 while True:
842 while True:
843 try:
843 try:
844 ids.append(next(iterTokens))
844 ids.append(next(iterTokens))
845 if not isId(ids[-1]):
845 if not isId(ids[-1]):
846 ids.pop(); break
846 ids.pop(); break
847 if not next(iterTokens) == '.':
847 if not next(iterTokens) == '.':
848 break
848 break
849 except StopIteration:
849 except StopIteration:
850 break
850 break
851 # lookup the candidate callable matches either using global_matches
851 # lookup the candidate callable matches either using global_matches
852 # or attr_matches for dotted names
852 # or attr_matches for dotted names
853 if len(ids) == 1:
853 if len(ids) == 1:
854 callableMatches = self.global_matches(ids[0])
854 callableMatches = self.global_matches(ids[0])
855 else:
855 else:
856 callableMatches = self.attr_matches('.'.join(ids[::-1]))
856 callableMatches = self.attr_matches('.'.join(ids[::-1]))
857 argMatches = []
857 argMatches = []
858 for callableMatch in callableMatches:
858 for callableMatch in callableMatches:
859 try:
859 try:
860 namedArgs = self._default_arguments(eval(callableMatch,
860 namedArgs = self._default_arguments(eval(callableMatch,
861 self.namespace))
861 self.namespace))
862 except:
862 except:
863 continue
863 continue
864
864
865 for namedArg in namedArgs:
865 for namedArg in namedArgs:
866 if namedArg.startswith(text):
866 if namedArg.startswith(text):
867 argMatches.append("%s=" %namedArg)
867 argMatches.append("%s=" %namedArg)
868 return argMatches
868 return argMatches
869
869
870 def dict_key_matches(self, text):
870 def dict_key_matches(self, text):
871 "Match string keys in a dictionary, after e.g. 'foo[' "
871 "Match string keys in a dictionary, after e.g. 'foo[' "
872 def get_keys(obj):
872 def get_keys(obj):
873 # Only allow completion for known in-memory dict-like types
873 # Only allow completion for known in-memory dict-like types
874 if isinstance(obj, dict) or\
874 if isinstance(obj, dict) or\
875 _safe_isinstance(obj, 'pandas', 'DataFrame'):
875 _safe_isinstance(obj, 'pandas', 'DataFrame'):
876 try:
876 try:
877 return list(obj.keys())
877 return list(obj.keys())
878 except Exception:
878 except Exception:
879 return []
879 return []
880 elif _safe_isinstance(obj, 'numpy', 'ndarray'):
880 elif _safe_isinstance(obj, 'numpy', 'ndarray'):
881 return obj.dtype.names or []
881 return obj.dtype.names or []
882 return []
882 return []
883
883
884 try:
884 try:
885 regexps = self.__dict_key_regexps
885 regexps = self.__dict_key_regexps
886 except AttributeError:
886 except AttributeError:
887 dict_key_re_fmt = r'''(?x)
887 dict_key_re_fmt = r'''(?x)
888 ( # match dict-referring expression wrt greedy setting
888 ( # match dict-referring expression wrt greedy setting
889 %s
889 %s
890 )
890 )
891 \[ # open bracket
891 \[ # open bracket
892 \s* # and optional whitespace
892 \s* # and optional whitespace
893 ([uUbB]? # string prefix (r not handled)
893 ([uUbB]? # string prefix (r not handled)
894 (?: # unclosed string
894 (?: # unclosed string
895 '(?:[^']|(?<!\\)\\')*
895 '(?:[^']|(?<!\\)\\')*
896 |
896 |
897 "(?:[^"]|(?<!\\)\\")*
897 "(?:[^"]|(?<!\\)\\")*
898 )
898 )
899 )?
899 )?
900 $
900 $
901 '''
901 '''
902 regexps = self.__dict_key_regexps = {
902 regexps = self.__dict_key_regexps = {
903 False: re.compile(dict_key_re_fmt % '''
903 False: re.compile(dict_key_re_fmt % '''
904 # identifiers separated by .
904 # identifiers separated by .
905 (?!\d)\w+
905 (?!\d)\w+
906 (?:\.(?!\d)\w+)*
906 (?:\.(?!\d)\w+)*
907 '''),
907 '''),
908 True: re.compile(dict_key_re_fmt % '''
908 True: re.compile(dict_key_re_fmt % '''
909 .+
909 .+
910 ''')
910 ''')
911 }
911 }
912
912
913 match = regexps[self.greedy].search(self.text_until_cursor)
913 match = regexps[self.greedy].search(self.text_until_cursor)
914 if match is None:
914 if match is None:
915 return []
915 return []
916
916
917 expr, prefix = match.groups()
917 expr, prefix = match.groups()
918 try:
918 try:
919 obj = eval(expr, self.namespace)
919 obj = eval(expr, self.namespace)
920 except Exception:
920 except Exception:
921 try:
921 try:
922 obj = eval(expr, self.global_namespace)
922 obj = eval(expr, self.global_namespace)
923 except Exception:
923 except Exception:
924 return []
924 return []
925
925
926 keys = get_keys(obj)
926 keys = get_keys(obj)
927 if not keys:
927 if not keys:
928 return keys
928 return keys
929 closing_quote, token_offset, matches = match_dict_keys(keys, prefix)
929 closing_quote, token_offset, matches = match_dict_keys(keys, prefix)
930 if not matches:
930 if not matches:
931 return matches
931 return matches
932
932
933 # get the cursor position of
933 # get the cursor position of
934 # - the text being completed
934 # - the text being completed
935 # - the start of the key text
935 # - the start of the key text
936 # - the start of the completion
936 # - the start of the completion
937 text_start = len(self.text_until_cursor) - len(text)
937 text_start = len(self.text_until_cursor) - len(text)
938 if prefix:
938 if prefix:
939 key_start = match.start(2)
939 key_start = match.start(2)
940 completion_start = key_start + token_offset
940 completion_start = key_start + token_offset
941 else:
941 else:
942 key_start = completion_start = match.end()
942 key_start = completion_start = match.end()
943
943
944 # grab the leading prefix, to make sure all completions start with `text`
944 # grab the leading prefix, to make sure all completions start with `text`
945 if text_start > key_start:
945 if text_start > key_start:
946 leading = ''
946 leading = ''
947 else:
947 else:
948 leading = text[text_start:completion_start]
948 leading = text[text_start:completion_start]
949
949
950 # the index of the `[` character
950 # the index of the `[` character
951 bracket_idx = match.end(1)
951 bracket_idx = match.end(1)
952
952
953 # append closing quote and bracket as appropriate
953 # append closing quote and bracket as appropriate
954 # this is *not* appropriate if the opening quote or bracket is outside
954 # this is *not* appropriate if the opening quote or bracket is outside
955 # the text given to this method
955 # the text given to this method
956 suf = ''
956 suf = ''
957 continuation = self.line_buffer[len(self.text_until_cursor):]
957 continuation = self.line_buffer[len(self.text_until_cursor):]
958 if key_start > text_start and closing_quote:
958 if key_start > text_start and closing_quote:
959 # quotes were opened inside text, maybe close them
959 # quotes were opened inside text, maybe close them
960 if continuation.startswith(closing_quote):
960 if continuation.startswith(closing_quote):
961 continuation = continuation[len(closing_quote):]
961 continuation = continuation[len(closing_quote):]
962 else:
962 else:
963 suf += closing_quote
963 suf += closing_quote
964 if bracket_idx > text_start:
964 if bracket_idx > text_start:
965 # brackets were opened inside text, maybe close them
965 # brackets were opened inside text, maybe close them
966 if not continuation.startswith(']'):
966 if not continuation.startswith(']'):
967 suf += ']'
967 suf += ']'
968
968
969 return [leading + k + suf for k in matches]
969 return [leading + k + suf for k in matches]
970
970
971 def latex_matches(self, text):
971 def latex_matches(self, text):
972 u"""Match Latex syntax for unicode characters.
973
974 This does both \\alp -> \\alpha and \\alpha -> Ξ±
975
976 Used on Python 3 only.
977 """
972 slashpos = text.rfind('\\')
978 slashpos = text.rfind('\\')
973 if slashpos > -1:
979 if slashpos > -1:
974 s = text[slashpos:]
980 s = text[slashpos:]
975 if s in latex_symbols:
981 if s in latex_symbols:
976 # Try to complete a full latex symbol to unicode
982 # Try to complete a full latex symbol to unicode
977 # \\alpha -> Ξ±
983 # \\alpha -> Ξ±
978 return s, [latex_symbols[s]]
984 return s, [latex_symbols[s]]
979 else:
985 else:
980 # If a user has partially typed a latex symbol, give them
986 # If a user has partially typed a latex symbol, give them
981 # a full list of options \al -> [\aleph, \alpha]
987 # a full list of options \al -> [\aleph, \alpha]
982 matches = [k for k in latex_symbols if k.startswith(s)]
988 matches = [k for k in latex_symbols if k.startswith(s)]
983 return s, matches
989 return s, matches
984 return u'', []
990 return u'', []
985
991
986 def dispatch_custom_completer(self, text):
992 def dispatch_custom_completer(self, text):
987 #io.rprint("Custom! '%s' %s" % (text, self.custom_completers)) # dbg
993 #io.rprint("Custom! '%s' %s" % (text, self.custom_completers)) # dbg
988 line = self.line_buffer
994 line = self.line_buffer
989 if not line.strip():
995 if not line.strip():
990 return None
996 return None
991
997
992 # Create a little structure to pass all the relevant information about
998 # Create a little structure to pass all the relevant information about
993 # the current completion to any custom completer.
999 # the current completion to any custom completer.
994 event = Bunch()
1000 event = Bunch()
995 event.line = line
1001 event.line = line
996 event.symbol = text
1002 event.symbol = text
997 cmd = line.split(None,1)[0]
1003 cmd = line.split(None,1)[0]
998 event.command = cmd
1004 event.command = cmd
999 event.text_until_cursor = self.text_until_cursor
1005 event.text_until_cursor = self.text_until_cursor
1000
1006
1001 #print "\ncustom:{%s]\n" % event # dbg
1007 #print "\ncustom:{%s]\n" % event # dbg
1002
1008
1003 # for foo etc, try also to find completer for %foo
1009 # for foo etc, try also to find completer for %foo
1004 if not cmd.startswith(self.magic_escape):
1010 if not cmd.startswith(self.magic_escape):
1005 try_magic = self.custom_completers.s_matches(
1011 try_magic = self.custom_completers.s_matches(
1006 self.magic_escape + cmd)
1012 self.magic_escape + cmd)
1007 else:
1013 else:
1008 try_magic = []
1014 try_magic = []
1009
1015
1010 for c in itertools.chain(self.custom_completers.s_matches(cmd),
1016 for c in itertools.chain(self.custom_completers.s_matches(cmd),
1011 try_magic,
1017 try_magic,
1012 self.custom_completers.flat_matches(self.text_until_cursor)):
1018 self.custom_completers.flat_matches(self.text_until_cursor)):
1013 #print "try",c # dbg
1019 #print "try",c # dbg
1014 try:
1020 try:
1015 res = c(event)
1021 res = c(event)
1016 if res:
1022 if res:
1017 # first, try case sensitive match
1023 # first, try case sensitive match
1018 withcase = [r for r in res if r.startswith(text)]
1024 withcase = [r for r in res if r.startswith(text)]
1019 if withcase:
1025 if withcase:
1020 return withcase
1026 return withcase
1021 # if none, then case insensitive ones are ok too
1027 # if none, then case insensitive ones are ok too
1022 text_low = text.lower()
1028 text_low = text.lower()
1023 return [r for r in res if r.lower().startswith(text_low)]
1029 return [r for r in res if r.lower().startswith(text_low)]
1024 except TryNext:
1030 except TryNext:
1025 pass
1031 pass
1026
1032
1027 return None
1033 return None
1028
1034
1029 def complete(self, text=None, line_buffer=None, cursor_pos=None):
1035 def complete(self, text=None, line_buffer=None, cursor_pos=None):
1030 """Find completions for the given text and line context.
1036 """Find completions for the given text and line context.
1031
1037
1032 Note that both the text and the line_buffer are optional, but at least
1038 Note that both the text and the line_buffer are optional, but at least
1033 one of them must be given.
1039 one of them must be given.
1034
1040
1035 Parameters
1041 Parameters
1036 ----------
1042 ----------
1037 text : string, optional
1043 text : string, optional
1038 Text to perform the completion on. If not given, the line buffer
1044 Text to perform the completion on. If not given, the line buffer
1039 is split using the instance's CompletionSplitter object.
1045 is split using the instance's CompletionSplitter object.
1040
1046
1041 line_buffer : string, optional
1047 line_buffer : string, optional
1042 If not given, the completer attempts to obtain the current line
1048 If not given, the completer attempts to obtain the current line
1043 buffer via readline. This keyword allows clients which are
1049 buffer via readline. This keyword allows clients which are
1044 requesting for text completions in non-readline contexts to inform
1050 requesting for text completions in non-readline contexts to inform
1045 the completer of the entire text.
1051 the completer of the entire text.
1046
1052
1047 cursor_pos : int, optional
1053 cursor_pos : int, optional
1048 Index of the cursor in the full line buffer. Should be provided by
1054 Index of the cursor in the full line buffer. Should be provided by
1049 remote frontends where kernel has no access to frontend state.
1055 remote frontends where kernel has no access to frontend state.
1050
1056
1051 Returns
1057 Returns
1052 -------
1058 -------
1053 text : str
1059 text : str
1054 Text that was actually used in the completion.
1060 Text that was actually used in the completion.
1055
1061
1056 matches : list
1062 matches : list
1057 A list of completion matches.
1063 A list of completion matches.
1058 """
1064 """
1059 # io.rprint('\nCOMP1 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg
1065 # io.rprint('\nCOMP1 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg
1060
1066
1061 # if the cursor position isn't given, the only sane assumption we can
1067 # if the cursor position isn't given, the only sane assumption we can
1062 # make is that it's at the end of the line (the common case)
1068 # make is that it's at the end of the line (the common case)
1063 if cursor_pos is None:
1069 if cursor_pos is None:
1064 cursor_pos = len(line_buffer) if text is None else len(text)
1070 cursor_pos = len(line_buffer) if text is None else len(text)
1065
1071
1066 if PY3:
1072 if PY3:
1067 latex_text = text if not line_buffer else line_buffer[:cursor_pos]
1073 latex_text = text if not line_buffer else line_buffer[:cursor_pos]
1068 latex_text, latex_matches = self.latex_matches(latex_text)
1074 latex_text, latex_matches = self.latex_matches(latex_text)
1069 if latex_matches:
1075 if latex_matches:
1070 return latex_text, latex_matches
1076 return latex_text, latex_matches
1071
1077
1072 # if text is either None or an empty string, rely on the line buffer
1078 # if text is either None or an empty string, rely on the line buffer
1073 if not text:
1079 if not text:
1074 text = self.splitter.split_line(line_buffer, cursor_pos)
1080 text = self.splitter.split_line(line_buffer, cursor_pos)
1075
1081
1076 # If no line buffer is given, assume the input text is all there was
1082 # If no line buffer is given, assume the input text is all there was
1077 if line_buffer is None:
1083 if line_buffer is None:
1078 line_buffer = text
1084 line_buffer = text
1079
1085
1080 self.line_buffer = line_buffer
1086 self.line_buffer = line_buffer
1081 self.text_until_cursor = self.line_buffer[:cursor_pos]
1087 self.text_until_cursor = self.line_buffer[:cursor_pos]
1082 # io.rprint('COMP2 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg
1088 # io.rprint('COMP2 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg
1083
1089
1084 # Start with a clean slate of completions
1090 # Start with a clean slate of completions
1085 self.matches[:] = []
1091 self.matches[:] = []
1086 custom_res = self.dispatch_custom_completer(text)
1092 custom_res = self.dispatch_custom_completer(text)
1087 if custom_res is not None:
1093 if custom_res is not None:
1088 # did custom completers produce something?
1094 # did custom completers produce something?
1089 self.matches = custom_res
1095 self.matches = custom_res
1090 else:
1096 else:
1091 # Extend the list of completions with the results of each
1097 # Extend the list of completions with the results of each
1092 # matcher, so we return results to the user from all
1098 # matcher, so we return results to the user from all
1093 # namespaces.
1099 # namespaces.
1094 if self.merge_completions:
1100 if self.merge_completions:
1095 self.matches = []
1101 self.matches = []
1096 for matcher in self.matchers:
1102 for matcher in self.matchers:
1097 try:
1103 try:
1098 self.matches.extend(matcher(text))
1104 self.matches.extend(matcher(text))
1099 except:
1105 except:
1100 # Show the ugly traceback if the matcher causes an
1106 # Show the ugly traceback if the matcher causes an
1101 # exception, but do NOT crash the kernel!
1107 # exception, but do NOT crash the kernel!
1102 sys.excepthook(*sys.exc_info())
1108 sys.excepthook(*sys.exc_info())
1103 else:
1109 else:
1104 for matcher in self.matchers:
1110 for matcher in self.matchers:
1105 self.matches = matcher(text)
1111 self.matches = matcher(text)
1106 if self.matches:
1112 if self.matches:
1107 break
1113 break
1108 # FIXME: we should extend our api to return a dict with completions for
1114 # FIXME: we should extend our api to return a dict with completions for
1109 # different types of objects. The rlcomplete() method could then
1115 # different types of objects. The rlcomplete() method could then
1110 # simply collapse the dict into a list for readline, but we'd have
1116 # simply collapse the dict into a list for readline, but we'd have
1111 # richer completion semantics in other evironments.
1117 # richer completion semantics in other evironments.
1112
1118
1113 # use penalize_magics_key to put magics after variables with same name
1119 # use penalize_magics_key to put magics after variables with same name
1114 self.matches = sorted(set(self.matches), key=penalize_magics_key)
1120 self.matches = sorted(set(self.matches), key=penalize_magics_key)
1115
1121
1116 #io.rprint('COMP TEXT, MATCHES: %r, %r' % (text, self.matches)) # dbg
1122 #io.rprint('COMP TEXT, MATCHES: %r, %r' % (text, self.matches)) # dbg
1117 return text, self.matches
1123 return text, self.matches
1118
1124
1119 def rlcomplete(self, text, state):
1125 def rlcomplete(self, text, state):
1120 """Return the state-th possible completion for 'text'.
1126 """Return the state-th possible completion for 'text'.
1121
1127
1122 This is called successively with state == 0, 1, 2, ... until it
1128 This is called successively with state == 0, 1, 2, ... until it
1123 returns None. The completion should begin with 'text'.
1129 returns None. The completion should begin with 'text'.
1124
1130
1125 Parameters
1131 Parameters
1126 ----------
1132 ----------
1127 text : string
1133 text : string
1128 Text to perform the completion on.
1134 Text to perform the completion on.
1129
1135
1130 state : int
1136 state : int
1131 Counter used by readline.
1137 Counter used by readline.
1132 """
1138 """
1133 if state==0:
1139 if state==0:
1134
1140
1135 self.line_buffer = line_buffer = self.readline.get_line_buffer()
1141 self.line_buffer = line_buffer = self.readline.get_line_buffer()
1136 cursor_pos = self.readline.get_endidx()
1142 cursor_pos = self.readline.get_endidx()
1137
1143
1138 #io.rprint("\nRLCOMPLETE: %r %r %r" %
1144 #io.rprint("\nRLCOMPLETE: %r %r %r" %
1139 # (text, line_buffer, cursor_pos) ) # dbg
1145 # (text, line_buffer, cursor_pos) ) # dbg
1140
1146
1141 # if there is only a tab on a line with only whitespace, instead of
1147 # if there is only a tab on a line with only whitespace, instead of
1142 # the mostly useless 'do you want to see all million completions'
1148 # the mostly useless 'do you want to see all million completions'
1143 # message, just do the right thing and give the user his tab!
1149 # message, just do the right thing and give the user his tab!
1144 # Incidentally, this enables pasting of tabbed text from an editor
1150 # Incidentally, this enables pasting of tabbed text from an editor
1145 # (as long as autoindent is off).
1151 # (as long as autoindent is off).
1146
1152
1147 # It should be noted that at least pyreadline still shows file
1153 # It should be noted that at least pyreadline still shows file
1148 # completions - is there a way around it?
1154 # completions - is there a way around it?
1149
1155
1150 # don't apply this on 'dumb' terminals, such as emacs buffers, so
1156 # don't apply this on 'dumb' terminals, such as emacs buffers, so
1151 # we don't interfere with their own tab-completion mechanism.
1157 # we don't interfere with their own tab-completion mechanism.
1152 if not (self.dumb_terminal or line_buffer.strip()):
1158 if not (self.dumb_terminal or line_buffer.strip()):
1153 self.readline.insert_text('\t')
1159 self.readline.insert_text('\t')
1154 sys.stdout.flush()
1160 sys.stdout.flush()
1155 return None
1161 return None
1156
1162
1157 # Note: debugging exceptions that may occur in completion is very
1163 # Note: debugging exceptions that may occur in completion is very
1158 # tricky, because readline unconditionally silences them. So if
1164 # tricky, because readline unconditionally silences them. So if
1159 # during development you suspect a bug in the completion code, turn
1165 # during development you suspect a bug in the completion code, turn
1160 # this flag on temporarily by uncommenting the second form (don't
1166 # this flag on temporarily by uncommenting the second form (don't
1161 # flip the value in the first line, as the '# dbg' marker can be
1167 # flip the value in the first line, as the '# dbg' marker can be
1162 # automatically detected and is used elsewhere).
1168 # automatically detected and is used elsewhere).
1163 DEBUG = False
1169 DEBUG = False
1164 #DEBUG = True # dbg
1170 #DEBUG = True # dbg
1165 if DEBUG:
1171 if DEBUG:
1166 try:
1172 try:
1167 self.complete(text, line_buffer, cursor_pos)
1173 self.complete(text, line_buffer, cursor_pos)
1168 except:
1174 except:
1169 import traceback; traceback.print_exc()
1175 import traceback; traceback.print_exc()
1170 else:
1176 else:
1171 # The normal production version is here
1177 # The normal production version is here
1172
1178
1173 # This method computes the self.matches array
1179 # This method computes the self.matches array
1174 self.complete(text, line_buffer, cursor_pos)
1180 self.complete(text, line_buffer, cursor_pos)
1175
1181
1176 try:
1182 try:
1177 return self.matches[state]
1183 return self.matches[state]
1178 except IndexError:
1184 except IndexError:
1179 return None
1185 return None
General Comments 0
You need to be logged in to leave comments. Login now