##// END OF EJS Templates
Merge pull request #10588 from Carreau/backport-no-unicomplete...
Thomas Kluyver -
r23681:9ddc9647 merge
parent child Browse files
Show More
@@ -1,1184 +1,1188
1 # encoding: utf-8
1 # encoding: utf-8
2 """Word completion for IPython.
2 """Word completion for IPython.
3
3
4 This module started as fork of the rlcompleter module in the Python standard
4 This module started as fork of the rlcompleter module in the Python standard
5 library. The original enhancements made to rlcompleter have been sent
5 library. The original enhancements made to rlcompleter have been sent
6 upstream and were accepted as of Python 2.3,
6 upstream and were accepted as of Python 2.3,
7
7
8 """
8 """
9
9
10 # Copyright (c) IPython Development Team.
10 # Copyright (c) IPython Development Team.
11 # Distributed under the terms of the Modified BSD License.
11 # Distributed under the terms of the Modified BSD License.
12 #
12 #
13 # Some of this code originated from rlcompleter in the Python standard library
13 # Some of this code originated from rlcompleter in the Python standard library
14 # Copyright (C) 2001 Python Software Foundation, www.python.org
14 # Copyright (C) 2001 Python Software Foundation, www.python.org
15
15
16 from __future__ import print_function
16 from __future__ import print_function
17
17
18 import __main__
18 import __main__
19 import glob
19 import glob
20 import inspect
20 import inspect
21 import itertools
21 import itertools
22 import keyword
22 import keyword
23 import os
23 import os
24 import re
24 import re
25 import sys
25 import sys
26 import unicodedata
26 import unicodedata
27 import string
27 import string
28 import warnings
28 import warnings
29
29
30 from traitlets.config.configurable import Configurable
30 from traitlets.config.configurable import Configurable
31 from IPython.core.error import TryNext
31 from IPython.core.error import TryNext
32 from IPython.core.inputsplitter import ESC_MAGIC
32 from IPython.core.inputsplitter import ESC_MAGIC
33 from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol
33 from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol
34 from IPython.utils import generics
34 from IPython.utils import generics
35 from IPython.utils.decorators import undoc
35 from IPython.utils.decorators import undoc
36 from IPython.utils.dir2 import dir2, get_real_method
36 from IPython.utils.dir2 import dir2, get_real_method
37 from IPython.utils.process import arg_split
37 from IPython.utils.process import arg_split
38 from IPython.utils.py3compat import builtin_mod, string_types, PY3, cast_unicode_py2
38 from IPython.utils.py3compat import builtin_mod, string_types, PY3, cast_unicode_py2
39 from traitlets import Bool, Enum, observe
39 from traitlets import Bool, Enum, observe
40
40
41
41
42 # Public API
42 # Public API
43 __all__ = ['Completer','IPCompleter']
43 __all__ = ['Completer','IPCompleter']
44
44
45 if sys.platform == 'win32':
45 if sys.platform == 'win32':
46 PROTECTABLES = ' '
46 PROTECTABLES = ' '
47 else:
47 else:
48 PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&'
48 PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&'
49
49
50
50
51 def has_open_quotes(s):
51 def has_open_quotes(s):
52 """Return whether a string has open quotes.
52 """Return whether a string has open quotes.
53
53
54 This simply counts whether the number of quote characters of either type in
54 This simply counts whether the number of quote characters of either type in
55 the string is odd.
55 the string is odd.
56
56
57 Returns
57 Returns
58 -------
58 -------
59 If there is an open quote, the quote character is returned. Else, return
59 If there is an open quote, the quote character is returned. Else, return
60 False.
60 False.
61 """
61 """
62 # We check " first, then ', so complex cases with nested quotes will get
62 # We check " first, then ', so complex cases with nested quotes will get
63 # the " to take precedence.
63 # the " to take precedence.
64 if s.count('"') % 2:
64 if s.count('"') % 2:
65 return '"'
65 return '"'
66 elif s.count("'") % 2:
66 elif s.count("'") % 2:
67 return "'"
67 return "'"
68 else:
68 else:
69 return False
69 return False
70
70
71
71
72 def protect_filename(s):
72 def protect_filename(s):
73 """Escape a string to protect certain characters."""
73 """Escape a string to protect certain characters."""
74 if set(s) & set(PROTECTABLES):
74 if set(s) & set(PROTECTABLES):
75 if sys.platform == "win32":
75 if sys.platform == "win32":
76 return '"' + s + '"'
76 return '"' + s + '"'
77 else:
77 else:
78 return "".join(("\\" + c if c in PROTECTABLES else c) for c in s)
78 return "".join(("\\" + c if c in PROTECTABLES else c) for c in s)
79 else:
79 else:
80 return s
80 return s
81
81
82
82
83 def expand_user(path):
83 def expand_user(path):
84 """Expand '~'-style usernames in strings.
84 """Expand '~'-style usernames in strings.
85
85
86 This is similar to :func:`os.path.expanduser`, but it computes and returns
86 This is similar to :func:`os.path.expanduser`, but it computes and returns
87 extra information that will be useful if the input was being used in
87 extra information that will be useful if the input was being used in
88 computing completions, and you wish to return the completions with the
88 computing completions, and you wish to return the completions with the
89 original '~' instead of its expanded value.
89 original '~' instead of its expanded value.
90
90
91 Parameters
91 Parameters
92 ----------
92 ----------
93 path : str
93 path : str
94 String to be expanded. If no ~ is present, the output is the same as the
94 String to be expanded. If no ~ is present, the output is the same as the
95 input.
95 input.
96
96
97 Returns
97 Returns
98 -------
98 -------
99 newpath : str
99 newpath : str
100 Result of ~ expansion in the input path.
100 Result of ~ expansion in the input path.
101 tilde_expand : bool
101 tilde_expand : bool
102 Whether any expansion was performed or not.
102 Whether any expansion was performed or not.
103 tilde_val : str
103 tilde_val : str
104 The value that ~ was replaced with.
104 The value that ~ was replaced with.
105 """
105 """
106 # Default values
106 # Default values
107 tilde_expand = False
107 tilde_expand = False
108 tilde_val = ''
108 tilde_val = ''
109 newpath = path
109 newpath = path
110
110
111 if path.startswith('~'):
111 if path.startswith('~'):
112 tilde_expand = True
112 tilde_expand = True
113 rest = len(path)-1
113 rest = len(path)-1
114 newpath = os.path.expanduser(path)
114 newpath = os.path.expanduser(path)
115 if rest:
115 if rest:
116 tilde_val = newpath[:-rest]
116 tilde_val = newpath[:-rest]
117 else:
117 else:
118 tilde_val = newpath
118 tilde_val = newpath
119
119
120 return newpath, tilde_expand, tilde_val
120 return newpath, tilde_expand, tilde_val
121
121
122
122
123 def compress_user(path, tilde_expand, tilde_val):
123 def compress_user(path, tilde_expand, tilde_val):
124 """Does the opposite of expand_user, with its outputs.
124 """Does the opposite of expand_user, with its outputs.
125 """
125 """
126 if tilde_expand:
126 if tilde_expand:
127 return path.replace(tilde_val, '~')
127 return path.replace(tilde_val, '~')
128 else:
128 else:
129 return path
129 return path
130
130
131
131
132 def completions_sorting_key(word):
132 def completions_sorting_key(word):
133 """key for sorting completions
133 """key for sorting completions
134
134
135 This does several things:
135 This does several things:
136
136
137 - Lowercase all completions, so they are sorted alphabetically with
137 - Lowercase all completions, so they are sorted alphabetically with
138 upper and lower case words mingled
138 upper and lower case words mingled
139 - Demote any completions starting with underscores to the end
139 - Demote any completions starting with underscores to the end
140 - Insert any %magic and %%cellmagic completions in the alphabetical order
140 - Insert any %magic and %%cellmagic completions in the alphabetical order
141 by their name
141 by their name
142 """
142 """
143 # Case insensitive sort
143 # Case insensitive sort
144 word = word.lower()
144 word = word.lower()
145
145
146 prio1, prio2 = 0, 0
146 prio1, prio2 = 0, 0
147
147
148 if word.startswith('__'):
148 if word.startswith('__'):
149 prio1 = 2
149 prio1 = 2
150 elif word.startswith('_'):
150 elif word.startswith('_'):
151 prio1 = 1
151 prio1 = 1
152
152
153 if word.endswith('='):
153 if word.endswith('='):
154 prio1 = -1
154 prio1 = -1
155
155
156 if word.startswith('%%'):
156 if word.startswith('%%'):
157 # If there's another % in there, this is something else, so leave it alone
157 # If there's another % in there, this is something else, so leave it alone
158 if not "%" in word[2:]:
158 if not "%" in word[2:]:
159 word = word[2:]
159 word = word[2:]
160 prio2 = 2
160 prio2 = 2
161 elif word.startswith('%'):
161 elif word.startswith('%'):
162 if not "%" in word[1:]:
162 if not "%" in word[1:]:
163 word = word[1:]
163 word = word[1:]
164 prio2 = 1
164 prio2 = 1
165
165
166 return prio1, word, prio2
166 return prio1, word, prio2
167
167
168
168
169 @undoc
169 @undoc
170 class Bunch(object): pass
170 class Bunch(object): pass
171
171
172
172
173 if sys.platform == 'win32':
173 if sys.platform == 'win32':
174 DELIMS = ' \t\n`!@#$^&*()=+[{]}|;\'",<>?'
174 DELIMS = ' \t\n`!@#$^&*()=+[{]}|;\'",<>?'
175 else:
175 else:
176 DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
176 DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
177
177
178 GREEDY_DELIMS = ' =\r\n'
178 GREEDY_DELIMS = ' =\r\n'
179
179
180
180
181 class CompletionSplitter(object):
181 class CompletionSplitter(object):
182 """An object to split an input line in a manner similar to readline.
182 """An object to split an input line in a manner similar to readline.
183
183
184 By having our own implementation, we can expose readline-like completion in
184 By having our own implementation, we can expose readline-like completion in
185 a uniform manner to all frontends. This object only needs to be given the
185 a uniform manner to all frontends. This object only needs to be given the
186 line of text to be split and the cursor position on said line, and it
186 line of text to be split and the cursor position on said line, and it
187 returns the 'word' to be completed on at the cursor after splitting the
187 returns the 'word' to be completed on at the cursor after splitting the
188 entire line.
188 entire line.
189
189
190 What characters are used as splitting delimiters can be controlled by
190 What characters are used as splitting delimiters can be controlled by
191 setting the `delims` attribute (this is a property that internally
191 setting the `delims` attribute (this is a property that internally
192 automatically builds the necessary regular expression)"""
192 automatically builds the necessary regular expression)"""
193
193
194 # Private interface
194 # Private interface
195
195
196 # A string of delimiter characters. The default value makes sense for
196 # A string of delimiter characters. The default value makes sense for
197 # IPython's most typical usage patterns.
197 # IPython's most typical usage patterns.
198 _delims = DELIMS
198 _delims = DELIMS
199
199
200 # The expression (a normal string) to be compiled into a regular expression
200 # The expression (a normal string) to be compiled into a regular expression
201 # for actual splitting. We store it as an attribute mostly for ease of
201 # for actual splitting. We store it as an attribute mostly for ease of
202 # debugging, since this type of code can be so tricky to debug.
202 # debugging, since this type of code can be so tricky to debug.
203 _delim_expr = None
203 _delim_expr = None
204
204
205 # The regular expression that does the actual splitting
205 # The regular expression that does the actual splitting
206 _delim_re = None
206 _delim_re = None
207
207
208 def __init__(self, delims=None):
208 def __init__(self, delims=None):
209 delims = CompletionSplitter._delims if delims is None else delims
209 delims = CompletionSplitter._delims if delims is None else delims
210 self.delims = delims
210 self.delims = delims
211
211
212 @property
212 @property
213 def delims(self):
213 def delims(self):
214 """Return the string of delimiter characters."""
214 """Return the string of delimiter characters."""
215 return self._delims
215 return self._delims
216
216
217 @delims.setter
217 @delims.setter
218 def delims(self, delims):
218 def delims(self, delims):
219 """Set the delimiters for line splitting."""
219 """Set the delimiters for line splitting."""
220 expr = '[' + ''.join('\\'+ c for c in delims) + ']'
220 expr = '[' + ''.join('\\'+ c for c in delims) + ']'
221 self._delim_re = re.compile(expr)
221 self._delim_re = re.compile(expr)
222 self._delims = delims
222 self._delims = delims
223 self._delim_expr = expr
223 self._delim_expr = expr
224
224
225 def split_line(self, line, cursor_pos=None):
225 def split_line(self, line, cursor_pos=None):
226 """Split a line of text with a cursor at the given position.
226 """Split a line of text with a cursor at the given position.
227 """
227 """
228 l = line if cursor_pos is None else line[:cursor_pos]
228 l = line if cursor_pos is None else line[:cursor_pos]
229 return self._delim_re.split(l)[-1]
229 return self._delim_re.split(l)[-1]
230
230
231
231
232 class Completer(Configurable):
232 class Completer(Configurable):
233
233
234 greedy = Bool(False,
234 greedy = Bool(False,
235 help="""Activate greedy completion
235 help="""Activate greedy completion
236 PENDING DEPRECTION. this is now mostly taken care of with Jedi.
236 PENDING DEPRECTION. this is now mostly taken care of with Jedi.
237
237
238 This will enable completion on elements of lists, results of function calls, etc.,
238 This will enable completion on elements of lists, results of function calls, etc.,
239 but can be unsafe because the code is actually evaluated on TAB.
239 but can be unsafe because the code is actually evaluated on TAB.
240 """
240 """
241 ).tag(config=True)
241 ).tag(config=True)
242
242
243 backslash_combining_completions = Bool(True,
244 help="Enable unicode completions, e.g. \\alpha<tab> . "
245 "Includes completion of latex commands, unicode names, and expanding "
246 "unicode characters back to latex commands.").tag(config=True)
243
247
244 def __init__(self, namespace=None, global_namespace=None, **kwargs):
248 def __init__(self, namespace=None, global_namespace=None, **kwargs):
245 """Create a new completer for the command line.
249 """Create a new completer for the command line.
246
250
247 Completer(namespace=ns, global_namespace=ns2) -> completer instance.
251 Completer(namespace=ns, global_namespace=ns2) -> completer instance.
248
252
249 If unspecified, the default namespace where completions are performed
253 If unspecified, the default namespace where completions are performed
250 is __main__ (technically, __main__.__dict__). Namespaces should be
254 is __main__ (technically, __main__.__dict__). Namespaces should be
251 given as dictionaries.
255 given as dictionaries.
252
256
253 An optional second namespace can be given. This allows the completer
257 An optional second namespace can be given. This allows the completer
254 to handle cases where both the local and global scopes need to be
258 to handle cases where both the local and global scopes need to be
255 distinguished.
259 distinguished.
256
260
257 Completer instances should be used as the completion mechanism of
261 Completer instances should be used as the completion mechanism of
258 readline via the set_completer() call:
262 readline via the set_completer() call:
259
263
260 readline.set_completer(Completer(my_namespace).complete)
264 readline.set_completer(Completer(my_namespace).complete)
261 """
265 """
262
266
263 # Don't bind to namespace quite yet, but flag whether the user wants a
267 # Don't bind to namespace quite yet, but flag whether the user wants a
264 # specific namespace or to use __main__.__dict__. This will allow us
268 # specific namespace or to use __main__.__dict__. This will allow us
265 # to bind to __main__.__dict__ at completion time, not now.
269 # to bind to __main__.__dict__ at completion time, not now.
266 if namespace is None:
270 if namespace is None:
267 self.use_main_ns = 1
271 self.use_main_ns = 1
268 else:
272 else:
269 self.use_main_ns = 0
273 self.use_main_ns = 0
270 self.namespace = namespace
274 self.namespace = namespace
271
275
272 # The global namespace, if given, can be bound directly
276 # The global namespace, if given, can be bound directly
273 if global_namespace is None:
277 if global_namespace is None:
274 self.global_namespace = {}
278 self.global_namespace = {}
275 else:
279 else:
276 self.global_namespace = global_namespace
280 self.global_namespace = global_namespace
277
281
278 super(Completer, self).__init__(**kwargs)
282 super(Completer, self).__init__(**kwargs)
279
283
280 def complete(self, text, state):
284 def complete(self, text, state):
281 """Return the next possible completion for 'text'.
285 """Return the next possible completion for 'text'.
282
286
283 This is called successively with state == 0, 1, 2, ... until it
287 This is called successively with state == 0, 1, 2, ... until it
284 returns None. The completion should begin with 'text'.
288 returns None. The completion should begin with 'text'.
285
289
286 """
290 """
287 if self.use_main_ns:
291 if self.use_main_ns:
288 self.namespace = __main__.__dict__
292 self.namespace = __main__.__dict__
289
293
290 if state == 0:
294 if state == 0:
291 if "." in text:
295 if "." in text:
292 self.matches = self.attr_matches(text)
296 self.matches = self.attr_matches(text)
293 else:
297 else:
294 self.matches = self.global_matches(text)
298 self.matches = self.global_matches(text)
295 try:
299 try:
296 return self.matches[state]
300 return self.matches[state]
297 except IndexError:
301 except IndexError:
298 return None
302 return None
299
303
300 def global_matches(self, text):
304 def global_matches(self, text):
301 """Compute matches when text is a simple name.
305 """Compute matches when text is a simple name.
302
306
303 Return a list of all keywords, built-in functions and names currently
307 Return a list of all keywords, built-in functions and names currently
304 defined in self.namespace or self.global_namespace that match.
308 defined in self.namespace or self.global_namespace that match.
305
309
306 """
310 """
307 matches = []
311 matches = []
308 match_append = matches.append
312 match_append = matches.append
309 n = len(text)
313 n = len(text)
310 for lst in [keyword.kwlist,
314 for lst in [keyword.kwlist,
311 builtin_mod.__dict__.keys(),
315 builtin_mod.__dict__.keys(),
312 self.namespace.keys(),
316 self.namespace.keys(),
313 self.global_namespace.keys()]:
317 self.global_namespace.keys()]:
314 for word in lst:
318 for word in lst:
315 if word[:n] == text and word != "__builtins__":
319 if word[:n] == text and word != "__builtins__":
316 match_append(word)
320 match_append(word)
317 return [cast_unicode_py2(m) for m in matches]
321 return [cast_unicode_py2(m) for m in matches]
318
322
319 def attr_matches(self, text):
323 def attr_matches(self, text):
320 """Compute matches when text contains a dot.
324 """Compute matches when text contains a dot.
321
325
322 Assuming the text is of the form NAME.NAME....[NAME], and is
326 Assuming the text is of the form NAME.NAME....[NAME], and is
323 evaluatable in self.namespace or self.global_namespace, it will be
327 evaluatable in self.namespace or self.global_namespace, it will be
324 evaluated and its attributes (as revealed by dir()) are used as
328 evaluated and its attributes (as revealed by dir()) are used as
325 possible completions. (For class instances, class members are are
329 possible completions. (For class instances, class members are are
326 also considered.)
330 also considered.)
327
331
328 WARNING: this can still invoke arbitrary C code, if an object
332 WARNING: this can still invoke arbitrary C code, if an object
329 with a __getattr__ hook is evaluated.
333 with a __getattr__ hook is evaluated.
330
334
331 """
335 """
332
336
333 # Another option, seems to work great. Catches things like ''.<tab>
337 # Another option, seems to work great. Catches things like ''.<tab>
334 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
338 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
335
339
336 if m:
340 if m:
337 expr, attr = m.group(1, 3)
341 expr, attr = m.group(1, 3)
338 elif self.greedy:
342 elif self.greedy:
339 m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer)
343 m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer)
340 if not m2:
344 if not m2:
341 return []
345 return []
342 expr, attr = m2.group(1,2)
346 expr, attr = m2.group(1,2)
343 else:
347 else:
344 return []
348 return []
345
349
346 try:
350 try:
347 obj = eval(expr, self.namespace)
351 obj = eval(expr, self.namespace)
348 except:
352 except:
349 try:
353 try:
350 obj = eval(expr, self.global_namespace)
354 obj = eval(expr, self.global_namespace)
351 except:
355 except:
352 return []
356 return []
353
357
354 if self.limit_to__all__ and hasattr(obj, '__all__'):
358 if self.limit_to__all__ and hasattr(obj, '__all__'):
355 words = get__all__entries(obj)
359 words = get__all__entries(obj)
356 else:
360 else:
357 words = dir2(obj)
361 words = dir2(obj)
358
362
359 try:
363 try:
360 words = generics.complete_object(obj, words)
364 words = generics.complete_object(obj, words)
361 except TryNext:
365 except TryNext:
362 pass
366 pass
363 except Exception:
367 except Exception:
364 # Silence errors from completion function
368 # Silence errors from completion function
365 #raise # dbg
369 #raise # dbg
366 pass
370 pass
367 # Build match list to return
371 # Build match list to return
368 n = len(attr)
372 n = len(attr)
369 return [u"%s.%s" % (expr, w) for w in words if w[:n] == attr ]
373 return [u"%s.%s" % (expr, w) for w in words if w[:n] == attr ]
370
374
371
375
372 def get__all__entries(obj):
376 def get__all__entries(obj):
373 """returns the strings in the __all__ attribute"""
377 """returns the strings in the __all__ attribute"""
374 try:
378 try:
375 words = getattr(obj, '__all__')
379 words = getattr(obj, '__all__')
376 except:
380 except:
377 return []
381 return []
378
382
379 return [cast_unicode_py2(w) for w in words if isinstance(w, string_types)]
383 return [cast_unicode_py2(w) for w in words if isinstance(w, string_types)]
380
384
381
385
382 def match_dict_keys(keys, prefix, delims):
386 def match_dict_keys(keys, prefix, delims):
383 """Used by dict_key_matches, matching the prefix to a list of keys"""
387 """Used by dict_key_matches, matching the prefix to a list of keys"""
384 if not prefix:
388 if not prefix:
385 return None, 0, [repr(k) for k in keys
389 return None, 0, [repr(k) for k in keys
386 if isinstance(k, (string_types, bytes))]
390 if isinstance(k, (string_types, bytes))]
387 quote_match = re.search('["\']', prefix)
391 quote_match = re.search('["\']', prefix)
388 quote = quote_match.group()
392 quote = quote_match.group()
389 try:
393 try:
390 prefix_str = eval(prefix + quote, {})
394 prefix_str = eval(prefix + quote, {})
391 except Exception:
395 except Exception:
392 return None, 0, []
396 return None, 0, []
393
397
394 pattern = '[^' + ''.join('\\' + c for c in delims) + ']*$'
398 pattern = '[^' + ''.join('\\' + c for c in delims) + ']*$'
395 token_match = re.search(pattern, prefix, re.UNICODE)
399 token_match = re.search(pattern, prefix, re.UNICODE)
396 token_start = token_match.start()
400 token_start = token_match.start()
397 token_prefix = token_match.group()
401 token_prefix = token_match.group()
398
402
399 # TODO: support bytes in Py3k
403 # TODO: support bytes in Py3k
400 matched = []
404 matched = []
401 for key in keys:
405 for key in keys:
402 try:
406 try:
403 if not key.startswith(prefix_str):
407 if not key.startswith(prefix_str):
404 continue
408 continue
405 except (AttributeError, TypeError, UnicodeError):
409 except (AttributeError, TypeError, UnicodeError):
406 # Python 3+ TypeError on b'a'.startswith('a') or vice-versa
410 # Python 3+ TypeError on b'a'.startswith('a') or vice-versa
407 continue
411 continue
408
412
409 # reformat remainder of key to begin with prefix
413 # reformat remainder of key to begin with prefix
410 rem = key[len(prefix_str):]
414 rem = key[len(prefix_str):]
411 # force repr wrapped in '
415 # force repr wrapped in '
412 rem_repr = repr(rem + '"')
416 rem_repr = repr(rem + '"')
413 if rem_repr.startswith('u') and prefix[0] not in 'uU':
417 if rem_repr.startswith('u') and prefix[0] not in 'uU':
414 # Found key is unicode, but prefix is Py2 string.
418 # Found key is unicode, but prefix is Py2 string.
415 # Therefore attempt to interpret key as string.
419 # Therefore attempt to interpret key as string.
416 try:
420 try:
417 rem_repr = repr(rem.encode('ascii') + '"')
421 rem_repr = repr(rem.encode('ascii') + '"')
418 except UnicodeEncodeError:
422 except UnicodeEncodeError:
419 continue
423 continue
420
424
421 rem_repr = rem_repr[1 + rem_repr.index("'"):-2]
425 rem_repr = rem_repr[1 + rem_repr.index("'"):-2]
422 if quote == '"':
426 if quote == '"':
423 # The entered prefix is quoted with ",
427 # The entered prefix is quoted with ",
424 # but the match is quoted with '.
428 # but the match is quoted with '.
425 # A contained " hence needs escaping for comparison:
429 # A contained " hence needs escaping for comparison:
426 rem_repr = rem_repr.replace('"', '\\"')
430 rem_repr = rem_repr.replace('"', '\\"')
427
431
428 # then reinsert prefix from start of token
432 # then reinsert prefix from start of token
429 matched.append('%s%s' % (token_prefix, rem_repr))
433 matched.append('%s%s' % (token_prefix, rem_repr))
430 return quote, token_start, matched
434 return quote, token_start, matched
431
435
432
436
433 def _safe_isinstance(obj, module, class_name):
437 def _safe_isinstance(obj, module, class_name):
434 """Checks if obj is an instance of module.class_name if loaded
438 """Checks if obj is an instance of module.class_name if loaded
435 """
439 """
436 return (module in sys.modules and
440 return (module in sys.modules and
437 isinstance(obj, getattr(__import__(module), class_name)))
441 isinstance(obj, getattr(__import__(module), class_name)))
438
442
439
443
440 def back_unicode_name_matches(text):
444 def back_unicode_name_matches(text):
441 u"""Match unicode characters back to unicode name
445 u"""Match unicode characters back to unicode name
442
446
443 This does β˜ƒ -> \\snowman
447 This does β˜ƒ -> \\snowman
444
448
445 Note that snowman is not a valid python3 combining character but will be expanded.
449 Note that snowman is not a valid python3 combining character but will be expanded.
446 Though it will not recombine back to the snowman character by the completion machinery.
450 Though it will not recombine back to the snowman character by the completion machinery.
447
451
448 This will not either back-complete standard sequences like \\n, \\b ...
452 This will not either back-complete standard sequences like \\n, \\b ...
449
453
450 Used on Python 3 only.
454 Used on Python 3 only.
451 """
455 """
452 if len(text)<2:
456 if len(text)<2:
453 return u'', ()
457 return u'', ()
454 maybe_slash = text[-2]
458 maybe_slash = text[-2]
455 if maybe_slash != '\\':
459 if maybe_slash != '\\':
456 return u'', ()
460 return u'', ()
457
461
458 char = text[-1]
462 char = text[-1]
459 # no expand on quote for completion in strings.
463 # no expand on quote for completion in strings.
460 # nor backcomplete standard ascii keys
464 # nor backcomplete standard ascii keys
461 if char in string.ascii_letters or char in ['"',"'"]:
465 if char in string.ascii_letters or char in ['"',"'"]:
462 return u'', ()
466 return u'', ()
463 try :
467 try :
464 unic = unicodedata.name(char)
468 unic = unicodedata.name(char)
465 return '\\'+char,['\\'+unic]
469 return '\\'+char,['\\'+unic]
466 except KeyError:
470 except KeyError:
467 pass
471 pass
468 return u'', ()
472 return u'', ()
469
473
470 def back_latex_name_matches(text):
474 def back_latex_name_matches(text):
471 u"""Match latex characters back to unicode name
475 u"""Match latex characters back to unicode name
472
476
473 This does ->\\sqrt
477 This does ->\\sqrt
474
478
475 Used on Python 3 only.
479 Used on Python 3 only.
476 """
480 """
477 if len(text)<2:
481 if len(text)<2:
478 return u'', ()
482 return u'', ()
479 maybe_slash = text[-2]
483 maybe_slash = text[-2]
480 if maybe_slash != '\\':
484 if maybe_slash != '\\':
481 return u'', ()
485 return u'', ()
482
486
483
487
484 char = text[-1]
488 char = text[-1]
485 # no expand on quote for completion in strings.
489 # no expand on quote for completion in strings.
486 # nor backcomplete standard ascii keys
490 # nor backcomplete standard ascii keys
487 if char in string.ascii_letters or char in ['"',"'"]:
491 if char in string.ascii_letters or char in ['"',"'"]:
488 return u'', ()
492 return u'', ()
489 try :
493 try :
490 latex = reverse_latex_symbol[char]
494 latex = reverse_latex_symbol[char]
491 # '\\' replace the \ as well
495 # '\\' replace the \ as well
492 return '\\'+char,[latex]
496 return '\\'+char,[latex]
493 except KeyError:
497 except KeyError:
494 pass
498 pass
495 return u'', ()
499 return u'', ()
496
500
497
501
498 class IPCompleter(Completer):
502 class IPCompleter(Completer):
499 """Extension of the completer class with IPython-specific features"""
503 """Extension of the completer class with IPython-specific features"""
500
504
501 @observe('greedy')
505 @observe('greedy')
502 def _greedy_changed(self, change):
506 def _greedy_changed(self, change):
503 """update the splitter and readline delims when greedy is changed"""
507 """update the splitter and readline delims when greedy is changed"""
504 if change['new']:
508 if change['new']:
505 self.splitter.delims = GREEDY_DELIMS
509 self.splitter.delims = GREEDY_DELIMS
506 else:
510 else:
507 self.splitter.delims = DELIMS
511 self.splitter.delims = DELIMS
508
512
509 if self.readline:
513 if self.readline:
510 self.readline.set_completer_delims(self.splitter.delims)
514 self.readline.set_completer_delims(self.splitter.delims)
511
515
512 merge_completions = Bool(True,
516 merge_completions = Bool(True,
513 help="""Whether to merge completion results into a single list
517 help="""Whether to merge completion results into a single list
514
518
515 If False, only the completion results from the first non-empty
519 If False, only the completion results from the first non-empty
516 completer will be returned.
520 completer will be returned.
517 """
521 """
518 ).tag(config=True)
522 ).tag(config=True)
519 omit__names = Enum((0,1,2), default_value=2,
523 omit__names = Enum((0,1,2), default_value=2,
520 help="""Instruct the completer to omit private method names
524 help="""Instruct the completer to omit private method names
521
525
522 Specifically, when completing on ``object.<tab>``.
526 Specifically, when completing on ``object.<tab>``.
523
527
524 When 2 [default]: all names that start with '_' will be excluded.
528 When 2 [default]: all names that start with '_' will be excluded.
525
529
526 When 1: all 'magic' names (``__foo__``) will be excluded.
530 When 1: all 'magic' names (``__foo__``) will be excluded.
527
531
528 When 0: nothing will be excluded.
532 When 0: nothing will be excluded.
529 """
533 """
530 ).tag(config=True)
534 ).tag(config=True)
531 limit_to__all__ = Bool(False,
535 limit_to__all__ = Bool(False,
532 help="""
536 help="""
533 DEPRECATED as of version 5.0.
537 DEPRECATED as of version 5.0.
534
538
535 Instruct the completer to use __all__ for the completion
539 Instruct the completer to use __all__ for the completion
536
540
537 Specifically, when completing on ``object.<tab>``.
541 Specifically, when completing on ``object.<tab>``.
538
542
539 When True: only those names in obj.__all__ will be included.
543 When True: only those names in obj.__all__ will be included.
540
544
541 When False [default]: the __all__ attribute is ignored
545 When False [default]: the __all__ attribute is ignored
542 """,
546 """,
543 ).tag(config=True)
547 ).tag(config=True)
544
548
545 @observe('limit_to__all__')
549 @observe('limit_to__all__')
546 def _limit_to_all_changed(self, change):
550 def _limit_to_all_changed(self, change):
547 warnings.warn('`IPython.core.IPCompleter.limit_to__all__` configuration '
551 warnings.warn('`IPython.core.IPCompleter.limit_to__all__` configuration '
548 'value has been deprecated since IPython 5.0, will be made to have '
552 'value has been deprecated since IPython 5.0, will be made to have '
549 'no effects and then removed in future version of IPython.',
553 'no effects and then removed in future version of IPython.',
550 UserWarning)
554 UserWarning)
551
555
552 def __init__(self, shell=None, namespace=None, global_namespace=None,
556 def __init__(self, shell=None, namespace=None, global_namespace=None,
553 use_readline=True, config=None, **kwargs):
557 use_readline=True, config=None, **kwargs):
554 """IPCompleter() -> completer
558 """IPCompleter() -> completer
555
559
556 Return a completer object suitable for use by the readline library
560 Return a completer object suitable for use by the readline library
557 via readline.set_completer().
561 via readline.set_completer().
558
562
559 Inputs:
563 Inputs:
560
564
561 - shell: a pointer to the ipython shell itself. This is needed
565 - shell: a pointer to the ipython shell itself. This is needed
562 because this completer knows about magic functions, and those can
566 because this completer knows about magic functions, and those can
563 only be accessed via the ipython instance.
567 only be accessed via the ipython instance.
564
568
565 - namespace: an optional dict where completions are performed.
569 - namespace: an optional dict where completions are performed.
566
570
567 - global_namespace: secondary optional dict for completions, to
571 - global_namespace: secondary optional dict for completions, to
568 handle cases (such as IPython embedded inside functions) where
572 handle cases (such as IPython embedded inside functions) where
569 both Python scopes are visible.
573 both Python scopes are visible.
570
574
571 use_readline : bool, optional
575 use_readline : bool, optional
572 If true, use the readline library. This completer can still function
576 If true, use the readline library. This completer can still function
573 without readline, though in that case callers must provide some extra
577 without readline, though in that case callers must provide some extra
574 information on each call about the current line."""
578 information on each call about the current line."""
575
579
576 self.magic_escape = ESC_MAGIC
580 self.magic_escape = ESC_MAGIC
577 self.splitter = CompletionSplitter()
581 self.splitter = CompletionSplitter()
578
582
579 # Readline configuration, only used by the rlcompleter method.
583 # Readline configuration, only used by the rlcompleter method.
580 if use_readline:
584 if use_readline:
581 # We store the right version of readline so that later code
585 # We store the right version of readline so that later code
582 import IPython.utils.rlineimpl as readline
586 import IPython.utils.rlineimpl as readline
583 self.readline = readline
587 self.readline = readline
584 else:
588 else:
585 self.readline = None
589 self.readline = None
586
590
587 # _greedy_changed() depends on splitter and readline being defined:
591 # _greedy_changed() depends on splitter and readline being defined:
588 Completer.__init__(self, namespace=namespace, global_namespace=global_namespace,
592 Completer.__init__(self, namespace=namespace, global_namespace=global_namespace,
589 config=config, **kwargs)
593 config=config, **kwargs)
590
594
591 # List where completion matches will be stored
595 # List where completion matches will be stored
592 self.matches = []
596 self.matches = []
593 self.shell = shell
597 self.shell = shell
594 # Regexp to split filenames with spaces in them
598 # Regexp to split filenames with spaces in them
595 self.space_name_re = re.compile(r'([^\\] )')
599 self.space_name_re = re.compile(r'([^\\] )')
596 # Hold a local ref. to glob.glob for speed
600 # Hold a local ref. to glob.glob for speed
597 self.glob = glob.glob
601 self.glob = glob.glob
598
602
599 # Determine if we are running on 'dumb' terminals, like (X)Emacs
603 # Determine if we are running on 'dumb' terminals, like (X)Emacs
600 # buffers, to avoid completion problems.
604 # buffers, to avoid completion problems.
601 term = os.environ.get('TERM','xterm')
605 term = os.environ.get('TERM','xterm')
602 self.dumb_terminal = term in ['dumb','emacs']
606 self.dumb_terminal = term in ['dumb','emacs']
603
607
604 # Special handling of backslashes needed in win32 platforms
608 # Special handling of backslashes needed in win32 platforms
605 if sys.platform == "win32":
609 if sys.platform == "win32":
606 self.clean_glob = self._clean_glob_win32
610 self.clean_glob = self._clean_glob_win32
607 else:
611 else:
608 self.clean_glob = self._clean_glob
612 self.clean_glob = self._clean_glob
609
613
610 #regexp to parse docstring for function signature
614 #regexp to parse docstring for function signature
611 self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
615 self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
612 self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
616 self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
613 #use this if positional argument name is also needed
617 #use this if positional argument name is also needed
614 #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)')
618 #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)')
615
619
616 # All active matcher routines for completion
620 # All active matcher routines for completion
617 self.matchers = [
621 self.matchers = [
618 self.python_matches,
622 self.python_matches,
619 self.file_matches,
623 self.file_matches,
620 self.magic_matches,
624 self.magic_matches,
621 self.python_func_kw_matches,
625 self.python_func_kw_matches,
622 self.dict_key_matches,
626 self.dict_key_matches,
623 ]
627 ]
624
628
625 # This is set externally by InteractiveShell
629 # This is set externally by InteractiveShell
626 self.custom_completers = None
630 self.custom_completers = None
627
631
628 def all_completions(self, text):
632 def all_completions(self, text):
629 """
633 """
630 Wrapper around the complete method for the benefit of emacs.
634 Wrapper around the complete method for the benefit of emacs.
631 """
635 """
632 return self.complete(text)[1]
636 return self.complete(text)[1]
633
637
634 def _clean_glob(self, text):
638 def _clean_glob(self, text):
635 return self.glob("%s*" % text)
639 return self.glob("%s*" % text)
636
640
637 def _clean_glob_win32(self,text):
641 def _clean_glob_win32(self,text):
638 return [f.replace("\\","/")
642 return [f.replace("\\","/")
639 for f in self.glob("%s*" % text)]
643 for f in self.glob("%s*" % text)]
640
644
641 def file_matches(self, text):
645 def file_matches(self, text):
642 """Match filenames, expanding ~USER type strings.
646 """Match filenames, expanding ~USER type strings.
643
647
644 Most of the seemingly convoluted logic in this completer is an
648 Most of the seemingly convoluted logic in this completer is an
645 attempt to handle filenames with spaces in them. And yet it's not
649 attempt to handle filenames with spaces in them. And yet it's not
646 quite perfect, because Python's readline doesn't expose all of the
650 quite perfect, because Python's readline doesn't expose all of the
647 GNU readline details needed for this to be done correctly.
651 GNU readline details needed for this to be done correctly.
648
652
649 For a filename with a space in it, the printed completions will be
653 For a filename with a space in it, the printed completions will be
650 only the parts after what's already been typed (instead of the
654 only the parts after what's already been typed (instead of the
651 full completions, as is normally done). I don't think with the
655 full completions, as is normally done). I don't think with the
652 current (as of Python 2.3) Python readline it's possible to do
656 current (as of Python 2.3) Python readline it's possible to do
653 better."""
657 better."""
654
658
655 # chars that require escaping with backslash - i.e. chars
659 # chars that require escaping with backslash - i.e. chars
656 # that readline treats incorrectly as delimiters, but we
660 # that readline treats incorrectly as delimiters, but we
657 # don't want to treat as delimiters in filename matching
661 # don't want to treat as delimiters in filename matching
658 # when escaped with backslash
662 # when escaped with backslash
659 if text.startswith('!'):
663 if text.startswith('!'):
660 text = text[1:]
664 text = text[1:]
661 text_prefix = u'!'
665 text_prefix = u'!'
662 else:
666 else:
663 text_prefix = u''
667 text_prefix = u''
664
668
665 text_until_cursor = self.text_until_cursor
669 text_until_cursor = self.text_until_cursor
666 # track strings with open quotes
670 # track strings with open quotes
667 open_quotes = has_open_quotes(text_until_cursor)
671 open_quotes = has_open_quotes(text_until_cursor)
668
672
669 if '(' in text_until_cursor or '[' in text_until_cursor:
673 if '(' in text_until_cursor or '[' in text_until_cursor:
670 lsplit = text
674 lsplit = text
671 else:
675 else:
672 try:
676 try:
673 # arg_split ~ shlex.split, but with unicode bugs fixed by us
677 # arg_split ~ shlex.split, but with unicode bugs fixed by us
674 lsplit = arg_split(text_until_cursor)[-1]
678 lsplit = arg_split(text_until_cursor)[-1]
675 except ValueError:
679 except ValueError:
676 # typically an unmatched ", or backslash without escaped char.
680 # typically an unmatched ", or backslash without escaped char.
677 if open_quotes:
681 if open_quotes:
678 lsplit = text_until_cursor.split(open_quotes)[-1]
682 lsplit = text_until_cursor.split(open_quotes)[-1]
679 else:
683 else:
680 return []
684 return []
681 except IndexError:
685 except IndexError:
682 # tab pressed on empty line
686 # tab pressed on empty line
683 lsplit = ""
687 lsplit = ""
684
688
685 if not open_quotes and lsplit != protect_filename(lsplit):
689 if not open_quotes and lsplit != protect_filename(lsplit):
686 # if protectables are found, do matching on the whole escaped name
690 # if protectables are found, do matching on the whole escaped name
687 has_protectables = True
691 has_protectables = True
688 text0,text = text,lsplit
692 text0,text = text,lsplit
689 else:
693 else:
690 has_protectables = False
694 has_protectables = False
691 text = os.path.expanduser(text)
695 text = os.path.expanduser(text)
692
696
693 if text == "":
697 if text == "":
694 return [text_prefix + cast_unicode_py2(protect_filename(f)) for f in self.glob("*")]
698 return [text_prefix + cast_unicode_py2(protect_filename(f)) for f in self.glob("*")]
695
699
696 # Compute the matches from the filesystem
700 # Compute the matches from the filesystem
697 if sys.platform == 'win32':
701 if sys.platform == 'win32':
698 m0 = self.clean_glob(text)
702 m0 = self.clean_glob(text)
699 else:
703 else:
700 m0 = self.clean_glob(text.replace('\\', ''))
704 m0 = self.clean_glob(text.replace('\\', ''))
701
705
702 if has_protectables:
706 if has_protectables:
703 # If we had protectables, we need to revert our changes to the
707 # If we had protectables, we need to revert our changes to the
704 # beginning of filename so that we don't double-write the part
708 # beginning of filename so that we don't double-write the part
705 # of the filename we have so far
709 # of the filename we have so far
706 len_lsplit = len(lsplit)
710 len_lsplit = len(lsplit)
707 matches = [text_prefix + text0 +
711 matches = [text_prefix + text0 +
708 protect_filename(f[len_lsplit:]) for f in m0]
712 protect_filename(f[len_lsplit:]) for f in m0]
709 else:
713 else:
710 if open_quotes:
714 if open_quotes:
711 # if we have a string with an open quote, we don't need to
715 # if we have a string with an open quote, we don't need to
712 # protect the names at all (and we _shouldn't_, as it
716 # protect the names at all (and we _shouldn't_, as it
713 # would cause bugs when the filesystem call is made).
717 # would cause bugs when the filesystem call is made).
714 matches = m0
718 matches = m0
715 else:
719 else:
716 matches = [text_prefix +
720 matches = [text_prefix +
717 protect_filename(f) for f in m0]
721 protect_filename(f) for f in m0]
718
722
719 # Mark directories in input list by appending '/' to their names.
723 # Mark directories in input list by appending '/' to their names.
720 return [cast_unicode_py2(x+'/') if os.path.isdir(x) else x for x in matches]
724 return [cast_unicode_py2(x+'/') if os.path.isdir(x) else x for x in matches]
721
725
722 def magic_matches(self, text):
726 def magic_matches(self, text):
723 """Match magics"""
727 """Match magics"""
724 # Get all shell magics now rather than statically, so magics loaded at
728 # Get all shell magics now rather than statically, so magics loaded at
725 # runtime show up too.
729 # runtime show up too.
726 lsm = self.shell.magics_manager.lsmagic()
730 lsm = self.shell.magics_manager.lsmagic()
727 line_magics = lsm['line']
731 line_magics = lsm['line']
728 cell_magics = lsm['cell']
732 cell_magics = lsm['cell']
729 pre = self.magic_escape
733 pre = self.magic_escape
730 pre2 = pre+pre
734 pre2 = pre+pre
731
735
732 # Completion logic:
736 # Completion logic:
733 # - user gives %%: only do cell magics
737 # - user gives %%: only do cell magics
734 # - user gives %: do both line and cell magics
738 # - user gives %: do both line and cell magics
735 # - no prefix: do both
739 # - no prefix: do both
736 # In other words, line magics are skipped if the user gives %% explicitly
740 # In other words, line magics are skipped if the user gives %% explicitly
737 bare_text = text.lstrip(pre)
741 bare_text = text.lstrip(pre)
738 comp = [ pre2+m for m in cell_magics if m.startswith(bare_text)]
742 comp = [ pre2+m for m in cell_magics if m.startswith(bare_text)]
739 if not text.startswith(pre2):
743 if not text.startswith(pre2):
740 comp += [ pre+m for m in line_magics if m.startswith(bare_text)]
744 comp += [ pre+m for m in line_magics if m.startswith(bare_text)]
741 return [cast_unicode_py2(c) for c in comp]
745 return [cast_unicode_py2(c) for c in comp]
742
746
743
747
744 def python_matches(self, text):
748 def python_matches(self, text):
745 """Match attributes or global python names"""
749 """Match attributes or global python names"""
746 if "." in text:
750 if "." in text:
747 try:
751 try:
748 matches = self.attr_matches(text)
752 matches = self.attr_matches(text)
749 if text.endswith('.') and self.omit__names:
753 if text.endswith('.') and self.omit__names:
750 if self.omit__names == 1:
754 if self.omit__names == 1:
751 # true if txt is _not_ a __ name, false otherwise:
755 # true if txt is _not_ a __ name, false otherwise:
752 no__name = (lambda txt:
756 no__name = (lambda txt:
753 re.match(r'.*\.__.*?__',txt) is None)
757 re.match(r'.*\.__.*?__',txt) is None)
754 else:
758 else:
755 # true if txt is _not_ a _ name, false otherwise:
759 # true if txt is _not_ a _ name, false otherwise:
756 no__name = (lambda txt:
760 no__name = (lambda txt:
757 re.match(r'\._.*?',txt[txt.rindex('.'):]) is None)
761 re.match(r'\._.*?',txt[txt.rindex('.'):]) is None)
758 matches = filter(no__name, matches)
762 matches = filter(no__name, matches)
759 except NameError:
763 except NameError:
760 # catches <undefined attributes>.<tab>
764 # catches <undefined attributes>.<tab>
761 matches = []
765 matches = []
762 else:
766 else:
763 matches = self.global_matches(text)
767 matches = self.global_matches(text)
764 return matches
768 return matches
765
769
766 def _default_arguments_from_docstring(self, doc):
770 def _default_arguments_from_docstring(self, doc):
767 """Parse the first line of docstring for call signature.
771 """Parse the first line of docstring for call signature.
768
772
769 Docstring should be of the form 'min(iterable[, key=func])\n'.
773 Docstring should be of the form 'min(iterable[, key=func])\n'.
770 It can also parse cython docstring of the form
774 It can also parse cython docstring of the form
771 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'.
775 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'.
772 """
776 """
773 if doc is None:
777 if doc is None:
774 return []
778 return []
775
779
776 #care only the firstline
780 #care only the firstline
777 line = doc.lstrip().splitlines()[0]
781 line = doc.lstrip().splitlines()[0]
778
782
779 #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
783 #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
780 #'min(iterable[, key=func])\n' -> 'iterable[, key=func]'
784 #'min(iterable[, key=func])\n' -> 'iterable[, key=func]'
781 sig = self.docstring_sig_re.search(line)
785 sig = self.docstring_sig_re.search(line)
782 if sig is None:
786 if sig is None:
783 return []
787 return []
784 # iterable[, key=func]' -> ['iterable[' ,' key=func]']
788 # iterable[, key=func]' -> ['iterable[' ,' key=func]']
785 sig = sig.groups()[0].split(',')
789 sig = sig.groups()[0].split(',')
786 ret = []
790 ret = []
787 for s in sig:
791 for s in sig:
788 #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
792 #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
789 ret += self.docstring_kwd_re.findall(s)
793 ret += self.docstring_kwd_re.findall(s)
790 return ret
794 return ret
791
795
792 def _default_arguments(self, obj):
796 def _default_arguments(self, obj):
793 """Return the list of default arguments of obj if it is callable,
797 """Return the list of default arguments of obj if it is callable,
794 or empty list otherwise."""
798 or empty list otherwise."""
795 call_obj = obj
799 call_obj = obj
796 ret = []
800 ret = []
797 if inspect.isbuiltin(obj):
801 if inspect.isbuiltin(obj):
798 pass
802 pass
799 elif not (inspect.isfunction(obj) or inspect.ismethod(obj)):
803 elif not (inspect.isfunction(obj) or inspect.ismethod(obj)):
800 if inspect.isclass(obj):
804 if inspect.isclass(obj):
801 #for cython embededsignature=True the constructor docstring
805 #for cython embededsignature=True the constructor docstring
802 #belongs to the object itself not __init__
806 #belongs to the object itself not __init__
803 ret += self._default_arguments_from_docstring(
807 ret += self._default_arguments_from_docstring(
804 getattr(obj, '__doc__', ''))
808 getattr(obj, '__doc__', ''))
805 # for classes, check for __init__,__new__
809 # for classes, check for __init__,__new__
806 call_obj = (getattr(obj, '__init__', None) or
810 call_obj = (getattr(obj, '__init__', None) or
807 getattr(obj, '__new__', None))
811 getattr(obj, '__new__', None))
808 # for all others, check if they are __call__able
812 # for all others, check if they are __call__able
809 elif hasattr(obj, '__call__'):
813 elif hasattr(obj, '__call__'):
810 call_obj = obj.__call__
814 call_obj = obj.__call__
811 ret += self._default_arguments_from_docstring(
815 ret += self._default_arguments_from_docstring(
812 getattr(call_obj, '__doc__', ''))
816 getattr(call_obj, '__doc__', ''))
813
817
814 if PY3:
818 if PY3:
815 _keeps = (inspect.Parameter.KEYWORD_ONLY,
819 _keeps = (inspect.Parameter.KEYWORD_ONLY,
816 inspect.Parameter.POSITIONAL_OR_KEYWORD)
820 inspect.Parameter.POSITIONAL_OR_KEYWORD)
817 signature = inspect.signature
821 signature = inspect.signature
818 else:
822 else:
819 import IPython.utils.signatures
823 import IPython.utils.signatures
820 _keeps = (IPython.utils.signatures.Parameter.KEYWORD_ONLY,
824 _keeps = (IPython.utils.signatures.Parameter.KEYWORD_ONLY,
821 IPython.utils.signatures.Parameter.POSITIONAL_OR_KEYWORD)
825 IPython.utils.signatures.Parameter.POSITIONAL_OR_KEYWORD)
822 signature = IPython.utils.signatures.signature
826 signature = IPython.utils.signatures.signature
823
827
824 try:
828 try:
825 sig = signature(call_obj)
829 sig = signature(call_obj)
826 ret.extend(k for k, v in sig.parameters.items() if
830 ret.extend(k for k, v in sig.parameters.items() if
827 v.kind in _keeps)
831 v.kind in _keeps)
828 except ValueError:
832 except ValueError:
829 pass
833 pass
830
834
831 return list(set(ret))
835 return list(set(ret))
832
836
833 def python_func_kw_matches(self,text):
837 def python_func_kw_matches(self,text):
834 """Match named parameters (kwargs) of the last open function"""
838 """Match named parameters (kwargs) of the last open function"""
835
839
836 if "." in text: # a parameter cannot be dotted
840 if "." in text: # a parameter cannot be dotted
837 return []
841 return []
838 try: regexp = self.__funcParamsRegex
842 try: regexp = self.__funcParamsRegex
839 except AttributeError:
843 except AttributeError:
840 regexp = self.__funcParamsRegex = re.compile(r'''
844 regexp = self.__funcParamsRegex = re.compile(r'''
841 '.*?(?<!\\)' | # single quoted strings or
845 '.*?(?<!\\)' | # single quoted strings or
842 ".*?(?<!\\)" | # double quoted strings or
846 ".*?(?<!\\)" | # double quoted strings or
843 \w+ | # identifier
847 \w+ | # identifier
844 \S # other characters
848 \S # other characters
845 ''', re.VERBOSE | re.DOTALL)
849 ''', re.VERBOSE | re.DOTALL)
846 # 1. find the nearest identifier that comes before an unclosed
850 # 1. find the nearest identifier that comes before an unclosed
847 # parenthesis before the cursor
851 # parenthesis before the cursor
848 # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo"
852 # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo"
849 tokens = regexp.findall(self.text_until_cursor)
853 tokens = regexp.findall(self.text_until_cursor)
850 tokens.reverse()
854 tokens.reverse()
851 iterTokens = iter(tokens); openPar = 0
855 iterTokens = iter(tokens); openPar = 0
852
856
853 for token in iterTokens:
857 for token in iterTokens:
854 if token == ')':
858 if token == ')':
855 openPar -= 1
859 openPar -= 1
856 elif token == '(':
860 elif token == '(':
857 openPar += 1
861 openPar += 1
858 if openPar > 0:
862 if openPar > 0:
859 # found the last unclosed parenthesis
863 # found the last unclosed parenthesis
860 break
864 break
861 else:
865 else:
862 return []
866 return []
863 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
867 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
864 ids = []
868 ids = []
865 isId = re.compile(r'\w+$').match
869 isId = re.compile(r'\w+$').match
866
870
867 while True:
871 while True:
868 try:
872 try:
869 ids.append(next(iterTokens))
873 ids.append(next(iterTokens))
870 if not isId(ids[-1]):
874 if not isId(ids[-1]):
871 ids.pop(); break
875 ids.pop(); break
872 if not next(iterTokens) == '.':
876 if not next(iterTokens) == '.':
873 break
877 break
874 except StopIteration:
878 except StopIteration:
875 break
879 break
876 # lookup the candidate callable matches either using global_matches
880 # lookup the candidate callable matches either using global_matches
877 # or attr_matches for dotted names
881 # or attr_matches for dotted names
878 if len(ids) == 1:
882 if len(ids) == 1:
879 callableMatches = self.global_matches(ids[0])
883 callableMatches = self.global_matches(ids[0])
880 else:
884 else:
881 callableMatches = self.attr_matches('.'.join(ids[::-1]))
885 callableMatches = self.attr_matches('.'.join(ids[::-1]))
882 argMatches = []
886 argMatches = []
883 for callableMatch in callableMatches:
887 for callableMatch in callableMatches:
884 try:
888 try:
885 namedArgs = self._default_arguments(eval(callableMatch,
889 namedArgs = self._default_arguments(eval(callableMatch,
886 self.namespace))
890 self.namespace))
887 except:
891 except:
888 continue
892 continue
889
893
890 for namedArg in namedArgs:
894 for namedArg in namedArgs:
891 if namedArg.startswith(text):
895 if namedArg.startswith(text):
892 argMatches.append(u"%s=" %namedArg)
896 argMatches.append(u"%s=" %namedArg)
893 return argMatches
897 return argMatches
894
898
895 def dict_key_matches(self, text):
899 def dict_key_matches(self, text):
896 "Match string keys in a dictionary, after e.g. 'foo[' "
900 "Match string keys in a dictionary, after e.g. 'foo[' "
897 def get_keys(obj):
901 def get_keys(obj):
898 # Objects can define their own completions by defining an
902 # Objects can define their own completions by defining an
899 # _ipy_key_completions_() method.
903 # _ipy_key_completions_() method.
900 method = get_real_method(obj, '_ipython_key_completions_')
904 method = get_real_method(obj, '_ipython_key_completions_')
901 if method is not None:
905 if method is not None:
902 return method()
906 return method()
903
907
904 # Special case some common in-memory dict-like types
908 # Special case some common in-memory dict-like types
905 if isinstance(obj, dict) or\
909 if isinstance(obj, dict) or\
906 _safe_isinstance(obj, 'pandas', 'DataFrame'):
910 _safe_isinstance(obj, 'pandas', 'DataFrame'):
907 try:
911 try:
908 return list(obj.keys())
912 return list(obj.keys())
909 except Exception:
913 except Exception:
910 return []
914 return []
911 elif _safe_isinstance(obj, 'numpy', 'ndarray') or\
915 elif _safe_isinstance(obj, 'numpy', 'ndarray') or\
912 _safe_isinstance(obj, 'numpy', 'void'):
916 _safe_isinstance(obj, 'numpy', 'void'):
913 return obj.dtype.names or []
917 return obj.dtype.names or []
914 return []
918 return []
915
919
916 try:
920 try:
917 regexps = self.__dict_key_regexps
921 regexps = self.__dict_key_regexps
918 except AttributeError:
922 except AttributeError:
919 dict_key_re_fmt = r'''(?x)
923 dict_key_re_fmt = r'''(?x)
920 ( # match dict-referring expression wrt greedy setting
924 ( # match dict-referring expression wrt greedy setting
921 %s
925 %s
922 )
926 )
923 \[ # open bracket
927 \[ # open bracket
924 \s* # and optional whitespace
928 \s* # and optional whitespace
925 ([uUbB]? # string prefix (r not handled)
929 ([uUbB]? # string prefix (r not handled)
926 (?: # unclosed string
930 (?: # unclosed string
927 '(?:[^']|(?<!\\)\\')*
931 '(?:[^']|(?<!\\)\\')*
928 |
932 |
929 "(?:[^"]|(?<!\\)\\")*
933 "(?:[^"]|(?<!\\)\\")*
930 )
934 )
931 )?
935 )?
932 $
936 $
933 '''
937 '''
934 regexps = self.__dict_key_regexps = {
938 regexps = self.__dict_key_regexps = {
935 False: re.compile(dict_key_re_fmt % '''
939 False: re.compile(dict_key_re_fmt % '''
936 # identifiers separated by .
940 # identifiers separated by .
937 (?!\d)\w+
941 (?!\d)\w+
938 (?:\.(?!\d)\w+)*
942 (?:\.(?!\d)\w+)*
939 '''),
943 '''),
940 True: re.compile(dict_key_re_fmt % '''
944 True: re.compile(dict_key_re_fmt % '''
941 .+
945 .+
942 ''')
946 ''')
943 }
947 }
944
948
945 match = regexps[self.greedy].search(self.text_until_cursor)
949 match = regexps[self.greedy].search(self.text_until_cursor)
946 if match is None:
950 if match is None:
947 return []
951 return []
948
952
949 expr, prefix = match.groups()
953 expr, prefix = match.groups()
950 try:
954 try:
951 obj = eval(expr, self.namespace)
955 obj = eval(expr, self.namespace)
952 except Exception:
956 except Exception:
953 try:
957 try:
954 obj = eval(expr, self.global_namespace)
958 obj = eval(expr, self.global_namespace)
955 except Exception:
959 except Exception:
956 return []
960 return []
957
961
958 keys = get_keys(obj)
962 keys = get_keys(obj)
959 if not keys:
963 if not keys:
960 return keys
964 return keys
961 closing_quote, token_offset, matches = match_dict_keys(keys, prefix, self.splitter.delims)
965 closing_quote, token_offset, matches = match_dict_keys(keys, prefix, self.splitter.delims)
962 if not matches:
966 if not matches:
963 return matches
967 return matches
964
968
965 # get the cursor position of
969 # get the cursor position of
966 # - the text being completed
970 # - the text being completed
967 # - the start of the key text
971 # - the start of the key text
968 # - the start of the completion
972 # - the start of the completion
969 text_start = len(self.text_until_cursor) - len(text)
973 text_start = len(self.text_until_cursor) - len(text)
970 if prefix:
974 if prefix:
971 key_start = match.start(2)
975 key_start = match.start(2)
972 completion_start = key_start + token_offset
976 completion_start = key_start + token_offset
973 else:
977 else:
974 key_start = completion_start = match.end()
978 key_start = completion_start = match.end()
975
979
976 # grab the leading prefix, to make sure all completions start with `text`
980 # grab the leading prefix, to make sure all completions start with `text`
977 if text_start > key_start:
981 if text_start > key_start:
978 leading = ''
982 leading = ''
979 else:
983 else:
980 leading = text[text_start:completion_start]
984 leading = text[text_start:completion_start]
981
985
982 # the index of the `[` character
986 # the index of the `[` character
983 bracket_idx = match.end(1)
987 bracket_idx = match.end(1)
984
988
985 # append closing quote and bracket as appropriate
989 # append closing quote and bracket as appropriate
986 # this is *not* appropriate if the opening quote or bracket is outside
990 # this is *not* appropriate if the opening quote or bracket is outside
987 # the text given to this method
991 # the text given to this method
988 suf = ''
992 suf = ''
989 continuation = self.line_buffer[len(self.text_until_cursor):]
993 continuation = self.line_buffer[len(self.text_until_cursor):]
990 if key_start > text_start and closing_quote:
994 if key_start > text_start and closing_quote:
991 # quotes were opened inside text, maybe close them
995 # quotes were opened inside text, maybe close them
992 if continuation.startswith(closing_quote):
996 if continuation.startswith(closing_quote):
993 continuation = continuation[len(closing_quote):]
997 continuation = continuation[len(closing_quote):]
994 else:
998 else:
995 suf += closing_quote
999 suf += closing_quote
996 if bracket_idx > text_start:
1000 if bracket_idx > text_start:
997 # brackets were opened inside text, maybe close them
1001 # brackets were opened inside text, maybe close them
998 if not continuation.startswith(']'):
1002 if not continuation.startswith(']'):
999 suf += ']'
1003 suf += ']'
1000
1004
1001 return [leading + k + suf for k in matches]
1005 return [leading + k + suf for k in matches]
1002
1006
1003 def unicode_name_matches(self, text):
1007 def unicode_name_matches(self, text):
1004 u"""Match Latex-like syntax for unicode characters base
1008 u"""Match Latex-like syntax for unicode characters base
1005 on the name of the character.
1009 on the name of the character.
1006
1010
1007 This does \\GREEK SMALL LETTER ETA -> Ξ·
1011 This does \\GREEK SMALL LETTER ETA -> Ξ·
1008
1012
1009 Works only on valid python 3 identifier, or on combining characters that
1013 Works only on valid python 3 identifier, or on combining characters that
1010 will combine to form a valid identifier.
1014 will combine to form a valid identifier.
1011
1015
1012 Used on Python 3 only.
1016 Used on Python 3 only.
1013 """
1017 """
1014 slashpos = text.rfind('\\')
1018 slashpos = text.rfind('\\')
1015 if slashpos > -1:
1019 if slashpos > -1:
1016 s = text[slashpos+1:]
1020 s = text[slashpos+1:]
1017 try :
1021 try :
1018 unic = unicodedata.lookup(s)
1022 unic = unicodedata.lookup(s)
1019 # allow combining chars
1023 # allow combining chars
1020 if ('a'+unic).isidentifier():
1024 if ('a'+unic).isidentifier():
1021 return '\\'+s,[unic]
1025 return '\\'+s,[unic]
1022 except KeyError:
1026 except KeyError:
1023 pass
1027 pass
1024 return u'', []
1028 return u'', []
1025
1029
1026
1030
1027
1031
1028
1032
1029 def latex_matches(self, text):
1033 def latex_matches(self, text):
1030 u"""Match Latex syntax for unicode characters.
1034 u"""Match Latex syntax for unicode characters.
1031
1035
1032 This does both \\alp -> \\alpha and \\alpha -> Ξ±
1036 This does both \\alp -> \\alpha and \\alpha -> Ξ±
1033
1037
1034 Used on Python 3 only.
1038 Used on Python 3 only.
1035 """
1039 """
1036 slashpos = text.rfind('\\')
1040 slashpos = text.rfind('\\')
1037 if slashpos > -1:
1041 if slashpos > -1:
1038 s = text[slashpos:]
1042 s = text[slashpos:]
1039 if s in latex_symbols:
1043 if s in latex_symbols:
1040 # Try to complete a full latex symbol to unicode
1044 # Try to complete a full latex symbol to unicode
1041 # \\alpha -> Ξ±
1045 # \\alpha -> Ξ±
1042 return s, [latex_symbols[s]]
1046 return s, [latex_symbols[s]]
1043 else:
1047 else:
1044 # If a user has partially typed a latex symbol, give them
1048 # If a user has partially typed a latex symbol, give them
1045 # a full list of options \al -> [\aleph, \alpha]
1049 # a full list of options \al -> [\aleph, \alpha]
1046 matches = [k for k in latex_symbols if k.startswith(s)]
1050 matches = [k for k in latex_symbols if k.startswith(s)]
1047 return s, matches
1051 return s, matches
1048 return u'', []
1052 return u'', []
1049
1053
1050 def dispatch_custom_completer(self, text):
1054 def dispatch_custom_completer(self, text):
1051 if not self.custom_completers:
1055 if not self.custom_completers:
1052 return
1056 return
1053
1057
1054 line = self.line_buffer
1058 line = self.line_buffer
1055 if not line.strip():
1059 if not line.strip():
1056 return None
1060 return None
1057
1061
1058 # Create a little structure to pass all the relevant information about
1062 # Create a little structure to pass all the relevant information about
1059 # the current completion to any custom completer.
1063 # the current completion to any custom completer.
1060 event = Bunch()
1064 event = Bunch()
1061 event.line = line
1065 event.line = line
1062 event.symbol = text
1066 event.symbol = text
1063 cmd = line.split(None,1)[0]
1067 cmd = line.split(None,1)[0]
1064 event.command = cmd
1068 event.command = cmd
1065 event.text_until_cursor = self.text_until_cursor
1069 event.text_until_cursor = self.text_until_cursor
1066
1070
1067 # for foo etc, try also to find completer for %foo
1071 # for foo etc, try also to find completer for %foo
1068 if not cmd.startswith(self.magic_escape):
1072 if not cmd.startswith(self.magic_escape):
1069 try_magic = self.custom_completers.s_matches(
1073 try_magic = self.custom_completers.s_matches(
1070 self.magic_escape + cmd)
1074 self.magic_escape + cmd)
1071 else:
1075 else:
1072 try_magic = []
1076 try_magic = []
1073
1077
1074 for c in itertools.chain(self.custom_completers.s_matches(cmd),
1078 for c in itertools.chain(self.custom_completers.s_matches(cmd),
1075 try_magic,
1079 try_magic,
1076 self.custom_completers.flat_matches(self.text_until_cursor)):
1080 self.custom_completers.flat_matches(self.text_until_cursor)):
1077 try:
1081 try:
1078 res = c(event)
1082 res = c(event)
1079 if res:
1083 if res:
1080 # first, try case sensitive match
1084 # first, try case sensitive match
1081 withcase = [cast_unicode_py2(r) for r in res if r.startswith(text)]
1085 withcase = [cast_unicode_py2(r) for r in res if r.startswith(text)]
1082 if withcase:
1086 if withcase:
1083 return withcase
1087 return withcase
1084 # if none, then case insensitive ones are ok too
1088 # if none, then case insensitive ones are ok too
1085 text_low = text.lower()
1089 text_low = text.lower()
1086 return [cast_unicode_py2(r) for r in res if r.lower().startswith(text_low)]
1090 return [cast_unicode_py2(r) for r in res if r.lower().startswith(text_low)]
1087 except TryNext:
1091 except TryNext:
1088 pass
1092 pass
1089
1093
1090 return None
1094 return None
1091
1095
1092 def complete(self, text=None, line_buffer=None, cursor_pos=None):
1096 def complete(self, text=None, line_buffer=None, cursor_pos=None):
1093 """Find completions for the given text and line context.
1097 """Find completions for the given text and line context.
1094
1098
1095 Note that both the text and the line_buffer are optional, but at least
1099 Note that both the text and the line_buffer are optional, but at least
1096 one of them must be given.
1100 one of them must be given.
1097
1101
1098 Parameters
1102 Parameters
1099 ----------
1103 ----------
1100 text : string, optional
1104 text : string, optional
1101 Text to perform the completion on. If not given, the line buffer
1105 Text to perform the completion on. If not given, the line buffer
1102 is split using the instance's CompletionSplitter object.
1106 is split using the instance's CompletionSplitter object.
1103
1107
1104 line_buffer : string, optional
1108 line_buffer : string, optional
1105 If not given, the completer attempts to obtain the current line
1109 If not given, the completer attempts to obtain the current line
1106 buffer via readline. This keyword allows clients which are
1110 buffer via readline. This keyword allows clients which are
1107 requesting for text completions in non-readline contexts to inform
1111 requesting for text completions in non-readline contexts to inform
1108 the completer of the entire text.
1112 the completer of the entire text.
1109
1113
1110 cursor_pos : int, optional
1114 cursor_pos : int, optional
1111 Index of the cursor in the full line buffer. Should be provided by
1115 Index of the cursor in the full line buffer. Should be provided by
1112 remote frontends where kernel has no access to frontend state.
1116 remote frontends where kernel has no access to frontend state.
1113
1117
1114 Returns
1118 Returns
1115 -------
1119 -------
1116 text : str
1120 text : str
1117 Text that was actually used in the completion.
1121 Text that was actually used in the completion.
1118
1122
1119 matches : list
1123 matches : list
1120 A list of completion matches.
1124 A list of completion matches.
1121 """
1125 """
1122 # if the cursor position isn't given, the only sane assumption we can
1126 # if the cursor position isn't given, the only sane assumption we can
1123 # make is that it's at the end of the line (the common case)
1127 # make is that it's at the end of the line (the common case)
1124 if cursor_pos is None:
1128 if cursor_pos is None:
1125 cursor_pos = len(line_buffer) if text is None else len(text)
1129 cursor_pos = len(line_buffer) if text is None else len(text)
1126
1130
1127 if self.use_main_ns:
1131 if self.use_main_ns:
1128 self.namespace = __main__.__dict__
1132 self.namespace = __main__.__dict__
1129
1133
1130 if PY3:
1134 if PY3 and self.backslash_combining_completions:
1131
1135
1132 base_text = text if not line_buffer else line_buffer[:cursor_pos]
1136 base_text = text if not line_buffer else line_buffer[:cursor_pos]
1133 latex_text, latex_matches = self.latex_matches(base_text)
1137 latex_text, latex_matches = self.latex_matches(base_text)
1134 if latex_matches:
1138 if latex_matches:
1135 return latex_text, latex_matches
1139 return latex_text, latex_matches
1136 name_text = ''
1140 name_text = ''
1137 name_matches = []
1141 name_matches = []
1138 for meth in (self.unicode_name_matches, back_latex_name_matches, back_unicode_name_matches):
1142 for meth in (self.unicode_name_matches, back_latex_name_matches, back_unicode_name_matches):
1139 name_text, name_matches = meth(base_text)
1143 name_text, name_matches = meth(base_text)
1140 if name_text:
1144 if name_text:
1141 return name_text, name_matches
1145 return name_text, name_matches
1142
1146
1143 # if text is either None or an empty string, rely on the line buffer
1147 # if text is either None or an empty string, rely on the line buffer
1144 if not text:
1148 if not text:
1145 text = self.splitter.split_line(line_buffer, cursor_pos)
1149 text = self.splitter.split_line(line_buffer, cursor_pos)
1146
1150
1147 # If no line buffer is given, assume the input text is all there was
1151 # If no line buffer is given, assume the input text is all there was
1148 if line_buffer is None:
1152 if line_buffer is None:
1149 line_buffer = text
1153 line_buffer = text
1150
1154
1151 self.line_buffer = line_buffer
1155 self.line_buffer = line_buffer
1152 self.text_until_cursor = self.line_buffer[:cursor_pos]
1156 self.text_until_cursor = self.line_buffer[:cursor_pos]
1153
1157
1154 # Start with a clean slate of completions
1158 # Start with a clean slate of completions
1155 self.matches[:] = []
1159 self.matches[:] = []
1156 custom_res = self.dispatch_custom_completer(text)
1160 custom_res = self.dispatch_custom_completer(text)
1157 if custom_res is not None:
1161 if custom_res is not None:
1158 # did custom completers produce something?
1162 # did custom completers produce something?
1159 self.matches = custom_res
1163 self.matches = custom_res
1160 else:
1164 else:
1161 # Extend the list of completions with the results of each
1165 # Extend the list of completions with the results of each
1162 # matcher, so we return results to the user from all
1166 # matcher, so we return results to the user from all
1163 # namespaces.
1167 # namespaces.
1164 if self.merge_completions:
1168 if self.merge_completions:
1165 self.matches = []
1169 self.matches = []
1166 for matcher in self.matchers:
1170 for matcher in self.matchers:
1167 try:
1171 try:
1168 self.matches.extend(matcher(text))
1172 self.matches.extend(matcher(text))
1169 except:
1173 except:
1170 # Show the ugly traceback if the matcher causes an
1174 # Show the ugly traceback if the matcher causes an
1171 # exception, but do NOT crash the kernel!
1175 # exception, but do NOT crash the kernel!
1172 sys.excepthook(*sys.exc_info())
1176 sys.excepthook(*sys.exc_info())
1173 else:
1177 else:
1174 for matcher in self.matchers:
1178 for matcher in self.matchers:
1175 self.matches = matcher(text)
1179 self.matches = matcher(text)
1176 if self.matches:
1180 if self.matches:
1177 break
1181 break
1178 # FIXME: we should extend our api to return a dict with completions for
1182 # FIXME: we should extend our api to return a dict with completions for
1179 # different types of objects. The rlcomplete() method could then
1183 # different types of objects. The rlcomplete() method could then
1180 # simply collapse the dict into a list for readline, but we'd have
1184 # simply collapse the dict into a list for readline, but we'd have
1181 # richer completion semantics in other evironments.
1185 # richer completion semantics in other evironments.
1182 self.matches = sorted(set(self.matches), key=completions_sorting_key)
1186 self.matches = sorted(set(self.matches), key=completions_sorting_key)
1183
1187
1184 return text, self.matches
1188 return text, self.matches
@@ -1,298 +1,302
1 ============
1 ============
2 5.x Series
2 5.x Series
3 ============
3 ============
4
4
5 IPython 5.4
5 IPython 5.4
6 ===========
6 ===========
7
7
8 Configurable TerminalInteractiveShell
8 Configurable TerminalInteractiveShell
9 -------------------------------------
9 -------------------------------------
10
10
11 Backported from the 6.x branch as an exceptional new feature. See
11 Backported from the 6.x branch as an exceptional new feature. See
12 :ghpull:`10373` and :ghissue:`10364`
12 :ghpull:`10373` and :ghissue:`10364`
13
13
14 IPython gained a new ``c.TerminalIPythonApp.interactive_shell_class`` option
14 IPython gained a new ``c.TerminalIPythonApp.interactive_shell_class`` option
15 that allow to customize the class used to start the terminal frontend. This
15 that allow to customize the class used to start the terminal frontend. This
16 should allow user to use custom interfaces, like reviving the former readline
16 should allow user to use custom interfaces, like reviving the former readline
17 interface which is now a separate package not maintained by the core team.
17 interface which is now a separate package not maintained by the core team.
18
18
19
20 * added ``Completer.backslash_combining_completions`` boolean option to
21 deactivate backslash-tab completion that may conflict with windows path.
22
19 IPython 5.3
23 IPython 5.3
20 ===========
24 ===========
21
25
22 Released on February 24th, 2017. Remarkable changes and fixes:
26 Released on February 24th, 2017. Remarkable changes and fixes:
23
27
24 * Fix a bug in ``set_next_input`` leading to a crash of terminal IPython.
28 * Fix a bug in ``set_next_input`` leading to a crash of terminal IPython.
25 :ghpull:`10231`, :ghissue:`10296`, :ghissue:`10229`
29 :ghpull:`10231`, :ghissue:`10296`, :ghissue:`10229`
26 * Always wait for editor inputhook for terminal IPython :ghpull:`10239`,
30 * Always wait for editor inputhook for terminal IPython :ghpull:`10239`,
27 :ghpull:`10240`
31 :ghpull:`10240`
28 * Disable ``_ipython_display_`` in terminal :ghpull:`10249`, :ghpull:`10274`
32 * Disable ``_ipython_display_`` in terminal :ghpull:`10249`, :ghpull:`10274`
29 * Update terminal colors to be more visible by default on windows
33 * Update terminal colors to be more visible by default on windows
30 :ghpull:`10260`, :ghpull:`10238`, :ghissue:`10281`
34 :ghpull:`10260`, :ghpull:`10238`, :ghissue:`10281`
31 * Add Ctrl-Z shortcut (suspend) in terminal debugger :ghpull:`10254`,
35 * Add Ctrl-Z shortcut (suspend) in terminal debugger :ghpull:`10254`,
32 :ghissue:`10273`
36 :ghissue:`10273`
33 * Indent on new line by looking at the text before the cursor :ghpull:`10264`,
37 * Indent on new line by looking at the text before the cursor :ghpull:`10264`,
34 :ghpull:`10275`, :ghissue:`9283`
38 :ghpull:`10275`, :ghissue:`9283`
35 * Update QtEventloop integration to fix some matplotlib integration issues
39 * Update QtEventloop integration to fix some matplotlib integration issues
36 :ghpull:`10201`, :ghpull:`10311`, :ghissue:`10201`
40 :ghpull:`10201`, :ghpull:`10311`, :ghissue:`10201`
37 * Respect completions display style in terminal debugger :ghpull:`10305`,
41 * Respect completions display style in terminal debugger :ghpull:`10305`,
38 :ghpull:`10313`
42 :ghpull:`10313`
39 * Add a config option ``TerminalInteractiveShell.extra_open_editor_shortcuts``
43 * Add a config option ``TerminalInteractiveShell.extra_open_editor_shortcuts``
40 to enable extra shortcuts to open the input in an editor. These are :kbd:`v`
44 to enable extra shortcuts to open the input in an editor. These are :kbd:`v`
41 in vi mode, and :kbd:`C-X C-E` in emacs mode (:ghpull:`10330`).
45 in vi mode, and :kbd:`C-X C-E` in emacs mode (:ghpull:`10330`).
42 The :kbd:`F2` shortcut is always enabled.
46 The :kbd:`F2` shortcut is always enabled.
43
47
44 IPython 5.2.2
48 IPython 5.2.2
45 =============
49 =============
46
50
47 * Fix error when starting with ``IPCompleter.limit_to__all__`` configured.
51 * Fix error when starting with ``IPCompleter.limit_to__all__`` configured.
48
52
49 IPython 5.2.1
53 IPython 5.2.1
50 =============
54 =============
51
55
52 * Fix tab completion in the debugger. :ghpull:`10223`
56 * Fix tab completion in the debugger. :ghpull:`10223`
53
57
54 IPython 5.2
58 IPython 5.2
55 ===========
59 ===========
56
60
57 Released on January 29th, 2017. Remarkable changes and fixes:
61 Released on January 29th, 2017. Remarkable changes and fixes:
58
62
59 * restore IPython's debugger to raise on quit. :ghpull:`10009`
63 * restore IPython's debugger to raise on quit. :ghpull:`10009`
60 * The configuration value ``c.TerminalInteractiveShell.highlighting_style`` can
64 * The configuration value ``c.TerminalInteractiveShell.highlighting_style`` can
61 now directly take a class argument for custom color style. :ghpull:`9848`
65 now directly take a class argument for custom color style. :ghpull:`9848`
62 * Correctly handle matplotlib figures dpi :ghpull:`9868`
66 * Correctly handle matplotlib figures dpi :ghpull:`9868`
63 * Deprecate ``-e`` flag for the ``%notebook`` magic that had no effects.
67 * Deprecate ``-e`` flag for the ``%notebook`` magic that had no effects.
64 :ghpull:`9872`
68 :ghpull:`9872`
65 * You can now press F2 while typing at a terminal prompt to edit the contents
69 * You can now press F2 while typing at a terminal prompt to edit the contents
66 in your favourite terminal editor. Set the :envvar:`EDITOR` environment
70 in your favourite terminal editor. Set the :envvar:`EDITOR` environment
67 variable to pick which editor is used. :ghpull:`9929`
71 variable to pick which editor is used. :ghpull:`9929`
68 * sdists will now only be ``.tar.gz`` as per upstream PyPI requirements.
72 * sdists will now only be ``.tar.gz`` as per upstream PyPI requirements.
69 :ghpull:`9925`
73 :ghpull:`9925`
70 * :any:`IPython.core.debugger` have gained a ``set_trace()`` method for
74 * :any:`IPython.core.debugger` have gained a ``set_trace()`` method for
71 convenience. :ghpull:`9947`
75 convenience. :ghpull:`9947`
72 * The 'smart command mode' added to the debugger in 5.0 was removed, as more
76 * The 'smart command mode' added to the debugger in 5.0 was removed, as more
73 people preferred the previous behaviour. Therefore, debugger commands such as
77 people preferred the previous behaviour. Therefore, debugger commands such as
74 ``c`` will act as debugger commands even when ``c`` is defined as a variable.
78 ``c`` will act as debugger commands even when ``c`` is defined as a variable.
75 :ghpull:`10050`
79 :ghpull:`10050`
76 * Fixes OS X event loop issues at startup, :ghpull:`10150`
80 * Fixes OS X event loop issues at startup, :ghpull:`10150`
77 * Deprecate the ``%autoindent`` magic. :ghpull:`10176`
81 * Deprecate the ``%autoindent`` magic. :ghpull:`10176`
78 * Emit a :any:`DeprecationWarning` when setting the deprecated
82 * Emit a :any:`DeprecationWarning` when setting the deprecated
79 ``limit_to_all`` option of the completer. :ghpull:`10198`
83 ``limit_to_all`` option of the completer. :ghpull:`10198`
80 * The :cellmagic:`capture` magic can now capture the result of a cell (from an
84 * The :cellmagic:`capture` magic can now capture the result of a cell (from an
81 expression on the last line), as well as printed and displayed output.
85 expression on the last line), as well as printed and displayed output.
82 :ghpull:`9851`.
86 :ghpull:`9851`.
83
87
84
88
85 Changes of behavior to :any:`InteractiveShellEmbed`.
89 Changes of behavior to :any:`InteractiveShellEmbed`.
86
90
87 :any:`InteractiveShellEmbed` interactive behavior have changed a bit in between
91 :any:`InteractiveShellEmbed` interactive behavior have changed a bit in between
88 5.1 and 5.2. By default ``%kill_embedded`` magic will prevent further invocation
92 5.1 and 5.2. By default ``%kill_embedded`` magic will prevent further invocation
89 of the current ``call location`` instead of preventing further invocation of
93 of the current ``call location`` instead of preventing further invocation of
90 the current instance creation location. For most use case this will not change
94 the current instance creation location. For most use case this will not change
91 much for you, though previous behavior was confusing and less consistent with
95 much for you, though previous behavior was confusing and less consistent with
92 previous IPython versions.
96 previous IPython versions.
93
97
94 You can now deactivate instances by using ``%kill_embedded --instance`` flag,
98 You can now deactivate instances by using ``%kill_embedded --instance`` flag,
95 (or ``-i`` in short). The ``%kill_embedded`` magic also gained a
99 (or ``-i`` in short). The ``%kill_embedded`` magic also gained a
96 ``--yes``/``-y`` option which skip confirmation step, and ``-x``/``--exit``
100 ``--yes``/``-y`` option which skip confirmation step, and ``-x``/``--exit``
97 which also exit the current embedded call without asking for confirmation.
101 which also exit the current embedded call without asking for confirmation.
98
102
99 See :ghpull:`10207`.
103 See :ghpull:`10207`.
100
104
101
105
102
106
103 IPython 5.1
107 IPython 5.1
104 ===========
108 ===========
105
109
106 * Broken ``%timeit`` on Python2 due to the use of ``__qualname__``. :ghpull:`9804`
110 * Broken ``%timeit`` on Python2 due to the use of ``__qualname__``. :ghpull:`9804`
107 * Restore ``%gui qt`` to create and return a ``QApplication`` if necessary. :ghpull:`9789`
111 * Restore ``%gui qt`` to create and return a ``QApplication`` if necessary. :ghpull:`9789`
108 * Don't set terminal title by default. :ghpull:`9801`
112 * Don't set terminal title by default. :ghpull:`9801`
109 * Preserve indentation when inserting newlines with ``Ctrl-O``. :ghpull:`9770`
113 * Preserve indentation when inserting newlines with ``Ctrl-O``. :ghpull:`9770`
110 * Restore completion in debugger. :ghpull:`9785`
114 * Restore completion in debugger. :ghpull:`9785`
111 * Deprecate ``IPython.core.debugger.Tracer()`` in favor of simpler, newer, APIs. :ghpull:`9731`
115 * Deprecate ``IPython.core.debugger.Tracer()`` in favor of simpler, newer, APIs. :ghpull:`9731`
112 * Restore ``NoOpContext`` context manager removed by mistake, and add `DeprecationWarning`. :ghpull:`9765`
116 * Restore ``NoOpContext`` context manager removed by mistake, and add `DeprecationWarning`. :ghpull:`9765`
113 * Add option allowing ``Prompt_toolkit`` to use 24bits colors. :ghpull:`9736`
117 * Add option allowing ``Prompt_toolkit`` to use 24bits colors. :ghpull:`9736`
114 * Fix for closing interactive matplotlib windows on OS X. :ghpull:`9854`
118 * Fix for closing interactive matplotlib windows on OS X. :ghpull:`9854`
115 * An embedded interactive shell instance can be used more than once. :ghpull:`9843`
119 * An embedded interactive shell instance can be used more than once. :ghpull:`9843`
116 * More robust check for whether IPython is in a terminal. :ghpull:`9833`
120 * More robust check for whether IPython is in a terminal. :ghpull:`9833`
117 * Better pretty-printing of dicts on PyPy. :ghpull:`9827`
121 * Better pretty-printing of dicts on PyPy. :ghpull:`9827`
118 * Some coloured output now looks better on dark background command prompts in Windows.
122 * Some coloured output now looks better on dark background command prompts in Windows.
119 :ghpull:`9838`
123 :ghpull:`9838`
120 * Improved tab completion of paths on Windows . :ghpull:`9826`
124 * Improved tab completion of paths on Windows . :ghpull:`9826`
121 * Fix tkinter event loop integration on Python 2 with ``future`` installed. :ghpull:`9824`
125 * Fix tkinter event loop integration on Python 2 with ``future`` installed. :ghpull:`9824`
122 * Restore ``Ctrl-\`` as a shortcut to quit IPython.
126 * Restore ``Ctrl-\`` as a shortcut to quit IPython.
123 * Make ``get_ipython()`` accessible when modules are imported by startup files. :ghpull:`9818`
127 * Make ``get_ipython()`` accessible when modules are imported by startup files. :ghpull:`9818`
124 * Add support for running directories containing a ``__main__.py`` file with the
128 * Add support for running directories containing a ``__main__.py`` file with the
125 ``ipython`` command. :ghpull:`9813`
129 ``ipython`` command. :ghpull:`9813`
126
130
127
131
128 True Color feature
132 True Color feature
129 ------------------
133 ------------------
130
134
131 ``prompt_toolkit`` uses pygments styles for syntax highlighting. By default, the
135 ``prompt_toolkit`` uses pygments styles for syntax highlighting. By default, the
132 colors specified in the style are approximated using a standard 256-color
136 colors specified in the style are approximated using a standard 256-color
133 palette. ``prompt_toolkit`` also supports 24bit, a.k.a. "true", a.k.a. 16-million
137 palette. ``prompt_toolkit`` also supports 24bit, a.k.a. "true", a.k.a. 16-million
134 color escape sequences which enable compatible terminals to display the exact
138 color escape sequences which enable compatible terminals to display the exact
135 colors specified instead of an approximation. This true_color option exposes
139 colors specified instead of an approximation. This true_color option exposes
136 that capability in prompt_toolkit to the IPython shell.
140 that capability in prompt_toolkit to the IPython shell.
137
141
138 Here is a good source for the current state of true color support in various
142 Here is a good source for the current state of true color support in various
139 terminal emulators and software projects: https://gist.github.com/XVilka/8346728
143 terminal emulators and software projects: https://gist.github.com/XVilka/8346728
140
144
141
145
142
146
143 IPython 5.0
147 IPython 5.0
144 ===========
148 ===========
145
149
146 Released July 7, 2016
150 Released July 7, 2016
147
151
148 New terminal interface
152 New terminal interface
149 ----------------------
153 ----------------------
150
154
151 IPython 5 features a major upgrade to the terminal interface, bringing live
155 IPython 5 features a major upgrade to the terminal interface, bringing live
152 syntax highlighting as you type, proper multiline editing and multiline paste,
156 syntax highlighting as you type, proper multiline editing and multiline paste,
153 and tab completions that don't clutter up your history.
157 and tab completions that don't clutter up your history.
154
158
155 .. image:: ../_images/ptshell_features.png
159 .. image:: ../_images/ptshell_features.png
156 :alt: New terminal interface features
160 :alt: New terminal interface features
157 :align: center
161 :align: center
158 :target: ../_images/ptshell_features.png
162 :target: ../_images/ptshell_features.png
159
163
160 These features are provided by the Python library `prompt_toolkit
164 These features are provided by the Python library `prompt_toolkit
161 <http://python-prompt-toolkit.readthedocs.io/en/stable/>`__, which replaces
165 <http://python-prompt-toolkit.readthedocs.io/en/stable/>`__, which replaces
162 ``readline`` throughout our terminal interface.
166 ``readline`` throughout our terminal interface.
163
167
164 Relying on this pure-Python, cross platform module also makes it simpler to
168 Relying on this pure-Python, cross platform module also makes it simpler to
165 install IPython. We have removed dependencies on ``pyreadline`` for Windows and
169 install IPython. We have removed dependencies on ``pyreadline`` for Windows and
166 ``gnureadline`` for Mac.
170 ``gnureadline`` for Mac.
167
171
168 Backwards incompatible changes
172 Backwards incompatible changes
169 ------------------------------
173 ------------------------------
170
174
171 - The ``%install_ext`` magic function, deprecated since 4.0, has now been deleted.
175 - The ``%install_ext`` magic function, deprecated since 4.0, has now been deleted.
172 You can distribute and install extensions as packages on PyPI.
176 You can distribute and install extensions as packages on PyPI.
173 - Callbacks registered while an event is being handled will now only be called
177 - Callbacks registered while an event is being handled will now only be called
174 for subsequent events; previously they could be called for the current event.
178 for subsequent events; previously they could be called for the current event.
175 Similarly, callbacks removed while handling an event *will* always get that
179 Similarly, callbacks removed while handling an event *will* always get that
176 event. See :ghissue:`9447` and :ghpull:`9453`.
180 event. See :ghissue:`9447` and :ghpull:`9453`.
177 - Integration with pydb has been removed since pydb development has been stopped
181 - Integration with pydb has been removed since pydb development has been stopped
178 since 2012, and pydb is not installable from PyPI.
182 since 2012, and pydb is not installable from PyPI.
179 - The ``autoedit_syntax`` option has apparently been broken for many years.
183 - The ``autoedit_syntax`` option has apparently been broken for many years.
180 It has been removed.
184 It has been removed.
181
185
182 New terminal interface
186 New terminal interface
183 ~~~~~~~~~~~~~~~~~~~~~~
187 ~~~~~~~~~~~~~~~~~~~~~~
184
188
185 The overhaul of the terminal interface will probably cause a range of minor
189 The overhaul of the terminal interface will probably cause a range of minor
186 issues for existing users.
190 issues for existing users.
187 This is inevitable for such a significant change, and we've done our best to
191 This is inevitable for such a significant change, and we've done our best to
188 minimise these issues.
192 minimise these issues.
189 Some changes that we're aware of, with suggestions on how to handle them:
193 Some changes that we're aware of, with suggestions on how to handle them:
190
194
191 IPython no longer uses readline configuration (``~/.inputrc``). We hope that
195 IPython no longer uses readline configuration (``~/.inputrc``). We hope that
192 the functionality you want (e.g. vi input mode) will be available by configuring
196 the functionality you want (e.g. vi input mode) will be available by configuring
193 IPython directly (see :doc:`/config/options/terminal`).
197 IPython directly (see :doc:`/config/options/terminal`).
194 If something's missing, please file an issue.
198 If something's missing, please file an issue.
195
199
196 The ``PromptManager`` class has been removed, and the prompt machinery simplified.
200 The ``PromptManager`` class has been removed, and the prompt machinery simplified.
197 See :ref:`custom_prompts` to customise prompts with the new machinery.
201 See :ref:`custom_prompts` to customise prompts with the new machinery.
198
202
199 :mod:`IPython.core.debugger` now provides a plainer interface.
203 :mod:`IPython.core.debugger` now provides a plainer interface.
200 :mod:`IPython.terminal.debugger` contains the terminal debugger using
204 :mod:`IPython.terminal.debugger` contains the terminal debugger using
201 prompt_toolkit.
205 prompt_toolkit.
202
206
203 There are new options to configure the colours used in syntax highlighting.
207 There are new options to configure the colours used in syntax highlighting.
204 We have tried to integrate them with our classic ``--colors`` option and
208 We have tried to integrate them with our classic ``--colors`` option and
205 ``%colors`` magic, but there's a mismatch in possibilities, so some configurations
209 ``%colors`` magic, but there's a mismatch in possibilities, so some configurations
206 may produce unexpected results. See :ref:`termcolour` for more information.
210 may produce unexpected results. See :ref:`termcolour` for more information.
207
211
208 The new interface is not compatible with Emacs 'inferior-shell' feature. To
212 The new interface is not compatible with Emacs 'inferior-shell' feature. To
209 continue using this, add the ``--simple-prompt`` flag to the command Emacs
213 continue using this, add the ``--simple-prompt`` flag to the command Emacs
210 runs. This flag disables most IPython features, relying on Emacs to provide
214 runs. This flag disables most IPython features, relying on Emacs to provide
211 things like tab completion.
215 things like tab completion.
212
216
213 Provisional Changes
217 Provisional Changes
214 -------------------
218 -------------------
215
219
216 Provisional changes are experimental functionality that may, or may not, make
220 Provisional changes are experimental functionality that may, or may not, make
217 it into a future version of IPython, and which API may change without warnings.
221 it into a future version of IPython, and which API may change without warnings.
218 Activating these features and using these API are at your own risk, and may have
222 Activating these features and using these API are at your own risk, and may have
219 security implication for your system, especially if used with the Jupyter notebook,
223 security implication for your system, especially if used with the Jupyter notebook,
220
224
221 When running via the Jupyter notebook interfaces, or other compatible client,
225 When running via the Jupyter notebook interfaces, or other compatible client,
222 you can enable rich documentation experimental functionality:
226 you can enable rich documentation experimental functionality:
223
227
224 When the ``docrepr`` package is installed setting the boolean flag
228 When the ``docrepr`` package is installed setting the boolean flag
225 ``InteractiveShell.sphinxify_docstring`` to ``True``, will process the various
229 ``InteractiveShell.sphinxify_docstring`` to ``True``, will process the various
226 object through sphinx before displaying them (see the ``docrepr`` package
230 object through sphinx before displaying them (see the ``docrepr`` package
227 documentation for more information.
231 documentation for more information.
228
232
229 You need to also enable the IPython pager display rich HTML representation
233 You need to also enable the IPython pager display rich HTML representation
230 using the ``InteractiveShell.enable_html_pager`` boolean configuration option.
234 using the ``InteractiveShell.enable_html_pager`` boolean configuration option.
231 As usual you can set these configuration options globally in your configuration
235 As usual you can set these configuration options globally in your configuration
232 files, alternatively you can turn them on dynamically using the following
236 files, alternatively you can turn them on dynamically using the following
233 snippet:
237 snippet:
234
238
235 .. code-block:: python
239 .. code-block:: python
236
240
237 ip = get_ipython()
241 ip = get_ipython()
238 ip.sphinxify_docstring = True
242 ip.sphinxify_docstring = True
239 ip.enable_html_pager = True
243 ip.enable_html_pager = True
240
244
241
245
242 You can test the effect of various combinations of the above configuration in
246 You can test the effect of various combinations of the above configuration in
243 the Jupyter notebook, with things example like :
247 the Jupyter notebook, with things example like :
244
248
245 .. code-block:: ipython
249 .. code-block:: ipython
246
250
247 import numpy as np
251 import numpy as np
248 np.histogram?
252 np.histogram?
249
253
250
254
251 This is part of an effort to make Documentation in Python richer and provide in
255 This is part of an effort to make Documentation in Python richer and provide in
252 the long term if possible dynamic examples that can contain math, images,
256 the long term if possible dynamic examples that can contain math, images,
253 widgets... As stated above this is nightly experimental feature with a lot of
257 widgets... As stated above this is nightly experimental feature with a lot of
254 (fun) problem to solve. We would be happy to get your feedback and expertise on
258 (fun) problem to solve. We would be happy to get your feedback and expertise on
255 it.
259 it.
256
260
257
261
258
262
259 Deprecated Features
263 Deprecated Features
260 -------------------
264 -------------------
261
265
262 Some deprecated features are listed in this section. Don't forget to enable
266 Some deprecated features are listed in this section. Don't forget to enable
263 ``DeprecationWarning`` as an error if you are using IPython in a Continuous
267 ``DeprecationWarning`` as an error if you are using IPython in a Continuous
264 Integration setup or in your testing in general:
268 Integration setup or in your testing in general:
265
269
266 .. code-block:: python
270 .. code-block:: python
267
271
268 import warnings
272 import warnings
269 warnings.filterwarnings('error', '.*', DeprecationWarning, module='yourmodule.*')
273 warnings.filterwarnings('error', '.*', DeprecationWarning, module='yourmodule.*')
270
274
271
275
272 - ``hooks.fix_error_editor`` seems unused and is pending deprecation.
276 - ``hooks.fix_error_editor`` seems unused and is pending deprecation.
273 - `IPython/core/excolors.py:ExceptionColors` is deprecated.
277 - `IPython/core/excolors.py:ExceptionColors` is deprecated.
274 - `IPython.core.InteractiveShell:write()` is deprecated; use `sys.stdout` instead.
278 - `IPython.core.InteractiveShell:write()` is deprecated; use `sys.stdout` instead.
275 - `IPython.core.InteractiveShell:write_err()` is deprecated; use `sys.stderr` instead.
279 - `IPython.core.InteractiveShell:write_err()` is deprecated; use `sys.stderr` instead.
276 - The `formatter` keyword argument to `Inspector.info` in `IPython.core.oinspec` has no effect.
280 - The `formatter` keyword argument to `Inspector.info` in `IPython.core.oinspec` has no effect.
277 - The `global_ns` keyword argument of IPython Embed was deprecated, and has no effect. Use `module` keyword argument instead.
281 - The `global_ns` keyword argument of IPython Embed was deprecated, and has no effect. Use `module` keyword argument instead.
278
282
279
283
280 Known Issues:
284 Known Issues:
281 -------------
285 -------------
282
286
283 - ``<Esc>`` Key does not dismiss the completer and does not clear the current
287 - ``<Esc>`` Key does not dismiss the completer and does not clear the current
284 buffer. This is an on purpose modification due to current technical
288 buffer. This is an on purpose modification due to current technical
285 limitation. Cf :ghpull:`9572`. Escape the control character which is used
289 limitation. Cf :ghpull:`9572`. Escape the control character which is used
286 for other shortcut, and there is no practical way to distinguish. Use Ctr-G
290 for other shortcut, and there is no practical way to distinguish. Use Ctr-G
287 or Ctrl-C as an alternative.
291 or Ctrl-C as an alternative.
288
292
289 - Cannot use ``Shift-Enter`` and ``Ctrl-Enter`` to submit code in terminal. cf
293 - Cannot use ``Shift-Enter`` and ``Ctrl-Enter`` to submit code in terminal. cf
290 :ghissue:`9587` and :ghissue:`9401`. In terminal there is no practical way to
294 :ghissue:`9587` and :ghissue:`9401`. In terminal there is no practical way to
291 distinguish these key sequences from a normal new line return.
295 distinguish these key sequences from a normal new line return.
292
296
293 - ``PageUp`` and ``pageDown`` do not move through completion menu.
297 - ``PageUp`` and ``pageDown`` do not move through completion menu.
294
298
295 - Color styles might not adapt to terminal emulator themes. This will need new
299 - Color styles might not adapt to terminal emulator themes. This will need new
296 version of Pygments to be released, and can be mitigated with custom themes.
300 version of Pygments to be released, and can be mitigated with custom themes.
297
301
298
302
General Comments 0
You need to be logged in to leave comments. Login now