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