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