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