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