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