Show More
@@ -1,2101 +1,2111 b'' | |||||
1 | """Completion for IPython. |
|
1 | """Completion for IPython. | |
2 |
|
2 | |||
3 | This module started as fork of the rlcompleter module in the Python standard |
|
3 | This module started as fork of the rlcompleter module in the Python standard | |
4 | library. The original enhancements made to rlcompleter have been sent |
|
4 | library. The original enhancements made to rlcompleter have been sent | |
5 | upstream and were accepted as of Python 2.3, |
|
5 | upstream and were accepted as of Python 2.3, | |
6 |
|
6 | |||
7 | This module now support a wide variety of completion mechanism both available |
|
7 | This module now support a wide variety of completion mechanism both available | |
8 | for normal classic Python code, as well as completer for IPython specific |
|
8 | for normal classic Python code, as well as completer for IPython specific | |
9 | Syntax like magics. |
|
9 | Syntax like magics. | |
10 |
|
10 | |||
11 | Latex and Unicode completion |
|
11 | Latex and Unicode completion | |
12 | ============================ |
|
12 | ============================ | |
13 |
|
13 | |||
14 | IPython and compatible frontends not only can complete your code, but can help |
|
14 | IPython and compatible frontends not only can complete your code, but can help | |
15 | you to input a wide range of characters. In particular we allow you to insert |
|
15 | you to input a wide range of characters. In particular we allow you to insert | |
16 | a unicode character using the tab completion mechanism. |
|
16 | a unicode character using the tab completion mechanism. | |
17 |
|
17 | |||
18 | Forward latex/unicode completion |
|
18 | Forward latex/unicode completion | |
19 | -------------------------------- |
|
19 | -------------------------------- | |
20 |
|
20 | |||
21 | Forward completion allows you to easily type a unicode character using its latex |
|
21 | Forward completion allows you to easily type a unicode character using its latex | |
22 | name, or unicode long description. To do so type a backslash follow by the |
|
22 | name, or unicode long description. To do so type a backslash follow by the | |
23 | relevant name and press tab: |
|
23 | relevant name and press tab: | |
24 |
|
24 | |||
25 |
|
25 | |||
26 | Using latex completion: |
|
26 | Using latex completion: | |
27 |
|
27 | |||
28 | .. code:: |
|
28 | .. code:: | |
29 |
|
29 | |||
30 | \\alpha<tab> |
|
30 | \\alpha<tab> | |
31 | Ξ± |
|
31 | Ξ± | |
32 |
|
32 | |||
33 | or using unicode completion: |
|
33 | or using unicode completion: | |
34 |
|
34 | |||
35 |
|
35 | |||
36 | .. code:: |
|
36 | .. code:: | |
37 |
|
37 | |||
38 | \\greek small letter alpha<tab> |
|
38 | \\greek small letter alpha<tab> | |
39 | Ξ± |
|
39 | Ξ± | |
40 |
|
40 | |||
41 |
|
41 | |||
42 | Only valid Python identifiers will complete. Combining characters (like arrow or |
|
42 | Only valid Python identifiers will complete. Combining characters (like arrow or | |
43 | dots) are also available, unlike latex they need to be put after the their |
|
43 | dots) are also available, unlike latex they need to be put after the their | |
44 | counterpart that is to say, `F\\\\vec<tab>` is correct, not `\\\\vec<tab>F`. |
|
44 | counterpart that is to say, `F\\\\vec<tab>` is correct, not `\\\\vec<tab>F`. | |
45 |
|
45 | |||
46 | Some browsers are known to display combining characters incorrectly. |
|
46 | Some browsers are known to display combining characters incorrectly. | |
47 |
|
47 | |||
48 | Backward latex completion |
|
48 | Backward latex completion | |
49 | ------------------------- |
|
49 | ------------------------- | |
50 |
|
50 | |||
51 | It is sometime challenging to know how to type a character, if you are using |
|
51 | It is sometime challenging to know how to type a character, if you are using | |
52 | IPython, or any compatible frontend you can prepend backslash to the character |
|
52 | IPython, or any compatible frontend you can prepend backslash to the character | |
53 | and press `<tab>` to expand it to its latex form. |
|
53 | and press `<tab>` to expand it to its latex form. | |
54 |
|
54 | |||
55 | .. code:: |
|
55 | .. code:: | |
56 |
|
56 | |||
57 | \\Ξ±<tab> |
|
57 | \\Ξ±<tab> | |
58 | \\alpha |
|
58 | \\alpha | |
59 |
|
59 | |||
60 |
|
60 | |||
61 | Both forward and backward completions can be deactivated by setting the |
|
61 | Both forward and backward completions can be deactivated by setting the | |
62 | ``Completer.backslash_combining_completions`` option to ``False``. |
|
62 | ``Completer.backslash_combining_completions`` option to ``False``. | |
63 |
|
63 | |||
64 |
|
64 | |||
65 | Experimental |
|
65 | Experimental | |
66 | ============ |
|
66 | ============ | |
67 |
|
67 | |||
68 | Starting with IPython 6.0, this module can make use of the Jedi library to |
|
68 | Starting with IPython 6.0, this module can make use of the Jedi library to | |
69 | generate completions both using static analysis of the code, and dynamically |
|
69 | generate completions both using static analysis of the code, and dynamically | |
70 | inspecting multiple namespaces. Jedi is an autocompletion and static analysis |
|
70 | inspecting multiple namespaces. Jedi is an autocompletion and static analysis | |
71 | for Python. The APIs attached to this new mechanism is unstable and will |
|
71 | for Python. The APIs attached to this new mechanism is unstable and will | |
72 | raise unless use in an :any:`provisionalcompleter` context manager. |
|
72 | raise unless use in an :any:`provisionalcompleter` context manager. | |
73 |
|
73 | |||
74 | You will find that the following are experimental: |
|
74 | You will find that the following are experimental: | |
75 |
|
75 | |||
76 | - :any:`provisionalcompleter` |
|
76 | - :any:`provisionalcompleter` | |
77 | - :any:`IPCompleter.completions` |
|
77 | - :any:`IPCompleter.completions` | |
78 | - :any:`Completion` |
|
78 | - :any:`Completion` | |
79 | - :any:`rectify_completions` |
|
79 | - :any:`rectify_completions` | |
80 |
|
80 | |||
81 | .. note:: |
|
81 | .. note:: | |
82 |
|
82 | |||
83 | better name for :any:`rectify_completions` ? |
|
83 | better name for :any:`rectify_completions` ? | |
84 |
|
84 | |||
85 | We welcome any feedback on these new API, and we also encourage you to try this |
|
85 | We welcome any feedback on these new API, and we also encourage you to try this | |
86 | module in debug mode (start IPython with ``--Completer.debug=True``) in order |
|
86 | module in debug mode (start IPython with ``--Completer.debug=True``) in order | |
87 | to have extra logging information if :any:`jedi` is crashing, or if current |
|
87 | to have extra logging information if :any:`jedi` is crashing, or if current | |
88 | IPython completer pending deprecations are returning results not yet handled |
|
88 | IPython completer pending deprecations are returning results not yet handled | |
89 | by :any:`jedi` |
|
89 | by :any:`jedi` | |
90 |
|
90 | |||
91 | Using Jedi for tab completion allow snippets like the following to work without |
|
91 | Using Jedi for tab completion allow snippets like the following to work without | |
92 | having to execute any code: |
|
92 | having to execute any code: | |
93 |
|
93 | |||
94 | >>> myvar = ['hello', 42] |
|
94 | >>> myvar = ['hello', 42] | |
95 | ... myvar[1].bi<tab> |
|
95 | ... myvar[1].bi<tab> | |
96 |
|
96 | |||
97 | Tab completion will be able to infer that ``myvar[1]`` is a real number without |
|
97 | Tab completion will be able to infer that ``myvar[1]`` is a real number without | |
98 | executing any code unlike the previously available ``IPCompleter.greedy`` |
|
98 | executing any code unlike the previously available ``IPCompleter.greedy`` | |
99 | option. |
|
99 | option. | |
100 |
|
100 | |||
101 | Be sure to update :any:`jedi` to the latest stable version or to try the |
|
101 | Be sure to update :any:`jedi` to the latest stable version or to try the | |
102 | current development version to get better completions. |
|
102 | current development version to get better completions. | |
103 | """ |
|
103 | """ | |
104 |
|
104 | |||
105 |
|
105 | |||
106 | # Copyright (c) IPython Development Team. |
|
106 | # Copyright (c) IPython Development Team. | |
107 | # Distributed under the terms of the Modified BSD License. |
|
107 | # Distributed under the terms of the Modified BSD License. | |
108 | # |
|
108 | # | |
109 | # Some of this code originated from rlcompleter in the Python standard library |
|
109 | # Some of this code originated from rlcompleter in the Python standard library | |
110 | # Copyright (C) 2001 Python Software Foundation, www.python.org |
|
110 | # Copyright (C) 2001 Python Software Foundation, www.python.org | |
111 |
|
111 | |||
112 |
|
112 | |||
113 | import builtins as builtin_mod |
|
113 | import builtins as builtin_mod | |
114 | import glob |
|
114 | import glob | |
115 | import inspect |
|
115 | import inspect | |
116 | import itertools |
|
116 | import itertools | |
117 | import keyword |
|
117 | import keyword | |
118 | import os |
|
118 | import os | |
119 | import re |
|
119 | import re | |
120 | import string |
|
120 | import string | |
121 | import sys |
|
121 | import sys | |
122 | import time |
|
122 | import time | |
123 | import unicodedata |
|
123 | import unicodedata | |
124 | import warnings |
|
124 | import warnings | |
125 | from contextlib import contextmanager |
|
125 | from contextlib import contextmanager | |
126 | from importlib import import_module |
|
126 | from importlib import import_module | |
127 | from types import SimpleNamespace |
|
127 | from types import SimpleNamespace | |
128 | from typing import Iterable, Iterator, List, Tuple |
|
128 | from typing import Iterable, Iterator, List, Tuple | |
129 |
|
129 | |||
130 | from IPython.core.error import TryNext |
|
130 | from IPython.core.error import TryNext | |
131 | from IPython.core.inputtransformer2 import ESC_MAGIC |
|
131 | from IPython.core.inputtransformer2 import ESC_MAGIC | |
132 | from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol |
|
132 | from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol | |
133 | from IPython.core.oinspect import InspectColors |
|
133 | from IPython.core.oinspect import InspectColors | |
134 | from IPython.utils import generics |
|
134 | from IPython.utils import generics | |
135 | from IPython.utils.dir2 import dir2, get_real_method |
|
135 | from IPython.utils.dir2 import dir2, get_real_method | |
136 | from IPython.utils.process import arg_split |
|
136 | from IPython.utils.process import arg_split | |
137 | from traitlets import Bool, Enum, Int, observe |
|
137 | from traitlets import Bool, Enum, Int, observe | |
138 | from traitlets.config.configurable import Configurable |
|
138 | from traitlets.config.configurable import Configurable | |
139 |
|
139 | |||
140 | import __main__ |
|
140 | import __main__ | |
141 |
|
141 | |||
142 | # skip module docstests |
|
142 | # skip module docstests | |
143 | skip_doctest = True |
|
143 | skip_doctest = True | |
144 |
|
144 | |||
145 | try: |
|
145 | try: | |
146 | import jedi |
|
146 | import jedi | |
147 | jedi.settings.case_insensitive_completion = False |
|
147 | jedi.settings.case_insensitive_completion = False | |
148 | import jedi.api.helpers |
|
148 | import jedi.api.helpers | |
149 | import jedi.api.classes |
|
149 | import jedi.api.classes | |
150 | JEDI_INSTALLED = True |
|
150 | JEDI_INSTALLED = True | |
151 | except ImportError: |
|
151 | except ImportError: | |
152 | JEDI_INSTALLED = False |
|
152 | JEDI_INSTALLED = False | |
153 | #----------------------------------------------------------------------------- |
|
153 | #----------------------------------------------------------------------------- | |
154 | # Globals |
|
154 | # Globals | |
155 | #----------------------------------------------------------------------------- |
|
155 | #----------------------------------------------------------------------------- | |
156 |
|
156 | |||
157 | # Public API |
|
157 | # Public API | |
158 | __all__ = ['Completer','IPCompleter'] |
|
158 | __all__ = ['Completer','IPCompleter'] | |
159 |
|
159 | |||
160 | if sys.platform == 'win32': |
|
160 | if sys.platform == 'win32': | |
161 | PROTECTABLES = ' ' |
|
161 | PROTECTABLES = ' ' | |
162 | else: |
|
162 | else: | |
163 | PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&' |
|
163 | PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&' | |
164 |
|
164 | |||
165 | # Protect against returning an enormous number of completions which the frontend |
|
165 | # Protect against returning an enormous number of completions which the frontend | |
166 | # may have trouble processing. |
|
166 | # may have trouble processing. | |
167 | MATCHES_LIMIT = 500 |
|
167 | MATCHES_LIMIT = 500 | |
168 |
|
168 | |||
169 | _deprecation_readline_sentinel = object() |
|
169 | _deprecation_readline_sentinel = object() | |
170 |
|
170 | |||
171 |
|
171 | |||
172 | class ProvisionalCompleterWarning(FutureWarning): |
|
172 | class ProvisionalCompleterWarning(FutureWarning): | |
173 | """ |
|
173 | """ | |
174 | Exception raise by an experimental feature in this module. |
|
174 | Exception raise by an experimental feature in this module. | |
175 |
|
175 | |||
176 | Wrap code in :any:`provisionalcompleter` context manager if you |
|
176 | Wrap code in :any:`provisionalcompleter` context manager if you | |
177 | are certain you want to use an unstable feature. |
|
177 | are certain you want to use an unstable feature. | |
178 | """ |
|
178 | """ | |
179 | pass |
|
179 | pass | |
180 |
|
180 | |||
181 | warnings.filterwarnings('error', category=ProvisionalCompleterWarning) |
|
181 | warnings.filterwarnings('error', category=ProvisionalCompleterWarning) | |
182 |
|
182 | |||
183 | @contextmanager |
|
183 | @contextmanager | |
184 | def provisionalcompleter(action='ignore'): |
|
184 | def provisionalcompleter(action='ignore'): | |
185 | """ |
|
185 | """ | |
186 |
|
186 | |||
187 |
|
187 | |||
188 | This context manager has to be used in any place where unstable completer |
|
188 | This context manager has to be used in any place where unstable completer | |
189 | behavior and API may be called. |
|
189 | behavior and API may be called. | |
190 |
|
190 | |||
191 | >>> with provisionalcompleter(): |
|
191 | >>> with provisionalcompleter(): | |
192 | ... completer.do_experimental_things() # works |
|
192 | ... completer.do_experimental_things() # works | |
193 |
|
193 | |||
194 | >>> completer.do_experimental_things() # raises. |
|
194 | >>> completer.do_experimental_things() # raises. | |
195 |
|
195 | |||
196 |
.. note:: |
|
196 | .. note:: | |
|
197 | ||||
|
198 | Unstable | |||
197 |
|
199 | |||
198 | By using this context manager you agree that the API in use may change |
|
200 | By using this context manager you agree that the API in use may change | |
199 | without warning, and that you won't complain if they do so. |
|
201 | without warning, and that you won't complain if they do so. | |
200 |
|
202 | |||
201 | You also understand that, if the API is not to your liking, you should report |
|
203 | You also understand that, if the API is not to your liking, you should report | |
202 | a bug to explain your use case upstream. |
|
204 | a bug to explain your use case upstream. | |
203 |
|
205 | |||
204 | We'll be happy to get your feedback, feature requests, and improvements on |
|
206 | We'll be happy to get your feedback, feature requests, and improvements on | |
205 | any of the unstable APIs! |
|
207 | any of the unstable APIs! | |
206 | """ |
|
208 | """ | |
207 | with warnings.catch_warnings(): |
|
209 | with warnings.catch_warnings(): | |
208 | warnings.filterwarnings(action, category=ProvisionalCompleterWarning) |
|
210 | warnings.filterwarnings(action, category=ProvisionalCompleterWarning) | |
209 | yield |
|
211 | yield | |
210 |
|
212 | |||
211 |
|
213 | |||
212 | def has_open_quotes(s): |
|
214 | def has_open_quotes(s): | |
213 | """Return whether a string has open quotes. |
|
215 | """Return whether a string has open quotes. | |
214 |
|
216 | |||
215 | This simply counts whether the number of quote characters of either type in |
|
217 | This simply counts whether the number of quote characters of either type in | |
216 | the string is odd. |
|
218 | the string is odd. | |
217 |
|
219 | |||
218 | Returns |
|
220 | Returns | |
219 | ------- |
|
221 | ------- | |
220 | If there is an open quote, the quote character is returned. Else, return |
|
222 | If there is an open quote, the quote character is returned. Else, return | |
221 | False. |
|
223 | False. | |
222 | """ |
|
224 | """ | |
223 | # We check " first, then ', so complex cases with nested quotes will get |
|
225 | # We check " first, then ', so complex cases with nested quotes will get | |
224 | # the " to take precedence. |
|
226 | # the " to take precedence. | |
225 | if s.count('"') % 2: |
|
227 | if s.count('"') % 2: | |
226 | return '"' |
|
228 | return '"' | |
227 | elif s.count("'") % 2: |
|
229 | elif s.count("'") % 2: | |
228 | return "'" |
|
230 | return "'" | |
229 | else: |
|
231 | else: | |
230 | return False |
|
232 | return False | |
231 |
|
233 | |||
232 |
|
234 | |||
233 | def protect_filename(s, protectables=PROTECTABLES): |
|
235 | def protect_filename(s, protectables=PROTECTABLES): | |
234 | """Escape a string to protect certain characters.""" |
|
236 | """Escape a string to protect certain characters.""" | |
235 | if set(s) & set(protectables): |
|
237 | if set(s) & set(protectables): | |
236 | if sys.platform == "win32": |
|
238 | if sys.platform == "win32": | |
237 | return '"' + s + '"' |
|
239 | return '"' + s + '"' | |
238 | else: |
|
240 | else: | |
239 | return "".join(("\\" + c if c in protectables else c) for c in s) |
|
241 | return "".join(("\\" + c if c in protectables else c) for c in s) | |
240 | else: |
|
242 | else: | |
241 | return s |
|
243 | return s | |
242 |
|
244 | |||
243 |
|
245 | |||
244 | def expand_user(path:str) -> Tuple[str, bool, str]: |
|
246 | def expand_user(path:str) -> Tuple[str, bool, str]: | |
245 | """Expand ``~``-style usernames in strings. |
|
247 | """Expand ``~``-style usernames in strings. | |
246 |
|
248 | |||
247 | This is similar to :func:`os.path.expanduser`, but it computes and returns |
|
249 | This is similar to :func:`os.path.expanduser`, but it computes and returns | |
248 | extra information that will be useful if the input was being used in |
|
250 | extra information that will be useful if the input was being used in | |
249 | computing completions, and you wish to return the completions with the |
|
251 | computing completions, and you wish to return the completions with the | |
250 | original '~' instead of its expanded value. |
|
252 | original '~' instead of its expanded value. | |
251 |
|
253 | |||
252 | Parameters |
|
254 | Parameters | |
253 | ---------- |
|
255 | ---------- | |
254 | path : str |
|
256 | path : str | |
255 | String to be expanded. If no ~ is present, the output is the same as the |
|
257 | String to be expanded. If no ~ is present, the output is the same as the | |
256 | input. |
|
258 | input. | |
257 |
|
259 | |||
258 | Returns |
|
260 | Returns | |
259 | ------- |
|
261 | ------- | |
260 | newpath : str |
|
262 | newpath : str | |
261 | Result of ~ expansion in the input path. |
|
263 | Result of ~ expansion in the input path. | |
262 | tilde_expand : bool |
|
264 | tilde_expand : bool | |
263 | Whether any expansion was performed or not. |
|
265 | Whether any expansion was performed or not. | |
264 | tilde_val : str |
|
266 | tilde_val : str | |
265 | The value that ~ was replaced with. |
|
267 | The value that ~ was replaced with. | |
266 | """ |
|
268 | """ | |
267 | # Default values |
|
269 | # Default values | |
268 | tilde_expand = False |
|
270 | tilde_expand = False | |
269 | tilde_val = '' |
|
271 | tilde_val = '' | |
270 | newpath = path |
|
272 | newpath = path | |
271 |
|
273 | |||
272 | if path.startswith('~'): |
|
274 | if path.startswith('~'): | |
273 | tilde_expand = True |
|
275 | tilde_expand = True | |
274 | rest = len(path)-1 |
|
276 | rest = len(path)-1 | |
275 | newpath = os.path.expanduser(path) |
|
277 | newpath = os.path.expanduser(path) | |
276 | if rest: |
|
278 | if rest: | |
277 | tilde_val = newpath[:-rest] |
|
279 | tilde_val = newpath[:-rest] | |
278 | else: |
|
280 | else: | |
279 | tilde_val = newpath |
|
281 | tilde_val = newpath | |
280 |
|
282 | |||
281 | return newpath, tilde_expand, tilde_val |
|
283 | return newpath, tilde_expand, tilde_val | |
282 |
|
284 | |||
283 |
|
285 | |||
284 | def compress_user(path:str, tilde_expand:bool, tilde_val:str) -> str: |
|
286 | def compress_user(path:str, tilde_expand:bool, tilde_val:str) -> str: | |
285 | """Does the opposite of expand_user, with its outputs. |
|
287 | """Does the opposite of expand_user, with its outputs. | |
286 | """ |
|
288 | """ | |
287 | if tilde_expand: |
|
289 | if tilde_expand: | |
288 | return path.replace(tilde_val, '~') |
|
290 | return path.replace(tilde_val, '~') | |
289 | else: |
|
291 | else: | |
290 | return path |
|
292 | return path | |
291 |
|
293 | |||
292 |
|
294 | |||
293 | def completions_sorting_key(word): |
|
295 | def completions_sorting_key(word): | |
294 | """key for sorting completions |
|
296 | """key for sorting completions | |
295 |
|
297 | |||
296 | This does several things: |
|
298 | This does several things: | |
297 |
|
299 | |||
298 | - Demote any completions starting with underscores to the end |
|
300 | - Demote any completions starting with underscores to the end | |
299 | - Insert any %magic and %%cellmagic completions in the alphabetical order |
|
301 | - Insert any %magic and %%cellmagic completions in the alphabetical order | |
300 | by their name |
|
302 | by their name | |
301 | """ |
|
303 | """ | |
302 | prio1, prio2 = 0, 0 |
|
304 | prio1, prio2 = 0, 0 | |
303 |
|
305 | |||
304 | if word.startswith('__'): |
|
306 | if word.startswith('__'): | |
305 | prio1 = 2 |
|
307 | prio1 = 2 | |
306 | elif word.startswith('_'): |
|
308 | elif word.startswith('_'): | |
307 | prio1 = 1 |
|
309 | prio1 = 1 | |
308 |
|
310 | |||
309 | if word.endswith('='): |
|
311 | if word.endswith('='): | |
310 | prio1 = -1 |
|
312 | prio1 = -1 | |
311 |
|
313 | |||
312 | if word.startswith('%%'): |
|
314 | if word.startswith('%%'): | |
313 | # If there's another % in there, this is something else, so leave it alone |
|
315 | # If there's another % in there, this is something else, so leave it alone | |
314 | if not "%" in word[2:]: |
|
316 | if not "%" in word[2:]: | |
315 | word = word[2:] |
|
317 | word = word[2:] | |
316 | prio2 = 2 |
|
318 | prio2 = 2 | |
317 | elif word.startswith('%'): |
|
319 | elif word.startswith('%'): | |
318 | if not "%" in word[1:]: |
|
320 | if not "%" in word[1:]: | |
319 | word = word[1:] |
|
321 | word = word[1:] | |
320 | prio2 = 1 |
|
322 | prio2 = 1 | |
321 |
|
323 | |||
322 | return prio1, word, prio2 |
|
324 | return prio1, word, prio2 | |
323 |
|
325 | |||
324 |
|
326 | |||
325 | class _FakeJediCompletion: |
|
327 | class _FakeJediCompletion: | |
326 | """ |
|
328 | """ | |
327 | This is a workaround to communicate to the UI that Jedi has crashed and to |
|
329 | This is a workaround to communicate to the UI that Jedi has crashed and to | |
328 | report a bug. Will be used only id :any:`IPCompleter.debug` is set to true. |
|
330 | report a bug. Will be used only id :any:`IPCompleter.debug` is set to true. | |
329 |
|
331 | |||
330 | Added in IPython 6.0 so should likely be removed for 7.0 |
|
332 | Added in IPython 6.0 so should likely be removed for 7.0 | |
331 |
|
333 | |||
332 | """ |
|
334 | """ | |
333 |
|
335 | |||
334 | def __init__(self, name): |
|
336 | def __init__(self, name): | |
335 |
|
337 | |||
336 | self.name = name |
|
338 | self.name = name | |
337 | self.complete = name |
|
339 | self.complete = name | |
338 | self.type = 'crashed' |
|
340 | self.type = 'crashed' | |
339 | self.name_with_symbols = name |
|
341 | self.name_with_symbols = name | |
340 | self.signature = '' |
|
342 | self.signature = '' | |
341 | self._origin = 'fake' |
|
343 | self._origin = 'fake' | |
342 |
|
344 | |||
343 | def __repr__(self): |
|
345 | def __repr__(self): | |
344 | return '<Fake completion object jedi has crashed>' |
|
346 | return '<Fake completion object jedi has crashed>' | |
345 |
|
347 | |||
346 |
|
348 | |||
347 | class Completion: |
|
349 | class Completion: | |
348 | """ |
|
350 | """ | |
349 | Completion object used and return by IPython completers. |
|
351 | Completion object used and return by IPython completers. | |
350 |
|
352 | |||
351 |
.. warning:: |
|
353 | .. warning:: | |
|
354 | ||||
|
355 | Unstable | |||
352 |
|
356 | |||
353 | This function is unstable, API may change without warning. |
|
357 | This function is unstable, API may change without warning. | |
354 | It will also raise unless use in proper context manager. |
|
358 | It will also raise unless use in proper context manager. | |
355 |
|
359 | |||
356 | This act as a middle ground :any:`Completion` object between the |
|
360 | This act as a middle ground :any:`Completion` object between the | |
357 | :any:`jedi.api.classes.Completion` object and the Prompt Toolkit completion |
|
361 | :any:`jedi.api.classes.Completion` object and the Prompt Toolkit completion | |
358 | object. While Jedi need a lot of information about evaluator and how the |
|
362 | object. While Jedi need a lot of information about evaluator and how the | |
359 | code should be ran/inspected, PromptToolkit (and other frontend) mostly |
|
363 | code should be ran/inspected, PromptToolkit (and other frontend) mostly | |
360 | need user facing information. |
|
364 | need user facing information. | |
361 |
|
365 | |||
362 | - Which range should be replaced replaced by what. |
|
366 | - Which range should be replaced replaced by what. | |
363 | - Some metadata (like completion type), or meta information to displayed to |
|
367 | - Some metadata (like completion type), or meta information to displayed to | |
364 | the use user. |
|
368 | the use user. | |
365 |
|
369 | |||
366 | For debugging purpose we can also store the origin of the completion (``jedi``, |
|
370 | For debugging purpose we can also store the origin of the completion (``jedi``, | |
367 | ``IPython.python_matches``, ``IPython.magics_matches``...). |
|
371 | ``IPython.python_matches``, ``IPython.magics_matches``...). | |
368 | """ |
|
372 | """ | |
369 |
|
373 | |||
370 | __slots__ = ['start', 'end', 'text', 'type', 'signature', '_origin'] |
|
374 | __slots__ = ['start', 'end', 'text', 'type', 'signature', '_origin'] | |
371 |
|
375 | |||
372 | def __init__(self, start: int, end: int, text: str, *, type: str=None, _origin='', signature='') -> None: |
|
376 | def __init__(self, start: int, end: int, text: str, *, type: str=None, _origin='', signature='') -> None: | |
373 | warnings.warn("``Completion`` is a provisional API (as of IPython 6.0). " |
|
377 | warnings.warn("``Completion`` is a provisional API (as of IPython 6.0). " | |
374 | "It may change without warnings. " |
|
378 | "It may change without warnings. " | |
375 | "Use in corresponding context manager.", |
|
379 | "Use in corresponding context manager.", | |
376 | category=ProvisionalCompleterWarning, stacklevel=2) |
|
380 | category=ProvisionalCompleterWarning, stacklevel=2) | |
377 |
|
381 | |||
378 | self.start = start |
|
382 | self.start = start | |
379 | self.end = end |
|
383 | self.end = end | |
380 | self.text = text |
|
384 | self.text = text | |
381 | self.type = type |
|
385 | self.type = type | |
382 | self.signature = signature |
|
386 | self.signature = signature | |
383 | self._origin = _origin |
|
387 | self._origin = _origin | |
384 |
|
388 | |||
385 | def __repr__(self): |
|
389 | def __repr__(self): | |
386 | return '<Completion start=%s end=%s text=%r type=%r, signature=%r,>' % \ |
|
390 | return '<Completion start=%s end=%s text=%r type=%r, signature=%r,>' % \ | |
387 | (self.start, self.end, self.text, self.type or '?', self.signature or '?') |
|
391 | (self.start, self.end, self.text, self.type or '?', self.signature or '?') | |
388 |
|
392 | |||
389 | def __eq__(self, other)->Bool: |
|
393 | def __eq__(self, other)->Bool: | |
390 | """ |
|
394 | """ | |
391 | Equality and hash do not hash the type (as some completer may not be |
|
395 | Equality and hash do not hash the type (as some completer may not be | |
392 | able to infer the type), but are use to (partially) de-duplicate |
|
396 | able to infer the type), but are use to (partially) de-duplicate | |
393 | completion. |
|
397 | completion. | |
394 |
|
398 | |||
395 | Completely de-duplicating completion is a bit tricker that just |
|
399 | Completely de-duplicating completion is a bit tricker that just | |
396 | comparing as it depends on surrounding text, which Completions are not |
|
400 | comparing as it depends on surrounding text, which Completions are not | |
397 | aware of. |
|
401 | aware of. | |
398 | """ |
|
402 | """ | |
399 | return self.start == other.start and \ |
|
403 | return self.start == other.start and \ | |
400 | self.end == other.end and \ |
|
404 | self.end == other.end and \ | |
401 | self.text == other.text |
|
405 | self.text == other.text | |
402 |
|
406 | |||
403 | def __hash__(self): |
|
407 | def __hash__(self): | |
404 | return hash((self.start, self.end, self.text)) |
|
408 | return hash((self.start, self.end, self.text)) | |
405 |
|
409 | |||
406 |
|
410 | |||
407 | _IC = Iterable[Completion] |
|
411 | _IC = Iterable[Completion] | |
408 |
|
412 | |||
409 |
|
413 | |||
410 | def _deduplicate_completions(text: str, completions: _IC)-> _IC: |
|
414 | def _deduplicate_completions(text: str, completions: _IC)-> _IC: | |
411 | """ |
|
415 | """ | |
412 | Deduplicate a set of completions. |
|
416 | Deduplicate a set of completions. | |
413 |
|
417 | |||
414 |
.. warning:: |
|
418 | .. warning:: | |
|
419 | ||||
|
420 | Unstable | |||
415 |
|
421 | |||
416 | This function is unstable, API may change without warning. |
|
422 | This function is unstable, API may change without warning. | |
417 |
|
423 | |||
418 | Parameters |
|
424 | Parameters | |
419 | ---------- |
|
425 | ---------- | |
420 | text: str |
|
426 | text: str | |
421 | text that should be completed. |
|
427 | text that should be completed. | |
422 | completions: Iterator[Completion] |
|
428 | completions: Iterator[Completion] | |
423 | iterator over the completions to deduplicate |
|
429 | iterator over the completions to deduplicate | |
424 |
|
430 | |||
425 | Yields |
|
431 | Yields | |
426 | ------ |
|
432 | ------ | |
427 | `Completions` objects |
|
433 | `Completions` objects | |
428 |
|
434 | |||
429 |
|
435 | |||
430 | Completions coming from multiple sources, may be different but end up having |
|
436 | Completions coming from multiple sources, may be different but end up having | |
431 | the same effect when applied to ``text``. If this is the case, this will |
|
437 | the same effect when applied to ``text``. If this is the case, this will | |
432 | consider completions as equal and only emit the first encountered. |
|
438 | consider completions as equal and only emit the first encountered. | |
433 |
|
439 | |||
434 | Not folded in `completions()` yet for debugging purpose, and to detect when |
|
440 | Not folded in `completions()` yet for debugging purpose, and to detect when | |
435 | the IPython completer does return things that Jedi does not, but should be |
|
441 | the IPython completer does return things that Jedi does not, but should be | |
436 | at some point. |
|
442 | at some point. | |
437 | """ |
|
443 | """ | |
438 | completions = list(completions) |
|
444 | completions = list(completions) | |
439 | if not completions: |
|
445 | if not completions: | |
440 | return |
|
446 | return | |
441 |
|
447 | |||
442 | new_start = min(c.start for c in completions) |
|
448 | new_start = min(c.start for c in completions) | |
443 | new_end = max(c.end for c in completions) |
|
449 | new_end = max(c.end for c in completions) | |
444 |
|
450 | |||
445 | seen = set() |
|
451 | seen = set() | |
446 | for c in completions: |
|
452 | for c in completions: | |
447 | new_text = text[new_start:c.start] + c.text + text[c.end:new_end] |
|
453 | new_text = text[new_start:c.start] + c.text + text[c.end:new_end] | |
448 | if new_text not in seen: |
|
454 | if new_text not in seen: | |
449 | yield c |
|
455 | yield c | |
450 | seen.add(new_text) |
|
456 | seen.add(new_text) | |
451 |
|
457 | |||
452 |
|
458 | |||
453 | def rectify_completions(text: str, completions: _IC, *, _debug=False)->_IC: |
|
459 | def rectify_completions(text: str, completions: _IC, *, _debug=False)->_IC: | |
454 | """ |
|
460 | """ | |
455 | Rectify a set of completions to all have the same ``start`` and ``end`` |
|
461 | Rectify a set of completions to all have the same ``start`` and ``end`` | |
456 |
|
462 | |||
457 |
.. warning:: |
|
463 | .. warning:: | |
|
464 | ||||
|
465 | Unstable | |||
458 |
|
466 | |||
459 | This function is unstable, API may change without warning. |
|
467 | This function is unstable, API may change without warning. | |
460 | It will also raise unless use in proper context manager. |
|
468 | It will also raise unless use in proper context manager. | |
461 |
|
469 | |||
462 | Parameters |
|
470 | Parameters | |
463 | ---------- |
|
471 | ---------- | |
464 | text: str |
|
472 | text: str | |
465 | text that should be completed. |
|
473 | text that should be completed. | |
466 | completions: Iterator[Completion] |
|
474 | completions: Iterator[Completion] | |
467 | iterator over the completions to rectify |
|
475 | iterator over the completions to rectify | |
468 |
|
476 | |||
469 |
|
477 | |||
470 | :any:`jedi.api.classes.Completion` s returned by Jedi may not have the same start and end, though |
|
478 | :any:`jedi.api.classes.Completion` s returned by Jedi may not have the same start and end, though | |
471 | the Jupyter Protocol requires them to behave like so. This will readjust |
|
479 | the Jupyter Protocol requires them to behave like so. This will readjust | |
472 | the completion to have the same ``start`` and ``end`` by padding both |
|
480 | the completion to have the same ``start`` and ``end`` by padding both | |
473 | extremities with surrounding text. |
|
481 | extremities with surrounding text. | |
474 |
|
482 | |||
475 | During stabilisation should support a ``_debug`` option to log which |
|
483 | During stabilisation should support a ``_debug`` option to log which | |
476 | completion are return by the IPython completer and not found in Jedi in |
|
484 | completion are return by the IPython completer and not found in Jedi in | |
477 | order to make upstream bug report. |
|
485 | order to make upstream bug report. | |
478 | """ |
|
486 | """ | |
479 | warnings.warn("`rectify_completions` is a provisional API (as of IPython 6.0). " |
|
487 | warnings.warn("`rectify_completions` is a provisional API (as of IPython 6.0). " | |
480 | "It may change without warnings. " |
|
488 | "It may change without warnings. " | |
481 | "Use in corresponding context manager.", |
|
489 | "Use in corresponding context manager.", | |
482 | category=ProvisionalCompleterWarning, stacklevel=2) |
|
490 | category=ProvisionalCompleterWarning, stacklevel=2) | |
483 |
|
491 | |||
484 | completions = list(completions) |
|
492 | completions = list(completions) | |
485 | if not completions: |
|
493 | if not completions: | |
486 | return |
|
494 | return | |
487 | starts = (c.start for c in completions) |
|
495 | starts = (c.start for c in completions) | |
488 | ends = (c.end for c in completions) |
|
496 | ends = (c.end for c in completions) | |
489 |
|
497 | |||
490 | new_start = min(starts) |
|
498 | new_start = min(starts) | |
491 | new_end = max(ends) |
|
499 | new_end = max(ends) | |
492 |
|
500 | |||
493 | seen_jedi = set() |
|
501 | seen_jedi = set() | |
494 | seen_python_matches = set() |
|
502 | seen_python_matches = set() | |
495 | for c in completions: |
|
503 | for c in completions: | |
496 | new_text = text[new_start:c.start] + c.text + text[c.end:new_end] |
|
504 | new_text = text[new_start:c.start] + c.text + text[c.end:new_end] | |
497 | if c._origin == 'jedi': |
|
505 | if c._origin == 'jedi': | |
498 | seen_jedi.add(new_text) |
|
506 | seen_jedi.add(new_text) | |
499 | elif c._origin == 'IPCompleter.python_matches': |
|
507 | elif c._origin == 'IPCompleter.python_matches': | |
500 | seen_python_matches.add(new_text) |
|
508 | seen_python_matches.add(new_text) | |
501 | yield Completion(new_start, new_end, new_text, type=c.type, _origin=c._origin, signature=c.signature) |
|
509 | yield Completion(new_start, new_end, new_text, type=c.type, _origin=c._origin, signature=c.signature) | |
502 | diff = seen_python_matches.difference(seen_jedi) |
|
510 | diff = seen_python_matches.difference(seen_jedi) | |
503 | if diff and _debug: |
|
511 | if diff and _debug: | |
504 | print('IPython.python matches have extras:', diff) |
|
512 | print('IPython.python matches have extras:', diff) | |
505 |
|
513 | |||
506 |
|
514 | |||
507 | if sys.platform == 'win32': |
|
515 | if sys.platform == 'win32': | |
508 | DELIMS = ' \t\n`!@#$^&*()=+[{]}|;\'",<>?' |
|
516 | DELIMS = ' \t\n`!@#$^&*()=+[{]}|;\'",<>?' | |
509 | else: |
|
517 | else: | |
510 | DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?' |
|
518 | DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?' | |
511 |
|
519 | |||
512 | GREEDY_DELIMS = ' =\r\n' |
|
520 | GREEDY_DELIMS = ' =\r\n' | |
513 |
|
521 | |||
514 |
|
522 | |||
515 | class CompletionSplitter(object): |
|
523 | class CompletionSplitter(object): | |
516 | """An object to split an input line in a manner similar to readline. |
|
524 | """An object to split an input line in a manner similar to readline. | |
517 |
|
525 | |||
518 | By having our own implementation, we can expose readline-like completion in |
|
526 | By having our own implementation, we can expose readline-like completion in | |
519 | a uniform manner to all frontends. This object only needs to be given the |
|
527 | a uniform manner to all frontends. This object only needs to be given the | |
520 | line of text to be split and the cursor position on said line, and it |
|
528 | line of text to be split and the cursor position on said line, and it | |
521 | returns the 'word' to be completed on at the cursor after splitting the |
|
529 | returns the 'word' to be completed on at the cursor after splitting the | |
522 | entire line. |
|
530 | entire line. | |
523 |
|
531 | |||
524 | What characters are used as splitting delimiters can be controlled by |
|
532 | What characters are used as splitting delimiters can be controlled by | |
525 | setting the ``delims`` attribute (this is a property that internally |
|
533 | setting the ``delims`` attribute (this is a property that internally | |
526 | automatically builds the necessary regular expression)""" |
|
534 | automatically builds the necessary regular expression)""" | |
527 |
|
535 | |||
528 | # Private interface |
|
536 | # Private interface | |
529 |
|
537 | |||
530 | # A string of delimiter characters. The default value makes sense for |
|
538 | # A string of delimiter characters. The default value makes sense for | |
531 | # IPython's most typical usage patterns. |
|
539 | # IPython's most typical usage patterns. | |
532 | _delims = DELIMS |
|
540 | _delims = DELIMS | |
533 |
|
541 | |||
534 | # The expression (a normal string) to be compiled into a regular expression |
|
542 | # The expression (a normal string) to be compiled into a regular expression | |
535 | # for actual splitting. We store it as an attribute mostly for ease of |
|
543 | # for actual splitting. We store it as an attribute mostly for ease of | |
536 | # debugging, since this type of code can be so tricky to debug. |
|
544 | # debugging, since this type of code can be so tricky to debug. | |
537 | _delim_expr = None |
|
545 | _delim_expr = None | |
538 |
|
546 | |||
539 | # The regular expression that does the actual splitting |
|
547 | # The regular expression that does the actual splitting | |
540 | _delim_re = None |
|
548 | _delim_re = None | |
541 |
|
549 | |||
542 | def __init__(self, delims=None): |
|
550 | def __init__(self, delims=None): | |
543 | delims = CompletionSplitter._delims if delims is None else delims |
|
551 | delims = CompletionSplitter._delims if delims is None else delims | |
544 | self.delims = delims |
|
552 | self.delims = delims | |
545 |
|
553 | |||
546 | @property |
|
554 | @property | |
547 | def delims(self): |
|
555 | def delims(self): | |
548 | """Return the string of delimiter characters.""" |
|
556 | """Return the string of delimiter characters.""" | |
549 | return self._delims |
|
557 | return self._delims | |
550 |
|
558 | |||
551 | @delims.setter |
|
559 | @delims.setter | |
552 | def delims(self, delims): |
|
560 | def delims(self, delims): | |
553 | """Set the delimiters for line splitting.""" |
|
561 | """Set the delimiters for line splitting.""" | |
554 | expr = '[' + ''.join('\\'+ c for c in delims) + ']' |
|
562 | expr = '[' + ''.join('\\'+ c for c in delims) + ']' | |
555 | self._delim_re = re.compile(expr) |
|
563 | self._delim_re = re.compile(expr) | |
556 | self._delims = delims |
|
564 | self._delims = delims | |
557 | self._delim_expr = expr |
|
565 | self._delim_expr = expr | |
558 |
|
566 | |||
559 | def split_line(self, line, cursor_pos=None): |
|
567 | def split_line(self, line, cursor_pos=None): | |
560 | """Split a line of text with a cursor at the given position. |
|
568 | """Split a line of text with a cursor at the given position. | |
561 | """ |
|
569 | """ | |
562 | l = line if cursor_pos is None else line[:cursor_pos] |
|
570 | l = line if cursor_pos is None else line[:cursor_pos] | |
563 | return self._delim_re.split(l)[-1] |
|
571 | return self._delim_re.split(l)[-1] | |
564 |
|
572 | |||
565 |
|
573 | |||
566 |
|
574 | |||
567 | class Completer(Configurable): |
|
575 | class Completer(Configurable): | |
568 |
|
576 | |||
569 | greedy = Bool(False, |
|
577 | greedy = Bool(False, | |
570 | help="""Activate greedy completion |
|
578 | help="""Activate greedy completion | |
571 | PENDING DEPRECTION. this is now mostly taken care of with Jedi. |
|
579 | PENDING DEPRECTION. this is now mostly taken care of with Jedi. | |
572 |
|
580 | |||
573 | This will enable completion on elements of lists, results of function calls, etc., |
|
581 | This will enable completion on elements of lists, results of function calls, etc., | |
574 | but can be unsafe because the code is actually evaluated on TAB. |
|
582 | but can be unsafe because the code is actually evaluated on TAB. | |
575 | """ |
|
583 | """ | |
576 | ).tag(config=True) |
|
584 | ).tag(config=True) | |
577 |
|
585 | |||
578 | use_jedi = Bool(default_value=JEDI_INSTALLED, |
|
586 | use_jedi = Bool(default_value=JEDI_INSTALLED, | |
579 | help="Experimental: Use Jedi to generate autocompletions. " |
|
587 | help="Experimental: Use Jedi to generate autocompletions. " | |
580 | "Default to True if jedi is installed.").tag(config=True) |
|
588 | "Default to True if jedi is installed.").tag(config=True) | |
581 |
|
589 | |||
582 | jedi_compute_type_timeout = Int(default_value=400, |
|
590 | jedi_compute_type_timeout = Int(default_value=400, | |
583 | help="""Experimental: restrict time (in milliseconds) during which Jedi can compute types. |
|
591 | help="""Experimental: restrict time (in milliseconds) during which Jedi can compute types. | |
584 | Set to 0 to stop computing types. Non-zero value lower than 100ms may hurt |
|
592 | Set to 0 to stop computing types. Non-zero value lower than 100ms may hurt | |
585 | performance by preventing jedi to build its cache. |
|
593 | performance by preventing jedi to build its cache. | |
586 | """).tag(config=True) |
|
594 | """).tag(config=True) | |
587 |
|
595 | |||
588 | debug = Bool(default_value=False, |
|
596 | debug = Bool(default_value=False, | |
589 | help='Enable debug for the Completer. Mostly print extra ' |
|
597 | help='Enable debug for the Completer. Mostly print extra ' | |
590 | 'information for experimental jedi integration.')\ |
|
598 | 'information for experimental jedi integration.')\ | |
591 | .tag(config=True) |
|
599 | .tag(config=True) | |
592 |
|
600 | |||
593 | backslash_combining_completions = Bool(True, |
|
601 | backslash_combining_completions = Bool(True, | |
594 | help="Enable unicode completions, e.g. \\alpha<tab> . " |
|
602 | help="Enable unicode completions, e.g. \\alpha<tab> . " | |
595 | "Includes completion of latex commands, unicode names, and expanding " |
|
603 | "Includes completion of latex commands, unicode names, and expanding " | |
596 | "unicode characters back to latex commands.").tag(config=True) |
|
604 | "unicode characters back to latex commands.").tag(config=True) | |
597 |
|
605 | |||
598 |
|
606 | |||
599 |
|
607 | |||
600 | def __init__(self, namespace=None, global_namespace=None, **kwargs): |
|
608 | def __init__(self, namespace=None, global_namespace=None, **kwargs): | |
601 | """Create a new completer for the command line. |
|
609 | """Create a new completer for the command line. | |
602 |
|
610 | |||
603 | Completer(namespace=ns, global_namespace=ns2) -> completer instance. |
|
611 | Completer(namespace=ns, global_namespace=ns2) -> completer instance. | |
604 |
|
612 | |||
605 | If unspecified, the default namespace where completions are performed |
|
613 | If unspecified, the default namespace where completions are performed | |
606 | is __main__ (technically, __main__.__dict__). Namespaces should be |
|
614 | is __main__ (technically, __main__.__dict__). Namespaces should be | |
607 | given as dictionaries. |
|
615 | given as dictionaries. | |
608 |
|
616 | |||
609 | An optional second namespace can be given. This allows the completer |
|
617 | An optional second namespace can be given. This allows the completer | |
610 | to handle cases where both the local and global scopes need to be |
|
618 | to handle cases where both the local and global scopes need to be | |
611 | distinguished. |
|
619 | distinguished. | |
612 | """ |
|
620 | """ | |
613 |
|
621 | |||
614 | # Don't bind to namespace quite yet, but flag whether the user wants a |
|
622 | # Don't bind to namespace quite yet, but flag whether the user wants a | |
615 | # specific namespace or to use __main__.__dict__. This will allow us |
|
623 | # specific namespace or to use __main__.__dict__. This will allow us | |
616 | # to bind to __main__.__dict__ at completion time, not now. |
|
624 | # to bind to __main__.__dict__ at completion time, not now. | |
617 | if namespace is None: |
|
625 | if namespace is None: | |
618 | self.use_main_ns = True |
|
626 | self.use_main_ns = True | |
619 | else: |
|
627 | else: | |
620 | self.use_main_ns = False |
|
628 | self.use_main_ns = False | |
621 | self.namespace = namespace |
|
629 | self.namespace = namespace | |
622 |
|
630 | |||
623 | # The global namespace, if given, can be bound directly |
|
631 | # The global namespace, if given, can be bound directly | |
624 | if global_namespace is None: |
|
632 | if global_namespace is None: | |
625 | self.global_namespace = {} |
|
633 | self.global_namespace = {} | |
626 | else: |
|
634 | else: | |
627 | self.global_namespace = global_namespace |
|
635 | self.global_namespace = global_namespace | |
628 |
|
636 | |||
629 | self.custom_matchers = [] |
|
637 | self.custom_matchers = [] | |
630 |
|
638 | |||
631 | super(Completer, self).__init__(**kwargs) |
|
639 | super(Completer, self).__init__(**kwargs) | |
632 |
|
640 | |||
633 | def complete(self, text, state): |
|
641 | def complete(self, text, state): | |
634 | """Return the next possible completion for 'text'. |
|
642 | """Return the next possible completion for 'text'. | |
635 |
|
643 | |||
636 | This is called successively with state == 0, 1, 2, ... until it |
|
644 | This is called successively with state == 0, 1, 2, ... until it | |
637 | returns None. The completion should begin with 'text'. |
|
645 | returns None. The completion should begin with 'text'. | |
638 |
|
646 | |||
639 | """ |
|
647 | """ | |
640 | if self.use_main_ns: |
|
648 | if self.use_main_ns: | |
641 | self.namespace = __main__.__dict__ |
|
649 | self.namespace = __main__.__dict__ | |
642 |
|
650 | |||
643 | if state == 0: |
|
651 | if state == 0: | |
644 | if "." in text: |
|
652 | if "." in text: | |
645 | self.matches = self.attr_matches(text) |
|
653 | self.matches = self.attr_matches(text) | |
646 | else: |
|
654 | else: | |
647 | self.matches = self.global_matches(text) |
|
655 | self.matches = self.global_matches(text) | |
648 | try: |
|
656 | try: | |
649 | return self.matches[state] |
|
657 | return self.matches[state] | |
650 | except IndexError: |
|
658 | except IndexError: | |
651 | return None |
|
659 | return None | |
652 |
|
660 | |||
653 | def global_matches(self, text): |
|
661 | def global_matches(self, text): | |
654 | """Compute matches when text is a simple name. |
|
662 | """Compute matches when text is a simple name. | |
655 |
|
663 | |||
656 | Return a list of all keywords, built-in functions and names currently |
|
664 | Return a list of all keywords, built-in functions and names currently | |
657 | defined in self.namespace or self.global_namespace that match. |
|
665 | defined in self.namespace or self.global_namespace that match. | |
658 |
|
666 | |||
659 | """ |
|
667 | """ | |
660 | matches = [] |
|
668 | matches = [] | |
661 | match_append = matches.append |
|
669 | match_append = matches.append | |
662 | n = len(text) |
|
670 | n = len(text) | |
663 | for lst in [keyword.kwlist, |
|
671 | for lst in [keyword.kwlist, | |
664 | builtin_mod.__dict__.keys(), |
|
672 | builtin_mod.__dict__.keys(), | |
665 | self.namespace.keys(), |
|
673 | self.namespace.keys(), | |
666 | self.global_namespace.keys()]: |
|
674 | self.global_namespace.keys()]: | |
667 | for word in lst: |
|
675 | for word in lst: | |
668 | if word[:n] == text and word != "__builtins__": |
|
676 | if word[:n] == text and word != "__builtins__": | |
669 | match_append(word) |
|
677 | match_append(word) | |
670 |
|
678 | |||
671 | snake_case_re = re.compile(r"[^_]+(_[^_]+)+?\Z") |
|
679 | snake_case_re = re.compile(r"[^_]+(_[^_]+)+?\Z") | |
672 | for lst in [self.namespace.keys(), |
|
680 | for lst in [self.namespace.keys(), | |
673 | self.global_namespace.keys()]: |
|
681 | self.global_namespace.keys()]: | |
674 | shortened = {"_".join([sub[0] for sub in word.split('_')]) : word |
|
682 | shortened = {"_".join([sub[0] for sub in word.split('_')]) : word | |
675 | for word in lst if snake_case_re.match(word)} |
|
683 | for word in lst if snake_case_re.match(word)} | |
676 | for word in shortened.keys(): |
|
684 | for word in shortened.keys(): | |
677 | if word[:n] == text and word != "__builtins__": |
|
685 | if word[:n] == text and word != "__builtins__": | |
678 | match_append(shortened[word]) |
|
686 | match_append(shortened[word]) | |
679 | return matches |
|
687 | return matches | |
680 |
|
688 | |||
681 | def attr_matches(self, text): |
|
689 | def attr_matches(self, text): | |
682 | """Compute matches when text contains a dot. |
|
690 | """Compute matches when text contains a dot. | |
683 |
|
691 | |||
684 | Assuming the text is of the form NAME.NAME....[NAME], and is |
|
692 | Assuming the text is of the form NAME.NAME....[NAME], and is | |
685 | evaluatable in self.namespace or self.global_namespace, it will be |
|
693 | evaluatable in self.namespace or self.global_namespace, it will be | |
686 | evaluated and its attributes (as revealed by dir()) are used as |
|
694 | evaluated and its attributes (as revealed by dir()) are used as | |
687 | possible completions. (For class instances, class members are |
|
695 | possible completions. (For class instances, class members are | |
688 | also considered.) |
|
696 | also considered.) | |
689 |
|
697 | |||
690 | WARNING: this can still invoke arbitrary C code, if an object |
|
698 | WARNING: this can still invoke arbitrary C code, if an object | |
691 | with a __getattr__ hook is evaluated. |
|
699 | with a __getattr__ hook is evaluated. | |
692 |
|
700 | |||
693 | """ |
|
701 | """ | |
694 |
|
702 | |||
695 | # Another option, seems to work great. Catches things like ''.<tab> |
|
703 | # Another option, seems to work great. Catches things like ''.<tab> | |
696 | m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text) |
|
704 | m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text) | |
697 |
|
705 | |||
698 | if m: |
|
706 | if m: | |
699 | expr, attr = m.group(1, 3) |
|
707 | expr, attr = m.group(1, 3) | |
700 | elif self.greedy: |
|
708 | elif self.greedy: | |
701 | m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer) |
|
709 | m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer) | |
702 | if not m2: |
|
710 | if not m2: | |
703 | return [] |
|
711 | return [] | |
704 | expr, attr = m2.group(1,2) |
|
712 | expr, attr = m2.group(1,2) | |
705 | else: |
|
713 | else: | |
706 | return [] |
|
714 | return [] | |
707 |
|
715 | |||
708 | try: |
|
716 | try: | |
709 | obj = eval(expr, self.namespace) |
|
717 | obj = eval(expr, self.namespace) | |
710 | except: |
|
718 | except: | |
711 | try: |
|
719 | try: | |
712 | obj = eval(expr, self.global_namespace) |
|
720 | obj = eval(expr, self.global_namespace) | |
713 | except: |
|
721 | except: | |
714 | return [] |
|
722 | return [] | |
715 |
|
723 | |||
716 | if self.limit_to__all__ and hasattr(obj, '__all__'): |
|
724 | if self.limit_to__all__ and hasattr(obj, '__all__'): | |
717 | words = get__all__entries(obj) |
|
725 | words = get__all__entries(obj) | |
718 | else: |
|
726 | else: | |
719 | words = dir2(obj) |
|
727 | words = dir2(obj) | |
720 |
|
728 | |||
721 | try: |
|
729 | try: | |
722 | words = generics.complete_object(obj, words) |
|
730 | words = generics.complete_object(obj, words) | |
723 | except TryNext: |
|
731 | except TryNext: | |
724 | pass |
|
732 | pass | |
725 | except AssertionError: |
|
733 | except AssertionError: | |
726 | raise |
|
734 | raise | |
727 | except Exception: |
|
735 | except Exception: | |
728 | # Silence errors from completion function |
|
736 | # Silence errors from completion function | |
729 | #raise # dbg |
|
737 | #raise # dbg | |
730 | pass |
|
738 | pass | |
731 | # Build match list to return |
|
739 | # Build match list to return | |
732 | n = len(attr) |
|
740 | n = len(attr) | |
733 | return [u"%s.%s" % (expr, w) for w in words if w[:n] == attr ] |
|
741 | return [u"%s.%s" % (expr, w) for w in words if w[:n] == attr ] | |
734 |
|
742 | |||
735 |
|
743 | |||
736 | def get__all__entries(obj): |
|
744 | def get__all__entries(obj): | |
737 | """returns the strings in the __all__ attribute""" |
|
745 | """returns the strings in the __all__ attribute""" | |
738 | try: |
|
746 | try: | |
739 | words = getattr(obj, '__all__') |
|
747 | words = getattr(obj, '__all__') | |
740 | except: |
|
748 | except: | |
741 | return [] |
|
749 | return [] | |
742 |
|
750 | |||
743 | return [w for w in words if isinstance(w, str)] |
|
751 | return [w for w in words if isinstance(w, str)] | |
744 |
|
752 | |||
745 |
|
753 | |||
746 | def match_dict_keys(keys: List[str], prefix: str, delims: str): |
|
754 | def match_dict_keys(keys: List[str], prefix: str, delims: str): | |
747 | """Used by dict_key_matches, matching the prefix to a list of keys |
|
755 | """Used by dict_key_matches, matching the prefix to a list of keys | |
748 |
|
756 | |||
749 | Parameters |
|
757 | Parameters | |
750 | ========== |
|
758 | ========== | |
751 | keys: |
|
759 | keys: | |
752 | list of keys in dictionary currently being completed. |
|
760 | list of keys in dictionary currently being completed. | |
753 | prefix: |
|
761 | prefix: | |
754 | Part of the text already typed by the user. e.g. `mydict[b'fo` |
|
762 | Part of the text already typed by the user. e.g. `mydict[b'fo` | |
755 | delims: |
|
763 | delims: | |
756 | String of delimiters to consider when finding the current key. |
|
764 | String of delimiters to consider when finding the current key. | |
757 |
|
765 | |||
758 | Returns |
|
766 | Returns | |
759 | ======= |
|
767 | ======= | |
760 |
|
768 | |||
761 | A tuple of three elements: ``quote``, ``token_start``, ``matched``, with |
|
769 | A tuple of three elements: ``quote``, ``token_start``, ``matched``, with | |
762 | ``quote`` being the quote that need to be used to close current string. |
|
770 | ``quote`` being the quote that need to be used to close current string. | |
763 | ``token_start`` the position where the replacement should start occurring, |
|
771 | ``token_start`` the position where the replacement should start occurring, | |
764 | ``matches`` a list of replacement/completion |
|
772 | ``matches`` a list of replacement/completion | |
765 |
|
773 | |||
766 | """ |
|
774 | """ | |
767 | if not prefix: |
|
775 | if not prefix: | |
768 | return None, 0, [repr(k) for k in keys |
|
776 | return None, 0, [repr(k) for k in keys | |
769 | if isinstance(k, (str, bytes))] |
|
777 | if isinstance(k, (str, bytes))] | |
770 | quote_match = re.search('["\']', prefix) |
|
778 | quote_match = re.search('["\']', prefix) | |
771 | quote = quote_match.group() |
|
779 | quote = quote_match.group() | |
772 | try: |
|
780 | try: | |
773 | prefix_str = eval(prefix + quote, {}) |
|
781 | prefix_str = eval(prefix + quote, {}) | |
774 | except Exception: |
|
782 | except Exception: | |
775 | return None, 0, [] |
|
783 | return None, 0, [] | |
776 |
|
784 | |||
777 | pattern = '[^' + ''.join('\\' + c for c in delims) + ']*$' |
|
785 | pattern = '[^' + ''.join('\\' + c for c in delims) + ']*$' | |
778 | token_match = re.search(pattern, prefix, re.UNICODE) |
|
786 | token_match = re.search(pattern, prefix, re.UNICODE) | |
779 | token_start = token_match.start() |
|
787 | token_start = token_match.start() | |
780 | token_prefix = token_match.group() |
|
788 | token_prefix = token_match.group() | |
781 |
|
789 | |||
782 | matched = [] |
|
790 | matched = [] | |
783 | for key in keys: |
|
791 | for key in keys: | |
784 | try: |
|
792 | try: | |
785 | if not key.startswith(prefix_str): |
|
793 | if not key.startswith(prefix_str): | |
786 | continue |
|
794 | continue | |
787 | except (AttributeError, TypeError, UnicodeError): |
|
795 | except (AttributeError, TypeError, UnicodeError): | |
788 | # Python 3+ TypeError on b'a'.startswith('a') or vice-versa |
|
796 | # Python 3+ TypeError on b'a'.startswith('a') or vice-versa | |
789 | continue |
|
797 | continue | |
790 |
|
798 | |||
791 | # reformat remainder of key to begin with prefix |
|
799 | # reformat remainder of key to begin with prefix | |
792 | rem = key[len(prefix_str):] |
|
800 | rem = key[len(prefix_str):] | |
793 | # force repr wrapped in ' |
|
801 | # force repr wrapped in ' | |
794 | rem_repr = repr(rem + '"') if isinstance(rem, str) else repr(rem + b'"') |
|
802 | rem_repr = repr(rem + '"') if isinstance(rem, str) else repr(rem + b'"') | |
795 | if rem_repr.startswith('u') and prefix[0] not in 'uU': |
|
803 | if rem_repr.startswith('u') and prefix[0] not in 'uU': | |
796 | # Found key is unicode, but prefix is Py2 string. |
|
804 | # Found key is unicode, but prefix is Py2 string. | |
797 | # Therefore attempt to interpret key as string. |
|
805 | # Therefore attempt to interpret key as string. | |
798 | try: |
|
806 | try: | |
799 | rem_repr = repr(rem.encode('ascii') + '"') |
|
807 | rem_repr = repr(rem.encode('ascii') + '"') | |
800 | except UnicodeEncodeError: |
|
808 | except UnicodeEncodeError: | |
801 | continue |
|
809 | continue | |
802 |
|
810 | |||
803 | rem_repr = rem_repr[1 + rem_repr.index("'"):-2] |
|
811 | rem_repr = rem_repr[1 + rem_repr.index("'"):-2] | |
804 | if quote == '"': |
|
812 | if quote == '"': | |
805 | # The entered prefix is quoted with ", |
|
813 | # The entered prefix is quoted with ", | |
806 | # but the match is quoted with '. |
|
814 | # but the match is quoted with '. | |
807 | # A contained " hence needs escaping for comparison: |
|
815 | # A contained " hence needs escaping for comparison: | |
808 | rem_repr = rem_repr.replace('"', '\\"') |
|
816 | rem_repr = rem_repr.replace('"', '\\"') | |
809 |
|
817 | |||
810 | # then reinsert prefix from start of token |
|
818 | # then reinsert prefix from start of token | |
811 | matched.append('%s%s' % (token_prefix, rem_repr)) |
|
819 | matched.append('%s%s' % (token_prefix, rem_repr)) | |
812 | return quote, token_start, matched |
|
820 | return quote, token_start, matched | |
813 |
|
821 | |||
814 |
|
822 | |||
815 | def cursor_to_position(text:str, line:int, column:int)->int: |
|
823 | def cursor_to_position(text:str, line:int, column:int)->int: | |
816 | """ |
|
824 | """ | |
817 |
|
825 | |||
818 | Convert the (line,column) position of the cursor in text to an offset in a |
|
826 | Convert the (line,column) position of the cursor in text to an offset in a | |
819 | string. |
|
827 | string. | |
820 |
|
828 | |||
821 | Parameters |
|
829 | Parameters | |
822 | ---------- |
|
830 | ---------- | |
823 |
|
831 | |||
824 | text : str |
|
832 | text : str | |
825 | The text in which to calculate the cursor offset |
|
833 | The text in which to calculate the cursor offset | |
826 | line : int |
|
834 | line : int | |
827 | Line of the cursor; 0-indexed |
|
835 | Line of the cursor; 0-indexed | |
828 | column : int |
|
836 | column : int | |
829 | Column of the cursor 0-indexed |
|
837 | Column of the cursor 0-indexed | |
830 |
|
838 | |||
831 | Return |
|
839 | Return | |
832 | ------ |
|
840 | ------ | |
833 | Position of the cursor in ``text``, 0-indexed. |
|
841 | Position of the cursor in ``text``, 0-indexed. | |
834 |
|
842 | |||
835 | See Also |
|
843 | See Also | |
836 | -------- |
|
844 | -------- | |
837 | position_to_cursor: reciprocal of this function |
|
845 | position_to_cursor: reciprocal of this function | |
838 |
|
846 | |||
839 | """ |
|
847 | """ | |
840 | lines = text.split('\n') |
|
848 | lines = text.split('\n') | |
841 | assert line <= len(lines), '{} <= {}'.format(str(line), str(len(lines))) |
|
849 | assert line <= len(lines), '{} <= {}'.format(str(line), str(len(lines))) | |
842 |
|
850 | |||
843 | return sum(len(l) + 1 for l in lines[:line]) + column |
|
851 | return sum(len(l) + 1 for l in lines[:line]) + column | |
844 |
|
852 | |||
845 | def position_to_cursor(text:str, offset:int)->Tuple[int, int]: |
|
853 | def position_to_cursor(text:str, offset:int)->Tuple[int, int]: | |
846 | """ |
|
854 | """ | |
847 | Convert the position of the cursor in text (0 indexed) to a line |
|
855 | Convert the position of the cursor in text (0 indexed) to a line | |
848 | number(0-indexed) and a column number (0-indexed) pair |
|
856 | number(0-indexed) and a column number (0-indexed) pair | |
849 |
|
857 | |||
850 | Position should be a valid position in ``text``. |
|
858 | Position should be a valid position in ``text``. | |
851 |
|
859 | |||
852 | Parameters |
|
860 | Parameters | |
853 | ---------- |
|
861 | ---------- | |
854 |
|
862 | |||
855 | text : str |
|
863 | text : str | |
856 | The text in which to calculate the cursor offset |
|
864 | The text in which to calculate the cursor offset | |
857 | offset : int |
|
865 | offset : int | |
858 | Position of the cursor in ``text``, 0-indexed. |
|
866 | Position of the cursor in ``text``, 0-indexed. | |
859 |
|
867 | |||
860 | Return |
|
868 | Return | |
861 | ------ |
|
869 | ------ | |
862 | (line, column) : (int, int) |
|
870 | (line, column) : (int, int) | |
863 | Line of the cursor; 0-indexed, column of the cursor 0-indexed |
|
871 | Line of the cursor; 0-indexed, column of the cursor 0-indexed | |
864 |
|
872 | |||
865 |
|
873 | |||
866 | See Also |
|
874 | See Also | |
867 | -------- |
|
875 | -------- | |
868 | cursor_to_position : reciprocal of this function |
|
876 | cursor_to_position : reciprocal of this function | |
869 |
|
877 | |||
870 |
|
878 | |||
871 | """ |
|
879 | """ | |
872 |
|
880 | |||
873 | assert 0 <= offset <= len(text) , "0 <= %s <= %s" % (offset , len(text)) |
|
881 | assert 0 <= offset <= len(text) , "0 <= %s <= %s" % (offset , len(text)) | |
874 |
|
882 | |||
875 | before = text[:offset] |
|
883 | before = text[:offset] | |
876 | blines = before.split('\n') # ! splitnes trim trailing \n |
|
884 | blines = before.split('\n') # ! splitnes trim trailing \n | |
877 | line = before.count('\n') |
|
885 | line = before.count('\n') | |
878 | col = len(blines[-1]) |
|
886 | col = len(blines[-1]) | |
879 | return line, col |
|
887 | return line, col | |
880 |
|
888 | |||
881 |
|
889 | |||
882 | def _safe_isinstance(obj, module, class_name): |
|
890 | def _safe_isinstance(obj, module, class_name): | |
883 | """Checks if obj is an instance of module.class_name if loaded |
|
891 | """Checks if obj is an instance of module.class_name if loaded | |
884 | """ |
|
892 | """ | |
885 | return (module in sys.modules and |
|
893 | return (module in sys.modules and | |
886 | isinstance(obj, getattr(import_module(module), class_name))) |
|
894 | isinstance(obj, getattr(import_module(module), class_name))) | |
887 |
|
895 | |||
888 |
|
896 | |||
889 | def back_unicode_name_matches(text): |
|
897 | def back_unicode_name_matches(text): | |
890 | u"""Match unicode characters back to unicode name |
|
898 | u"""Match unicode characters back to unicode name | |
891 |
|
899 | |||
892 | This does ``β`` -> ``\\snowman`` |
|
900 | This does ``β`` -> ``\\snowman`` | |
893 |
|
901 | |||
894 | Note that snowman is not a valid python3 combining character but will be expanded. |
|
902 | Note that snowman is not a valid python3 combining character but will be expanded. | |
895 | Though it will not recombine back to the snowman character by the completion machinery. |
|
903 | Though it will not recombine back to the snowman character by the completion machinery. | |
896 |
|
904 | |||
897 | This will not either back-complete standard sequences like \\n, \\b ... |
|
905 | This will not either back-complete standard sequences like \\n, \\b ... | |
898 |
|
906 | |||
899 | Used on Python 3 only. |
|
907 | Used on Python 3 only. | |
900 | """ |
|
908 | """ | |
901 | if len(text)<2: |
|
909 | if len(text)<2: | |
902 | return u'', () |
|
910 | return u'', () | |
903 | maybe_slash = text[-2] |
|
911 | maybe_slash = text[-2] | |
904 | if maybe_slash != '\\': |
|
912 | if maybe_slash != '\\': | |
905 | return u'', () |
|
913 | return u'', () | |
906 |
|
914 | |||
907 | char = text[-1] |
|
915 | char = text[-1] | |
908 | # no expand on quote for completion in strings. |
|
916 | # no expand on quote for completion in strings. | |
909 | # nor backcomplete standard ascii keys |
|
917 | # nor backcomplete standard ascii keys | |
910 | if char in string.ascii_letters or char in ['"',"'"]: |
|
918 | if char in string.ascii_letters or char in ['"',"'"]: | |
911 | return u'', () |
|
919 | return u'', () | |
912 | try : |
|
920 | try : | |
913 | unic = unicodedata.name(char) |
|
921 | unic = unicodedata.name(char) | |
914 | return '\\'+char,['\\'+unic] |
|
922 | return '\\'+char,['\\'+unic] | |
915 | except KeyError: |
|
923 | except KeyError: | |
916 | pass |
|
924 | pass | |
917 | return u'', () |
|
925 | return u'', () | |
918 |
|
926 | |||
919 | def back_latex_name_matches(text:str): |
|
927 | def back_latex_name_matches(text:str): | |
920 | """Match latex characters back to unicode name |
|
928 | """Match latex characters back to unicode name | |
921 |
|
929 | |||
922 | This does ``\\β΅`` -> ``\\aleph`` |
|
930 | This does ``\\β΅`` -> ``\\aleph`` | |
923 |
|
931 | |||
924 | Used on Python 3 only. |
|
932 | Used on Python 3 only. | |
925 | """ |
|
933 | """ | |
926 | if len(text)<2: |
|
934 | if len(text)<2: | |
927 | return u'', () |
|
935 | return u'', () | |
928 | maybe_slash = text[-2] |
|
936 | maybe_slash = text[-2] | |
929 | if maybe_slash != '\\': |
|
937 | if maybe_slash != '\\': | |
930 | return u'', () |
|
938 | return u'', () | |
931 |
|
939 | |||
932 |
|
940 | |||
933 | char = text[-1] |
|
941 | char = text[-1] | |
934 | # no expand on quote for completion in strings. |
|
942 | # no expand on quote for completion in strings. | |
935 | # nor backcomplete standard ascii keys |
|
943 | # nor backcomplete standard ascii keys | |
936 | if char in string.ascii_letters or char in ['"',"'"]: |
|
944 | if char in string.ascii_letters or char in ['"',"'"]: | |
937 | return u'', () |
|
945 | return u'', () | |
938 | try : |
|
946 | try : | |
939 | latex = reverse_latex_symbol[char] |
|
947 | latex = reverse_latex_symbol[char] | |
940 | # '\\' replace the \ as well |
|
948 | # '\\' replace the \ as well | |
941 | return '\\'+char,[latex] |
|
949 | return '\\'+char,[latex] | |
942 | except KeyError: |
|
950 | except KeyError: | |
943 | pass |
|
951 | pass | |
944 | return u'', () |
|
952 | return u'', () | |
945 |
|
953 | |||
946 |
|
954 | |||
947 | def _formatparamchildren(parameter) -> str: |
|
955 | def _formatparamchildren(parameter) -> str: | |
948 | """ |
|
956 | """ | |
949 | Get parameter name and value from Jedi Private API |
|
957 | Get parameter name and value from Jedi Private API | |
950 |
|
958 | |||
951 | Jedi does not expose a simple way to get `param=value` from its API. |
|
959 | Jedi does not expose a simple way to get `param=value` from its API. | |
952 |
|
960 | |||
953 | Parameter |
|
961 | Parameter | |
954 | ========= |
|
962 | ========= | |
955 |
|
963 | |||
956 | parameter: |
|
964 | parameter: | |
957 | Jedi's function `Param` |
|
965 | Jedi's function `Param` | |
958 |
|
966 | |||
959 | Returns |
|
967 | Returns | |
960 | ======= |
|
968 | ======= | |
961 |
|
969 | |||
962 | A string like 'a', 'b=1', '*args', '**kwargs' |
|
970 | A string like 'a', 'b=1', '*args', '**kwargs' | |
963 |
|
971 | |||
964 |
|
972 | |||
965 | """ |
|
973 | """ | |
966 | description = parameter.description |
|
974 | description = parameter.description | |
967 | if not description.startswith('param '): |
|
975 | if not description.startswith('param '): | |
968 | raise ValueError('Jedi function parameter description have change format.' |
|
976 | raise ValueError('Jedi function parameter description have change format.' | |
969 | 'Expected "param ...", found %r".' % description) |
|
977 | 'Expected "param ...", found %r".' % description) | |
970 | return description[6:] |
|
978 | return description[6:] | |
971 |
|
979 | |||
972 | def _make_signature(completion)-> str: |
|
980 | def _make_signature(completion)-> str: | |
973 | """ |
|
981 | """ | |
974 | Make the signature from a jedi completion |
|
982 | Make the signature from a jedi completion | |
975 |
|
983 | |||
976 | Parameter |
|
984 | Parameter | |
977 | ========= |
|
985 | ========= | |
978 |
|
986 | |||
979 | completion: jedi.Completion |
|
987 | completion: jedi.Completion | |
980 | object does not complete a function type |
|
988 | object does not complete a function type | |
981 |
|
989 | |||
982 | Returns |
|
990 | Returns | |
983 | ======= |
|
991 | ======= | |
984 |
|
992 | |||
985 | a string consisting of the function signature, with the parenthesis but |
|
993 | a string consisting of the function signature, with the parenthesis but | |
986 | without the function name. example: |
|
994 | without the function name. example: | |
987 | `(a, *args, b=1, **kwargs)` |
|
995 | `(a, *args, b=1, **kwargs)` | |
988 |
|
996 | |||
989 | """ |
|
997 | """ | |
990 |
|
998 | |||
991 | # it looks like this might work on jedi 0.17 |
|
999 | # it looks like this might work on jedi 0.17 | |
992 | if hasattr(completion, 'get_signatures'): |
|
1000 | if hasattr(completion, 'get_signatures'): | |
993 | signatures = completion.get_signatures() |
|
1001 | signatures = completion.get_signatures() | |
994 | if not signatures: |
|
1002 | if not signatures: | |
995 | return '(?)' |
|
1003 | return '(?)' | |
996 |
|
1004 | |||
997 | c0 = completion.get_signatures()[0] |
|
1005 | c0 = completion.get_signatures()[0] | |
998 | return '('+c0.to_string().split('(', maxsplit=1)[1] |
|
1006 | return '('+c0.to_string().split('(', maxsplit=1)[1] | |
999 |
|
1007 | |||
1000 | return '(%s)'% ', '.join([f for f in (_formatparamchildren(p) for signature in completion.get_signatures() |
|
1008 | return '(%s)'% ', '.join([f for f in (_formatparamchildren(p) for signature in completion.get_signatures() | |
1001 | for p in signature.defined_names()) if f]) |
|
1009 | for p in signature.defined_names()) if f]) | |
1002 |
|
1010 | |||
1003 | class IPCompleter(Completer): |
|
1011 | class IPCompleter(Completer): | |
1004 | """Extension of the completer class with IPython-specific features""" |
|
1012 | """Extension of the completer class with IPython-specific features""" | |
1005 |
|
1013 | |||
1006 | _names = None |
|
1014 | _names = None | |
1007 |
|
1015 | |||
1008 | @observe('greedy') |
|
1016 | @observe('greedy') | |
1009 | def _greedy_changed(self, change): |
|
1017 | def _greedy_changed(self, change): | |
1010 | """update the splitter and readline delims when greedy is changed""" |
|
1018 | """update the splitter and readline delims when greedy is changed""" | |
1011 | if change['new']: |
|
1019 | if change['new']: | |
1012 | self.splitter.delims = GREEDY_DELIMS |
|
1020 | self.splitter.delims = GREEDY_DELIMS | |
1013 | else: |
|
1021 | else: | |
1014 | self.splitter.delims = DELIMS |
|
1022 | self.splitter.delims = DELIMS | |
1015 |
|
1023 | |||
1016 | dict_keys_only = Bool(False, |
|
1024 | dict_keys_only = Bool(False, | |
1017 | help="""Whether to show dict key matches only""") |
|
1025 | help="""Whether to show dict key matches only""") | |
1018 |
|
1026 | |||
1019 | merge_completions = Bool(True, |
|
1027 | merge_completions = Bool(True, | |
1020 | help="""Whether to merge completion results into a single list |
|
1028 | help="""Whether to merge completion results into a single list | |
1021 |
|
1029 | |||
1022 | If False, only the completion results from the first non-empty |
|
1030 | If False, only the completion results from the first non-empty | |
1023 | completer will be returned. |
|
1031 | completer will be returned. | |
1024 | """ |
|
1032 | """ | |
1025 | ).tag(config=True) |
|
1033 | ).tag(config=True) | |
1026 | omit__names = Enum((0,1,2), default_value=2, |
|
1034 | omit__names = Enum((0,1,2), default_value=2, | |
1027 | help="""Instruct the completer to omit private method names |
|
1035 | help="""Instruct the completer to omit private method names | |
1028 |
|
1036 | |||
1029 | Specifically, when completing on ``object.<tab>``. |
|
1037 | Specifically, when completing on ``object.<tab>``. | |
1030 |
|
1038 | |||
1031 | When 2 [default]: all names that start with '_' will be excluded. |
|
1039 | When 2 [default]: all names that start with '_' will be excluded. | |
1032 |
|
1040 | |||
1033 | When 1: all 'magic' names (``__foo__``) will be excluded. |
|
1041 | When 1: all 'magic' names (``__foo__``) will be excluded. | |
1034 |
|
1042 | |||
1035 | When 0: nothing will be excluded. |
|
1043 | When 0: nothing will be excluded. | |
1036 | """ |
|
1044 | """ | |
1037 | ).tag(config=True) |
|
1045 | ).tag(config=True) | |
1038 | limit_to__all__ = Bool(False, |
|
1046 | limit_to__all__ = Bool(False, | |
1039 | help=""" |
|
1047 | help=""" | |
1040 | DEPRECATED as of version 5.0. |
|
1048 | DEPRECATED as of version 5.0. | |
1041 |
|
1049 | |||
1042 | Instruct the completer to use __all__ for the completion |
|
1050 | Instruct the completer to use __all__ for the completion | |
1043 |
|
1051 | |||
1044 | Specifically, when completing on ``object.<tab>``. |
|
1052 | Specifically, when completing on ``object.<tab>``. | |
1045 |
|
1053 | |||
1046 | When True: only those names in obj.__all__ will be included. |
|
1054 | When True: only those names in obj.__all__ will be included. | |
1047 |
|
1055 | |||
1048 | When False [default]: the __all__ attribute is ignored |
|
1056 | When False [default]: the __all__ attribute is ignored | |
1049 | """, |
|
1057 | """, | |
1050 | ).tag(config=True) |
|
1058 | ).tag(config=True) | |
1051 |
|
1059 | |||
1052 | @observe('limit_to__all__') |
|
1060 | @observe('limit_to__all__') | |
1053 | def _limit_to_all_changed(self, change): |
|
1061 | def _limit_to_all_changed(self, change): | |
1054 | warnings.warn('`IPython.core.IPCompleter.limit_to__all__` configuration ' |
|
1062 | warnings.warn('`IPython.core.IPCompleter.limit_to__all__` configuration ' | |
1055 | 'value has been deprecated since IPython 5.0, will be made to have ' |
|
1063 | 'value has been deprecated since IPython 5.0, will be made to have ' | |
1056 | 'no effects and then removed in future version of IPython.', |
|
1064 | 'no effects and then removed in future version of IPython.', | |
1057 | UserWarning) |
|
1065 | UserWarning) | |
1058 |
|
1066 | |||
1059 | def __init__(self, shell=None, namespace=None, global_namespace=None, |
|
1067 | def __init__(self, shell=None, namespace=None, global_namespace=None, | |
1060 | use_readline=_deprecation_readline_sentinel, config=None, **kwargs): |
|
1068 | use_readline=_deprecation_readline_sentinel, config=None, **kwargs): | |
1061 | """IPCompleter() -> completer |
|
1069 | """IPCompleter() -> completer | |
1062 |
|
1070 | |||
1063 | Return a completer object. |
|
1071 | Return a completer object. | |
1064 |
|
1072 | |||
1065 | Parameters |
|
1073 | Parameters | |
1066 | ---------- |
|
1074 | ---------- | |
1067 |
|
1075 | |||
1068 | shell |
|
1076 | shell | |
1069 | a pointer to the ipython shell itself. This is needed |
|
1077 | a pointer to the ipython shell itself. This is needed | |
1070 | because this completer knows about magic functions, and those can |
|
1078 | because this completer knows about magic functions, and those can | |
1071 | only be accessed via the ipython instance. |
|
1079 | only be accessed via the ipython instance. | |
1072 |
|
1080 | |||
1073 | namespace : dict, optional |
|
1081 | namespace : dict, optional | |
1074 | an optional dict where completions are performed. |
|
1082 | an optional dict where completions are performed. | |
1075 |
|
1083 | |||
1076 | global_namespace : dict, optional |
|
1084 | global_namespace : dict, optional | |
1077 | secondary optional dict for completions, to |
|
1085 | secondary optional dict for completions, to | |
1078 | handle cases (such as IPython embedded inside functions) where |
|
1086 | handle cases (such as IPython embedded inside functions) where | |
1079 | both Python scopes are visible. |
|
1087 | both Python scopes are visible. | |
1080 |
|
1088 | |||
1081 | use_readline : bool, optional |
|
1089 | use_readline : bool, optional | |
1082 | DEPRECATED, ignored since IPython 6.0, will have no effects |
|
1090 | DEPRECATED, ignored since IPython 6.0, will have no effects | |
1083 | """ |
|
1091 | """ | |
1084 |
|
1092 | |||
1085 | self.magic_escape = ESC_MAGIC |
|
1093 | self.magic_escape = ESC_MAGIC | |
1086 | self.splitter = CompletionSplitter() |
|
1094 | self.splitter = CompletionSplitter() | |
1087 |
|
1095 | |||
1088 | if use_readline is not _deprecation_readline_sentinel: |
|
1096 | if use_readline is not _deprecation_readline_sentinel: | |
1089 | warnings.warn('The `use_readline` parameter is deprecated and ignored since IPython 6.0.', |
|
1097 | warnings.warn('The `use_readline` parameter is deprecated and ignored since IPython 6.0.', | |
1090 | DeprecationWarning, stacklevel=2) |
|
1098 | DeprecationWarning, stacklevel=2) | |
1091 |
|
1099 | |||
1092 | # _greedy_changed() depends on splitter and readline being defined: |
|
1100 | # _greedy_changed() depends on splitter and readline being defined: | |
1093 | Completer.__init__(self, namespace=namespace, global_namespace=global_namespace, |
|
1101 | Completer.__init__(self, namespace=namespace, global_namespace=global_namespace, | |
1094 | config=config, **kwargs) |
|
1102 | config=config, **kwargs) | |
1095 |
|
1103 | |||
1096 | # List where completion matches will be stored |
|
1104 | # List where completion matches will be stored | |
1097 | self.matches = [] |
|
1105 | self.matches = [] | |
1098 | self.shell = shell |
|
1106 | self.shell = shell | |
1099 | # Regexp to split filenames with spaces in them |
|
1107 | # Regexp to split filenames with spaces in them | |
1100 | self.space_name_re = re.compile(r'([^\\] )') |
|
1108 | self.space_name_re = re.compile(r'([^\\] )') | |
1101 | # Hold a local ref. to glob.glob for speed |
|
1109 | # Hold a local ref. to glob.glob for speed | |
1102 | self.glob = glob.glob |
|
1110 | self.glob = glob.glob | |
1103 |
|
1111 | |||
1104 | # Determine if we are running on 'dumb' terminals, like (X)Emacs |
|
1112 | # Determine if we are running on 'dumb' terminals, like (X)Emacs | |
1105 | # buffers, to avoid completion problems. |
|
1113 | # buffers, to avoid completion problems. | |
1106 | term = os.environ.get('TERM','xterm') |
|
1114 | term = os.environ.get('TERM','xterm') | |
1107 | self.dumb_terminal = term in ['dumb','emacs'] |
|
1115 | self.dumb_terminal = term in ['dumb','emacs'] | |
1108 |
|
1116 | |||
1109 | # Special handling of backslashes needed in win32 platforms |
|
1117 | # Special handling of backslashes needed in win32 platforms | |
1110 | if sys.platform == "win32": |
|
1118 | if sys.platform == "win32": | |
1111 | self.clean_glob = self._clean_glob_win32 |
|
1119 | self.clean_glob = self._clean_glob_win32 | |
1112 | else: |
|
1120 | else: | |
1113 | self.clean_glob = self._clean_glob |
|
1121 | self.clean_glob = self._clean_glob | |
1114 |
|
1122 | |||
1115 | #regexp to parse docstring for function signature |
|
1123 | #regexp to parse docstring for function signature | |
1116 | self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*') |
|
1124 | self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*') | |
1117 | self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)') |
|
1125 | self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)') | |
1118 | #use this if positional argument name is also needed |
|
1126 | #use this if positional argument name is also needed | |
1119 | #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)') |
|
1127 | #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)') | |
1120 |
|
1128 | |||
1121 | self.magic_arg_matchers = [ |
|
1129 | self.magic_arg_matchers = [ | |
1122 | self.magic_config_matches, |
|
1130 | self.magic_config_matches, | |
1123 | self.magic_color_matches, |
|
1131 | self.magic_color_matches, | |
1124 | ] |
|
1132 | ] | |
1125 |
|
1133 | |||
1126 | # This is set externally by InteractiveShell |
|
1134 | # This is set externally by InteractiveShell | |
1127 | self.custom_completers = None |
|
1135 | self.custom_completers = None | |
1128 |
|
1136 | |||
1129 | @property |
|
1137 | @property | |
1130 | def matchers(self): |
|
1138 | def matchers(self): | |
1131 | """All active matcher routines for completion""" |
|
1139 | """All active matcher routines for completion""" | |
1132 | if self.dict_keys_only: |
|
1140 | if self.dict_keys_only: | |
1133 | return [self.dict_key_matches] |
|
1141 | return [self.dict_key_matches] | |
1134 |
|
1142 | |||
1135 | if self.use_jedi: |
|
1143 | if self.use_jedi: | |
1136 | return [ |
|
1144 | return [ | |
1137 | *self.custom_matchers, |
|
1145 | *self.custom_matchers, | |
1138 | self.file_matches, |
|
1146 | self.file_matches, | |
1139 | self.magic_matches, |
|
1147 | self.magic_matches, | |
1140 | self.dict_key_matches, |
|
1148 | self.dict_key_matches, | |
1141 | ] |
|
1149 | ] | |
1142 | else: |
|
1150 | else: | |
1143 | return [ |
|
1151 | return [ | |
1144 | *self.custom_matchers, |
|
1152 | *self.custom_matchers, | |
1145 | self.python_matches, |
|
1153 | self.python_matches, | |
1146 | self.file_matches, |
|
1154 | self.file_matches, | |
1147 | self.magic_matches, |
|
1155 | self.magic_matches, | |
1148 | self.python_func_kw_matches, |
|
1156 | self.python_func_kw_matches, | |
1149 | self.dict_key_matches, |
|
1157 | self.dict_key_matches, | |
1150 | ] |
|
1158 | ] | |
1151 |
|
1159 | |||
1152 | def all_completions(self, text) -> List[str]: |
|
1160 | def all_completions(self, text) -> List[str]: | |
1153 | """ |
|
1161 | """ | |
1154 | Wrapper around the completion methods for the benefit of emacs. |
|
1162 | Wrapper around the completion methods for the benefit of emacs. | |
1155 | """ |
|
1163 | """ | |
1156 | prefix = text.rpartition('.')[0] |
|
1164 | prefix = text.rpartition('.')[0] | |
1157 | with provisionalcompleter(): |
|
1165 | with provisionalcompleter(): | |
1158 | return ['.'.join([prefix, c.text]) if prefix and self.use_jedi else c.text |
|
1166 | return ['.'.join([prefix, c.text]) if prefix and self.use_jedi else c.text | |
1159 | for c in self.completions(text, len(text))] |
|
1167 | for c in self.completions(text, len(text))] | |
1160 |
|
1168 | |||
1161 | return self.complete(text)[1] |
|
1169 | return self.complete(text)[1] | |
1162 |
|
1170 | |||
1163 | def _clean_glob(self, text): |
|
1171 | def _clean_glob(self, text): | |
1164 | return self.glob("%s*" % text) |
|
1172 | return self.glob("%s*" % text) | |
1165 |
|
1173 | |||
1166 | def _clean_glob_win32(self,text): |
|
1174 | def _clean_glob_win32(self,text): | |
1167 | return [f.replace("\\","/") |
|
1175 | return [f.replace("\\","/") | |
1168 | for f in self.glob("%s*" % text)] |
|
1176 | for f in self.glob("%s*" % text)] | |
1169 |
|
1177 | |||
1170 | def file_matches(self, text): |
|
1178 | def file_matches(self, text): | |
1171 | """Match filenames, expanding ~USER type strings. |
|
1179 | """Match filenames, expanding ~USER type strings. | |
1172 |
|
1180 | |||
1173 | Most of the seemingly convoluted logic in this completer is an |
|
1181 | Most of the seemingly convoluted logic in this completer is an | |
1174 | attempt to handle filenames with spaces in them. And yet it's not |
|
1182 | attempt to handle filenames with spaces in them. And yet it's not | |
1175 | quite perfect, because Python's readline doesn't expose all of the |
|
1183 | quite perfect, because Python's readline doesn't expose all of the | |
1176 | GNU readline details needed for this to be done correctly. |
|
1184 | GNU readline details needed for this to be done correctly. | |
1177 |
|
1185 | |||
1178 | For a filename with a space in it, the printed completions will be |
|
1186 | For a filename with a space in it, the printed completions will be | |
1179 | only the parts after what's already been typed (instead of the |
|
1187 | only the parts after what's already been typed (instead of the | |
1180 | full completions, as is normally done). I don't think with the |
|
1188 | full completions, as is normally done). I don't think with the | |
1181 | current (as of Python 2.3) Python readline it's possible to do |
|
1189 | current (as of Python 2.3) Python readline it's possible to do | |
1182 | better.""" |
|
1190 | better.""" | |
1183 |
|
1191 | |||
1184 | # chars that require escaping with backslash - i.e. chars |
|
1192 | # chars that require escaping with backslash - i.e. chars | |
1185 | # that readline treats incorrectly as delimiters, but we |
|
1193 | # that readline treats incorrectly as delimiters, but we | |
1186 | # don't want to treat as delimiters in filename matching |
|
1194 | # don't want to treat as delimiters in filename matching | |
1187 | # when escaped with backslash |
|
1195 | # when escaped with backslash | |
1188 | if text.startswith('!'): |
|
1196 | if text.startswith('!'): | |
1189 | text = text[1:] |
|
1197 | text = text[1:] | |
1190 | text_prefix = u'!' |
|
1198 | text_prefix = u'!' | |
1191 | else: |
|
1199 | else: | |
1192 | text_prefix = u'' |
|
1200 | text_prefix = u'' | |
1193 |
|
1201 | |||
1194 | text_until_cursor = self.text_until_cursor |
|
1202 | text_until_cursor = self.text_until_cursor | |
1195 | # track strings with open quotes |
|
1203 | # track strings with open quotes | |
1196 | open_quotes = has_open_quotes(text_until_cursor) |
|
1204 | open_quotes = has_open_quotes(text_until_cursor) | |
1197 |
|
1205 | |||
1198 | if '(' in text_until_cursor or '[' in text_until_cursor: |
|
1206 | if '(' in text_until_cursor or '[' in text_until_cursor: | |
1199 | lsplit = text |
|
1207 | lsplit = text | |
1200 | else: |
|
1208 | else: | |
1201 | try: |
|
1209 | try: | |
1202 | # arg_split ~ shlex.split, but with unicode bugs fixed by us |
|
1210 | # arg_split ~ shlex.split, but with unicode bugs fixed by us | |
1203 | lsplit = arg_split(text_until_cursor)[-1] |
|
1211 | lsplit = arg_split(text_until_cursor)[-1] | |
1204 | except ValueError: |
|
1212 | except ValueError: | |
1205 | # typically an unmatched ", or backslash without escaped char. |
|
1213 | # typically an unmatched ", or backslash without escaped char. | |
1206 | if open_quotes: |
|
1214 | if open_quotes: | |
1207 | lsplit = text_until_cursor.split(open_quotes)[-1] |
|
1215 | lsplit = text_until_cursor.split(open_quotes)[-1] | |
1208 | else: |
|
1216 | else: | |
1209 | return [] |
|
1217 | return [] | |
1210 | except IndexError: |
|
1218 | except IndexError: | |
1211 | # tab pressed on empty line |
|
1219 | # tab pressed on empty line | |
1212 | lsplit = "" |
|
1220 | lsplit = "" | |
1213 |
|
1221 | |||
1214 | if not open_quotes and lsplit != protect_filename(lsplit): |
|
1222 | if not open_quotes and lsplit != protect_filename(lsplit): | |
1215 | # if protectables are found, do matching on the whole escaped name |
|
1223 | # if protectables are found, do matching on the whole escaped name | |
1216 | has_protectables = True |
|
1224 | has_protectables = True | |
1217 | text0,text = text,lsplit |
|
1225 | text0,text = text,lsplit | |
1218 | else: |
|
1226 | else: | |
1219 | has_protectables = False |
|
1227 | has_protectables = False | |
1220 | text = os.path.expanduser(text) |
|
1228 | text = os.path.expanduser(text) | |
1221 |
|
1229 | |||
1222 | if text == "": |
|
1230 | if text == "": | |
1223 | return [text_prefix + protect_filename(f) for f in self.glob("*")] |
|
1231 | return [text_prefix + protect_filename(f) for f in self.glob("*")] | |
1224 |
|
1232 | |||
1225 | # Compute the matches from the filesystem |
|
1233 | # Compute the matches from the filesystem | |
1226 | if sys.platform == 'win32': |
|
1234 | if sys.platform == 'win32': | |
1227 | m0 = self.clean_glob(text) |
|
1235 | m0 = self.clean_glob(text) | |
1228 | else: |
|
1236 | else: | |
1229 | m0 = self.clean_glob(text.replace('\\', '')) |
|
1237 | m0 = self.clean_glob(text.replace('\\', '')) | |
1230 |
|
1238 | |||
1231 | if has_protectables: |
|
1239 | if has_protectables: | |
1232 | # If we had protectables, we need to revert our changes to the |
|
1240 | # If we had protectables, we need to revert our changes to the | |
1233 | # beginning of filename so that we don't double-write the part |
|
1241 | # beginning of filename so that we don't double-write the part | |
1234 | # of the filename we have so far |
|
1242 | # of the filename we have so far | |
1235 | len_lsplit = len(lsplit) |
|
1243 | len_lsplit = len(lsplit) | |
1236 | matches = [text_prefix + text0 + |
|
1244 | matches = [text_prefix + text0 + | |
1237 | protect_filename(f[len_lsplit:]) for f in m0] |
|
1245 | protect_filename(f[len_lsplit:]) for f in m0] | |
1238 | else: |
|
1246 | else: | |
1239 | if open_quotes: |
|
1247 | if open_quotes: | |
1240 | # if we have a string with an open quote, we don't need to |
|
1248 | # if we have a string with an open quote, we don't need to | |
1241 | # protect the names beyond the quote (and we _shouldn't_, as |
|
1249 | # protect the names beyond the quote (and we _shouldn't_, as | |
1242 | # it would cause bugs when the filesystem call is made). |
|
1250 | # it would cause bugs when the filesystem call is made). | |
1243 | matches = m0 if sys.platform == "win32" else\ |
|
1251 | matches = m0 if sys.platform == "win32" else\ | |
1244 | [protect_filename(f, open_quotes) for f in m0] |
|
1252 | [protect_filename(f, open_quotes) for f in m0] | |
1245 | else: |
|
1253 | else: | |
1246 | matches = [text_prefix + |
|
1254 | matches = [text_prefix + | |
1247 | protect_filename(f) for f in m0] |
|
1255 | protect_filename(f) for f in m0] | |
1248 |
|
1256 | |||
1249 | # Mark directories in input list by appending '/' to their names. |
|
1257 | # Mark directories in input list by appending '/' to their names. | |
1250 | return [x+'/' if os.path.isdir(x) else x for x in matches] |
|
1258 | return [x+'/' if os.path.isdir(x) else x for x in matches] | |
1251 |
|
1259 | |||
1252 | def magic_matches(self, text): |
|
1260 | def magic_matches(self, text): | |
1253 | """Match magics""" |
|
1261 | """Match magics""" | |
1254 | # Get all shell magics now rather than statically, so magics loaded at |
|
1262 | # Get all shell magics now rather than statically, so magics loaded at | |
1255 | # runtime show up too. |
|
1263 | # runtime show up too. | |
1256 | lsm = self.shell.magics_manager.lsmagic() |
|
1264 | lsm = self.shell.magics_manager.lsmagic() | |
1257 | line_magics = lsm['line'] |
|
1265 | line_magics = lsm['line'] | |
1258 | cell_magics = lsm['cell'] |
|
1266 | cell_magics = lsm['cell'] | |
1259 | pre = self.magic_escape |
|
1267 | pre = self.magic_escape | |
1260 | pre2 = pre+pre |
|
1268 | pre2 = pre+pre | |
1261 |
|
1269 | |||
1262 | explicit_magic = text.startswith(pre) |
|
1270 | explicit_magic = text.startswith(pre) | |
1263 |
|
1271 | |||
1264 | # Completion logic: |
|
1272 | # Completion logic: | |
1265 | # - user gives %%: only do cell magics |
|
1273 | # - user gives %%: only do cell magics | |
1266 | # - user gives %: do both line and cell magics |
|
1274 | # - user gives %: do both line and cell magics | |
1267 | # - no prefix: do both |
|
1275 | # - no prefix: do both | |
1268 | # In other words, line magics are skipped if the user gives %% explicitly |
|
1276 | # In other words, line magics are skipped if the user gives %% explicitly | |
1269 | # |
|
1277 | # | |
1270 | # We also exclude magics that match any currently visible names: |
|
1278 | # We also exclude magics that match any currently visible names: | |
1271 | # https://github.com/ipython/ipython/issues/4877, unless the user has |
|
1279 | # https://github.com/ipython/ipython/issues/4877, unless the user has | |
1272 | # typed a %: |
|
1280 | # typed a %: | |
1273 | # https://github.com/ipython/ipython/issues/10754 |
|
1281 | # https://github.com/ipython/ipython/issues/10754 | |
1274 | bare_text = text.lstrip(pre) |
|
1282 | bare_text = text.lstrip(pre) | |
1275 | global_matches = self.global_matches(bare_text) |
|
1283 | global_matches = self.global_matches(bare_text) | |
1276 | if not explicit_magic: |
|
1284 | if not explicit_magic: | |
1277 | def matches(magic): |
|
1285 | def matches(magic): | |
1278 | """ |
|
1286 | """ | |
1279 | Filter magics, in particular remove magics that match |
|
1287 | Filter magics, in particular remove magics that match | |
1280 | a name present in global namespace. |
|
1288 | a name present in global namespace. | |
1281 | """ |
|
1289 | """ | |
1282 | return ( magic.startswith(bare_text) and |
|
1290 | return ( magic.startswith(bare_text) and | |
1283 | magic not in global_matches ) |
|
1291 | magic not in global_matches ) | |
1284 | else: |
|
1292 | else: | |
1285 | def matches(magic): |
|
1293 | def matches(magic): | |
1286 | return magic.startswith(bare_text) |
|
1294 | return magic.startswith(bare_text) | |
1287 |
|
1295 | |||
1288 | comp = [ pre2+m for m in cell_magics if matches(m)] |
|
1296 | comp = [ pre2+m for m in cell_magics if matches(m)] | |
1289 | if not text.startswith(pre2): |
|
1297 | if not text.startswith(pre2): | |
1290 | comp += [ pre+m for m in line_magics if matches(m)] |
|
1298 | comp += [ pre+m for m in line_magics if matches(m)] | |
1291 |
|
1299 | |||
1292 | return comp |
|
1300 | return comp | |
1293 |
|
1301 | |||
1294 | def magic_config_matches(self, text:str) -> List[str]: |
|
1302 | def magic_config_matches(self, text:str) -> List[str]: | |
1295 | """ Match class names and attributes for %config magic """ |
|
1303 | """ Match class names and attributes for %config magic """ | |
1296 | texts = text.strip().split() |
|
1304 | texts = text.strip().split() | |
1297 |
|
1305 | |||
1298 | if len(texts) > 0 and (texts[0] == 'config' or texts[0] == '%config'): |
|
1306 | if len(texts) > 0 and (texts[0] == 'config' or texts[0] == '%config'): | |
1299 | # get all configuration classes |
|
1307 | # get all configuration classes | |
1300 | classes = sorted(set([ c for c in self.shell.configurables |
|
1308 | classes = sorted(set([ c for c in self.shell.configurables | |
1301 | if c.__class__.class_traits(config=True) |
|
1309 | if c.__class__.class_traits(config=True) | |
1302 | ]), key=lambda x: x.__class__.__name__) |
|
1310 | ]), key=lambda x: x.__class__.__name__) | |
1303 | classnames = [ c.__class__.__name__ for c in classes ] |
|
1311 | classnames = [ c.__class__.__name__ for c in classes ] | |
1304 |
|
1312 | |||
1305 | # return all classnames if config or %config is given |
|
1313 | # return all classnames if config or %config is given | |
1306 | if len(texts) == 1: |
|
1314 | if len(texts) == 1: | |
1307 | return classnames |
|
1315 | return classnames | |
1308 |
|
1316 | |||
1309 | # match classname |
|
1317 | # match classname | |
1310 | classname_texts = texts[1].split('.') |
|
1318 | classname_texts = texts[1].split('.') | |
1311 | classname = classname_texts[0] |
|
1319 | classname = classname_texts[0] | |
1312 | classname_matches = [ c for c in classnames |
|
1320 | classname_matches = [ c for c in classnames | |
1313 | if c.startswith(classname) ] |
|
1321 | if c.startswith(classname) ] | |
1314 |
|
1322 | |||
1315 | # return matched classes or the matched class with attributes |
|
1323 | # return matched classes or the matched class with attributes | |
1316 | if texts[1].find('.') < 0: |
|
1324 | if texts[1].find('.') < 0: | |
1317 | return classname_matches |
|
1325 | return classname_matches | |
1318 | elif len(classname_matches) == 1 and \ |
|
1326 | elif len(classname_matches) == 1 and \ | |
1319 | classname_matches[0] == classname: |
|
1327 | classname_matches[0] == classname: | |
1320 | cls = classes[classnames.index(classname)].__class__ |
|
1328 | cls = classes[classnames.index(classname)].__class__ | |
1321 | help = cls.class_get_help() |
|
1329 | help = cls.class_get_help() | |
1322 | # strip leading '--' from cl-args: |
|
1330 | # strip leading '--' from cl-args: | |
1323 | help = re.sub(re.compile(r'^--', re.MULTILINE), '', help) |
|
1331 | help = re.sub(re.compile(r'^--', re.MULTILINE), '', help) | |
1324 | return [ attr.split('=')[0] |
|
1332 | return [ attr.split('=')[0] | |
1325 | for attr in help.strip().splitlines() |
|
1333 | for attr in help.strip().splitlines() | |
1326 | if attr.startswith(texts[1]) ] |
|
1334 | if attr.startswith(texts[1]) ] | |
1327 | return [] |
|
1335 | return [] | |
1328 |
|
1336 | |||
1329 | def magic_color_matches(self, text:str) -> List[str] : |
|
1337 | def magic_color_matches(self, text:str) -> List[str] : | |
1330 | """ Match color schemes for %colors magic""" |
|
1338 | """ Match color schemes for %colors magic""" | |
1331 | texts = text.split() |
|
1339 | texts = text.split() | |
1332 | if text.endswith(' '): |
|
1340 | if text.endswith(' '): | |
1333 | # .split() strips off the trailing whitespace. Add '' back |
|
1341 | # .split() strips off the trailing whitespace. Add '' back | |
1334 | # so that: '%colors ' -> ['%colors', ''] |
|
1342 | # so that: '%colors ' -> ['%colors', ''] | |
1335 | texts.append('') |
|
1343 | texts.append('') | |
1336 |
|
1344 | |||
1337 | if len(texts) == 2 and (texts[0] == 'colors' or texts[0] == '%colors'): |
|
1345 | if len(texts) == 2 and (texts[0] == 'colors' or texts[0] == '%colors'): | |
1338 | prefix = texts[1] |
|
1346 | prefix = texts[1] | |
1339 | return [ color for color in InspectColors.keys() |
|
1347 | return [ color for color in InspectColors.keys() | |
1340 | if color.startswith(prefix) ] |
|
1348 | if color.startswith(prefix) ] | |
1341 | return [] |
|
1349 | return [] | |
1342 |
|
1350 | |||
1343 | def _jedi_matches(self, cursor_column:int, cursor_line:int, text:str): |
|
1351 | def _jedi_matches(self, cursor_column:int, cursor_line:int, text:str): | |
1344 | """ |
|
1352 | """ | |
1345 |
|
1353 | |||
1346 | Return a list of :any:`jedi.api.Completions` object from a ``text`` and |
|
1354 | Return a list of :any:`jedi.api.Completions` object from a ``text`` and | |
1347 | cursor position. |
|
1355 | cursor position. | |
1348 |
|
1356 | |||
1349 | Parameters |
|
1357 | Parameters | |
1350 | ---------- |
|
1358 | ---------- | |
1351 | cursor_column : int |
|
1359 | cursor_column : int | |
1352 | column position of the cursor in ``text``, 0-indexed. |
|
1360 | column position of the cursor in ``text``, 0-indexed. | |
1353 | cursor_line : int |
|
1361 | cursor_line : int | |
1354 | line position of the cursor in ``text``, 0-indexed |
|
1362 | line position of the cursor in ``text``, 0-indexed | |
1355 | text : str |
|
1363 | text : str | |
1356 | text to complete |
|
1364 | text to complete | |
1357 |
|
1365 | |||
1358 | Debugging |
|
1366 | Debugging | |
1359 | --------- |
|
1367 | --------- | |
1360 |
|
1368 | |||
1361 | If ``IPCompleter.debug`` is ``True`` may return a :any:`_FakeJediCompletion` |
|
1369 | If ``IPCompleter.debug`` is ``True`` may return a :any:`_FakeJediCompletion` | |
1362 | object containing a string with the Jedi debug information attached. |
|
1370 | object containing a string with the Jedi debug information attached. | |
1363 | """ |
|
1371 | """ | |
1364 | namespaces = [self.namespace] |
|
1372 | namespaces = [self.namespace] | |
1365 | if self.global_namespace is not None: |
|
1373 | if self.global_namespace is not None: | |
1366 | namespaces.append(self.global_namespace) |
|
1374 | namespaces.append(self.global_namespace) | |
1367 |
|
1375 | |||
1368 | completion_filter = lambda x:x |
|
1376 | completion_filter = lambda x:x | |
1369 | offset = cursor_to_position(text, cursor_line, cursor_column) |
|
1377 | offset = cursor_to_position(text, cursor_line, cursor_column) | |
1370 | # filter output if we are completing for object members |
|
1378 | # filter output if we are completing for object members | |
1371 | if offset: |
|
1379 | if offset: | |
1372 | pre = text[offset-1] |
|
1380 | pre = text[offset-1] | |
1373 | if pre == '.': |
|
1381 | if pre == '.': | |
1374 | if self.omit__names == 2: |
|
1382 | if self.omit__names == 2: | |
1375 | completion_filter = lambda c:not c.name.startswith('_') |
|
1383 | completion_filter = lambda c:not c.name.startswith('_') | |
1376 | elif self.omit__names == 1: |
|
1384 | elif self.omit__names == 1: | |
1377 | completion_filter = lambda c:not (c.name.startswith('__') and c.name.endswith('__')) |
|
1385 | completion_filter = lambda c:not (c.name.startswith('__') and c.name.endswith('__')) | |
1378 | elif self.omit__names == 0: |
|
1386 | elif self.omit__names == 0: | |
1379 | completion_filter = lambda x:x |
|
1387 | completion_filter = lambda x:x | |
1380 | else: |
|
1388 | else: | |
1381 | raise ValueError("Don't understand self.omit__names == {}".format(self.omit__names)) |
|
1389 | raise ValueError("Don't understand self.omit__names == {}".format(self.omit__names)) | |
1382 |
|
1390 | |||
1383 | interpreter = jedi.Interpreter(text[:offset], namespaces) |
|
1391 | interpreter = jedi.Interpreter(text[:offset], namespaces) | |
1384 | try_jedi = True |
|
1392 | try_jedi = True | |
1385 |
|
1393 | |||
1386 | try: |
|
1394 | try: | |
1387 | # find the first token in the current tree -- if it is a ' or " then we are in a string |
|
1395 | # find the first token in the current tree -- if it is a ' or " then we are in a string | |
1388 | completing_string = False |
|
1396 | completing_string = False | |
1389 | try: |
|
1397 | try: | |
1390 | first_child = next(c for c in interpreter._get_module().tree_node.children if hasattr(c, 'value')) |
|
1398 | first_child = next(c for c in interpreter._get_module().tree_node.children if hasattr(c, 'value')) | |
1391 | except StopIteration: |
|
1399 | except StopIteration: | |
1392 | pass |
|
1400 | pass | |
1393 | else: |
|
1401 | else: | |
1394 | # note the value may be ', ", or it may also be ''' or """, or |
|
1402 | # note the value may be ', ", or it may also be ''' or """, or | |
1395 | # in some cases, """what/you/typed..., but all of these are |
|
1403 | # in some cases, """what/you/typed..., but all of these are | |
1396 | # strings. |
|
1404 | # strings. | |
1397 | completing_string = len(first_child.value) > 0 and first_child.value[0] in {"'", '"'} |
|
1405 | completing_string = len(first_child.value) > 0 and first_child.value[0] in {"'", '"'} | |
1398 |
|
1406 | |||
1399 | # if we are in a string jedi is likely not the right candidate for |
|
1407 | # if we are in a string jedi is likely not the right candidate for | |
1400 | # now. Skip it. |
|
1408 | # now. Skip it. | |
1401 | try_jedi = not completing_string |
|
1409 | try_jedi = not completing_string | |
1402 | except Exception as e: |
|
1410 | except Exception as e: | |
1403 | # many of things can go wrong, we are using private API just don't crash. |
|
1411 | # many of things can go wrong, we are using private API just don't crash. | |
1404 | if self.debug: |
|
1412 | if self.debug: | |
1405 | print("Error detecting if completing a non-finished string :", e, '|') |
|
1413 | print("Error detecting if completing a non-finished string :", e, '|') | |
1406 |
|
1414 | |||
1407 | if not try_jedi: |
|
1415 | if not try_jedi: | |
1408 | return [] |
|
1416 | return [] | |
1409 | try: |
|
1417 | try: | |
1410 | return filter(completion_filter, interpreter.complete(column=cursor_column, line=cursor_line + 1)) |
|
1418 | return filter(completion_filter, interpreter.complete(column=cursor_column, line=cursor_line + 1)) | |
1411 | except Exception as e: |
|
1419 | except Exception as e: | |
1412 | if self.debug: |
|
1420 | if self.debug: | |
1413 | return [_FakeJediCompletion('Oops Jedi has crashed, please report a bug with the following:\n"""\n%s\ns"""' % (e))] |
|
1421 | return [_FakeJediCompletion('Oops Jedi has crashed, please report a bug with the following:\n"""\n%s\ns"""' % (e))] | |
1414 | else: |
|
1422 | else: | |
1415 | return [] |
|
1423 | return [] | |
1416 |
|
1424 | |||
1417 | def python_matches(self, text): |
|
1425 | def python_matches(self, text): | |
1418 | """Match attributes or global python names""" |
|
1426 | """Match attributes or global python names""" | |
1419 | if "." in text: |
|
1427 | if "." in text: | |
1420 | try: |
|
1428 | try: | |
1421 | matches = self.attr_matches(text) |
|
1429 | matches = self.attr_matches(text) | |
1422 | if text.endswith('.') and self.omit__names: |
|
1430 | if text.endswith('.') and self.omit__names: | |
1423 | if self.omit__names == 1: |
|
1431 | if self.omit__names == 1: | |
1424 | # true if txt is _not_ a __ name, false otherwise: |
|
1432 | # true if txt is _not_ a __ name, false otherwise: | |
1425 | no__name = (lambda txt: |
|
1433 | no__name = (lambda txt: | |
1426 | re.match(r'.*\.__.*?__',txt) is None) |
|
1434 | re.match(r'.*\.__.*?__',txt) is None) | |
1427 | else: |
|
1435 | else: | |
1428 | # true if txt is _not_ a _ name, false otherwise: |
|
1436 | # true if txt is _not_ a _ name, false otherwise: | |
1429 | no__name = (lambda txt: |
|
1437 | no__name = (lambda txt: | |
1430 | re.match(r'\._.*?',txt[txt.rindex('.'):]) is None) |
|
1438 | re.match(r'\._.*?',txt[txt.rindex('.'):]) is None) | |
1431 | matches = filter(no__name, matches) |
|
1439 | matches = filter(no__name, matches) | |
1432 | except NameError: |
|
1440 | except NameError: | |
1433 | # catches <undefined attributes>.<tab> |
|
1441 | # catches <undefined attributes>.<tab> | |
1434 | matches = [] |
|
1442 | matches = [] | |
1435 | else: |
|
1443 | else: | |
1436 | matches = self.global_matches(text) |
|
1444 | matches = self.global_matches(text) | |
1437 | return matches |
|
1445 | return matches | |
1438 |
|
1446 | |||
1439 | def _default_arguments_from_docstring(self, doc): |
|
1447 | def _default_arguments_from_docstring(self, doc): | |
1440 | """Parse the first line of docstring for call signature. |
|
1448 | """Parse the first line of docstring for call signature. | |
1441 |
|
1449 | |||
1442 | Docstring should be of the form 'min(iterable[, key=func])\n'. |
|
1450 | Docstring should be of the form 'min(iterable[, key=func])\n'. | |
1443 | It can also parse cython docstring of the form |
|
1451 | It can also parse cython docstring of the form | |
1444 | 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'. |
|
1452 | 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'. | |
1445 | """ |
|
1453 | """ | |
1446 | if doc is None: |
|
1454 | if doc is None: | |
1447 | return [] |
|
1455 | return [] | |
1448 |
|
1456 | |||
1449 | #care only the firstline |
|
1457 | #care only the firstline | |
1450 | line = doc.lstrip().splitlines()[0] |
|
1458 | line = doc.lstrip().splitlines()[0] | |
1451 |
|
1459 | |||
1452 | #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*') |
|
1460 | #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*') | |
1453 | #'min(iterable[, key=func])\n' -> 'iterable[, key=func]' |
|
1461 | #'min(iterable[, key=func])\n' -> 'iterable[, key=func]' | |
1454 | sig = self.docstring_sig_re.search(line) |
|
1462 | sig = self.docstring_sig_re.search(line) | |
1455 | if sig is None: |
|
1463 | if sig is None: | |
1456 | return [] |
|
1464 | return [] | |
1457 | # iterable[, key=func]' -> ['iterable[' ,' key=func]'] |
|
1465 | # iterable[, key=func]' -> ['iterable[' ,' key=func]'] | |
1458 | sig = sig.groups()[0].split(',') |
|
1466 | sig = sig.groups()[0].split(',') | |
1459 | ret = [] |
|
1467 | ret = [] | |
1460 | for s in sig: |
|
1468 | for s in sig: | |
1461 | #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)') |
|
1469 | #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)') | |
1462 | ret += self.docstring_kwd_re.findall(s) |
|
1470 | ret += self.docstring_kwd_re.findall(s) | |
1463 | return ret |
|
1471 | return ret | |
1464 |
|
1472 | |||
1465 | def _default_arguments(self, obj): |
|
1473 | def _default_arguments(self, obj): | |
1466 | """Return the list of default arguments of obj if it is callable, |
|
1474 | """Return the list of default arguments of obj if it is callable, | |
1467 | or empty list otherwise.""" |
|
1475 | or empty list otherwise.""" | |
1468 | call_obj = obj |
|
1476 | call_obj = obj | |
1469 | ret = [] |
|
1477 | ret = [] | |
1470 | if inspect.isbuiltin(obj): |
|
1478 | if inspect.isbuiltin(obj): | |
1471 | pass |
|
1479 | pass | |
1472 | elif not (inspect.isfunction(obj) or inspect.ismethod(obj)): |
|
1480 | elif not (inspect.isfunction(obj) or inspect.ismethod(obj)): | |
1473 | if inspect.isclass(obj): |
|
1481 | if inspect.isclass(obj): | |
1474 | #for cython embedsignature=True the constructor docstring |
|
1482 | #for cython embedsignature=True the constructor docstring | |
1475 | #belongs to the object itself not __init__ |
|
1483 | #belongs to the object itself not __init__ | |
1476 | ret += self._default_arguments_from_docstring( |
|
1484 | ret += self._default_arguments_from_docstring( | |
1477 | getattr(obj, '__doc__', '')) |
|
1485 | getattr(obj, '__doc__', '')) | |
1478 | # for classes, check for __init__,__new__ |
|
1486 | # for classes, check for __init__,__new__ | |
1479 | call_obj = (getattr(obj, '__init__', None) or |
|
1487 | call_obj = (getattr(obj, '__init__', None) or | |
1480 | getattr(obj, '__new__', None)) |
|
1488 | getattr(obj, '__new__', None)) | |
1481 | # for all others, check if they are __call__able |
|
1489 | # for all others, check if they are __call__able | |
1482 | elif hasattr(obj, '__call__'): |
|
1490 | elif hasattr(obj, '__call__'): | |
1483 | call_obj = obj.__call__ |
|
1491 | call_obj = obj.__call__ | |
1484 | ret += self._default_arguments_from_docstring( |
|
1492 | ret += self._default_arguments_from_docstring( | |
1485 | getattr(call_obj, '__doc__', '')) |
|
1493 | getattr(call_obj, '__doc__', '')) | |
1486 |
|
1494 | |||
1487 | _keeps = (inspect.Parameter.KEYWORD_ONLY, |
|
1495 | _keeps = (inspect.Parameter.KEYWORD_ONLY, | |
1488 | inspect.Parameter.POSITIONAL_OR_KEYWORD) |
|
1496 | inspect.Parameter.POSITIONAL_OR_KEYWORD) | |
1489 |
|
1497 | |||
1490 | try: |
|
1498 | try: | |
1491 | sig = inspect.signature(call_obj) |
|
1499 | sig = inspect.signature(call_obj) | |
1492 | ret.extend(k for k, v in sig.parameters.items() if |
|
1500 | ret.extend(k for k, v in sig.parameters.items() if | |
1493 | v.kind in _keeps) |
|
1501 | v.kind in _keeps) | |
1494 | except ValueError: |
|
1502 | except ValueError: | |
1495 | pass |
|
1503 | pass | |
1496 |
|
1504 | |||
1497 | return list(set(ret)) |
|
1505 | return list(set(ret)) | |
1498 |
|
1506 | |||
1499 | def python_func_kw_matches(self,text): |
|
1507 | def python_func_kw_matches(self,text): | |
1500 | """Match named parameters (kwargs) of the last open function""" |
|
1508 | """Match named parameters (kwargs) of the last open function""" | |
1501 |
|
1509 | |||
1502 | if "." in text: # a parameter cannot be dotted |
|
1510 | if "." in text: # a parameter cannot be dotted | |
1503 | return [] |
|
1511 | return [] | |
1504 | try: regexp = self.__funcParamsRegex |
|
1512 | try: regexp = self.__funcParamsRegex | |
1505 | except AttributeError: |
|
1513 | except AttributeError: | |
1506 | regexp = self.__funcParamsRegex = re.compile(r''' |
|
1514 | regexp = self.__funcParamsRegex = re.compile(r''' | |
1507 | '.*?(?<!\\)' | # single quoted strings or |
|
1515 | '.*?(?<!\\)' | # single quoted strings or | |
1508 | ".*?(?<!\\)" | # double quoted strings or |
|
1516 | ".*?(?<!\\)" | # double quoted strings or | |
1509 | \w+ | # identifier |
|
1517 | \w+ | # identifier | |
1510 | \S # other characters |
|
1518 | \S # other characters | |
1511 | ''', re.VERBOSE | re.DOTALL) |
|
1519 | ''', re.VERBOSE | re.DOTALL) | |
1512 | # 1. find the nearest identifier that comes before an unclosed |
|
1520 | # 1. find the nearest identifier that comes before an unclosed | |
1513 | # parenthesis before the cursor |
|
1521 | # parenthesis before the cursor | |
1514 | # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo" |
|
1522 | # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo" | |
1515 | tokens = regexp.findall(self.text_until_cursor) |
|
1523 | tokens = regexp.findall(self.text_until_cursor) | |
1516 | iterTokens = reversed(tokens); openPar = 0 |
|
1524 | iterTokens = reversed(tokens); openPar = 0 | |
1517 |
|
1525 | |||
1518 | for token in iterTokens: |
|
1526 | for token in iterTokens: | |
1519 | if token == ')': |
|
1527 | if token == ')': | |
1520 | openPar -= 1 |
|
1528 | openPar -= 1 | |
1521 | elif token == '(': |
|
1529 | elif token == '(': | |
1522 | openPar += 1 |
|
1530 | openPar += 1 | |
1523 | if openPar > 0: |
|
1531 | if openPar > 0: | |
1524 | # found the last unclosed parenthesis |
|
1532 | # found the last unclosed parenthesis | |
1525 | break |
|
1533 | break | |
1526 | else: |
|
1534 | else: | |
1527 | return [] |
|
1535 | return [] | |
1528 | # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" ) |
|
1536 | # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" ) | |
1529 | ids = [] |
|
1537 | ids = [] | |
1530 | isId = re.compile(r'\w+$').match |
|
1538 | isId = re.compile(r'\w+$').match | |
1531 |
|
1539 | |||
1532 | while True: |
|
1540 | while True: | |
1533 | try: |
|
1541 | try: | |
1534 | ids.append(next(iterTokens)) |
|
1542 | ids.append(next(iterTokens)) | |
1535 | if not isId(ids[-1]): |
|
1543 | if not isId(ids[-1]): | |
1536 | ids.pop(); break |
|
1544 | ids.pop(); break | |
1537 | if not next(iterTokens) == '.': |
|
1545 | if not next(iterTokens) == '.': | |
1538 | break |
|
1546 | break | |
1539 | except StopIteration: |
|
1547 | except StopIteration: | |
1540 | break |
|
1548 | break | |
1541 |
|
1549 | |||
1542 | # Find all named arguments already assigned to, as to avoid suggesting |
|
1550 | # Find all named arguments already assigned to, as to avoid suggesting | |
1543 | # them again |
|
1551 | # them again | |
1544 | usedNamedArgs = set() |
|
1552 | usedNamedArgs = set() | |
1545 | par_level = -1 |
|
1553 | par_level = -1 | |
1546 | for token, next_token in zip(tokens, tokens[1:]): |
|
1554 | for token, next_token in zip(tokens, tokens[1:]): | |
1547 | if token == '(': |
|
1555 | if token == '(': | |
1548 | par_level += 1 |
|
1556 | par_level += 1 | |
1549 | elif token == ')': |
|
1557 | elif token == ')': | |
1550 | par_level -= 1 |
|
1558 | par_level -= 1 | |
1551 |
|
1559 | |||
1552 | if par_level != 0: |
|
1560 | if par_level != 0: | |
1553 | continue |
|
1561 | continue | |
1554 |
|
1562 | |||
1555 | if next_token != '=': |
|
1563 | if next_token != '=': | |
1556 | continue |
|
1564 | continue | |
1557 |
|
1565 | |||
1558 | usedNamedArgs.add(token) |
|
1566 | usedNamedArgs.add(token) | |
1559 |
|
1567 | |||
1560 | argMatches = [] |
|
1568 | argMatches = [] | |
1561 | try: |
|
1569 | try: | |
1562 | callableObj = '.'.join(ids[::-1]) |
|
1570 | callableObj = '.'.join(ids[::-1]) | |
1563 | namedArgs = self._default_arguments(eval(callableObj, |
|
1571 | namedArgs = self._default_arguments(eval(callableObj, | |
1564 | self.namespace)) |
|
1572 | self.namespace)) | |
1565 |
|
1573 | |||
1566 | # Remove used named arguments from the list, no need to show twice |
|
1574 | # Remove used named arguments from the list, no need to show twice | |
1567 | for namedArg in set(namedArgs) - usedNamedArgs: |
|
1575 | for namedArg in set(namedArgs) - usedNamedArgs: | |
1568 | if namedArg.startswith(text): |
|
1576 | if namedArg.startswith(text): | |
1569 | argMatches.append(u"%s=" %namedArg) |
|
1577 | argMatches.append(u"%s=" %namedArg) | |
1570 | except: |
|
1578 | except: | |
1571 | pass |
|
1579 | pass | |
1572 |
|
1580 | |||
1573 | return argMatches |
|
1581 | return argMatches | |
1574 |
|
1582 | |||
1575 | def dict_key_matches(self, text): |
|
1583 | def dict_key_matches(self, text): | |
1576 | "Match string keys in a dictionary, after e.g. 'foo[' " |
|
1584 | "Match string keys in a dictionary, after e.g. 'foo[' " | |
1577 | def get_keys(obj): |
|
1585 | def get_keys(obj): | |
1578 | # Objects can define their own completions by defining an |
|
1586 | # Objects can define their own completions by defining an | |
1579 | # _ipy_key_completions_() method. |
|
1587 | # _ipy_key_completions_() method. | |
1580 | method = get_real_method(obj, '_ipython_key_completions_') |
|
1588 | method = get_real_method(obj, '_ipython_key_completions_') | |
1581 | if method is not None: |
|
1589 | if method is not None: | |
1582 | return method() |
|
1590 | return method() | |
1583 |
|
1591 | |||
1584 | # Special case some common in-memory dict-like types |
|
1592 | # Special case some common in-memory dict-like types | |
1585 | if isinstance(obj, dict) or\ |
|
1593 | if isinstance(obj, dict) or\ | |
1586 | _safe_isinstance(obj, 'pandas', 'DataFrame'): |
|
1594 | _safe_isinstance(obj, 'pandas', 'DataFrame'): | |
1587 | try: |
|
1595 | try: | |
1588 | return list(obj.keys()) |
|
1596 | return list(obj.keys()) | |
1589 | except Exception: |
|
1597 | except Exception: | |
1590 | return [] |
|
1598 | return [] | |
1591 | elif _safe_isinstance(obj, 'numpy', 'ndarray') or\ |
|
1599 | elif _safe_isinstance(obj, 'numpy', 'ndarray') or\ | |
1592 | _safe_isinstance(obj, 'numpy', 'void'): |
|
1600 | _safe_isinstance(obj, 'numpy', 'void'): | |
1593 | return obj.dtype.names or [] |
|
1601 | return obj.dtype.names or [] | |
1594 | return [] |
|
1602 | return [] | |
1595 |
|
1603 | |||
1596 | try: |
|
1604 | try: | |
1597 | regexps = self.__dict_key_regexps |
|
1605 | regexps = self.__dict_key_regexps | |
1598 | except AttributeError: |
|
1606 | except AttributeError: | |
1599 | dict_key_re_fmt = r'''(?x) |
|
1607 | dict_key_re_fmt = r'''(?x) | |
1600 | ( # match dict-referring expression wrt greedy setting |
|
1608 | ( # match dict-referring expression wrt greedy setting | |
1601 | %s |
|
1609 | %s | |
1602 | ) |
|
1610 | ) | |
1603 | \[ # open bracket |
|
1611 | \[ # open bracket | |
1604 | \s* # and optional whitespace |
|
1612 | \s* # and optional whitespace | |
1605 | ([uUbB]? # string prefix (r not handled) |
|
1613 | ([uUbB]? # string prefix (r not handled) | |
1606 | (?: # unclosed string |
|
1614 | (?: # unclosed string | |
1607 | '(?:[^']|(?<!\\)\\')* |
|
1615 | '(?:[^']|(?<!\\)\\')* | |
1608 | | |
|
1616 | | | |
1609 | "(?:[^"]|(?<!\\)\\")* |
|
1617 | "(?:[^"]|(?<!\\)\\")* | |
1610 | ) |
|
1618 | ) | |
1611 | )? |
|
1619 | )? | |
1612 | $ |
|
1620 | $ | |
1613 | ''' |
|
1621 | ''' | |
1614 | regexps = self.__dict_key_regexps = { |
|
1622 | regexps = self.__dict_key_regexps = { | |
1615 | False: re.compile(dict_key_re_fmt % r''' |
|
1623 | False: re.compile(dict_key_re_fmt % r''' | |
1616 | # identifiers separated by . |
|
1624 | # identifiers separated by . | |
1617 | (?!\d)\w+ |
|
1625 | (?!\d)\w+ | |
1618 | (?:\.(?!\d)\w+)* |
|
1626 | (?:\.(?!\d)\w+)* | |
1619 | '''), |
|
1627 | '''), | |
1620 | True: re.compile(dict_key_re_fmt % ''' |
|
1628 | True: re.compile(dict_key_re_fmt % ''' | |
1621 | .+ |
|
1629 | .+ | |
1622 | ''') |
|
1630 | ''') | |
1623 | } |
|
1631 | } | |
1624 |
|
1632 | |||
1625 | match = regexps[self.greedy].search(self.text_until_cursor) |
|
1633 | match = regexps[self.greedy].search(self.text_until_cursor) | |
1626 | if match is None: |
|
1634 | if match is None: | |
1627 | return [] |
|
1635 | return [] | |
1628 |
|
1636 | |||
1629 | expr, prefix = match.groups() |
|
1637 | expr, prefix = match.groups() | |
1630 | try: |
|
1638 | try: | |
1631 | obj = eval(expr, self.namespace) |
|
1639 | obj = eval(expr, self.namespace) | |
1632 | except Exception: |
|
1640 | except Exception: | |
1633 | try: |
|
1641 | try: | |
1634 | obj = eval(expr, self.global_namespace) |
|
1642 | obj = eval(expr, self.global_namespace) | |
1635 | except Exception: |
|
1643 | except Exception: | |
1636 | return [] |
|
1644 | return [] | |
1637 |
|
1645 | |||
1638 | keys = get_keys(obj) |
|
1646 | keys = get_keys(obj) | |
1639 | if not keys: |
|
1647 | if not keys: | |
1640 | return keys |
|
1648 | return keys | |
1641 | closing_quote, token_offset, matches = match_dict_keys(keys, prefix, self.splitter.delims) |
|
1649 | closing_quote, token_offset, matches = match_dict_keys(keys, prefix, self.splitter.delims) | |
1642 | if not matches: |
|
1650 | if not matches: | |
1643 | return matches |
|
1651 | return matches | |
1644 |
|
1652 | |||
1645 | # get the cursor position of |
|
1653 | # get the cursor position of | |
1646 | # - the text being completed |
|
1654 | # - the text being completed | |
1647 | # - the start of the key text |
|
1655 | # - the start of the key text | |
1648 | # - the start of the completion |
|
1656 | # - the start of the completion | |
1649 | text_start = len(self.text_until_cursor) - len(text) |
|
1657 | text_start = len(self.text_until_cursor) - len(text) | |
1650 | if prefix: |
|
1658 | if prefix: | |
1651 | key_start = match.start(2) |
|
1659 | key_start = match.start(2) | |
1652 | completion_start = key_start + token_offset |
|
1660 | completion_start = key_start + token_offset | |
1653 | else: |
|
1661 | else: | |
1654 | key_start = completion_start = match.end() |
|
1662 | key_start = completion_start = match.end() | |
1655 |
|
1663 | |||
1656 | # grab the leading prefix, to make sure all completions start with `text` |
|
1664 | # grab the leading prefix, to make sure all completions start with `text` | |
1657 | if text_start > key_start: |
|
1665 | if text_start > key_start: | |
1658 | leading = '' |
|
1666 | leading = '' | |
1659 | else: |
|
1667 | else: | |
1660 | leading = text[text_start:completion_start] |
|
1668 | leading = text[text_start:completion_start] | |
1661 |
|
1669 | |||
1662 | # the index of the `[` character |
|
1670 | # the index of the `[` character | |
1663 | bracket_idx = match.end(1) |
|
1671 | bracket_idx = match.end(1) | |
1664 |
|
1672 | |||
1665 | # append closing quote and bracket as appropriate |
|
1673 | # append closing quote and bracket as appropriate | |
1666 | # this is *not* appropriate if the opening quote or bracket is outside |
|
1674 | # this is *not* appropriate if the opening quote or bracket is outside | |
1667 | # the text given to this method |
|
1675 | # the text given to this method | |
1668 | suf = '' |
|
1676 | suf = '' | |
1669 | continuation = self.line_buffer[len(self.text_until_cursor):] |
|
1677 | continuation = self.line_buffer[len(self.text_until_cursor):] | |
1670 | if key_start > text_start and closing_quote: |
|
1678 | if key_start > text_start and closing_quote: | |
1671 | # quotes were opened inside text, maybe close them |
|
1679 | # quotes were opened inside text, maybe close them | |
1672 | if continuation.startswith(closing_quote): |
|
1680 | if continuation.startswith(closing_quote): | |
1673 | continuation = continuation[len(closing_quote):] |
|
1681 | continuation = continuation[len(closing_quote):] | |
1674 | else: |
|
1682 | else: | |
1675 | suf += closing_quote |
|
1683 | suf += closing_quote | |
1676 | if bracket_idx > text_start: |
|
1684 | if bracket_idx > text_start: | |
1677 | # brackets were opened inside text, maybe close them |
|
1685 | # brackets were opened inside text, maybe close them | |
1678 | if not continuation.startswith(']'): |
|
1686 | if not continuation.startswith(']'): | |
1679 | suf += ']' |
|
1687 | suf += ']' | |
1680 |
|
1688 | |||
1681 | return [leading + k + suf for k in matches] |
|
1689 | return [leading + k + suf for k in matches] | |
1682 |
|
1690 | |||
1683 | def unicode_name_matches(self, text): |
|
1691 | def unicode_name_matches(self, text): | |
1684 | u"""Match Latex-like syntax for unicode characters base |
|
1692 | u"""Match Latex-like syntax for unicode characters base | |
1685 | on the name of the character. |
|
1693 | on the name of the character. | |
1686 |
|
1694 | |||
1687 | This does ``\\GREEK SMALL LETTER ETA`` -> ``Ξ·`` |
|
1695 | This does ``\\GREEK SMALL LETTER ETA`` -> ``Ξ·`` | |
1688 |
|
1696 | |||
1689 | Works only on valid python 3 identifier, or on combining characters that |
|
1697 | Works only on valid python 3 identifier, or on combining characters that | |
1690 | will combine to form a valid identifier. |
|
1698 | will combine to form a valid identifier. | |
1691 |
|
1699 | |||
1692 | Used on Python 3 only. |
|
1700 | Used on Python 3 only. | |
1693 | """ |
|
1701 | """ | |
1694 | slashpos = text.rfind('\\') |
|
1702 | slashpos = text.rfind('\\') | |
1695 | if slashpos > -1: |
|
1703 | if slashpos > -1: | |
1696 | s = text[slashpos+1:] |
|
1704 | s = text[slashpos+1:] | |
1697 | try : |
|
1705 | try : | |
1698 | unic = unicodedata.lookup(s) |
|
1706 | unic = unicodedata.lookup(s) | |
1699 | # allow combining chars |
|
1707 | # allow combining chars | |
1700 | if ('a'+unic).isidentifier(): |
|
1708 | if ('a'+unic).isidentifier(): | |
1701 | return '\\'+s,[unic] |
|
1709 | return '\\'+s,[unic] | |
1702 | except KeyError: |
|
1710 | except KeyError: | |
1703 | pass |
|
1711 | pass | |
1704 | return u'', [] |
|
1712 | return u'', [] | |
1705 |
|
1713 | |||
1706 |
|
1714 | |||
1707 | def latex_matches(self, text): |
|
1715 | def latex_matches(self, text): | |
1708 | u"""Match Latex syntax for unicode characters. |
|
1716 | u"""Match Latex syntax for unicode characters. | |
1709 |
|
1717 | |||
1710 | This does both ``\\alp`` -> ``\\alpha`` and ``\\alpha`` -> ``Ξ±`` |
|
1718 | This does both ``\\alp`` -> ``\\alpha`` and ``\\alpha`` -> ``Ξ±`` | |
1711 | """ |
|
1719 | """ | |
1712 | slashpos = text.rfind('\\') |
|
1720 | slashpos = text.rfind('\\') | |
1713 | if slashpos > -1: |
|
1721 | if slashpos > -1: | |
1714 | s = text[slashpos:] |
|
1722 | s = text[slashpos:] | |
1715 | if s in latex_symbols: |
|
1723 | if s in latex_symbols: | |
1716 | # Try to complete a full latex symbol to unicode |
|
1724 | # Try to complete a full latex symbol to unicode | |
1717 | # \\alpha -> Ξ± |
|
1725 | # \\alpha -> Ξ± | |
1718 | return s, [latex_symbols[s]] |
|
1726 | return s, [latex_symbols[s]] | |
1719 | else: |
|
1727 | else: | |
1720 | # If a user has partially typed a latex symbol, give them |
|
1728 | # If a user has partially typed a latex symbol, give them | |
1721 | # a full list of options \al -> [\aleph, \alpha] |
|
1729 | # a full list of options \al -> [\aleph, \alpha] | |
1722 | matches = [k for k in latex_symbols if k.startswith(s)] |
|
1730 | matches = [k for k in latex_symbols if k.startswith(s)] | |
1723 | if matches: |
|
1731 | if matches: | |
1724 | return s, matches |
|
1732 | return s, matches | |
1725 | return u'', [] |
|
1733 | return u'', [] | |
1726 |
|
1734 | |||
1727 | def dispatch_custom_completer(self, text): |
|
1735 | def dispatch_custom_completer(self, text): | |
1728 | if not self.custom_completers: |
|
1736 | if not self.custom_completers: | |
1729 | return |
|
1737 | return | |
1730 |
|
1738 | |||
1731 | line = self.line_buffer |
|
1739 | line = self.line_buffer | |
1732 | if not line.strip(): |
|
1740 | if not line.strip(): | |
1733 | return None |
|
1741 | return None | |
1734 |
|
1742 | |||
1735 | # Create a little structure to pass all the relevant information about |
|
1743 | # Create a little structure to pass all the relevant information about | |
1736 | # the current completion to any custom completer. |
|
1744 | # the current completion to any custom completer. | |
1737 | event = SimpleNamespace() |
|
1745 | event = SimpleNamespace() | |
1738 | event.line = line |
|
1746 | event.line = line | |
1739 | event.symbol = text |
|
1747 | event.symbol = text | |
1740 | cmd = line.split(None,1)[0] |
|
1748 | cmd = line.split(None,1)[0] | |
1741 | event.command = cmd |
|
1749 | event.command = cmd | |
1742 | event.text_until_cursor = self.text_until_cursor |
|
1750 | event.text_until_cursor = self.text_until_cursor | |
1743 |
|
1751 | |||
1744 | # for foo etc, try also to find completer for %foo |
|
1752 | # for foo etc, try also to find completer for %foo | |
1745 | if not cmd.startswith(self.magic_escape): |
|
1753 | if not cmd.startswith(self.magic_escape): | |
1746 | try_magic = self.custom_completers.s_matches( |
|
1754 | try_magic = self.custom_completers.s_matches( | |
1747 | self.magic_escape + cmd) |
|
1755 | self.magic_escape + cmd) | |
1748 | else: |
|
1756 | else: | |
1749 | try_magic = [] |
|
1757 | try_magic = [] | |
1750 |
|
1758 | |||
1751 | for c in itertools.chain(self.custom_completers.s_matches(cmd), |
|
1759 | for c in itertools.chain(self.custom_completers.s_matches(cmd), | |
1752 | try_magic, |
|
1760 | try_magic, | |
1753 | self.custom_completers.flat_matches(self.text_until_cursor)): |
|
1761 | self.custom_completers.flat_matches(self.text_until_cursor)): | |
1754 | try: |
|
1762 | try: | |
1755 | res = c(event) |
|
1763 | res = c(event) | |
1756 | if res: |
|
1764 | if res: | |
1757 | # first, try case sensitive match |
|
1765 | # first, try case sensitive match | |
1758 | withcase = [r for r in res if r.startswith(text)] |
|
1766 | withcase = [r for r in res if r.startswith(text)] | |
1759 | if withcase: |
|
1767 | if withcase: | |
1760 | return withcase |
|
1768 | return withcase | |
1761 | # if none, then case insensitive ones are ok too |
|
1769 | # if none, then case insensitive ones are ok too | |
1762 | text_low = text.lower() |
|
1770 | text_low = text.lower() | |
1763 | return [r for r in res if r.lower().startswith(text_low)] |
|
1771 | return [r for r in res if r.lower().startswith(text_low)] | |
1764 | except TryNext: |
|
1772 | except TryNext: | |
1765 | pass |
|
1773 | pass | |
1766 | except KeyboardInterrupt: |
|
1774 | except KeyboardInterrupt: | |
1767 | """ |
|
1775 | """ | |
1768 | If custom completer take too long, |
|
1776 | If custom completer take too long, | |
1769 | let keyboard interrupt abort and return nothing. |
|
1777 | let keyboard interrupt abort and return nothing. | |
1770 | """ |
|
1778 | """ | |
1771 | break |
|
1779 | break | |
1772 |
|
1780 | |||
1773 | return None |
|
1781 | return None | |
1774 |
|
1782 | |||
1775 | def completions(self, text: str, offset: int)->Iterator[Completion]: |
|
1783 | def completions(self, text: str, offset: int)->Iterator[Completion]: | |
1776 | """ |
|
1784 | """ | |
1777 | Returns an iterator over the possible completions |
|
1785 | Returns an iterator over the possible completions | |
1778 |
|
1786 | |||
1779 |
.. warning:: |
|
1787 | .. warning:: | |
|
1788 | ||||
|
1789 | Unstable | |||
1780 |
|
1790 | |||
1781 | This function is unstable, API may change without warning. |
|
1791 | This function is unstable, API may change without warning. | |
1782 | It will also raise unless use in proper context manager. |
|
1792 | It will also raise unless use in proper context manager. | |
1783 |
|
1793 | |||
1784 | Parameters |
|
1794 | Parameters | |
1785 | ---------- |
|
1795 | ---------- | |
1786 |
|
1796 | |||
1787 | text:str |
|
1797 | text:str | |
1788 | Full text of the current input, multi line string. |
|
1798 | Full text of the current input, multi line string. | |
1789 | offset:int |
|
1799 | offset:int | |
1790 | Integer representing the position of the cursor in ``text``. Offset |
|
1800 | Integer representing the position of the cursor in ``text``. Offset | |
1791 | is 0-based indexed. |
|
1801 | is 0-based indexed. | |
1792 |
|
1802 | |||
1793 | Yields |
|
1803 | Yields | |
1794 | ------ |
|
1804 | ------ | |
1795 | :any:`Completion` object |
|
1805 | :any:`Completion` object | |
1796 |
|
1806 | |||
1797 |
|
1807 | |||
1798 | The cursor on a text can either be seen as being "in between" |
|
1808 | The cursor on a text can either be seen as being "in between" | |
1799 | characters or "On" a character depending on the interface visible to |
|
1809 | characters or "On" a character depending on the interface visible to | |
1800 | the user. For consistency the cursor being on "in between" characters X |
|
1810 | the user. For consistency the cursor being on "in between" characters X | |
1801 | and Y is equivalent to the cursor being "on" character Y, that is to say |
|
1811 | and Y is equivalent to the cursor being "on" character Y, that is to say | |
1802 | the character the cursor is on is considered as being after the cursor. |
|
1812 | the character the cursor is on is considered as being after the cursor. | |
1803 |
|
1813 | |||
1804 | Combining characters may span more that one position in the |
|
1814 | Combining characters may span more that one position in the | |
1805 | text. |
|
1815 | text. | |
1806 |
|
1816 | |||
1807 |
|
1817 | |||
1808 | .. note:: |
|
1818 | .. note:: | |
1809 |
|
1819 | |||
1810 | If ``IPCompleter.debug`` is :any:`True` will yield a ``--jedi/ipython--`` |
|
1820 | If ``IPCompleter.debug`` is :any:`True` will yield a ``--jedi/ipython--`` | |
1811 | fake Completion token to distinguish completion returned by Jedi |
|
1821 | fake Completion token to distinguish completion returned by Jedi | |
1812 | and usual IPython completion. |
|
1822 | and usual IPython completion. | |
1813 |
|
1823 | |||
1814 | .. note:: |
|
1824 | .. note:: | |
1815 |
|
1825 | |||
1816 | Completions are not completely deduplicated yet. If identical |
|
1826 | Completions are not completely deduplicated yet. If identical | |
1817 | completions are coming from different sources this function does not |
|
1827 | completions are coming from different sources this function does not | |
1818 | ensure that each completion object will only be present once. |
|
1828 | ensure that each completion object will only be present once. | |
1819 | """ |
|
1829 | """ | |
1820 | warnings.warn("_complete is a provisional API (as of IPython 6.0). " |
|
1830 | warnings.warn("_complete is a provisional API (as of IPython 6.0). " | |
1821 | "It may change without warnings. " |
|
1831 | "It may change without warnings. " | |
1822 | "Use in corresponding context manager.", |
|
1832 | "Use in corresponding context manager.", | |
1823 | category=ProvisionalCompleterWarning, stacklevel=2) |
|
1833 | category=ProvisionalCompleterWarning, stacklevel=2) | |
1824 |
|
1834 | |||
1825 | seen = set() |
|
1835 | seen = set() | |
1826 | try: |
|
1836 | try: | |
1827 | for c in self._completions(text, offset, _timeout=self.jedi_compute_type_timeout/1000): |
|
1837 | for c in self._completions(text, offset, _timeout=self.jedi_compute_type_timeout/1000): | |
1828 | if c and (c in seen): |
|
1838 | if c and (c in seen): | |
1829 | continue |
|
1839 | continue | |
1830 | yield c |
|
1840 | yield c | |
1831 | seen.add(c) |
|
1841 | seen.add(c) | |
1832 | except KeyboardInterrupt: |
|
1842 | except KeyboardInterrupt: | |
1833 | """if completions take too long and users send keyboard interrupt, |
|
1843 | """if completions take too long and users send keyboard interrupt, | |
1834 | do not crash and return ASAP. """ |
|
1844 | do not crash and return ASAP. """ | |
1835 | pass |
|
1845 | pass | |
1836 |
|
1846 | |||
1837 | def _completions(self, full_text: str, offset: int, *, _timeout)->Iterator[Completion]: |
|
1847 | def _completions(self, full_text: str, offset: int, *, _timeout)->Iterator[Completion]: | |
1838 | """ |
|
1848 | """ | |
1839 | Core completion module.Same signature as :any:`completions`, with the |
|
1849 | Core completion module.Same signature as :any:`completions`, with the | |
1840 | extra `timeout` parameter (in seconds). |
|
1850 | extra `timeout` parameter (in seconds). | |
1841 |
|
1851 | |||
1842 |
|
1852 | |||
1843 | Computing jedi's completion ``.type`` can be quite expensive (it is a |
|
1853 | Computing jedi's completion ``.type`` can be quite expensive (it is a | |
1844 | lazy property) and can require some warm-up, more warm up than just |
|
1854 | lazy property) and can require some warm-up, more warm up than just | |
1845 | computing the ``name`` of a completion. The warm-up can be : |
|
1855 | computing the ``name`` of a completion. The warm-up can be : | |
1846 |
|
1856 | |||
1847 | - Long warm-up the first time a module is encountered after |
|
1857 | - Long warm-up the first time a module is encountered after | |
1848 | install/update: actually build parse/inference tree. |
|
1858 | install/update: actually build parse/inference tree. | |
1849 |
|
1859 | |||
1850 | - first time the module is encountered in a session: load tree from |
|
1860 | - first time the module is encountered in a session: load tree from | |
1851 | disk. |
|
1861 | disk. | |
1852 |
|
1862 | |||
1853 | We don't want to block completions for tens of seconds so we give the |
|
1863 | We don't want to block completions for tens of seconds so we give the | |
1854 | completer a "budget" of ``_timeout`` seconds per invocation to compute |
|
1864 | completer a "budget" of ``_timeout`` seconds per invocation to compute | |
1855 | completions types, the completions that have not yet been computed will |
|
1865 | completions types, the completions that have not yet been computed will | |
1856 | be marked as "unknown" an will have a chance to be computed next round |
|
1866 | be marked as "unknown" an will have a chance to be computed next round | |
1857 | are things get cached. |
|
1867 | are things get cached. | |
1858 |
|
1868 | |||
1859 | Keep in mind that Jedi is not the only thing treating the completion so |
|
1869 | Keep in mind that Jedi is not the only thing treating the completion so | |
1860 | keep the timeout short-ish as if we take more than 0.3 second we still |
|
1870 | keep the timeout short-ish as if we take more than 0.3 second we still | |
1861 | have lots of processing to do. |
|
1871 | have lots of processing to do. | |
1862 |
|
1872 | |||
1863 | """ |
|
1873 | """ | |
1864 | deadline = time.monotonic() + _timeout |
|
1874 | deadline = time.monotonic() + _timeout | |
1865 |
|
1875 | |||
1866 |
|
1876 | |||
1867 | before = full_text[:offset] |
|
1877 | before = full_text[:offset] | |
1868 | cursor_line, cursor_column = position_to_cursor(full_text, offset) |
|
1878 | cursor_line, cursor_column = position_to_cursor(full_text, offset) | |
1869 |
|
1879 | |||
1870 | matched_text, matches, matches_origin, jedi_matches = self._complete( |
|
1880 | matched_text, matches, matches_origin, jedi_matches = self._complete( | |
1871 | full_text=full_text, cursor_line=cursor_line, cursor_pos=cursor_column) |
|
1881 | full_text=full_text, cursor_line=cursor_line, cursor_pos=cursor_column) | |
1872 |
|
1882 | |||
1873 | iter_jm = iter(jedi_matches) |
|
1883 | iter_jm = iter(jedi_matches) | |
1874 | if _timeout: |
|
1884 | if _timeout: | |
1875 | for jm in iter_jm: |
|
1885 | for jm in iter_jm: | |
1876 | try: |
|
1886 | try: | |
1877 | type_ = jm.type |
|
1887 | type_ = jm.type | |
1878 | except Exception: |
|
1888 | except Exception: | |
1879 | if self.debug: |
|
1889 | if self.debug: | |
1880 | print("Error in Jedi getting type of ", jm) |
|
1890 | print("Error in Jedi getting type of ", jm) | |
1881 | type_ = None |
|
1891 | type_ = None | |
1882 | delta = len(jm.name_with_symbols) - len(jm.complete) |
|
1892 | delta = len(jm.name_with_symbols) - len(jm.complete) | |
1883 | if type_ == 'function': |
|
1893 | if type_ == 'function': | |
1884 | signature = _make_signature(jm) |
|
1894 | signature = _make_signature(jm) | |
1885 | else: |
|
1895 | else: | |
1886 | signature = '' |
|
1896 | signature = '' | |
1887 | yield Completion(start=offset - delta, |
|
1897 | yield Completion(start=offset - delta, | |
1888 | end=offset, |
|
1898 | end=offset, | |
1889 | text=jm.name_with_symbols, |
|
1899 | text=jm.name_with_symbols, | |
1890 | type=type_, |
|
1900 | type=type_, | |
1891 | signature=signature, |
|
1901 | signature=signature, | |
1892 | _origin='jedi') |
|
1902 | _origin='jedi') | |
1893 |
|
1903 | |||
1894 | if time.monotonic() > deadline: |
|
1904 | if time.monotonic() > deadline: | |
1895 | break |
|
1905 | break | |
1896 |
|
1906 | |||
1897 | for jm in iter_jm: |
|
1907 | for jm in iter_jm: | |
1898 | delta = len(jm.name_with_symbols) - len(jm.complete) |
|
1908 | delta = len(jm.name_with_symbols) - len(jm.complete) | |
1899 | yield Completion(start=offset - delta, |
|
1909 | yield Completion(start=offset - delta, | |
1900 | end=offset, |
|
1910 | end=offset, | |
1901 | text=jm.name_with_symbols, |
|
1911 | text=jm.name_with_symbols, | |
1902 | type='<unknown>', # don't compute type for speed |
|
1912 | type='<unknown>', # don't compute type for speed | |
1903 | _origin='jedi', |
|
1913 | _origin='jedi', | |
1904 | signature='') |
|
1914 | signature='') | |
1905 |
|
1915 | |||
1906 |
|
1916 | |||
1907 | start_offset = before.rfind(matched_text) |
|
1917 | start_offset = before.rfind(matched_text) | |
1908 |
|
1918 | |||
1909 | # TODO: |
|
1919 | # TODO: | |
1910 | # Suppress this, right now just for debug. |
|
1920 | # Suppress this, right now just for debug. | |
1911 | if jedi_matches and matches and self.debug: |
|
1921 | if jedi_matches and matches and self.debug: | |
1912 | yield Completion(start=start_offset, end=offset, text='--jedi/ipython--', |
|
1922 | yield Completion(start=start_offset, end=offset, text='--jedi/ipython--', | |
1913 | _origin='debug', type='none', signature='') |
|
1923 | _origin='debug', type='none', signature='') | |
1914 |
|
1924 | |||
1915 | # I'm unsure if this is always true, so let's assert and see if it |
|
1925 | # I'm unsure if this is always true, so let's assert and see if it | |
1916 | # crash |
|
1926 | # crash | |
1917 | assert before.endswith(matched_text) |
|
1927 | assert before.endswith(matched_text) | |
1918 | for m, t in zip(matches, matches_origin): |
|
1928 | for m, t in zip(matches, matches_origin): | |
1919 | yield Completion(start=start_offset, end=offset, text=m, _origin=t, signature='', type='<unknown>') |
|
1929 | yield Completion(start=start_offset, end=offset, text=m, _origin=t, signature='', type='<unknown>') | |
1920 |
|
1930 | |||
1921 |
|
1931 | |||
1922 | def complete(self, text=None, line_buffer=None, cursor_pos=None): |
|
1932 | def complete(self, text=None, line_buffer=None, cursor_pos=None): | |
1923 | """Find completions for the given text and line context. |
|
1933 | """Find completions for the given text and line context. | |
1924 |
|
1934 | |||
1925 | Note that both the text and the line_buffer are optional, but at least |
|
1935 | Note that both the text and the line_buffer are optional, but at least | |
1926 | one of them must be given. |
|
1936 | one of them must be given. | |
1927 |
|
1937 | |||
1928 | Parameters |
|
1938 | Parameters | |
1929 | ---------- |
|
1939 | ---------- | |
1930 | text : string, optional |
|
1940 | text : string, optional | |
1931 | Text to perform the completion on. If not given, the line buffer |
|
1941 | Text to perform the completion on. If not given, the line buffer | |
1932 | is split using the instance's CompletionSplitter object. |
|
1942 | is split using the instance's CompletionSplitter object. | |
1933 |
|
1943 | |||
1934 | line_buffer : string, optional |
|
1944 | line_buffer : string, optional | |
1935 | If not given, the completer attempts to obtain the current line |
|
1945 | If not given, the completer attempts to obtain the current line | |
1936 | buffer via readline. This keyword allows clients which are |
|
1946 | buffer via readline. This keyword allows clients which are | |
1937 | requesting for text completions in non-readline contexts to inform |
|
1947 | requesting for text completions in non-readline contexts to inform | |
1938 | the completer of the entire text. |
|
1948 | the completer of the entire text. | |
1939 |
|
1949 | |||
1940 | cursor_pos : int, optional |
|
1950 | cursor_pos : int, optional | |
1941 | Index of the cursor in the full line buffer. Should be provided by |
|
1951 | Index of the cursor in the full line buffer. Should be provided by | |
1942 | remote frontends where kernel has no access to frontend state. |
|
1952 | remote frontends where kernel has no access to frontend state. | |
1943 |
|
1953 | |||
1944 | Returns |
|
1954 | Returns | |
1945 | ------- |
|
1955 | ------- | |
1946 | text : str |
|
1956 | text : str | |
1947 | Text that was actually used in the completion. |
|
1957 | Text that was actually used in the completion. | |
1948 |
|
1958 | |||
1949 | matches : list |
|
1959 | matches : list | |
1950 | A list of completion matches. |
|
1960 | A list of completion matches. | |
1951 |
|
1961 | |||
1952 |
|
1962 | |||
1953 | .. note:: |
|
1963 | .. note:: | |
1954 |
|
1964 | |||
1955 | This API is likely to be deprecated and replaced by |
|
1965 | This API is likely to be deprecated and replaced by | |
1956 | :any:`IPCompleter.completions` in the future. |
|
1966 | :any:`IPCompleter.completions` in the future. | |
1957 |
|
1967 | |||
1958 |
|
1968 | |||
1959 | """ |
|
1969 | """ | |
1960 | warnings.warn('`Completer.complete` is pending deprecation since ' |
|
1970 | warnings.warn('`Completer.complete` is pending deprecation since ' | |
1961 | 'IPython 6.0 and will be replaced by `Completer.completions`.', |
|
1971 | 'IPython 6.0 and will be replaced by `Completer.completions`.', | |
1962 | PendingDeprecationWarning) |
|
1972 | PendingDeprecationWarning) | |
1963 | # potential todo, FOLD the 3rd throw away argument of _complete |
|
1973 | # potential todo, FOLD the 3rd throw away argument of _complete | |
1964 | # into the first 2 one. |
|
1974 | # into the first 2 one. | |
1965 | return self._complete(line_buffer=line_buffer, cursor_pos=cursor_pos, text=text, cursor_line=0)[:2] |
|
1975 | return self._complete(line_buffer=line_buffer, cursor_pos=cursor_pos, text=text, cursor_line=0)[:2] | |
1966 |
|
1976 | |||
1967 | def _complete(self, *, cursor_line, cursor_pos, line_buffer=None, text=None, |
|
1977 | def _complete(self, *, cursor_line, cursor_pos, line_buffer=None, text=None, | |
1968 | full_text=None) -> Tuple[str, List[str], List[str], Iterable[_FakeJediCompletion]]: |
|
1978 | full_text=None) -> Tuple[str, List[str], List[str], Iterable[_FakeJediCompletion]]: | |
1969 | """ |
|
1979 | """ | |
1970 |
|
1980 | |||
1971 | Like complete but can also returns raw jedi completions as well as the |
|
1981 | Like complete but can also returns raw jedi completions as well as the | |
1972 | origin of the completion text. This could (and should) be made much |
|
1982 | origin of the completion text. This could (and should) be made much | |
1973 | cleaner but that will be simpler once we drop the old (and stateful) |
|
1983 | cleaner but that will be simpler once we drop the old (and stateful) | |
1974 | :any:`complete` API. |
|
1984 | :any:`complete` API. | |
1975 |
|
1985 | |||
1976 |
|
1986 | |||
1977 | With current provisional API, cursor_pos act both (depending on the |
|
1987 | With current provisional API, cursor_pos act both (depending on the | |
1978 | caller) as the offset in the ``text`` or ``line_buffer``, or as the |
|
1988 | caller) as the offset in the ``text`` or ``line_buffer``, or as the | |
1979 | ``column`` when passing multiline strings this could/should be renamed |
|
1989 | ``column`` when passing multiline strings this could/should be renamed | |
1980 | but would add extra noise. |
|
1990 | but would add extra noise. | |
1981 | """ |
|
1991 | """ | |
1982 |
|
1992 | |||
1983 | # if the cursor position isn't given, the only sane assumption we can |
|
1993 | # if the cursor position isn't given, the only sane assumption we can | |
1984 | # make is that it's at the end of the line (the common case) |
|
1994 | # make is that it's at the end of the line (the common case) | |
1985 | if cursor_pos is None: |
|
1995 | if cursor_pos is None: | |
1986 | cursor_pos = len(line_buffer) if text is None else len(text) |
|
1996 | cursor_pos = len(line_buffer) if text is None else len(text) | |
1987 |
|
1997 | |||
1988 | if self.use_main_ns: |
|
1998 | if self.use_main_ns: | |
1989 | self.namespace = __main__.__dict__ |
|
1999 | self.namespace = __main__.__dict__ | |
1990 |
|
2000 | |||
1991 | # if text is either None or an empty string, rely on the line buffer |
|
2001 | # if text is either None or an empty string, rely on the line buffer | |
1992 | if (not line_buffer) and full_text: |
|
2002 | if (not line_buffer) and full_text: | |
1993 | line_buffer = full_text.split('\n')[cursor_line] |
|
2003 | line_buffer = full_text.split('\n')[cursor_line] | |
1994 | if not text: # issue #11508: check line_buffer before calling split_line |
|
2004 | if not text: # issue #11508: check line_buffer before calling split_line | |
1995 | text = self.splitter.split_line(line_buffer, cursor_pos) if line_buffer else '' |
|
2005 | text = self.splitter.split_line(line_buffer, cursor_pos) if line_buffer else '' | |
1996 |
|
2006 | |||
1997 | if self.backslash_combining_completions: |
|
2007 | if self.backslash_combining_completions: | |
1998 | # allow deactivation of these on windows. |
|
2008 | # allow deactivation of these on windows. | |
1999 | base_text = text if not line_buffer else line_buffer[:cursor_pos] |
|
2009 | base_text = text if not line_buffer else line_buffer[:cursor_pos] | |
2000 | latex_text, latex_matches = self.latex_matches(base_text) |
|
2010 | latex_text, latex_matches = self.latex_matches(base_text) | |
2001 | if latex_matches: |
|
2011 | if latex_matches: | |
2002 | return latex_text, latex_matches, ['latex_matches']*len(latex_matches), () |
|
2012 | return latex_text, latex_matches, ['latex_matches']*len(latex_matches), () | |
2003 | name_text = '' |
|
2013 | name_text = '' | |
2004 | name_matches = [] |
|
2014 | name_matches = [] | |
2005 | # need to add self.fwd_unicode_match() function here when done |
|
2015 | # need to add self.fwd_unicode_match() function here when done | |
2006 | for meth in (self.unicode_name_matches, back_latex_name_matches, back_unicode_name_matches, self.fwd_unicode_match): |
|
2016 | for meth in (self.unicode_name_matches, back_latex_name_matches, back_unicode_name_matches, self.fwd_unicode_match): | |
2007 | name_text, name_matches = meth(base_text) |
|
2017 | name_text, name_matches = meth(base_text) | |
2008 | if name_text: |
|
2018 | if name_text: | |
2009 | return name_text, name_matches[:MATCHES_LIMIT], \ |
|
2019 | return name_text, name_matches[:MATCHES_LIMIT], \ | |
2010 | [meth.__qualname__]*min(len(name_matches), MATCHES_LIMIT), () |
|
2020 | [meth.__qualname__]*min(len(name_matches), MATCHES_LIMIT), () | |
2011 |
|
2021 | |||
2012 |
|
2022 | |||
2013 | # If no line buffer is given, assume the input text is all there was |
|
2023 | # If no line buffer is given, assume the input text is all there was | |
2014 | if line_buffer is None: |
|
2024 | if line_buffer is None: | |
2015 | line_buffer = text |
|
2025 | line_buffer = text | |
2016 |
|
2026 | |||
2017 | self.line_buffer = line_buffer |
|
2027 | self.line_buffer = line_buffer | |
2018 | self.text_until_cursor = self.line_buffer[:cursor_pos] |
|
2028 | self.text_until_cursor = self.line_buffer[:cursor_pos] | |
2019 |
|
2029 | |||
2020 | # Do magic arg matches |
|
2030 | # Do magic arg matches | |
2021 | for matcher in self.magic_arg_matchers: |
|
2031 | for matcher in self.magic_arg_matchers: | |
2022 | matches = list(matcher(line_buffer))[:MATCHES_LIMIT] |
|
2032 | matches = list(matcher(line_buffer))[:MATCHES_LIMIT] | |
2023 | if matches: |
|
2033 | if matches: | |
2024 | origins = [matcher.__qualname__] * len(matches) |
|
2034 | origins = [matcher.__qualname__] * len(matches) | |
2025 | return text, matches, origins, () |
|
2035 | return text, matches, origins, () | |
2026 |
|
2036 | |||
2027 | # Start with a clean slate of completions |
|
2037 | # Start with a clean slate of completions | |
2028 | matches = [] |
|
2038 | matches = [] | |
2029 |
|
2039 | |||
2030 | # FIXME: we should extend our api to return a dict with completions for |
|
2040 | # FIXME: we should extend our api to return a dict with completions for | |
2031 | # different types of objects. The rlcomplete() method could then |
|
2041 | # different types of objects. The rlcomplete() method could then | |
2032 | # simply collapse the dict into a list for readline, but we'd have |
|
2042 | # simply collapse the dict into a list for readline, but we'd have | |
2033 | # richer completion semantics in other environments. |
|
2043 | # richer completion semantics in other environments. | |
2034 | completions = () |
|
2044 | completions = () | |
2035 | if self.use_jedi: |
|
2045 | if self.use_jedi: | |
2036 | if not full_text: |
|
2046 | if not full_text: | |
2037 | full_text = line_buffer |
|
2047 | full_text = line_buffer | |
2038 | completions = self._jedi_matches( |
|
2048 | completions = self._jedi_matches( | |
2039 | cursor_pos, cursor_line, full_text) |
|
2049 | cursor_pos, cursor_line, full_text) | |
2040 |
|
2050 | |||
2041 | if self.merge_completions: |
|
2051 | if self.merge_completions: | |
2042 | matches = [] |
|
2052 | matches = [] | |
2043 | for matcher in self.matchers: |
|
2053 | for matcher in self.matchers: | |
2044 | try: |
|
2054 | try: | |
2045 | matches.extend([(m, matcher.__qualname__) |
|
2055 | matches.extend([(m, matcher.__qualname__) | |
2046 | for m in matcher(text)]) |
|
2056 | for m in matcher(text)]) | |
2047 | except: |
|
2057 | except: | |
2048 | # Show the ugly traceback if the matcher causes an |
|
2058 | # Show the ugly traceback if the matcher causes an | |
2049 | # exception, but do NOT crash the kernel! |
|
2059 | # exception, but do NOT crash the kernel! | |
2050 | sys.excepthook(*sys.exc_info()) |
|
2060 | sys.excepthook(*sys.exc_info()) | |
2051 | else: |
|
2061 | else: | |
2052 | for matcher in self.matchers: |
|
2062 | for matcher in self.matchers: | |
2053 | matches = [(m, matcher.__qualname__) |
|
2063 | matches = [(m, matcher.__qualname__) | |
2054 | for m in matcher(text)] |
|
2064 | for m in matcher(text)] | |
2055 | if matches: |
|
2065 | if matches: | |
2056 | break |
|
2066 | break | |
2057 |
|
2067 | |||
2058 | seen = set() |
|
2068 | seen = set() | |
2059 | filtered_matches = set() |
|
2069 | filtered_matches = set() | |
2060 | for m in matches: |
|
2070 | for m in matches: | |
2061 | t, c = m |
|
2071 | t, c = m | |
2062 | if t not in seen: |
|
2072 | if t not in seen: | |
2063 | filtered_matches.add(m) |
|
2073 | filtered_matches.add(m) | |
2064 | seen.add(t) |
|
2074 | seen.add(t) | |
2065 |
|
2075 | |||
2066 | _filtered_matches = sorted(filtered_matches, key=lambda x: completions_sorting_key(x[0])) |
|
2076 | _filtered_matches = sorted(filtered_matches, key=lambda x: completions_sorting_key(x[0])) | |
2067 |
|
2077 | |||
2068 | custom_res = [(m, 'custom') for m in self.dispatch_custom_completer(text) or []] |
|
2078 | custom_res = [(m, 'custom') for m in self.dispatch_custom_completer(text) or []] | |
2069 |
|
2079 | |||
2070 | _filtered_matches = custom_res or _filtered_matches |
|
2080 | _filtered_matches = custom_res or _filtered_matches | |
2071 |
|
2081 | |||
2072 | _filtered_matches = _filtered_matches[:MATCHES_LIMIT] |
|
2082 | _filtered_matches = _filtered_matches[:MATCHES_LIMIT] | |
2073 | _matches = [m[0] for m in _filtered_matches] |
|
2083 | _matches = [m[0] for m in _filtered_matches] | |
2074 | origins = [m[1] for m in _filtered_matches] |
|
2084 | origins = [m[1] for m in _filtered_matches] | |
2075 |
|
2085 | |||
2076 | self.matches = _matches |
|
2086 | self.matches = _matches | |
2077 |
|
2087 | |||
2078 | return text, _matches, origins, completions |
|
2088 | return text, _matches, origins, completions | |
2079 |
|
2089 | |||
2080 | def fwd_unicode_match(self, text:str) -> Tuple[str, list]: |
|
2090 | def fwd_unicode_match(self, text:str) -> Tuple[str, list]: | |
2081 | if self._names is None: |
|
2091 | if self._names is None: | |
2082 | self._names = [] |
|
2092 | self._names = [] | |
2083 | for c in range(0,0x10FFFF + 1): |
|
2093 | for c in range(0,0x10FFFF + 1): | |
2084 | try: |
|
2094 | try: | |
2085 | self._names.append(unicodedata.name(chr(c))) |
|
2095 | self._names.append(unicodedata.name(chr(c))) | |
2086 | except ValueError: |
|
2096 | except ValueError: | |
2087 | pass |
|
2097 | pass | |
2088 |
|
2098 | |||
2089 | slashpos = text.rfind('\\') |
|
2099 | slashpos = text.rfind('\\') | |
2090 | # if text starts with slash |
|
2100 | # if text starts with slash | |
2091 | if slashpos > -1: |
|
2101 | if slashpos > -1: | |
2092 | s = text[slashpos+1:] |
|
2102 | s = text[slashpos+1:] | |
2093 | candidates = [x for x in self._names if x.startswith(s)] |
|
2103 | candidates = [x for x in self._names if x.startswith(s)] | |
2094 | if candidates: |
|
2104 | if candidates: | |
2095 | return s, candidates |
|
2105 | return s, candidates | |
2096 | else: |
|
2106 | else: | |
2097 | return '', () |
|
2107 | return '', () | |
2098 |
|
2108 | |||
2099 | # if text does not start with slash |
|
2109 | # if text does not start with slash | |
2100 | else: |
|
2110 | else: | |
2101 | return u'', () |
|
2111 | return u'', () |
@@ -1,1527 +1,1527 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Top-level display functions for displaying object in different formats.""" |
|
2 | """Top-level display functions for displaying object in different formats.""" | |
3 |
|
3 | |||
4 | # Copyright (c) IPython Development Team. |
|
4 | # Copyright (c) IPython Development Team. | |
5 | # Distributed under the terms of the Modified BSD License. |
|
5 | # Distributed under the terms of the Modified BSD License. | |
6 |
|
6 | |||
7 |
|
7 | |||
8 | from binascii import b2a_hex, b2a_base64, hexlify |
|
8 | from binascii import b2a_hex, b2a_base64, hexlify | |
9 | import json |
|
9 | import json | |
10 | import mimetypes |
|
10 | import mimetypes | |
11 | import os |
|
11 | import os | |
12 | import struct |
|
12 | import struct | |
13 | import sys |
|
13 | import sys | |
14 | import warnings |
|
14 | import warnings | |
15 | from copy import deepcopy |
|
15 | from copy import deepcopy | |
16 | from os.path import splitext |
|
16 | from os.path import splitext | |
17 | from pathlib import Path, PurePath |
|
17 | from pathlib import Path, PurePath | |
18 |
|
18 | |||
19 | from IPython.utils.py3compat import cast_unicode |
|
19 | from IPython.utils.py3compat import cast_unicode | |
20 | from IPython.testing.skipdoctest import skip_doctest |
|
20 | from IPython.testing.skipdoctest import skip_doctest | |
21 |
|
21 | |||
22 | __all__ = ['display', 'display_pretty', 'display_html', 'display_markdown', |
|
22 | __all__ = ['display', 'display_pretty', 'display_html', 'display_markdown', | |
23 | 'display_svg', 'display_png', 'display_jpeg', 'display_latex', 'display_json', |
|
23 | 'display_svg', 'display_png', 'display_jpeg', 'display_latex', 'display_json', | |
24 | 'display_javascript', 'display_pdf', 'DisplayObject', 'TextDisplayObject', |
|
24 | 'display_javascript', 'display_pdf', 'DisplayObject', 'TextDisplayObject', | |
25 | 'Pretty', 'HTML', 'Markdown', 'Math', 'Latex', 'SVG', 'ProgressBar', 'JSON', |
|
25 | 'Pretty', 'HTML', 'Markdown', 'Math', 'Latex', 'SVG', 'ProgressBar', 'JSON', | |
26 | 'GeoJSON', 'Javascript', 'Image', 'clear_output', 'set_matplotlib_formats', |
|
26 | 'GeoJSON', 'Javascript', 'Image', 'clear_output', 'set_matplotlib_formats', | |
27 | 'set_matplotlib_close', 'publish_display_data', 'update_display', 'DisplayHandle', |
|
27 | 'set_matplotlib_close', 'publish_display_data', 'update_display', 'DisplayHandle', | |
28 | 'Video'] |
|
28 | 'Video'] | |
29 |
|
29 | |||
30 | #----------------------------------------------------------------------------- |
|
30 | #----------------------------------------------------------------------------- | |
31 | # utility functions |
|
31 | # utility functions | |
32 | #----------------------------------------------------------------------------- |
|
32 | #----------------------------------------------------------------------------- | |
33 |
|
33 | |||
34 | def _safe_exists(path): |
|
34 | def _safe_exists(path): | |
35 | """Check path, but don't let exceptions raise""" |
|
35 | """Check path, but don't let exceptions raise""" | |
36 | try: |
|
36 | try: | |
37 | return os.path.exists(path) |
|
37 | return os.path.exists(path) | |
38 | except Exception: |
|
38 | except Exception: | |
39 | return False |
|
39 | return False | |
40 |
|
40 | |||
41 | def _merge(d1, d2): |
|
41 | def _merge(d1, d2): | |
42 | """Like update, but merges sub-dicts instead of clobbering at the top level. |
|
42 | """Like update, but merges sub-dicts instead of clobbering at the top level. | |
43 |
|
43 | |||
44 | Updates d1 in-place |
|
44 | Updates d1 in-place | |
45 | """ |
|
45 | """ | |
46 |
|
46 | |||
47 | if not isinstance(d2, dict) or not isinstance(d1, dict): |
|
47 | if not isinstance(d2, dict) or not isinstance(d1, dict): | |
48 | return d2 |
|
48 | return d2 | |
49 | for key, value in d2.items(): |
|
49 | for key, value in d2.items(): | |
50 | d1[key] = _merge(d1.get(key), value) |
|
50 | d1[key] = _merge(d1.get(key), value) | |
51 | return d1 |
|
51 | return d1 | |
52 |
|
52 | |||
53 | def _display_mimetype(mimetype, objs, raw=False, metadata=None): |
|
53 | def _display_mimetype(mimetype, objs, raw=False, metadata=None): | |
54 | """internal implementation of all display_foo methods |
|
54 | """internal implementation of all display_foo methods | |
55 |
|
55 | |||
56 | Parameters |
|
56 | Parameters | |
57 | ---------- |
|
57 | ---------- | |
58 | mimetype : str |
|
58 | mimetype : str | |
59 | The mimetype to be published (e.g. 'image/png') |
|
59 | The mimetype to be published (e.g. 'image/png') | |
60 | objs : tuple of objects |
|
60 | objs : tuple of objects | |
61 | The Python objects to display, or if raw=True raw text data to |
|
61 | The Python objects to display, or if raw=True raw text data to | |
62 | display. |
|
62 | display. | |
63 | raw : bool |
|
63 | raw : bool | |
64 | Are the data objects raw data or Python objects that need to be |
|
64 | Are the data objects raw data or Python objects that need to be | |
65 | formatted before display? [default: False] |
|
65 | formatted before display? [default: False] | |
66 | metadata : dict (optional) |
|
66 | metadata : dict (optional) | |
67 | Metadata to be associated with the specific mimetype output. |
|
67 | Metadata to be associated with the specific mimetype output. | |
68 | """ |
|
68 | """ | |
69 | if metadata: |
|
69 | if metadata: | |
70 | metadata = {mimetype: metadata} |
|
70 | metadata = {mimetype: metadata} | |
71 | if raw: |
|
71 | if raw: | |
72 | # turn list of pngdata into list of { 'image/png': pngdata } |
|
72 | # turn list of pngdata into list of { 'image/png': pngdata } | |
73 | objs = [ {mimetype: obj} for obj in objs ] |
|
73 | objs = [ {mimetype: obj} for obj in objs ] | |
74 | display(*objs, raw=raw, metadata=metadata, include=[mimetype]) |
|
74 | display(*objs, raw=raw, metadata=metadata, include=[mimetype]) | |
75 |
|
75 | |||
76 | #----------------------------------------------------------------------------- |
|
76 | #----------------------------------------------------------------------------- | |
77 | # Main functions |
|
77 | # Main functions | |
78 | #----------------------------------------------------------------------------- |
|
78 | #----------------------------------------------------------------------------- | |
79 |
|
79 | |||
80 | # use * to indicate transient is keyword-only |
|
80 | # use * to indicate transient is keyword-only | |
81 | def publish_display_data(data, metadata=None, source=None, *, transient=None, **kwargs): |
|
81 | def publish_display_data(data, metadata=None, source=None, *, transient=None, **kwargs): | |
82 | """Publish data and metadata to all frontends. |
|
82 | """Publish data and metadata to all frontends. | |
83 |
|
83 | |||
84 | See the ``display_data`` message in the messaging documentation for |
|
84 | See the ``display_data`` message in the messaging documentation for | |
85 | more details about this message type. |
|
85 | more details about this message type. | |
86 |
|
86 | |||
87 | Keys of data and metadata can be any mime-type. |
|
87 | Keys of data and metadata can be any mime-type. | |
88 |
|
88 | |||
89 | Parameters |
|
89 | Parameters | |
90 | ---------- |
|
90 | ---------- | |
91 | data : dict |
|
91 | data : dict | |
92 | A dictionary having keys that are valid MIME types (like |
|
92 | A dictionary having keys that are valid MIME types (like | |
93 | 'text/plain' or 'image/svg+xml') and values that are the data for |
|
93 | 'text/plain' or 'image/svg+xml') and values that are the data for | |
94 | that MIME type. The data itself must be a JSON'able data |
|
94 | that MIME type. The data itself must be a JSON'able data | |
95 | structure. Minimally all data should have the 'text/plain' data, |
|
95 | structure. Minimally all data should have the 'text/plain' data, | |
96 | which can be displayed by all frontends. If more than the plain |
|
96 | which can be displayed by all frontends. If more than the plain | |
97 | text is given, it is up to the frontend to decide which |
|
97 | text is given, it is up to the frontend to decide which | |
98 | representation to use. |
|
98 | representation to use. | |
99 | metadata : dict |
|
99 | metadata : dict | |
100 | A dictionary for metadata related to the data. This can contain |
|
100 | A dictionary for metadata related to the data. This can contain | |
101 | arbitrary key, value pairs that frontends can use to interpret |
|
101 | arbitrary key, value pairs that frontends can use to interpret | |
102 | the data. mime-type keys matching those in data can be used |
|
102 | the data. mime-type keys matching those in data can be used | |
103 | to specify metadata about particular representations. |
|
103 | to specify metadata about particular representations. | |
104 | source : str, deprecated |
|
104 | source : str, deprecated | |
105 | Unused. |
|
105 | Unused. | |
106 | transient : dict, keyword-only |
|
106 | transient : dict, keyword-only | |
107 | A dictionary of transient data, such as display_id. |
|
107 | A dictionary of transient data, such as display_id. | |
108 | """ |
|
108 | """ | |
109 | from IPython.core.interactiveshell import InteractiveShell |
|
109 | from IPython.core.interactiveshell import InteractiveShell | |
110 |
|
110 | |||
111 | display_pub = InteractiveShell.instance().display_pub |
|
111 | display_pub = InteractiveShell.instance().display_pub | |
112 |
|
112 | |||
113 | # only pass transient if supplied, |
|
113 | # only pass transient if supplied, | |
114 | # to avoid errors with older ipykernel. |
|
114 | # to avoid errors with older ipykernel. | |
115 | # TODO: We could check for ipykernel version and provide a detailed upgrade message. |
|
115 | # TODO: We could check for ipykernel version and provide a detailed upgrade message. | |
116 | if transient: |
|
116 | if transient: | |
117 | kwargs['transient'] = transient |
|
117 | kwargs['transient'] = transient | |
118 |
|
118 | |||
119 | display_pub.publish( |
|
119 | display_pub.publish( | |
120 | data=data, |
|
120 | data=data, | |
121 | metadata=metadata, |
|
121 | metadata=metadata, | |
122 | **kwargs |
|
122 | **kwargs | |
123 | ) |
|
123 | ) | |
124 |
|
124 | |||
125 |
|
125 | |||
126 | def _new_id(): |
|
126 | def _new_id(): | |
127 | """Generate a new random text id with urandom""" |
|
127 | """Generate a new random text id with urandom""" | |
128 | return b2a_hex(os.urandom(16)).decode('ascii') |
|
128 | return b2a_hex(os.urandom(16)).decode('ascii') | |
129 |
|
129 | |||
130 |
|
130 | |||
131 | def display(*objs, include=None, exclude=None, metadata=None, transient=None, display_id=None, **kwargs): |
|
131 | def display(*objs, include=None, exclude=None, metadata=None, transient=None, display_id=None, **kwargs): | |
132 | """Display a Python object in all frontends. |
|
132 | """Display a Python object in all frontends. | |
133 |
|
133 | |||
134 | By default all representations will be computed and sent to the frontends. |
|
134 | By default all representations will be computed and sent to the frontends. | |
135 | Frontends can decide which representation is used and how. |
|
135 | Frontends can decide which representation is used and how. | |
136 |
|
136 | |||
137 | In terminal IPython this will be similar to using :func:`print`, for use in richer |
|
137 | In terminal IPython this will be similar to using :func:`print`, for use in richer | |
138 | frontends see Jupyter notebook examples with rich display logic. |
|
138 | frontends see Jupyter notebook examples with rich display logic. | |
139 |
|
139 | |||
140 | Parameters |
|
140 | Parameters | |
141 | ---------- |
|
141 | ---------- | |
142 | objs : tuple of objects |
|
142 | objs : tuple of objects | |
143 | The Python objects to display. |
|
143 | The Python objects to display. | |
144 | raw : bool, optional |
|
144 | raw : bool, optional | |
145 | Are the objects to be displayed already mimetype-keyed dicts of raw display data, |
|
145 | Are the objects to be displayed already mimetype-keyed dicts of raw display data, | |
146 | or Python objects that need to be formatted before display? [default: False] |
|
146 | or Python objects that need to be formatted before display? [default: False] | |
147 | include : list, tuple or set, optional |
|
147 | include : list, tuple or set, optional | |
148 | A list of format type strings (MIME types) to include in the |
|
148 | A list of format type strings (MIME types) to include in the | |
149 | format data dict. If this is set *only* the format types included |
|
149 | format data dict. If this is set *only* the format types included | |
150 | in this list will be computed. |
|
150 | in this list will be computed. | |
151 | exclude : list, tuple or set, optional |
|
151 | exclude : list, tuple or set, optional | |
152 | A list of format type strings (MIME types) to exclude in the format |
|
152 | A list of format type strings (MIME types) to exclude in the format | |
153 | data dict. If this is set all format types will be computed, |
|
153 | data dict. If this is set all format types will be computed, | |
154 | except for those included in this argument. |
|
154 | except for those included in this argument. | |
155 | metadata : dict, optional |
|
155 | metadata : dict, optional | |
156 | A dictionary of metadata to associate with the output. |
|
156 | A dictionary of metadata to associate with the output. | |
157 | mime-type keys in this dictionary will be associated with the individual |
|
157 | mime-type keys in this dictionary will be associated with the individual | |
158 | representation formats, if they exist. |
|
158 | representation formats, if they exist. | |
159 | transient : dict, optional |
|
159 | transient : dict, optional | |
160 | A dictionary of transient data to associate with the output. |
|
160 | A dictionary of transient data to associate with the output. | |
161 | Data in this dict should not be persisted to files (e.g. notebooks). |
|
161 | Data in this dict should not be persisted to files (e.g. notebooks). | |
162 | display_id : str, bool optional |
|
162 | display_id : str, bool optional | |
163 | Set an id for the display. |
|
163 | Set an id for the display. | |
164 | This id can be used for updating this display area later via update_display. |
|
164 | This id can be used for updating this display area later via update_display. | |
165 | If given as `True`, generate a new `display_id` |
|
165 | If given as `True`, generate a new `display_id` | |
166 | kwargs: additional keyword-args, optional |
|
166 | kwargs: additional keyword-args, optional | |
167 | Additional keyword-arguments are passed through to the display publisher. |
|
167 | Additional keyword-arguments are passed through to the display publisher. | |
168 |
|
168 | |||
169 | Returns |
|
169 | Returns | |
170 | ------- |
|
170 | ------- | |
171 |
|
171 | |||
172 | handle: DisplayHandle |
|
172 | handle: DisplayHandle | |
173 | Returns a handle on updatable displays for use with :func:`update_display`, |
|
173 | Returns a handle on updatable displays for use with :func:`update_display`, | |
174 | if `display_id` is given. Returns :any:`None` if no `display_id` is given |
|
174 | if `display_id` is given. Returns :any:`None` if no `display_id` is given | |
175 | (default). |
|
175 | (default). | |
176 |
|
176 | |||
177 | Examples |
|
177 | Examples | |
178 | -------- |
|
178 | -------- | |
179 |
|
179 | |||
180 | >>> class Json(object): |
|
180 | >>> class Json(object): | |
181 | ... def __init__(self, json): |
|
181 | ... def __init__(self, json): | |
182 | ... self.json = json |
|
182 | ... self.json = json | |
183 | ... def _repr_pretty_(self, pp, cycle): |
|
183 | ... def _repr_pretty_(self, pp, cycle): | |
184 | ... import json |
|
184 | ... import json | |
185 | ... pp.text(json.dumps(self.json, indent=2)) |
|
185 | ... pp.text(json.dumps(self.json, indent=2)) | |
186 | ... def __repr__(self): |
|
186 | ... def __repr__(self): | |
187 | ... return str(self.json) |
|
187 | ... return str(self.json) | |
188 | ... |
|
188 | ... | |
189 |
|
189 | |||
190 | >>> d = Json({1:2, 3: {4:5}}) |
|
190 | >>> d = Json({1:2, 3: {4:5}}) | |
191 |
|
191 | |||
192 | >>> print(d) |
|
192 | >>> print(d) | |
193 | {1: 2, 3: {4: 5}} |
|
193 | {1: 2, 3: {4: 5}} | |
194 |
|
194 | |||
195 | >>> display(d) |
|
195 | >>> display(d) | |
196 | { |
|
196 | { | |
197 | "1": 2, |
|
197 | "1": 2, | |
198 | "3": { |
|
198 | "3": { | |
199 | "4": 5 |
|
199 | "4": 5 | |
200 | } |
|
200 | } | |
201 | } |
|
201 | } | |
202 |
|
202 | |||
203 | >>> def int_formatter(integer, pp, cycle): |
|
203 | >>> def int_formatter(integer, pp, cycle): | |
204 | ... pp.text('I'*integer) |
|
204 | ... pp.text('I'*integer) | |
205 |
|
205 | |||
206 | >>> plain = get_ipython().display_formatter.formatters['text/plain'] |
|
206 | >>> plain = get_ipython().display_formatter.formatters['text/plain'] | |
207 | >>> plain.for_type(int, int_formatter) |
|
207 | >>> plain.for_type(int, int_formatter) | |
208 | <function _repr_pprint at 0x...> |
|
208 | <function _repr_pprint at 0x...> | |
209 | >>> display(7-5) |
|
209 | >>> display(7-5) | |
210 | II |
|
210 | II | |
211 |
|
211 | |||
212 | >>> del plain.type_printers[int] |
|
212 | >>> del plain.type_printers[int] | |
213 | >>> display(7-5) |
|
213 | >>> display(7-5) | |
214 | 2 |
|
214 | 2 | |
215 |
|
215 | |||
216 | See Also |
|
216 | See Also | |
217 | -------- |
|
217 | -------- | |
218 |
|
218 | |||
219 | :func:`update_display` |
|
219 | :func:`update_display` | |
220 |
|
220 | |||
221 | Notes |
|
221 | Notes | |
222 | ----- |
|
222 | ----- | |
223 |
|
223 | |||
224 | In Python, objects can declare their textual representation using the |
|
224 | In Python, objects can declare their textual representation using the | |
225 | `__repr__` method. IPython expands on this idea and allows objects to declare |
|
225 | `__repr__` method. IPython expands on this idea and allows objects to declare | |
226 | other, rich representations including: |
|
226 | other, rich representations including: | |
227 |
|
227 | |||
228 | - HTML |
|
228 | - HTML | |
229 | - JSON |
|
229 | - JSON | |
230 | - PNG |
|
230 | - PNG | |
231 | - JPEG |
|
231 | - JPEG | |
232 | - SVG |
|
232 | - SVG | |
233 | - LaTeX |
|
233 | - LaTeX | |
234 |
|
234 | |||
235 | A single object can declare some or all of these representations; all are |
|
235 | A single object can declare some or all of these representations; all are | |
236 | handled by IPython's display system. |
|
236 | handled by IPython's display system. | |
237 |
|
237 | |||
238 | The main idea of the first approach is that you have to implement special |
|
238 | The main idea of the first approach is that you have to implement special | |
239 | display methods when you define your class, one for each representation you |
|
239 | display methods when you define your class, one for each representation you | |
240 | want to use. Here is a list of the names of the special methods and the |
|
240 | want to use. Here is a list of the names of the special methods and the | |
241 | values they must return: |
|
241 | values they must return: | |
242 |
|
242 | |||
243 | - `_repr_html_`: return raw HTML as a string, or a tuple (see below). |
|
243 | - `_repr_html_`: return raw HTML as a string, or a tuple (see below). | |
244 | - `_repr_json_`: return a JSONable dict, or a tuple (see below). |
|
244 | - `_repr_json_`: return a JSONable dict, or a tuple (see below). | |
245 | - `_repr_jpeg_`: return raw JPEG data, or a tuple (see below). |
|
245 | - `_repr_jpeg_`: return raw JPEG data, or a tuple (see below). | |
246 | - `_repr_png_`: return raw PNG data, or a tuple (see below). |
|
246 | - `_repr_png_`: return raw PNG data, or a tuple (see below). | |
247 | - `_repr_svg_`: return raw SVG data as a string, or a tuple (see below). |
|
247 | - `_repr_svg_`: return raw SVG data as a string, or a tuple (see below). | |
248 | - `_repr_latex_`: return LaTeX commands in a string surrounded by "$", |
|
248 | - `_repr_latex_`: return LaTeX commands in a string surrounded by "$", | |
249 | or a tuple (see below). |
|
249 | or a tuple (see below). | |
250 | - `_repr_mimebundle_`: return a full mimebundle containing the mapping |
|
250 | - `_repr_mimebundle_`: return a full mimebundle containing the mapping | |
251 | from all mimetypes to data. |
|
251 | from all mimetypes to data. | |
252 | Use this for any mime-type not listed above. |
|
252 | Use this for any mime-type not listed above. | |
253 |
|
253 | |||
254 | The above functions may also return the object's metadata alonside the |
|
254 | The above functions may also return the object's metadata alonside the | |
255 | data. If the metadata is available, the functions will return a tuple |
|
255 | data. If the metadata is available, the functions will return a tuple | |
256 | containing the data and metadata, in that order. If there is no metadata |
|
256 | containing the data and metadata, in that order. If there is no metadata | |
257 | available, then the functions will return the data only. |
|
257 | available, then the functions will return the data only. | |
258 |
|
258 | |||
259 | When you are directly writing your own classes, you can adapt them for |
|
259 | When you are directly writing your own classes, you can adapt them for | |
260 | display in IPython by following the above approach. But in practice, you |
|
260 | display in IPython by following the above approach. But in practice, you | |
261 | often need to work with existing classes that you can't easily modify. |
|
261 | often need to work with existing classes that you can't easily modify. | |
262 |
|
262 | |||
263 | You can refer to the documentation on integrating with the display system in |
|
263 | You can refer to the documentation on integrating with the display system in | |
264 | order to register custom formatters for already existing types |
|
264 | order to register custom formatters for already existing types | |
265 | (:ref:`integrating_rich_display`). |
|
265 | (:ref:`integrating_rich_display`). | |
266 |
|
266 | |||
267 | .. versionadded:: 5.4 display available without import |
|
267 | .. versionadded:: 5.4 display available without import | |
268 | .. versionadded:: 6.1 display available without import |
|
268 | .. versionadded:: 6.1 display available without import | |
269 |
|
269 | |||
270 | Since IPython 5.4 and 6.1 :func:`display` is automatically made available to |
|
270 | Since IPython 5.4 and 6.1 :func:`display` is automatically made available to | |
271 | the user without import. If you are using display in a document that might |
|
271 | the user without import. If you are using display in a document that might | |
272 | be used in a pure python context or with older version of IPython, use the |
|
272 | be used in a pure python context or with older version of IPython, use the | |
273 | following import at the top of your file:: |
|
273 | following import at the top of your file:: | |
274 |
|
274 | |||
275 | from IPython.display import display |
|
275 | from IPython.display import display | |
276 |
|
276 | |||
277 | """ |
|
277 | """ | |
278 | from IPython.core.interactiveshell import InteractiveShell |
|
278 | from IPython.core.interactiveshell import InteractiveShell | |
279 |
|
279 | |||
280 | if not InteractiveShell.initialized(): |
|
280 | if not InteractiveShell.initialized(): | |
281 | # Directly print objects. |
|
281 | # Directly print objects. | |
282 | print(*objs) |
|
282 | print(*objs) | |
283 | return |
|
283 | return | |
284 |
|
284 | |||
285 | raw = kwargs.pop('raw', False) |
|
285 | raw = kwargs.pop('raw', False) | |
286 | if transient is None: |
|
286 | if transient is None: | |
287 | transient = {} |
|
287 | transient = {} | |
288 | if metadata is None: |
|
288 | if metadata is None: | |
289 | metadata={} |
|
289 | metadata={} | |
290 | if display_id: |
|
290 | if display_id: | |
291 | if display_id is True: |
|
291 | if display_id is True: | |
292 | display_id = _new_id() |
|
292 | display_id = _new_id() | |
293 | transient['display_id'] = display_id |
|
293 | transient['display_id'] = display_id | |
294 | if kwargs.get('update') and 'display_id' not in transient: |
|
294 | if kwargs.get('update') and 'display_id' not in transient: | |
295 | raise TypeError('display_id required for update_display') |
|
295 | raise TypeError('display_id required for update_display') | |
296 | if transient: |
|
296 | if transient: | |
297 | kwargs['transient'] = transient |
|
297 | kwargs['transient'] = transient | |
298 |
|
298 | |||
299 | if not objs and display_id: |
|
299 | if not objs and display_id: | |
300 | # if given no objects, but still a request for a display_id, |
|
300 | # if given no objects, but still a request for a display_id, | |
301 | # we assume the user wants to insert an empty output that |
|
301 | # we assume the user wants to insert an empty output that | |
302 | # can be updated later |
|
302 | # can be updated later | |
303 | objs = [{}] |
|
303 | objs = [{}] | |
304 | raw = True |
|
304 | raw = True | |
305 |
|
305 | |||
306 | if not raw: |
|
306 | if not raw: | |
307 | format = InteractiveShell.instance().display_formatter.format |
|
307 | format = InteractiveShell.instance().display_formatter.format | |
308 |
|
308 | |||
309 | for obj in objs: |
|
309 | for obj in objs: | |
310 | if raw: |
|
310 | if raw: | |
311 | publish_display_data(data=obj, metadata=metadata, **kwargs) |
|
311 | publish_display_data(data=obj, metadata=metadata, **kwargs) | |
312 | else: |
|
312 | else: | |
313 | format_dict, md_dict = format(obj, include=include, exclude=exclude) |
|
313 | format_dict, md_dict = format(obj, include=include, exclude=exclude) | |
314 | if not format_dict: |
|
314 | if not format_dict: | |
315 | # nothing to display (e.g. _ipython_display_ took over) |
|
315 | # nothing to display (e.g. _ipython_display_ took over) | |
316 | continue |
|
316 | continue | |
317 | if metadata: |
|
317 | if metadata: | |
318 | # kwarg-specified metadata gets precedence |
|
318 | # kwarg-specified metadata gets precedence | |
319 | _merge(md_dict, metadata) |
|
319 | _merge(md_dict, metadata) | |
320 | publish_display_data(data=format_dict, metadata=md_dict, **kwargs) |
|
320 | publish_display_data(data=format_dict, metadata=md_dict, **kwargs) | |
321 | if display_id: |
|
321 | if display_id: | |
322 | return DisplayHandle(display_id) |
|
322 | return DisplayHandle(display_id) | |
323 |
|
323 | |||
324 |
|
324 | |||
325 | # use * for keyword-only display_id arg |
|
325 | # use * for keyword-only display_id arg | |
326 | def update_display(obj, *, display_id, **kwargs): |
|
326 | def update_display(obj, *, display_id, **kwargs): | |
327 | """Update an existing display by id |
|
327 | """Update an existing display by id | |
328 |
|
328 | |||
329 | Parameters |
|
329 | Parameters | |
330 | ---------- |
|
330 | ---------- | |
331 |
|
331 | |||
332 | obj: |
|
332 | obj: | |
333 | The object with which to update the display |
|
333 | The object with which to update the display | |
334 | display_id: keyword-only |
|
334 | display_id: keyword-only | |
335 | The id of the display to update |
|
335 | The id of the display to update | |
336 |
|
336 | |||
337 | See Also |
|
337 | See Also | |
338 | -------- |
|
338 | -------- | |
339 |
|
339 | |||
340 | :func:`display` |
|
340 | :func:`display` | |
341 | """ |
|
341 | """ | |
342 | kwargs['update'] = True |
|
342 | kwargs['update'] = True | |
343 | display(obj, display_id=display_id, **kwargs) |
|
343 | display(obj, display_id=display_id, **kwargs) | |
344 |
|
344 | |||
345 |
|
345 | |||
346 | class DisplayHandle(object): |
|
346 | class DisplayHandle(object): | |
347 | """A handle on an updatable display |
|
347 | """A handle on an updatable display | |
348 |
|
348 | |||
349 | Call `.update(obj)` to display a new object. |
|
349 | Call `.update(obj)` to display a new object. | |
350 |
|
350 | |||
351 | Call `.display(obj`) to add a new instance of this display, |
|
351 | Call `.display(obj`) to add a new instance of this display, | |
352 | and update existing instances. |
|
352 | and update existing instances. | |
353 |
|
353 | |||
354 | See Also |
|
354 | See Also | |
355 | -------- |
|
355 | -------- | |
356 |
|
356 | |||
357 | :func:`display`, :func:`update_display` |
|
357 | :func:`display`, :func:`update_display` | |
358 |
|
358 | |||
359 | """ |
|
359 | """ | |
360 |
|
360 | |||
361 | def __init__(self, display_id=None): |
|
361 | def __init__(self, display_id=None): | |
362 | if display_id is None: |
|
362 | if display_id is None: | |
363 | display_id = _new_id() |
|
363 | display_id = _new_id() | |
364 | self.display_id = display_id |
|
364 | self.display_id = display_id | |
365 |
|
365 | |||
366 | def __repr__(self): |
|
366 | def __repr__(self): | |
367 | return "<%s display_id=%s>" % (self.__class__.__name__, self.display_id) |
|
367 | return "<%s display_id=%s>" % (self.__class__.__name__, self.display_id) | |
368 |
|
368 | |||
369 | def display(self, obj, **kwargs): |
|
369 | def display(self, obj, **kwargs): | |
370 | """Make a new display with my id, updating existing instances. |
|
370 | """Make a new display with my id, updating existing instances. | |
371 |
|
371 | |||
372 | Parameters |
|
372 | Parameters | |
373 | ---------- |
|
373 | ---------- | |
374 |
|
374 | |||
375 | obj: |
|
375 | obj: | |
376 | object to display |
|
376 | object to display | |
377 | **kwargs: |
|
377 | **kwargs: | |
378 | additional keyword arguments passed to display |
|
378 | additional keyword arguments passed to display | |
379 | """ |
|
379 | """ | |
380 | display(obj, display_id=self.display_id, **kwargs) |
|
380 | display(obj, display_id=self.display_id, **kwargs) | |
381 |
|
381 | |||
382 | def update(self, obj, **kwargs): |
|
382 | def update(self, obj, **kwargs): | |
383 | """Update existing displays with my id |
|
383 | """Update existing displays with my id | |
384 |
|
384 | |||
385 | Parameters |
|
385 | Parameters | |
386 | ---------- |
|
386 | ---------- | |
387 |
|
387 | |||
388 | obj: |
|
388 | obj: | |
389 | object to display |
|
389 | object to display | |
390 | **kwargs: |
|
390 | **kwargs: | |
391 | additional keyword arguments passed to update_display |
|
391 | additional keyword arguments passed to update_display | |
392 | """ |
|
392 | """ | |
393 | update_display(obj, display_id=self.display_id, **kwargs) |
|
393 | update_display(obj, display_id=self.display_id, **kwargs) | |
394 |
|
394 | |||
395 |
|
395 | |||
396 | def display_pretty(*objs, **kwargs): |
|
396 | def display_pretty(*objs, **kwargs): | |
397 | """Display the pretty (default) representation of an object. |
|
397 | """Display the pretty (default) representation of an object. | |
398 |
|
398 | |||
399 | Parameters |
|
399 | Parameters | |
400 | ---------- |
|
400 | ---------- | |
401 | objs : tuple of objects |
|
401 | objs : tuple of objects | |
402 | The Python objects to display, or if raw=True raw text data to |
|
402 | The Python objects to display, or if raw=True raw text data to | |
403 | display. |
|
403 | display. | |
404 | raw : bool |
|
404 | raw : bool | |
405 | Are the data objects raw data or Python objects that need to be |
|
405 | Are the data objects raw data or Python objects that need to be | |
406 | formatted before display? [default: False] |
|
406 | formatted before display? [default: False] | |
407 | metadata : dict (optional) |
|
407 | metadata : dict (optional) | |
408 | Metadata to be associated with the specific mimetype output. |
|
408 | Metadata to be associated with the specific mimetype output. | |
409 | """ |
|
409 | """ | |
410 | _display_mimetype('text/plain', objs, **kwargs) |
|
410 | _display_mimetype('text/plain', objs, **kwargs) | |
411 |
|
411 | |||
412 |
|
412 | |||
413 | def display_html(*objs, **kwargs): |
|
413 | def display_html(*objs, **kwargs): | |
414 | """Display the HTML representation of an object. |
|
414 | """Display the HTML representation of an object. | |
415 |
|
415 | |||
416 | Note: If raw=False and the object does not have a HTML |
|
416 | Note: If raw=False and the object does not have a HTML | |
417 | representation, no HTML will be shown. |
|
417 | representation, no HTML will be shown. | |
418 |
|
418 | |||
419 | Parameters |
|
419 | Parameters | |
420 | ---------- |
|
420 | ---------- | |
421 | objs : tuple of objects |
|
421 | objs : tuple of objects | |
422 | The Python objects to display, or if raw=True raw HTML data to |
|
422 | The Python objects to display, or if raw=True raw HTML data to | |
423 | display. |
|
423 | display. | |
424 | raw : bool |
|
424 | raw : bool | |
425 | Are the data objects raw data or Python objects that need to be |
|
425 | Are the data objects raw data or Python objects that need to be | |
426 | formatted before display? [default: False] |
|
426 | formatted before display? [default: False] | |
427 | metadata : dict (optional) |
|
427 | metadata : dict (optional) | |
428 | Metadata to be associated with the specific mimetype output. |
|
428 | Metadata to be associated with the specific mimetype output. | |
429 | """ |
|
429 | """ | |
430 | _display_mimetype('text/html', objs, **kwargs) |
|
430 | _display_mimetype('text/html', objs, **kwargs) | |
431 |
|
431 | |||
432 |
|
432 | |||
433 | def display_markdown(*objs, **kwargs): |
|
433 | def display_markdown(*objs, **kwargs): | |
434 | """Displays the Markdown representation of an object. |
|
434 | """Displays the Markdown representation of an object. | |
435 |
|
435 | |||
436 | Parameters |
|
436 | Parameters | |
437 | ---------- |
|
437 | ---------- | |
438 | objs : tuple of objects |
|
438 | objs : tuple of objects | |
439 | The Python objects to display, or if raw=True raw markdown data to |
|
439 | The Python objects to display, or if raw=True raw markdown data to | |
440 | display. |
|
440 | display. | |
441 | raw : bool |
|
441 | raw : bool | |
442 | Are the data objects raw data or Python objects that need to be |
|
442 | Are the data objects raw data or Python objects that need to be | |
443 | formatted before display? [default: False] |
|
443 | formatted before display? [default: False] | |
444 | metadata : dict (optional) |
|
444 | metadata : dict (optional) | |
445 | Metadata to be associated with the specific mimetype output. |
|
445 | Metadata to be associated with the specific mimetype output. | |
446 | """ |
|
446 | """ | |
447 |
|
447 | |||
448 | _display_mimetype('text/markdown', objs, **kwargs) |
|
448 | _display_mimetype('text/markdown', objs, **kwargs) | |
449 |
|
449 | |||
450 |
|
450 | |||
451 | def display_svg(*objs, **kwargs): |
|
451 | def display_svg(*objs, **kwargs): | |
452 | """Display the SVG representation of an object. |
|
452 | """Display the SVG representation of an object. | |
453 |
|
453 | |||
454 | Parameters |
|
454 | Parameters | |
455 | ---------- |
|
455 | ---------- | |
456 | objs : tuple of objects |
|
456 | objs : tuple of objects | |
457 | The Python objects to display, or if raw=True raw svg data to |
|
457 | The Python objects to display, or if raw=True raw svg data to | |
458 | display. |
|
458 | display. | |
459 | raw : bool |
|
459 | raw : bool | |
460 | Are the data objects raw data or Python objects that need to be |
|
460 | Are the data objects raw data or Python objects that need to be | |
461 | formatted before display? [default: False] |
|
461 | formatted before display? [default: False] | |
462 | metadata : dict (optional) |
|
462 | metadata : dict (optional) | |
463 | Metadata to be associated with the specific mimetype output. |
|
463 | Metadata to be associated with the specific mimetype output. | |
464 | """ |
|
464 | """ | |
465 | _display_mimetype('image/svg+xml', objs, **kwargs) |
|
465 | _display_mimetype('image/svg+xml', objs, **kwargs) | |
466 |
|
466 | |||
467 |
|
467 | |||
468 | def display_png(*objs, **kwargs): |
|
468 | def display_png(*objs, **kwargs): | |
469 | """Display the PNG representation of an object. |
|
469 | """Display the PNG representation of an object. | |
470 |
|
470 | |||
471 | Parameters |
|
471 | Parameters | |
472 | ---------- |
|
472 | ---------- | |
473 | objs : tuple of objects |
|
473 | objs : tuple of objects | |
474 | The Python objects to display, or if raw=True raw png data to |
|
474 | The Python objects to display, or if raw=True raw png data to | |
475 | display. |
|
475 | display. | |
476 | raw : bool |
|
476 | raw : bool | |
477 | Are the data objects raw data or Python objects that need to be |
|
477 | Are the data objects raw data or Python objects that need to be | |
478 | formatted before display? [default: False] |
|
478 | formatted before display? [default: False] | |
479 | metadata : dict (optional) |
|
479 | metadata : dict (optional) | |
480 | Metadata to be associated with the specific mimetype output. |
|
480 | Metadata to be associated with the specific mimetype output. | |
481 | """ |
|
481 | """ | |
482 | _display_mimetype('image/png', objs, **kwargs) |
|
482 | _display_mimetype('image/png', objs, **kwargs) | |
483 |
|
483 | |||
484 |
|
484 | |||
485 | def display_jpeg(*objs, **kwargs): |
|
485 | def display_jpeg(*objs, **kwargs): | |
486 | """Display the JPEG representation of an object. |
|
486 | """Display the JPEG representation of an object. | |
487 |
|
487 | |||
488 | Parameters |
|
488 | Parameters | |
489 | ---------- |
|
489 | ---------- | |
490 | objs : tuple of objects |
|
490 | objs : tuple of objects | |
491 | The Python objects to display, or if raw=True raw JPEG data to |
|
491 | The Python objects to display, or if raw=True raw JPEG data to | |
492 | display. |
|
492 | display. | |
493 | raw : bool |
|
493 | raw : bool | |
494 | Are the data objects raw data or Python objects that need to be |
|
494 | Are the data objects raw data or Python objects that need to be | |
495 | formatted before display? [default: False] |
|
495 | formatted before display? [default: False] | |
496 | metadata : dict (optional) |
|
496 | metadata : dict (optional) | |
497 | Metadata to be associated with the specific mimetype output. |
|
497 | Metadata to be associated with the specific mimetype output. | |
498 | """ |
|
498 | """ | |
499 | _display_mimetype('image/jpeg', objs, **kwargs) |
|
499 | _display_mimetype('image/jpeg', objs, **kwargs) | |
500 |
|
500 | |||
501 |
|
501 | |||
502 | def display_latex(*objs, **kwargs): |
|
502 | def display_latex(*objs, **kwargs): | |
503 | """Display the LaTeX representation of an object. |
|
503 | """Display the LaTeX representation of an object. | |
504 |
|
504 | |||
505 | Parameters |
|
505 | Parameters | |
506 | ---------- |
|
506 | ---------- | |
507 | objs : tuple of objects |
|
507 | objs : tuple of objects | |
508 | The Python objects to display, or if raw=True raw latex data to |
|
508 | The Python objects to display, or if raw=True raw latex data to | |
509 | display. |
|
509 | display. | |
510 | raw : bool |
|
510 | raw : bool | |
511 | Are the data objects raw data or Python objects that need to be |
|
511 | Are the data objects raw data or Python objects that need to be | |
512 | formatted before display? [default: False] |
|
512 | formatted before display? [default: False] | |
513 | metadata : dict (optional) |
|
513 | metadata : dict (optional) | |
514 | Metadata to be associated with the specific mimetype output. |
|
514 | Metadata to be associated with the specific mimetype output. | |
515 | """ |
|
515 | """ | |
516 | _display_mimetype('text/latex', objs, **kwargs) |
|
516 | _display_mimetype('text/latex', objs, **kwargs) | |
517 |
|
517 | |||
518 |
|
518 | |||
519 | def display_json(*objs, **kwargs): |
|
519 | def display_json(*objs, **kwargs): | |
520 | """Display the JSON representation of an object. |
|
520 | """Display the JSON representation of an object. | |
521 |
|
521 | |||
522 | Note that not many frontends support displaying JSON. |
|
522 | Note that not many frontends support displaying JSON. | |
523 |
|
523 | |||
524 | Parameters |
|
524 | Parameters | |
525 | ---------- |
|
525 | ---------- | |
526 | objs : tuple of objects |
|
526 | objs : tuple of objects | |
527 | The Python objects to display, or if raw=True raw json data to |
|
527 | The Python objects to display, or if raw=True raw json data to | |
528 | display. |
|
528 | display. | |
529 | raw : bool |
|
529 | raw : bool | |
530 | Are the data objects raw data or Python objects that need to be |
|
530 | Are the data objects raw data or Python objects that need to be | |
531 | formatted before display? [default: False] |
|
531 | formatted before display? [default: False] | |
532 | metadata : dict (optional) |
|
532 | metadata : dict (optional) | |
533 | Metadata to be associated with the specific mimetype output. |
|
533 | Metadata to be associated with the specific mimetype output. | |
534 | """ |
|
534 | """ | |
535 | _display_mimetype('application/json', objs, **kwargs) |
|
535 | _display_mimetype('application/json', objs, **kwargs) | |
536 |
|
536 | |||
537 |
|
537 | |||
538 | def display_javascript(*objs, **kwargs): |
|
538 | def display_javascript(*objs, **kwargs): | |
539 | """Display the Javascript representation of an object. |
|
539 | """Display the Javascript representation of an object. | |
540 |
|
540 | |||
541 | Parameters |
|
541 | Parameters | |
542 | ---------- |
|
542 | ---------- | |
543 | objs : tuple of objects |
|
543 | objs : tuple of objects | |
544 | The Python objects to display, or if raw=True raw javascript data to |
|
544 | The Python objects to display, or if raw=True raw javascript data to | |
545 | display. |
|
545 | display. | |
546 | raw : bool |
|
546 | raw : bool | |
547 | Are the data objects raw data or Python objects that need to be |
|
547 | Are the data objects raw data or Python objects that need to be | |
548 | formatted before display? [default: False] |
|
548 | formatted before display? [default: False] | |
549 | metadata : dict (optional) |
|
549 | metadata : dict (optional) | |
550 | Metadata to be associated with the specific mimetype output. |
|
550 | Metadata to be associated with the specific mimetype output. | |
551 | """ |
|
551 | """ | |
552 | _display_mimetype('application/javascript', objs, **kwargs) |
|
552 | _display_mimetype('application/javascript', objs, **kwargs) | |
553 |
|
553 | |||
554 |
|
554 | |||
555 | def display_pdf(*objs, **kwargs): |
|
555 | def display_pdf(*objs, **kwargs): | |
556 | """Display the PDF representation of an object. |
|
556 | """Display the PDF representation of an object. | |
557 |
|
557 | |||
558 | Parameters |
|
558 | Parameters | |
559 | ---------- |
|
559 | ---------- | |
560 | objs : tuple of objects |
|
560 | objs : tuple of objects | |
561 | The Python objects to display, or if raw=True raw javascript data to |
|
561 | The Python objects to display, or if raw=True raw javascript data to | |
562 | display. |
|
562 | display. | |
563 | raw : bool |
|
563 | raw : bool | |
564 | Are the data objects raw data or Python objects that need to be |
|
564 | Are the data objects raw data or Python objects that need to be | |
565 | formatted before display? [default: False] |
|
565 | formatted before display? [default: False] | |
566 | metadata : dict (optional) |
|
566 | metadata : dict (optional) | |
567 | Metadata to be associated with the specific mimetype output. |
|
567 | Metadata to be associated with the specific mimetype output. | |
568 | """ |
|
568 | """ | |
569 | _display_mimetype('application/pdf', objs, **kwargs) |
|
569 | _display_mimetype('application/pdf', objs, **kwargs) | |
570 |
|
570 | |||
571 |
|
571 | |||
572 | #----------------------------------------------------------------------------- |
|
572 | #----------------------------------------------------------------------------- | |
573 | # Smart classes |
|
573 | # Smart classes | |
574 | #----------------------------------------------------------------------------- |
|
574 | #----------------------------------------------------------------------------- | |
575 |
|
575 | |||
576 |
|
576 | |||
577 | class DisplayObject(object): |
|
577 | class DisplayObject(object): | |
578 | """An object that wraps data to be displayed.""" |
|
578 | """An object that wraps data to be displayed.""" | |
579 |
|
579 | |||
580 | _read_flags = 'r' |
|
580 | _read_flags = 'r' | |
581 | _show_mem_addr = False |
|
581 | _show_mem_addr = False | |
582 | metadata = None |
|
582 | metadata = None | |
583 |
|
583 | |||
584 | def __init__(self, data=None, url=None, filename=None, metadata=None): |
|
584 | def __init__(self, data=None, url=None, filename=None, metadata=None): | |
585 | """Create a display object given raw data. |
|
585 | """Create a display object given raw data. | |
586 |
|
586 | |||
587 | When this object is returned by an expression or passed to the |
|
587 | When this object is returned by an expression or passed to the | |
588 | display function, it will result in the data being displayed |
|
588 | display function, it will result in the data being displayed | |
589 | in the frontend. The MIME type of the data should match the |
|
589 | in the frontend. The MIME type of the data should match the | |
590 | subclasses used, so the Png subclass should be used for 'image/png' |
|
590 | subclasses used, so the Png subclass should be used for 'image/png' | |
591 | data. If the data is a URL, the data will first be downloaded |
|
591 | data. If the data is a URL, the data will first be downloaded | |
592 | and then displayed. If |
|
592 | and then displayed. If | |
593 |
|
593 | |||
594 | Parameters |
|
594 | Parameters | |
595 | ---------- |
|
595 | ---------- | |
596 | data : unicode, str or bytes |
|
596 | data : unicode, str or bytes | |
597 | The raw data or a URL or file to load the data from |
|
597 | The raw data or a URL or file to load the data from | |
598 | url : unicode |
|
598 | url : unicode | |
599 | A URL to download the data from. |
|
599 | A URL to download the data from. | |
600 | filename : unicode |
|
600 | filename : unicode | |
601 | Path to a local file to load the data from. |
|
601 | Path to a local file to load the data from. | |
602 | metadata : dict |
|
602 | metadata : dict | |
603 | Dict of metadata associated to be the object when displayed |
|
603 | Dict of metadata associated to be the object when displayed | |
604 | """ |
|
604 | """ | |
605 | if isinstance(data, (Path, PurePath)): |
|
605 | if isinstance(data, (Path, PurePath)): | |
606 | data = str(data) |
|
606 | data = str(data) | |
607 |
|
607 | |||
608 | if data is not None and isinstance(data, str): |
|
608 | if data is not None and isinstance(data, str): | |
609 | if data.startswith('http') and url is None: |
|
609 | if data.startswith('http') and url is None: | |
610 | url = data |
|
610 | url = data | |
611 | filename = None |
|
611 | filename = None | |
612 | data = None |
|
612 | data = None | |
613 | elif _safe_exists(data) and filename is None: |
|
613 | elif _safe_exists(data) and filename is None: | |
614 | url = None |
|
614 | url = None | |
615 | filename = data |
|
615 | filename = data | |
616 | data = None |
|
616 | data = None | |
617 |
|
617 | |||
618 | self.url = url |
|
618 | self.url = url | |
619 | self.filename = filename |
|
619 | self.filename = filename | |
620 | # because of @data.setter methods in |
|
620 | # because of @data.setter methods in | |
621 | # subclasses ensure url and filename are set |
|
621 | # subclasses ensure url and filename are set | |
622 | # before assigning to self.data |
|
622 | # before assigning to self.data | |
623 | self.data = data |
|
623 | self.data = data | |
624 |
|
624 | |||
625 | if metadata is not None: |
|
625 | if metadata is not None: | |
626 | self.metadata = metadata |
|
626 | self.metadata = metadata | |
627 | elif self.metadata is None: |
|
627 | elif self.metadata is None: | |
628 | self.metadata = {} |
|
628 | self.metadata = {} | |
629 |
|
629 | |||
630 | self.reload() |
|
630 | self.reload() | |
631 | self._check_data() |
|
631 | self._check_data() | |
632 |
|
632 | |||
633 | def __repr__(self): |
|
633 | def __repr__(self): | |
634 | if not self._show_mem_addr: |
|
634 | if not self._show_mem_addr: | |
635 | cls = self.__class__ |
|
635 | cls = self.__class__ | |
636 | r = "<%s.%s object>" % (cls.__module__, cls.__name__) |
|
636 | r = "<%s.%s object>" % (cls.__module__, cls.__name__) | |
637 | else: |
|
637 | else: | |
638 | r = super(DisplayObject, self).__repr__() |
|
638 | r = super(DisplayObject, self).__repr__() | |
639 | return r |
|
639 | return r | |
640 |
|
640 | |||
641 | def _check_data(self): |
|
641 | def _check_data(self): | |
642 | """Override in subclasses if there's something to check.""" |
|
642 | """Override in subclasses if there's something to check.""" | |
643 | pass |
|
643 | pass | |
644 |
|
644 | |||
645 | def _data_and_metadata(self): |
|
645 | def _data_and_metadata(self): | |
646 | """shortcut for returning metadata with shape information, if defined""" |
|
646 | """shortcut for returning metadata with shape information, if defined""" | |
647 | if self.metadata: |
|
647 | if self.metadata: | |
648 | return self.data, deepcopy(self.metadata) |
|
648 | return self.data, deepcopy(self.metadata) | |
649 | else: |
|
649 | else: | |
650 | return self.data |
|
650 | return self.data | |
651 |
|
651 | |||
652 | def reload(self): |
|
652 | def reload(self): | |
653 | """Reload the raw data from file or URL.""" |
|
653 | """Reload the raw data from file or URL.""" | |
654 | if self.filename is not None: |
|
654 | if self.filename is not None: | |
655 | with open(self.filename, self._read_flags) as f: |
|
655 | with open(self.filename, self._read_flags) as f: | |
656 | self.data = f.read() |
|
656 | self.data = f.read() | |
657 | elif self.url is not None: |
|
657 | elif self.url is not None: | |
658 | # Deferred import |
|
658 | # Deferred import | |
659 | from urllib.request import urlopen |
|
659 | from urllib.request import urlopen | |
660 | response = urlopen(self.url) |
|
660 | response = urlopen(self.url) | |
661 | data = response.read() |
|
661 | data = response.read() | |
662 | # extract encoding from header, if there is one: |
|
662 | # extract encoding from header, if there is one: | |
663 | encoding = None |
|
663 | encoding = None | |
664 | if 'content-type' in response.headers: |
|
664 | if 'content-type' in response.headers: | |
665 | for sub in response.headers['content-type'].split(';'): |
|
665 | for sub in response.headers['content-type'].split(';'): | |
666 | sub = sub.strip() |
|
666 | sub = sub.strip() | |
667 | if sub.startswith('charset'): |
|
667 | if sub.startswith('charset'): | |
668 | encoding = sub.split('=')[-1].strip() |
|
668 | encoding = sub.split('=')[-1].strip() | |
669 | break |
|
669 | break | |
670 | if 'content-encoding' in response.headers: |
|
670 | if 'content-encoding' in response.headers: | |
671 | # TODO: do deflate? |
|
671 | # TODO: do deflate? | |
672 | if 'gzip' in response.headers['content-encoding']: |
|
672 | if 'gzip' in response.headers['content-encoding']: | |
673 | import gzip |
|
673 | import gzip | |
674 | from io import BytesIO |
|
674 | from io import BytesIO | |
675 | with gzip.open(BytesIO(data), 'rt', encoding=encoding) as fp: |
|
675 | with gzip.open(BytesIO(data), 'rt', encoding=encoding) as fp: | |
676 | encoding = None |
|
676 | encoding = None | |
677 | data = fp.read() |
|
677 | data = fp.read() | |
678 |
|
678 | |||
679 | # decode data, if an encoding was specified |
|
679 | # decode data, if an encoding was specified | |
680 | # We only touch self.data once since |
|
680 | # We only touch self.data once since | |
681 | # subclasses such as SVG have @data.setter methods |
|
681 | # subclasses such as SVG have @data.setter methods | |
682 | # that transform self.data into ... well svg. |
|
682 | # that transform self.data into ... well svg. | |
683 | if encoding: |
|
683 | if encoding: | |
684 | self.data = data.decode(encoding, 'replace') |
|
684 | self.data = data.decode(encoding, 'replace') | |
685 | else: |
|
685 | else: | |
686 | self.data = data |
|
686 | self.data = data | |
687 |
|
687 | |||
688 |
|
688 | |||
689 | class TextDisplayObject(DisplayObject): |
|
689 | class TextDisplayObject(DisplayObject): | |
690 | """Validate that display data is text""" |
|
690 | """Validate that display data is text""" | |
691 | def _check_data(self): |
|
691 | def _check_data(self): | |
692 | if self.data is not None and not isinstance(self.data, str): |
|
692 | if self.data is not None and not isinstance(self.data, str): | |
693 | raise TypeError("%s expects text, not %r" % (self.__class__.__name__, self.data)) |
|
693 | raise TypeError("%s expects text, not %r" % (self.__class__.__name__, self.data)) | |
694 |
|
694 | |||
695 | class Pretty(TextDisplayObject): |
|
695 | class Pretty(TextDisplayObject): | |
696 |
|
696 | |||
697 | def _repr_pretty_(self, pp, cycle): |
|
697 | def _repr_pretty_(self, pp, cycle): | |
698 | return pp.text(self.data) |
|
698 | return pp.text(self.data) | |
699 |
|
699 | |||
700 |
|
700 | |||
701 | class HTML(TextDisplayObject): |
|
701 | class HTML(TextDisplayObject): | |
702 |
|
702 | |||
703 | def __init__(self, data=None, url=None, filename=None, metadata=None): |
|
703 | def __init__(self, data=None, url=None, filename=None, metadata=None): | |
704 | def warn(): |
|
704 | def warn(): | |
705 | if not data: |
|
705 | if not data: | |
706 | return False |
|
706 | return False | |
707 |
|
707 | |||
708 | # |
|
708 | # | |
709 | # Avoid calling lower() on the entire data, because it could be a |
|
709 | # Avoid calling lower() on the entire data, because it could be a | |
710 | # long string and we're only interested in its beginning and end. |
|
710 | # long string and we're only interested in its beginning and end. | |
711 | # |
|
711 | # | |
712 | prefix = data[:10].lower() |
|
712 | prefix = data[:10].lower() | |
713 | suffix = data[-10:].lower() |
|
713 | suffix = data[-10:].lower() | |
714 | return prefix.startswith("<iframe ") and suffix.endswith("</iframe>") |
|
714 | return prefix.startswith("<iframe ") and suffix.endswith("</iframe>") | |
715 |
|
715 | |||
716 | if warn(): |
|
716 | if warn(): | |
717 | warnings.warn("Consider using IPython.display.IFrame instead") |
|
717 | warnings.warn("Consider using IPython.display.IFrame instead") | |
718 | super(HTML, self).__init__(data=data, url=url, filename=filename, metadata=metadata) |
|
718 | super(HTML, self).__init__(data=data, url=url, filename=filename, metadata=metadata) | |
719 |
|
719 | |||
720 | def _repr_html_(self): |
|
720 | def _repr_html_(self): | |
721 | return self._data_and_metadata() |
|
721 | return self._data_and_metadata() | |
722 |
|
722 | |||
723 | def __html__(self): |
|
723 | def __html__(self): | |
724 | """ |
|
724 | """ | |
725 | This method exists to inform other HTML-using modules (e.g. Markupsafe, |
|
725 | This method exists to inform other HTML-using modules (e.g. Markupsafe, | |
726 | htmltag, etc) that this object is HTML and does not need things like |
|
726 | htmltag, etc) that this object is HTML and does not need things like | |
727 | special characters (<>&) escaped. |
|
727 | special characters (<>&) escaped. | |
728 | """ |
|
728 | """ | |
729 | return self._repr_html_() |
|
729 | return self._repr_html_() | |
730 |
|
730 | |||
731 |
|
731 | |||
732 | class Markdown(TextDisplayObject): |
|
732 | class Markdown(TextDisplayObject): | |
733 |
|
733 | |||
734 | def _repr_markdown_(self): |
|
734 | def _repr_markdown_(self): | |
735 | return self._data_and_metadata() |
|
735 | return self._data_and_metadata() | |
736 |
|
736 | |||
737 |
|
737 | |||
738 | class Math(TextDisplayObject): |
|
738 | class Math(TextDisplayObject): | |
739 |
|
739 | |||
740 | def _repr_latex_(self): |
|
740 | def _repr_latex_(self): | |
741 | s = r"$\displaystyle %s$" % self.data.strip('$') |
|
741 | s = r"$\displaystyle %s$" % self.data.strip('$') | |
742 | if self.metadata: |
|
742 | if self.metadata: | |
743 | return s, deepcopy(self.metadata) |
|
743 | return s, deepcopy(self.metadata) | |
744 | else: |
|
744 | else: | |
745 | return s |
|
745 | return s | |
746 |
|
746 | |||
747 |
|
747 | |||
748 | class Latex(TextDisplayObject): |
|
748 | class Latex(TextDisplayObject): | |
749 |
|
749 | |||
750 | def _repr_latex_(self): |
|
750 | def _repr_latex_(self): | |
751 | return self._data_and_metadata() |
|
751 | return self._data_and_metadata() | |
752 |
|
752 | |||
753 |
|
753 | |||
754 | class SVG(DisplayObject): |
|
754 | class SVG(DisplayObject): | |
755 | """Embed an SVG into the display. |
|
755 | """Embed an SVG into the display. | |
756 |
|
756 | |||
757 | Note if you just want to view a svg image via a URL use `:class:Image` with |
|
757 | Note if you just want to view a svg image via a URL use `:class:Image` with | |
758 | a url=URL keyword argument. |
|
758 | a url=URL keyword argument. | |
759 | """ |
|
759 | """ | |
760 |
|
760 | |||
761 | _read_flags = 'rb' |
|
761 | _read_flags = 'rb' | |
762 | # wrap data in a property, which extracts the <svg> tag, discarding |
|
762 | # wrap data in a property, which extracts the <svg> tag, discarding | |
763 | # document headers |
|
763 | # document headers | |
764 | _data = None |
|
764 | _data = None | |
765 |
|
765 | |||
766 | @property |
|
766 | @property | |
767 | def data(self): |
|
767 | def data(self): | |
768 | return self._data |
|
768 | return self._data | |
769 |
|
769 | |||
770 | @data.setter |
|
770 | @data.setter | |
771 | def data(self, svg): |
|
771 | def data(self, svg): | |
772 | if svg is None: |
|
772 | if svg is None: | |
773 | self._data = None |
|
773 | self._data = None | |
774 | return |
|
774 | return | |
775 | # parse into dom object |
|
775 | # parse into dom object | |
776 | from xml.dom import minidom |
|
776 | from xml.dom import minidom | |
777 | x = minidom.parseString(svg) |
|
777 | x = minidom.parseString(svg) | |
778 | # get svg tag (should be 1) |
|
778 | # get svg tag (should be 1) | |
779 | found_svg = x.getElementsByTagName('svg') |
|
779 | found_svg = x.getElementsByTagName('svg') | |
780 | if found_svg: |
|
780 | if found_svg: | |
781 | svg = found_svg[0].toxml() |
|
781 | svg = found_svg[0].toxml() | |
782 | else: |
|
782 | else: | |
783 | # fallback on the input, trust the user |
|
783 | # fallback on the input, trust the user | |
784 | # but this is probably an error. |
|
784 | # but this is probably an error. | |
785 | pass |
|
785 | pass | |
786 | svg = cast_unicode(svg) |
|
786 | svg = cast_unicode(svg) | |
787 | self._data = svg |
|
787 | self._data = svg | |
788 |
|
788 | |||
789 | def _repr_svg_(self): |
|
789 | def _repr_svg_(self): | |
790 | return self._data_and_metadata() |
|
790 | return self._data_and_metadata() | |
791 |
|
791 | |||
792 | class ProgressBar(DisplayObject): |
|
792 | class ProgressBar(DisplayObject): | |
793 | """Progressbar supports displaying a progressbar like element |
|
793 | """Progressbar supports displaying a progressbar like element | |
794 | """ |
|
794 | """ | |
795 | def __init__(self, total): |
|
795 | def __init__(self, total): | |
796 | """Creates a new progressbar |
|
796 | """Creates a new progressbar | |
797 |
|
797 | |||
798 | Parameters |
|
798 | Parameters | |
799 | ---------- |
|
799 | ---------- | |
800 | total : int |
|
800 | total : int | |
801 | maximum size of the progressbar |
|
801 | maximum size of the progressbar | |
802 | """ |
|
802 | """ | |
803 | self.total = total |
|
803 | self.total = total | |
804 | self._progress = 0 |
|
804 | self._progress = 0 | |
805 | self.html_width = '60ex' |
|
805 | self.html_width = '60ex' | |
806 | self.text_width = 60 |
|
806 | self.text_width = 60 | |
807 | self._display_id = hexlify(os.urandom(8)).decode('ascii') |
|
807 | self._display_id = hexlify(os.urandom(8)).decode('ascii') | |
808 |
|
808 | |||
809 | def __repr__(self): |
|
809 | def __repr__(self): | |
810 | fraction = self.progress / self.total |
|
810 | fraction = self.progress / self.total | |
811 | filled = '=' * int(fraction * self.text_width) |
|
811 | filled = '=' * int(fraction * self.text_width) | |
812 | rest = ' ' * (self.text_width - len(filled)) |
|
812 | rest = ' ' * (self.text_width - len(filled)) | |
813 | return '[{}{}] {}/{}'.format( |
|
813 | return '[{}{}] {}/{}'.format( | |
814 | filled, rest, |
|
814 | filled, rest, | |
815 | self.progress, self.total, |
|
815 | self.progress, self.total, | |
816 | ) |
|
816 | ) | |
817 |
|
817 | |||
818 | def _repr_html_(self): |
|
818 | def _repr_html_(self): | |
819 | return "<progress style='width:{}' max='{}' value='{}'></progress>".format( |
|
819 | return "<progress style='width:{}' max='{}' value='{}'></progress>".format( | |
820 | self.html_width, self.total, self.progress) |
|
820 | self.html_width, self.total, self.progress) | |
821 |
|
821 | |||
822 | def display(self): |
|
822 | def display(self): | |
823 | display(self, display_id=self._display_id) |
|
823 | display(self, display_id=self._display_id) | |
824 |
|
824 | |||
825 | def update(self): |
|
825 | def update(self): | |
826 | display(self, display_id=self._display_id, update=True) |
|
826 | display(self, display_id=self._display_id, update=True) | |
827 |
|
827 | |||
828 | @property |
|
828 | @property | |
829 | def progress(self): |
|
829 | def progress(self): | |
830 | return self._progress |
|
830 | return self._progress | |
831 |
|
831 | |||
832 | @progress.setter |
|
832 | @progress.setter | |
833 | def progress(self, value): |
|
833 | def progress(self, value): | |
834 | self._progress = value |
|
834 | self._progress = value | |
835 | self.update() |
|
835 | self.update() | |
836 |
|
836 | |||
837 | def __iter__(self): |
|
837 | def __iter__(self): | |
838 | self.display() |
|
838 | self.display() | |
839 | self._progress = -1 # First iteration is 0 |
|
839 | self._progress = -1 # First iteration is 0 | |
840 | return self |
|
840 | return self | |
841 |
|
841 | |||
842 | def __next__(self): |
|
842 | def __next__(self): | |
843 | """Returns current value and increments display by one.""" |
|
843 | """Returns current value and increments display by one.""" | |
844 | self.progress += 1 |
|
844 | self.progress += 1 | |
845 | if self.progress < self.total: |
|
845 | if self.progress < self.total: | |
846 | return self.progress |
|
846 | return self.progress | |
847 | else: |
|
847 | else: | |
848 | raise StopIteration() |
|
848 | raise StopIteration() | |
849 |
|
849 | |||
850 | class JSON(DisplayObject): |
|
850 | class JSON(DisplayObject): | |
851 | """JSON expects a JSON-able dict or list |
|
851 | """JSON expects a JSON-able dict or list | |
852 |
|
852 | |||
853 | not an already-serialized JSON string. |
|
853 | not an already-serialized JSON string. | |
854 |
|
854 | |||
855 | Scalar types (None, number, string) are not allowed, only dict or list containers. |
|
855 | Scalar types (None, number, string) are not allowed, only dict or list containers. | |
856 | """ |
|
856 | """ | |
857 | # wrap data in a property, which warns about passing already-serialized JSON |
|
857 | # wrap data in a property, which warns about passing already-serialized JSON | |
858 | _data = None |
|
858 | _data = None | |
859 | def __init__(self, data=None, url=None, filename=None, expanded=False, metadata=None, root='root', **kwargs): |
|
859 | def __init__(self, data=None, url=None, filename=None, expanded=False, metadata=None, root='root', **kwargs): | |
860 | """Create a JSON display object given raw data. |
|
860 | """Create a JSON display object given raw data. | |
861 |
|
861 | |||
862 | Parameters |
|
862 | Parameters | |
863 | ---------- |
|
863 | ---------- | |
864 | data : dict or list |
|
864 | data : dict or list | |
865 | JSON data to display. Not an already-serialized JSON string. |
|
865 | JSON data to display. Not an already-serialized JSON string. | |
866 | Scalar types (None, number, string) are not allowed, only dict |
|
866 | Scalar types (None, number, string) are not allowed, only dict | |
867 | or list containers. |
|
867 | or list containers. | |
868 | url : unicode |
|
868 | url : unicode | |
869 | A URL to download the data from. |
|
869 | A URL to download the data from. | |
870 | filename : unicode |
|
870 | filename : unicode | |
871 | Path to a local file to load the data from. |
|
871 | Path to a local file to load the data from. | |
872 | expanded : boolean |
|
872 | expanded : boolean | |
873 | Metadata to control whether a JSON display component is expanded. |
|
873 | Metadata to control whether a JSON display component is expanded. | |
874 | metadata: dict |
|
874 | metadata: dict | |
875 | Specify extra metadata to attach to the json display object. |
|
875 | Specify extra metadata to attach to the json display object. | |
876 | root : str |
|
876 | root : str | |
877 | The name of the root element of the JSON tree |
|
877 | The name of the root element of the JSON tree | |
878 | """ |
|
878 | """ | |
879 | self.metadata = { |
|
879 | self.metadata = { | |
880 | 'expanded': expanded, |
|
880 | 'expanded': expanded, | |
881 | 'root': root, |
|
881 | 'root': root, | |
882 | } |
|
882 | } | |
883 | if metadata: |
|
883 | if metadata: | |
884 | self.metadata.update(metadata) |
|
884 | self.metadata.update(metadata) | |
885 | if kwargs: |
|
885 | if kwargs: | |
886 | self.metadata.update(kwargs) |
|
886 | self.metadata.update(kwargs) | |
887 | super(JSON, self).__init__(data=data, url=url, filename=filename) |
|
887 | super(JSON, self).__init__(data=data, url=url, filename=filename) | |
888 |
|
888 | |||
889 | def _check_data(self): |
|
889 | def _check_data(self): | |
890 | if self.data is not None and not isinstance(self.data, (dict, list)): |
|
890 | if self.data is not None and not isinstance(self.data, (dict, list)): | |
891 | raise TypeError("%s expects JSONable dict or list, not %r" % (self.__class__.__name__, self.data)) |
|
891 | raise TypeError("%s expects JSONable dict or list, not %r" % (self.__class__.__name__, self.data)) | |
892 |
|
892 | |||
893 | @property |
|
893 | @property | |
894 | def data(self): |
|
894 | def data(self): | |
895 | return self._data |
|
895 | return self._data | |
896 |
|
896 | |||
897 | @data.setter |
|
897 | @data.setter | |
898 | def data(self, data): |
|
898 | def data(self, data): | |
899 | if isinstance(data, (Path, PurePath)): |
|
899 | if isinstance(data, (Path, PurePath)): | |
900 | data = str(data) |
|
900 | data = str(data) | |
901 |
|
901 | |||
902 | if isinstance(data, str): |
|
902 | if isinstance(data, str): | |
903 | if self.filename is None and self.url is None: |
|
903 | if self.filename is None and self.url is None: | |
904 | warnings.warn("JSON expects JSONable dict or list, not JSON strings") |
|
904 | warnings.warn("JSON expects JSONable dict or list, not JSON strings") | |
905 | data = json.loads(data) |
|
905 | data = json.loads(data) | |
906 | self._data = data |
|
906 | self._data = data | |
907 |
|
907 | |||
908 | def _data_and_metadata(self): |
|
908 | def _data_and_metadata(self): | |
909 | return self.data, self.metadata |
|
909 | return self.data, self.metadata | |
910 |
|
910 | |||
911 | def _repr_json_(self): |
|
911 | def _repr_json_(self): | |
912 | return self._data_and_metadata() |
|
912 | return self._data_and_metadata() | |
913 |
|
913 | |||
914 | _css_t = """var link = document.createElement("link"); |
|
914 | _css_t = """var link = document.createElement("link"); | |
915 | link.ref = "stylesheet"; |
|
915 | link.ref = "stylesheet"; | |
916 | link.type = "text/css"; |
|
916 | link.type = "text/css"; | |
917 | link.href = "%s"; |
|
917 | link.href = "%s"; | |
918 | document.head.appendChild(link); |
|
918 | document.head.appendChild(link); | |
919 | """ |
|
919 | """ | |
920 |
|
920 | |||
921 | _lib_t1 = """new Promise(function(resolve, reject) { |
|
921 | _lib_t1 = """new Promise(function(resolve, reject) { | |
922 | var script = document.createElement("script"); |
|
922 | var script = document.createElement("script"); | |
923 | script.onload = resolve; |
|
923 | script.onload = resolve; | |
924 | script.onerror = reject; |
|
924 | script.onerror = reject; | |
925 | script.src = "%s"; |
|
925 | script.src = "%s"; | |
926 | document.head.appendChild(script); |
|
926 | document.head.appendChild(script); | |
927 | }).then(() => { |
|
927 | }).then(() => { | |
928 | """ |
|
928 | """ | |
929 |
|
929 | |||
930 | _lib_t2 = """ |
|
930 | _lib_t2 = """ | |
931 | });""" |
|
931 | });""" | |
932 |
|
932 | |||
933 | class GeoJSON(JSON): |
|
933 | class GeoJSON(JSON): | |
934 | """GeoJSON expects JSON-able dict |
|
934 | """GeoJSON expects JSON-able dict | |
935 |
|
935 | |||
936 | not an already-serialized JSON string. |
|
936 | not an already-serialized JSON string. | |
937 |
|
937 | |||
938 | Scalar types (None, number, string) are not allowed, only dict containers. |
|
938 | Scalar types (None, number, string) are not allowed, only dict containers. | |
939 | """ |
|
939 | """ | |
940 |
|
940 | |||
941 | def __init__(self, *args, **kwargs): |
|
941 | def __init__(self, *args, **kwargs): | |
942 | """Create a GeoJSON display object given raw data. |
|
942 | """Create a GeoJSON display object given raw data. | |
943 |
|
943 | |||
944 | Parameters |
|
944 | Parameters | |
945 | ---------- |
|
945 | ---------- | |
946 | data : dict or list |
|
946 | data : dict or list | |
947 | VegaLite data. Not an already-serialized JSON string. |
|
947 | VegaLite data. Not an already-serialized JSON string. | |
948 | Scalar types (None, number, string) are not allowed, only dict |
|
948 | Scalar types (None, number, string) are not allowed, only dict | |
949 | or list containers. |
|
949 | or list containers. | |
950 | url_template : string |
|
950 | url_template : string | |
951 | Leaflet TileLayer URL template: http://leafletjs.com/reference.html#url-template |
|
951 | Leaflet TileLayer URL template: http://leafletjs.com/reference.html#url-template | |
952 | layer_options : dict |
|
952 | layer_options : dict | |
953 | Leaflet TileLayer options: http://leafletjs.com/reference.html#tilelayer-options |
|
953 | Leaflet TileLayer options: http://leafletjs.com/reference.html#tilelayer-options | |
954 | url : unicode |
|
954 | url : unicode | |
955 | A URL to download the data from. |
|
955 | A URL to download the data from. | |
956 | filename : unicode |
|
956 | filename : unicode | |
957 | Path to a local file to load the data from. |
|
957 | Path to a local file to load the data from. | |
958 | metadata: dict |
|
958 | metadata: dict | |
959 | Specify extra metadata to attach to the json display object. |
|
959 | Specify extra metadata to attach to the json display object. | |
960 |
|
960 | |||
961 | Examples |
|
961 | Examples | |
962 | -------- |
|
962 | -------- | |
963 |
|
963 | |||
964 | The following will display an interactive map of Mars with a point of |
|
964 | The following will display an interactive map of Mars with a point of | |
965 | interest on frontend that do support GeoJSON display. |
|
965 | interest on frontend that do support GeoJSON display. | |
966 |
|
966 | |||
967 | >>> from IPython.display import GeoJSON |
|
967 | >>> from IPython.display import GeoJSON | |
968 |
|
968 | |||
969 | >>> GeoJSON(data={ |
|
969 | >>> GeoJSON(data={ | |
970 | ... "type": "Feature", |
|
970 | ... "type": "Feature", | |
971 | ... "geometry": { |
|
971 | ... "geometry": { | |
972 | ... "type": "Point", |
|
972 | ... "type": "Point", | |
973 | ... "coordinates": [-81.327, 296.038] |
|
973 | ... "coordinates": [-81.327, 296.038] | |
974 | ... } |
|
974 | ... } | |
975 | ... }, |
|
975 | ... }, | |
976 | ... url_template="http://s3-eu-west-1.amazonaws.com/whereonmars.cartodb.net/{basemap_id}/{z}/{x}/{y}.png", |
|
976 | ... url_template="http://s3-eu-west-1.amazonaws.com/whereonmars.cartodb.net/{basemap_id}/{z}/{x}/{y}.png", | |
977 | ... layer_options={ |
|
977 | ... layer_options={ | |
978 | ... "basemap_id": "celestia_mars-shaded-16k_global", |
|
978 | ... "basemap_id": "celestia_mars-shaded-16k_global", | |
979 | ... "attribution" : "Celestia/praesepe", |
|
979 | ... "attribution" : "Celestia/praesepe", | |
980 | ... "minZoom" : 0, |
|
980 | ... "minZoom" : 0, | |
981 | ... "maxZoom" : 18, |
|
981 | ... "maxZoom" : 18, | |
982 | ... }) |
|
982 | ... }) | |
983 | <IPython.core.display.GeoJSON object> |
|
983 | <IPython.core.display.GeoJSON object> | |
984 |
|
984 | |||
985 | In the terminal IPython, you will only see the text representation of |
|
985 | In the terminal IPython, you will only see the text representation of | |
986 | the GeoJSON object. |
|
986 | the GeoJSON object. | |
987 |
|
987 | |||
988 | """ |
|
988 | """ | |
989 |
|
989 | |||
990 | super(GeoJSON, self).__init__(*args, **kwargs) |
|
990 | super(GeoJSON, self).__init__(*args, **kwargs) | |
991 |
|
991 | |||
992 |
|
992 | |||
993 | def _ipython_display_(self): |
|
993 | def _ipython_display_(self): | |
994 | bundle = { |
|
994 | bundle = { | |
995 | 'application/geo+json': self.data, |
|
995 | 'application/geo+json': self.data, | |
996 | 'text/plain': '<IPython.display.GeoJSON object>' |
|
996 | 'text/plain': '<IPython.display.GeoJSON object>' | |
997 | } |
|
997 | } | |
998 | metadata = { |
|
998 | metadata = { | |
999 | 'application/geo+json': self.metadata |
|
999 | 'application/geo+json': self.metadata | |
1000 | } |
|
1000 | } | |
1001 | display(bundle, metadata=metadata, raw=True) |
|
1001 | display(bundle, metadata=metadata, raw=True) | |
1002 |
|
1002 | |||
1003 | class Javascript(TextDisplayObject): |
|
1003 | class Javascript(TextDisplayObject): | |
1004 |
|
1004 | |||
1005 | def __init__(self, data=None, url=None, filename=None, lib=None, css=None): |
|
1005 | def __init__(self, data=None, url=None, filename=None, lib=None, css=None): | |
1006 | """Create a Javascript display object given raw data. |
|
1006 | """Create a Javascript display object given raw data. | |
1007 |
|
1007 | |||
1008 | When this object is returned by an expression or passed to the |
|
1008 | When this object is returned by an expression or passed to the | |
1009 | display function, it will result in the data being displayed |
|
1009 | display function, it will result in the data being displayed | |
1010 | in the frontend. If the data is a URL, the data will first be |
|
1010 | in the frontend. If the data is a URL, the data will first be | |
1011 | downloaded and then displayed. |
|
1011 | downloaded and then displayed. | |
1012 |
|
1012 | |||
1013 | In the Notebook, the containing element will be available as `element`, |
|
1013 | In the Notebook, the containing element will be available as `element`, | |
1014 | and jQuery will be available. Content appended to `element` will be |
|
1014 | and jQuery will be available. Content appended to `element` will be | |
1015 | visible in the output area. |
|
1015 | visible in the output area. | |
1016 |
|
1016 | |||
1017 | Parameters |
|
1017 | Parameters | |
1018 | ---------- |
|
1018 | ---------- | |
1019 | data : unicode, str or bytes |
|
1019 | data : unicode, str or bytes | |
1020 | The Javascript source code or a URL to download it from. |
|
1020 | The Javascript source code or a URL to download it from. | |
1021 | url : unicode |
|
1021 | url : unicode | |
1022 | A URL to download the data from. |
|
1022 | A URL to download the data from. | |
1023 | filename : unicode |
|
1023 | filename : unicode | |
1024 | Path to a local file to load the data from. |
|
1024 | Path to a local file to load the data from. | |
1025 | lib : list or str |
|
1025 | lib : list or str | |
1026 | A sequence of Javascript library URLs to load asynchronously before |
|
1026 | A sequence of Javascript library URLs to load asynchronously before | |
1027 | running the source code. The full URLs of the libraries should |
|
1027 | running the source code. The full URLs of the libraries should | |
1028 | be given. A single Javascript library URL can also be given as a |
|
1028 | be given. A single Javascript library URL can also be given as a | |
1029 | string. |
|
1029 | string. | |
1030 | css: : list or str |
|
1030 | css: : list or str | |
1031 | A sequence of css files to load before running the source code. |
|
1031 | A sequence of css files to load before running the source code. | |
1032 | The full URLs of the css files should be given. A single css URL |
|
1032 | The full URLs of the css files should be given. A single css URL | |
1033 | can also be given as a string. |
|
1033 | can also be given as a string. | |
1034 | """ |
|
1034 | """ | |
1035 | if isinstance(lib, str): |
|
1035 | if isinstance(lib, str): | |
1036 | lib = [lib] |
|
1036 | lib = [lib] | |
1037 | elif lib is None: |
|
1037 | elif lib is None: | |
1038 | lib = [] |
|
1038 | lib = [] | |
1039 | if isinstance(css, str): |
|
1039 | if isinstance(css, str): | |
1040 | css = [css] |
|
1040 | css = [css] | |
1041 | elif css is None: |
|
1041 | elif css is None: | |
1042 | css = [] |
|
1042 | css = [] | |
1043 | if not isinstance(lib, (list,tuple)): |
|
1043 | if not isinstance(lib, (list,tuple)): | |
1044 | raise TypeError('expected sequence, got: %r' % lib) |
|
1044 | raise TypeError('expected sequence, got: %r' % lib) | |
1045 | if not isinstance(css, (list,tuple)): |
|
1045 | if not isinstance(css, (list,tuple)): | |
1046 | raise TypeError('expected sequence, got: %r' % css) |
|
1046 | raise TypeError('expected sequence, got: %r' % css) | |
1047 | self.lib = lib |
|
1047 | self.lib = lib | |
1048 | self.css = css |
|
1048 | self.css = css | |
1049 | super(Javascript, self).__init__(data=data, url=url, filename=filename) |
|
1049 | super(Javascript, self).__init__(data=data, url=url, filename=filename) | |
1050 |
|
1050 | |||
1051 | def _repr_javascript_(self): |
|
1051 | def _repr_javascript_(self): | |
1052 | r = '' |
|
1052 | r = '' | |
1053 | for c in self.css: |
|
1053 | for c in self.css: | |
1054 | r += _css_t % c |
|
1054 | r += _css_t % c | |
1055 | for l in self.lib: |
|
1055 | for l in self.lib: | |
1056 | r += _lib_t1 % l |
|
1056 | r += _lib_t1 % l | |
1057 | r += self.data |
|
1057 | r += self.data | |
1058 | r += _lib_t2*len(self.lib) |
|
1058 | r += _lib_t2*len(self.lib) | |
1059 | return r |
|
1059 | return r | |
1060 |
|
1060 | |||
1061 | # constants for identifying png/jpeg data |
|
1061 | # constants for identifying png/jpeg data | |
1062 | _PNG = b'\x89PNG\r\n\x1a\n' |
|
1062 | _PNG = b'\x89PNG\r\n\x1a\n' | |
1063 | _JPEG = b'\xff\xd8' |
|
1063 | _JPEG = b'\xff\xd8' | |
1064 |
|
1064 | |||
1065 | def _pngxy(data): |
|
1065 | def _pngxy(data): | |
1066 | """read the (width, height) from a PNG header""" |
|
1066 | """read the (width, height) from a PNG header""" | |
1067 | ihdr = data.index(b'IHDR') |
|
1067 | ihdr = data.index(b'IHDR') | |
1068 | # next 8 bytes are width/height |
|
1068 | # next 8 bytes are width/height | |
1069 | return struct.unpack('>ii', data[ihdr+4:ihdr+12]) |
|
1069 | return struct.unpack('>ii', data[ihdr+4:ihdr+12]) | |
1070 |
|
1070 | |||
1071 | def _jpegxy(data): |
|
1071 | def _jpegxy(data): | |
1072 | """read the (width, height) from a JPEG header""" |
|
1072 | """read the (width, height) from a JPEG header""" | |
1073 | # adapted from http://www.64lines.com/jpeg-width-height |
|
1073 | # adapted from http://www.64lines.com/jpeg-width-height | |
1074 |
|
1074 | |||
1075 | idx = 4 |
|
1075 | idx = 4 | |
1076 | while True: |
|
1076 | while True: | |
1077 | block_size = struct.unpack('>H', data[idx:idx+2])[0] |
|
1077 | block_size = struct.unpack('>H', data[idx:idx+2])[0] | |
1078 | idx = idx + block_size |
|
1078 | idx = idx + block_size | |
1079 | if data[idx:idx+2] == b'\xFF\xC0': |
|
1079 | if data[idx:idx+2] == b'\xFF\xC0': | |
1080 | # found Start of Frame |
|
1080 | # found Start of Frame | |
1081 | iSOF = idx |
|
1081 | iSOF = idx | |
1082 | break |
|
1082 | break | |
1083 | else: |
|
1083 | else: | |
1084 | # read another block |
|
1084 | # read another block | |
1085 | idx += 2 |
|
1085 | idx += 2 | |
1086 |
|
1086 | |||
1087 | h, w = struct.unpack('>HH', data[iSOF+5:iSOF+9]) |
|
1087 | h, w = struct.unpack('>HH', data[iSOF+5:iSOF+9]) | |
1088 | return w, h |
|
1088 | return w, h | |
1089 |
|
1089 | |||
1090 | def _gifxy(data): |
|
1090 | def _gifxy(data): | |
1091 | """read the (width, height) from a GIF header""" |
|
1091 | """read the (width, height) from a GIF header""" | |
1092 | return struct.unpack('<HH', data[6:10]) |
|
1092 | return struct.unpack('<HH', data[6:10]) | |
1093 |
|
1093 | |||
1094 |
|
1094 | |||
1095 | class Image(DisplayObject): |
|
1095 | class Image(DisplayObject): | |
1096 |
|
1096 | |||
1097 | _read_flags = 'rb' |
|
1097 | _read_flags = 'rb' | |
1098 | _FMT_JPEG = u'jpeg' |
|
1098 | _FMT_JPEG = u'jpeg' | |
1099 | _FMT_PNG = u'png' |
|
1099 | _FMT_PNG = u'png' | |
1100 | _FMT_GIF = u'gif' |
|
1100 | _FMT_GIF = u'gif' | |
1101 | _ACCEPTABLE_EMBEDDINGS = [_FMT_JPEG, _FMT_PNG, _FMT_GIF] |
|
1101 | _ACCEPTABLE_EMBEDDINGS = [_FMT_JPEG, _FMT_PNG, _FMT_GIF] | |
1102 | _MIMETYPES = { |
|
1102 | _MIMETYPES = { | |
1103 | _FMT_PNG: 'image/png', |
|
1103 | _FMT_PNG: 'image/png', | |
1104 | _FMT_JPEG: 'image/jpeg', |
|
1104 | _FMT_JPEG: 'image/jpeg', | |
1105 | _FMT_GIF: 'image/gif', |
|
1105 | _FMT_GIF: 'image/gif', | |
1106 | } |
|
1106 | } | |
1107 |
|
1107 | |||
1108 | def __init__(self, data=None, url=None, filename=None, format=None, |
|
1108 | def __init__(self, data=None, url=None, filename=None, format=None, | |
1109 | embed=None, width=None, height=None, retina=False, |
|
1109 | embed=None, width=None, height=None, retina=False, | |
1110 | unconfined=False, metadata=None): |
|
1110 | unconfined=False, metadata=None): | |
1111 | """Create a PNG/JPEG/GIF image object given raw data. |
|
1111 | """Create a PNG/JPEG/GIF image object given raw data. | |
1112 |
|
1112 | |||
1113 | When this object is returned by an input cell or passed to the |
|
1113 | When this object is returned by an input cell or passed to the | |
1114 | display function, it will result in the image being displayed |
|
1114 | display function, it will result in the image being displayed | |
1115 | in the frontend. |
|
1115 | in the frontend. | |
1116 |
|
1116 | |||
1117 | Parameters |
|
1117 | Parameters | |
1118 | ---------- |
|
1118 | ---------- | |
1119 | data : unicode, str or bytes |
|
1119 | data : unicode, str or bytes | |
1120 | The raw image data or a URL or filename to load the data from. |
|
1120 | The raw image data or a URL or filename to load the data from. | |
1121 | This always results in embedded image data. |
|
1121 | This always results in embedded image data. | |
1122 | url : unicode |
|
1122 | url : unicode | |
1123 | A URL to download the data from. If you specify `url=`, |
|
1123 | A URL to download the data from. If you specify `url=`, | |
1124 | the image data will not be embedded unless you also specify `embed=True`. |
|
1124 | the image data will not be embedded unless you also specify `embed=True`. | |
1125 | filename : unicode |
|
1125 | filename : unicode | |
1126 | Path to a local file to load the data from. |
|
1126 | Path to a local file to load the data from. | |
1127 | Images from a file are always embedded. |
|
1127 | Images from a file are always embedded. | |
1128 | format : unicode |
|
1128 | format : unicode | |
1129 | The format of the image data (png/jpeg/jpg/gif). If a filename or URL is given |
|
1129 | The format of the image data (png/jpeg/jpg/gif). If a filename or URL is given | |
1130 | for format will be inferred from the filename extension. |
|
1130 | for format will be inferred from the filename extension. | |
1131 | embed : bool |
|
1131 | embed : bool | |
1132 | Should the image data be embedded using a data URI (True) or be |
|
1132 | Should the image data be embedded using a data URI (True) or be | |
1133 | loaded using an <img> tag. Set this to True if you want the image |
|
1133 | loaded using an <img> tag. Set this to True if you want the image | |
1134 | to be viewable later with no internet connection in the notebook. |
|
1134 | to be viewable later with no internet connection in the notebook. | |
1135 |
|
1135 | |||
1136 | Default is `True`, unless the keyword argument `url` is set, then |
|
1136 | Default is `True`, unless the keyword argument `url` is set, then | |
1137 | default value is `False`. |
|
1137 | default value is `False`. | |
1138 |
|
1138 | |||
1139 | Note that QtConsole is not able to display images if `embed` is set to `False` |
|
1139 | Note that QtConsole is not able to display images if `embed` is set to `False` | |
1140 | width : int |
|
1140 | width : int | |
1141 | Width in pixels to which to constrain the image in html |
|
1141 | Width in pixels to which to constrain the image in html | |
1142 | height : int |
|
1142 | height : int | |
1143 | Height in pixels to which to constrain the image in html |
|
1143 | Height in pixels to which to constrain the image in html | |
1144 | retina : bool |
|
1144 | retina : bool | |
1145 | Automatically set the width and height to half of the measured |
|
1145 | Automatically set the width and height to half of the measured | |
1146 | width and height. |
|
1146 | width and height. | |
1147 | This only works for embedded images because it reads the width/height |
|
1147 | This only works for embedded images because it reads the width/height | |
1148 | from image data. |
|
1148 | from image data. | |
1149 | For non-embedded images, you can just set the desired display width |
|
1149 | For non-embedded images, you can just set the desired display width | |
1150 | and height directly. |
|
1150 | and height directly. | |
1151 | unconfined: bool |
|
1151 | unconfined: bool | |
1152 | Set unconfined=True to disable max-width confinement of the image. |
|
1152 | Set unconfined=True to disable max-width confinement of the image. | |
1153 | metadata: dict |
|
1153 | metadata: dict | |
1154 | Specify extra metadata to attach to the image. |
|
1154 | Specify extra metadata to attach to the image. | |
1155 |
|
1155 | |||
1156 | Examples |
|
1156 | Examples | |
1157 | -------- |
|
1157 | -------- | |
1158 | # embedded image data, works in qtconsole and notebook |
|
1158 | # embedded image data, works in qtconsole and notebook | |
1159 | # when passed positionally, the first arg can be any of raw image data, |
|
1159 | # when passed positionally, the first arg can be any of raw image data, | |
1160 | # a URL, or a filename from which to load image data. |
|
1160 | # a URL, or a filename from which to load image data. | |
1161 | # The result is always embedding image data for inline images. |
|
1161 | # The result is always embedding image data for inline images. | |
1162 | Image('http://www.google.fr/images/srpr/logo3w.png') |
|
1162 | Image('http://www.google.fr/images/srpr/logo3w.png') | |
1163 | Image('/path/to/image.jpg') |
|
1163 | Image('/path/to/image.jpg') | |
1164 | Image(b'RAW_PNG_DATA...') |
|
1164 | Image(b'RAW_PNG_DATA...') | |
1165 |
|
1165 | |||
1166 | # Specifying Image(url=...) does not embed the image data, |
|
1166 | # Specifying Image(url=...) does not embed the image data, | |
1167 | # it only generates `<img>` tag with a link to the source. |
|
1167 | # it only generates `<img>` tag with a link to the source. | |
1168 | # This will not work in the qtconsole or offline. |
|
1168 | # This will not work in the qtconsole or offline. | |
1169 | Image(url='http://www.google.fr/images/srpr/logo3w.png') |
|
1169 | Image(url='http://www.google.fr/images/srpr/logo3w.png') | |
1170 |
|
1170 | |||
1171 | """ |
|
1171 | """ | |
1172 | if isinstance(data, (Path, PurePath)): |
|
1172 | if isinstance(data, (Path, PurePath)): | |
1173 | data = str(data) |
|
1173 | data = str(data) | |
1174 |
|
1174 | |||
1175 | if filename is not None: |
|
1175 | if filename is not None: | |
1176 | ext = self._find_ext(filename) |
|
1176 | ext = self._find_ext(filename) | |
1177 | elif url is not None: |
|
1177 | elif url is not None: | |
1178 | ext = self._find_ext(url) |
|
1178 | ext = self._find_ext(url) | |
1179 | elif data is None: |
|
1179 | elif data is None: | |
1180 | raise ValueError("No image data found. Expecting filename, url, or data.") |
|
1180 | raise ValueError("No image data found. Expecting filename, url, or data.") | |
1181 | elif isinstance(data, str) and ( |
|
1181 | elif isinstance(data, str) and ( | |
1182 | data.startswith('http') or _safe_exists(data) |
|
1182 | data.startswith('http') or _safe_exists(data) | |
1183 | ): |
|
1183 | ): | |
1184 | ext = self._find_ext(data) |
|
1184 | ext = self._find_ext(data) | |
1185 | else: |
|
1185 | else: | |
1186 | ext = None |
|
1186 | ext = None | |
1187 |
|
1187 | |||
1188 | if format is None: |
|
1188 | if format is None: | |
1189 | if ext is not None: |
|
1189 | if ext is not None: | |
1190 | if ext == u'jpg' or ext == u'jpeg': |
|
1190 | if ext == u'jpg' or ext == u'jpeg': | |
1191 | format = self._FMT_JPEG |
|
1191 | format = self._FMT_JPEG | |
1192 | elif ext == u'png': |
|
1192 | elif ext == u'png': | |
1193 | format = self._FMT_PNG |
|
1193 | format = self._FMT_PNG | |
1194 | elif ext == u'gif': |
|
1194 | elif ext == u'gif': | |
1195 | format = self._FMT_GIF |
|
1195 | format = self._FMT_GIF | |
1196 | else: |
|
1196 | else: | |
1197 | format = ext.lower() |
|
1197 | format = ext.lower() | |
1198 | elif isinstance(data, bytes): |
|
1198 | elif isinstance(data, bytes): | |
1199 | # infer image type from image data header, |
|
1199 | # infer image type from image data header, | |
1200 | # only if format has not been specified. |
|
1200 | # only if format has not been specified. | |
1201 | if data[:2] == _JPEG: |
|
1201 | if data[:2] == _JPEG: | |
1202 | format = self._FMT_JPEG |
|
1202 | format = self._FMT_JPEG | |
1203 |
|
1203 | |||
1204 | # failed to detect format, default png |
|
1204 | # failed to detect format, default png | |
1205 | if format is None: |
|
1205 | if format is None: | |
1206 | format = self._FMT_PNG |
|
1206 | format = self._FMT_PNG | |
1207 |
|
1207 | |||
1208 | if format.lower() == 'jpg': |
|
1208 | if format.lower() == 'jpg': | |
1209 | # jpg->jpeg |
|
1209 | # jpg->jpeg | |
1210 | format = self._FMT_JPEG |
|
1210 | format = self._FMT_JPEG | |
1211 |
|
1211 | |||
1212 | self.format = format.lower() |
|
1212 | self.format = format.lower() | |
1213 | self.embed = embed if embed is not None else (url is None) |
|
1213 | self.embed = embed if embed is not None else (url is None) | |
1214 |
|
1214 | |||
1215 | if self.embed and self.format not in self._ACCEPTABLE_EMBEDDINGS: |
|
1215 | if self.embed and self.format not in self._ACCEPTABLE_EMBEDDINGS: | |
1216 | raise ValueError("Cannot embed the '%s' image format" % (self.format)) |
|
1216 | raise ValueError("Cannot embed the '%s' image format" % (self.format)) | |
1217 | if self.embed: |
|
1217 | if self.embed: | |
1218 | self._mimetype = self._MIMETYPES.get(self.format) |
|
1218 | self._mimetype = self._MIMETYPES.get(self.format) | |
1219 |
|
1219 | |||
1220 | self.width = width |
|
1220 | self.width = width | |
1221 | self.height = height |
|
1221 | self.height = height | |
1222 | self.retina = retina |
|
1222 | self.retina = retina | |
1223 | self.unconfined = unconfined |
|
1223 | self.unconfined = unconfined | |
1224 | super(Image, self).__init__(data=data, url=url, filename=filename, |
|
1224 | super(Image, self).__init__(data=data, url=url, filename=filename, | |
1225 | metadata=metadata) |
|
1225 | metadata=metadata) | |
1226 |
|
1226 | |||
1227 | if self.width is None and self.metadata.get('width', {}): |
|
1227 | if self.width is None and self.metadata.get('width', {}): | |
1228 | self.width = metadata['width'] |
|
1228 | self.width = metadata['width'] | |
1229 |
|
1229 | |||
1230 | if self.height is None and self.metadata.get('height', {}): |
|
1230 | if self.height is None and self.metadata.get('height', {}): | |
1231 | self.height = metadata['height'] |
|
1231 | self.height = metadata['height'] | |
1232 |
|
1232 | |||
1233 | if retina: |
|
1233 | if retina: | |
1234 | self._retina_shape() |
|
1234 | self._retina_shape() | |
1235 |
|
1235 | |||
1236 |
|
1236 | |||
1237 | def _retina_shape(self): |
|
1237 | def _retina_shape(self): | |
1238 | """load pixel-doubled width and height from image data""" |
|
1238 | """load pixel-doubled width and height from image data""" | |
1239 | if not self.embed: |
|
1239 | if not self.embed: | |
1240 | return |
|
1240 | return | |
1241 | if self.format == self._FMT_PNG: |
|
1241 | if self.format == self._FMT_PNG: | |
1242 | w, h = _pngxy(self.data) |
|
1242 | w, h = _pngxy(self.data) | |
1243 | elif self.format == self._FMT_JPEG: |
|
1243 | elif self.format == self._FMT_JPEG: | |
1244 | w, h = _jpegxy(self.data) |
|
1244 | w, h = _jpegxy(self.data) | |
1245 | elif self.format == self._FMT_GIF: |
|
1245 | elif self.format == self._FMT_GIF: | |
1246 | w, h = _gifxy(self.data) |
|
1246 | w, h = _gifxy(self.data) | |
1247 | else: |
|
1247 | else: | |
1248 | # retina only supports png |
|
1248 | # retina only supports png | |
1249 | return |
|
1249 | return | |
1250 | self.width = w // 2 |
|
1250 | self.width = w // 2 | |
1251 | self.height = h // 2 |
|
1251 | self.height = h // 2 | |
1252 |
|
1252 | |||
1253 | def reload(self): |
|
1253 | def reload(self): | |
1254 | """Reload the raw data from file or URL.""" |
|
1254 | """Reload the raw data from file or URL.""" | |
1255 | if self.embed: |
|
1255 | if self.embed: | |
1256 | super(Image,self).reload() |
|
1256 | super(Image,self).reload() | |
1257 | if self.retina: |
|
1257 | if self.retina: | |
1258 | self._retina_shape() |
|
1258 | self._retina_shape() | |
1259 |
|
1259 | |||
1260 | def _repr_html_(self): |
|
1260 | def _repr_html_(self): | |
1261 | if not self.embed: |
|
1261 | if not self.embed: | |
1262 | width = height = klass = '' |
|
1262 | width = height = klass = '' | |
1263 | if self.width: |
|
1263 | if self.width: | |
1264 | width = ' width="%d"' % self.width |
|
1264 | width = ' width="%d"' % self.width | |
1265 | if self.height: |
|
1265 | if self.height: | |
1266 | height = ' height="%d"' % self.height |
|
1266 | height = ' height="%d"' % self.height | |
1267 | if self.unconfined: |
|
1267 | if self.unconfined: | |
1268 | klass = ' class="unconfined"' |
|
1268 | klass = ' class="unconfined"' | |
1269 | return u'<img src="{url}"{width}{height}{klass}/>'.format( |
|
1269 | return u'<img src="{url}"{width}{height}{klass}/>'.format( | |
1270 | url=self.url, |
|
1270 | url=self.url, | |
1271 | width=width, |
|
1271 | width=width, | |
1272 | height=height, |
|
1272 | height=height, | |
1273 | klass=klass, |
|
1273 | klass=klass, | |
1274 | ) |
|
1274 | ) | |
1275 |
|
1275 | |||
1276 | def _repr_mimebundle_(self, include=None, exclude=None): |
|
1276 | def _repr_mimebundle_(self, include=None, exclude=None): | |
1277 | """Return the image as a mimebundle |
|
1277 | """Return the image as a mimebundle | |
1278 |
|
1278 | |||
1279 | Any new mimetype support should be implemented here. |
|
1279 | Any new mimetype support should be implemented here. | |
1280 | """ |
|
1280 | """ | |
1281 | if self.embed: |
|
1281 | if self.embed: | |
1282 | mimetype = self._mimetype |
|
1282 | mimetype = self._mimetype | |
1283 | data, metadata = self._data_and_metadata(always_both=True) |
|
1283 | data, metadata = self._data_and_metadata(always_both=True) | |
1284 | if metadata: |
|
1284 | if metadata: | |
1285 | metadata = {mimetype: metadata} |
|
1285 | metadata = {mimetype: metadata} | |
1286 | return {mimetype: data}, metadata |
|
1286 | return {mimetype: data}, metadata | |
1287 | else: |
|
1287 | else: | |
1288 | return {'text/html': self._repr_html_()} |
|
1288 | return {'text/html': self._repr_html_()} | |
1289 |
|
1289 | |||
1290 | def _data_and_metadata(self, always_both=False): |
|
1290 | def _data_and_metadata(self, always_both=False): | |
1291 | """shortcut for returning metadata with shape information, if defined""" |
|
1291 | """shortcut for returning metadata with shape information, if defined""" | |
1292 | try: |
|
1292 | try: | |
1293 | b64_data = b2a_base64(self.data).decode('ascii') |
|
1293 | b64_data = b2a_base64(self.data).decode('ascii') | |
1294 | except TypeError: |
|
1294 | except TypeError: | |
1295 | raise FileNotFoundError( |
|
1295 | raise FileNotFoundError( | |
1296 | "No such file or directory: '%s'" % (self.data)) |
|
1296 | "No such file or directory: '%s'" % (self.data)) | |
1297 | md = {} |
|
1297 | md = {} | |
1298 | if self.metadata: |
|
1298 | if self.metadata: | |
1299 | md.update(self.metadata) |
|
1299 | md.update(self.metadata) | |
1300 | if self.width: |
|
1300 | if self.width: | |
1301 | md['width'] = self.width |
|
1301 | md['width'] = self.width | |
1302 | if self.height: |
|
1302 | if self.height: | |
1303 | md['height'] = self.height |
|
1303 | md['height'] = self.height | |
1304 | if self.unconfined: |
|
1304 | if self.unconfined: | |
1305 | md['unconfined'] = self.unconfined |
|
1305 | md['unconfined'] = self.unconfined | |
1306 | if md or always_both: |
|
1306 | if md or always_both: | |
1307 | return b64_data, md |
|
1307 | return b64_data, md | |
1308 | else: |
|
1308 | else: | |
1309 | return b64_data |
|
1309 | return b64_data | |
1310 |
|
1310 | |||
1311 | def _repr_png_(self): |
|
1311 | def _repr_png_(self): | |
1312 | if self.embed and self.format == self._FMT_PNG: |
|
1312 | if self.embed and self.format == self._FMT_PNG: | |
1313 | return self._data_and_metadata() |
|
1313 | return self._data_and_metadata() | |
1314 |
|
1314 | |||
1315 | def _repr_jpeg_(self): |
|
1315 | def _repr_jpeg_(self): | |
1316 | if self.embed and self.format == self._FMT_JPEG: |
|
1316 | if self.embed and self.format == self._FMT_JPEG: | |
1317 | return self._data_and_metadata() |
|
1317 | return self._data_and_metadata() | |
1318 |
|
1318 | |||
1319 | def _find_ext(self, s): |
|
1319 | def _find_ext(self, s): | |
1320 | base, ext = splitext(s) |
|
1320 | base, ext = splitext(s) | |
1321 |
|
1321 | |||
1322 | if not ext: |
|
1322 | if not ext: | |
1323 | return base |
|
1323 | return base | |
1324 |
|
1324 | |||
1325 | # `splitext` includes leading period, so we skip it |
|
1325 | # `splitext` includes leading period, so we skip it | |
1326 | return ext[1:].lower() |
|
1326 | return ext[1:].lower() | |
1327 |
|
1327 | |||
1328 |
|
1328 | |||
1329 | class Video(DisplayObject): |
|
1329 | class Video(DisplayObject): | |
1330 |
|
1330 | |||
1331 | def __init__(self, data=None, url=None, filename=None, embed=False, |
|
1331 | def __init__(self, data=None, url=None, filename=None, embed=False, | |
1332 | mimetype=None, width=None, height=None, html_attributes="controls"): |
|
1332 | mimetype=None, width=None, height=None, html_attributes="controls"): | |
1333 | """Create a video object given raw data or an URL. |
|
1333 | """Create a video object given raw data or an URL. | |
1334 |
|
1334 | |||
1335 | When this object is returned by an input cell or passed to the |
|
1335 | When this object is returned by an input cell or passed to the | |
1336 | display function, it will result in the video being displayed |
|
1336 | display function, it will result in the video being displayed | |
1337 | in the frontend. |
|
1337 | in the frontend. | |
1338 |
|
1338 | |||
1339 | Parameters |
|
1339 | Parameters | |
1340 | ---------- |
|
1340 | ---------- | |
1341 | data : unicode, str or bytes |
|
1341 | data : unicode, str or bytes | |
1342 | The raw video data or a URL or filename to load the data from. |
|
1342 | The raw video data or a URL or filename to load the data from. | |
1343 | Raw data will require passing `embed=True`. |
|
1343 | Raw data will require passing ``embed=True``. | |
1344 | url : unicode |
|
1344 | url : unicode | |
1345 | A URL for the video. If you specify `url=`, |
|
1345 | A URL for the video. If you specify ``url=``, | |
1346 | the image data will not be embedded. |
|
1346 | the image data will not be embedded. | |
1347 | filename : unicode |
|
1347 | filename : unicode | |
1348 | Path to a local file containing the video. |
|
1348 | Path to a local file containing the video. | |
1349 | Will be interpreted as a local URL unless `embed=True`. |
|
1349 | Will be interpreted as a local URL unless ``embed=True``. | |
1350 | embed : bool |
|
1350 | embed : bool | |
1351 | Should the video be embedded using a data URI (True) or be |
|
1351 | Should the video be embedded using a data URI (True) or be | |
1352 | loaded using a <video> tag (False). |
|
1352 | loaded using a <video> tag (False). | |
1353 |
|
1353 | |||
1354 | Since videos are large, embedding them should be avoided, if possible. |
|
1354 | Since videos are large, embedding them should be avoided, if possible. | |
1355 | You must confirm embedding as your intention by passing `embed=True`. |
|
1355 | You must confirm embedding as your intention by passing ``embed=True``. | |
1356 |
|
1356 | |||
1357 | Local files can be displayed with URLs without embedding the content, via:: |
|
1357 | Local files can be displayed with URLs without embedding the content, via:: | |
1358 |
|
1358 | |||
1359 | Video('./video.mp4') |
|
1359 | Video('./video.mp4') | |
1360 |
|
1360 | |||
1361 | mimetype: unicode |
|
1361 | mimetype: unicode | |
1362 | Specify the mimetype for embedded videos. |
|
1362 | Specify the mimetype for embedded videos. | |
1363 | Default will be guessed from file extension, if available. |
|
1363 | Default will be guessed from file extension, if available. | |
1364 | width : int |
|
1364 | width : int | |
1365 | Width in pixels to which to constrain the video in HTML. |
|
1365 | Width in pixels to which to constrain the video in HTML. | |
1366 | If not supplied, defaults to the width of the video. |
|
1366 | If not supplied, defaults to the width of the video. | |
1367 | height : int |
|
1367 | height : int | |
1368 | Height in pixels to which to constrain the video in html. |
|
1368 | Height in pixels to which to constrain the video in html. | |
1369 | If not supplied, defaults to the height of the video. |
|
1369 | If not supplied, defaults to the height of the video. | |
1370 | html_attributes : str |
|
1370 | html_attributes : str | |
1371 | Attributes for the HTML `<video>` block. |
|
1371 | Attributes for the HTML ``<video>`` block. | |
1372 | Default: `"controls"` to get video controls. |
|
1372 | Default: ``"controls"`` to get video controls. | |
1373 | Other examples: `"controls muted"` for muted video with controls, |
|
1373 | Other examples: ``"controls muted"`` for muted video with controls, | |
1374 | `"loop autoplay"` for looping autoplaying video without controls. |
|
1374 | ``"loop autoplay"`` for looping autoplaying video without controls. | |
1375 |
|
1375 | |||
1376 | Examples |
|
1376 | Examples | |
1377 | -------- |
|
1377 | -------- | |
1378 |
|
1378 | |||
1379 | :: |
|
1379 | :: | |
1380 |
|
1380 | |||
1381 | Video('https://archive.org/download/Sita_Sings_the_Blues/Sita_Sings_the_Blues_small.mp4') |
|
1381 | Video('https://archive.org/download/Sita_Sings_the_Blues/Sita_Sings_the_Blues_small.mp4') | |
1382 | Video('path/to/video.mp4') |
|
1382 | Video('path/to/video.mp4') | |
1383 | Video('path/to/video.mp4', embed=True) |
|
1383 | Video('path/to/video.mp4', embed=True) | |
1384 | Video('path/to/video.mp4', embed=True, html_attributes="controls muted autoplay") |
|
1384 | Video('path/to/video.mp4', embed=True, html_attributes="controls muted autoplay") | |
1385 | Video(b'raw-videodata', embed=True) |
|
1385 | Video(b'raw-videodata', embed=True) | |
1386 | """ |
|
1386 | """ | |
1387 | if isinstance(data, (Path, PurePath)): |
|
1387 | if isinstance(data, (Path, PurePath)): | |
1388 | data = str(data) |
|
1388 | data = str(data) | |
1389 |
|
1389 | |||
1390 | if url is None and isinstance(data, str) and data.startswith(('http:', 'https:')): |
|
1390 | if url is None and isinstance(data, str) and data.startswith(('http:', 'https:')): | |
1391 | url = data |
|
1391 | url = data | |
1392 | data = None |
|
1392 | data = None | |
1393 | elif os.path.exists(data): |
|
1393 | elif os.path.exists(data): | |
1394 | filename = data |
|
1394 | filename = data | |
1395 | data = None |
|
1395 | data = None | |
1396 |
|
1396 | |||
1397 | if data and not embed: |
|
1397 | if data and not embed: | |
1398 | msg = ''.join([ |
|
1398 | msg = ''.join([ | |
1399 | "To embed videos, you must pass embed=True ", |
|
1399 | "To embed videos, you must pass embed=True ", | |
1400 | "(this may make your notebook files huge)\n", |
|
1400 | "(this may make your notebook files huge)\n", | |
1401 | "Consider passing Video(url='...')", |
|
1401 | "Consider passing Video(url='...')", | |
1402 | ]) |
|
1402 | ]) | |
1403 | raise ValueError(msg) |
|
1403 | raise ValueError(msg) | |
1404 |
|
1404 | |||
1405 | self.mimetype = mimetype |
|
1405 | self.mimetype = mimetype | |
1406 | self.embed = embed |
|
1406 | self.embed = embed | |
1407 | self.width = width |
|
1407 | self.width = width | |
1408 | self.height = height |
|
1408 | self.height = height | |
1409 | self.html_attributes = html_attributes |
|
1409 | self.html_attributes = html_attributes | |
1410 | super(Video, self).__init__(data=data, url=url, filename=filename) |
|
1410 | super(Video, self).__init__(data=data, url=url, filename=filename) | |
1411 |
|
1411 | |||
1412 | def _repr_html_(self): |
|
1412 | def _repr_html_(self): | |
1413 | width = height = '' |
|
1413 | width = height = '' | |
1414 | if self.width: |
|
1414 | if self.width: | |
1415 | width = ' width="%d"' % self.width |
|
1415 | width = ' width="%d"' % self.width | |
1416 | if self.height: |
|
1416 | if self.height: | |
1417 | height = ' height="%d"' % self.height |
|
1417 | height = ' height="%d"' % self.height | |
1418 |
|
1418 | |||
1419 | # External URLs and potentially local files are not embedded into the |
|
1419 | # External URLs and potentially local files are not embedded into the | |
1420 | # notebook output. |
|
1420 | # notebook output. | |
1421 | if not self.embed: |
|
1421 | if not self.embed: | |
1422 | url = self.url if self.url is not None else self.filename |
|
1422 | url = self.url if self.url is not None else self.filename | |
1423 | output = """<video src="{0}" {1} {2} {3}> |
|
1423 | output = """<video src="{0}" {1} {2} {3}> | |
1424 | Your browser does not support the <code>video</code> element. |
|
1424 | Your browser does not support the <code>video</code> element. | |
1425 | </video>""".format(url, self.html_attributes, width, height) |
|
1425 | </video>""".format(url, self.html_attributes, width, height) | |
1426 | return output |
|
1426 | return output | |
1427 |
|
1427 | |||
1428 | # Embedded videos are base64-encoded. |
|
1428 | # Embedded videos are base64-encoded. | |
1429 | mimetype = self.mimetype |
|
1429 | mimetype = self.mimetype | |
1430 | if self.filename is not None: |
|
1430 | if self.filename is not None: | |
1431 | if not mimetype: |
|
1431 | if not mimetype: | |
1432 | mimetype, _ = mimetypes.guess_type(self.filename) |
|
1432 | mimetype, _ = mimetypes.guess_type(self.filename) | |
1433 |
|
1433 | |||
1434 | with open(self.filename, 'rb') as f: |
|
1434 | with open(self.filename, 'rb') as f: | |
1435 | video = f.read() |
|
1435 | video = f.read() | |
1436 | else: |
|
1436 | else: | |
1437 | video = self.data |
|
1437 | video = self.data | |
1438 | if isinstance(video, str): |
|
1438 | if isinstance(video, str): | |
1439 | # unicode input is already b64-encoded |
|
1439 | # unicode input is already b64-encoded | |
1440 | b64_video = video |
|
1440 | b64_video = video | |
1441 | else: |
|
1441 | else: | |
1442 | b64_video = b2a_base64(video).decode('ascii').rstrip() |
|
1442 | b64_video = b2a_base64(video).decode('ascii').rstrip() | |
1443 |
|
1443 | |||
1444 | output = """<video {0} {1} {2}> |
|
1444 | output = """<video {0} {1} {2}> | |
1445 | <source src="data:{3};base64,{4}" type="{3}"> |
|
1445 | <source src="data:{3};base64,{4}" type="{3}"> | |
1446 | Your browser does not support the video tag. |
|
1446 | Your browser does not support the video tag. | |
1447 | </video>""".format(self.html_attributes, width, height, mimetype, b64_video) |
|
1447 | </video>""".format(self.html_attributes, width, height, mimetype, b64_video) | |
1448 | return output |
|
1448 | return output | |
1449 |
|
1449 | |||
1450 | def reload(self): |
|
1450 | def reload(self): | |
1451 | # TODO |
|
1451 | # TODO | |
1452 | pass |
|
1452 | pass | |
1453 |
|
1453 | |||
1454 |
|
1454 | |||
1455 | def clear_output(wait=False): |
|
1455 | def clear_output(wait=False): | |
1456 | """Clear the output of the current cell receiving output. |
|
1456 | """Clear the output of the current cell receiving output. | |
1457 |
|
1457 | |||
1458 | Parameters |
|
1458 | Parameters | |
1459 | ---------- |
|
1459 | ---------- | |
1460 | wait : bool [default: false] |
|
1460 | wait : bool [default: false] | |
1461 | Wait to clear the output until new output is available to replace it.""" |
|
1461 | Wait to clear the output until new output is available to replace it.""" | |
1462 | from IPython.core.interactiveshell import InteractiveShell |
|
1462 | from IPython.core.interactiveshell import InteractiveShell | |
1463 | if InteractiveShell.initialized(): |
|
1463 | if InteractiveShell.initialized(): | |
1464 | InteractiveShell.instance().display_pub.clear_output(wait) |
|
1464 | InteractiveShell.instance().display_pub.clear_output(wait) | |
1465 | else: |
|
1465 | else: | |
1466 | print('\033[2K\r', end='') |
|
1466 | print('\033[2K\r', end='') | |
1467 | sys.stdout.flush() |
|
1467 | sys.stdout.flush() | |
1468 | print('\033[2K\r', end='') |
|
1468 | print('\033[2K\r', end='') | |
1469 | sys.stderr.flush() |
|
1469 | sys.stderr.flush() | |
1470 |
|
1470 | |||
1471 |
|
1471 | |||
1472 | @skip_doctest |
|
1472 | @skip_doctest | |
1473 | def set_matplotlib_formats(*formats, **kwargs): |
|
1473 | def set_matplotlib_formats(*formats, **kwargs): | |
1474 | """Select figure formats for the inline backend. Optionally pass quality for JPEG. |
|
1474 | """Select figure formats for the inline backend. Optionally pass quality for JPEG. | |
1475 |
|
1475 | |||
1476 | For example, this enables PNG and JPEG output with a JPEG quality of 90%:: |
|
1476 | For example, this enables PNG and JPEG output with a JPEG quality of 90%:: | |
1477 |
|
1477 | |||
1478 | In [1]: set_matplotlib_formats('png', 'jpeg', quality=90) |
|
1478 | In [1]: set_matplotlib_formats('png', 'jpeg', quality=90) | |
1479 |
|
1479 | |||
1480 | To set this in your config files use the following:: |
|
1480 | To set this in your config files use the following:: | |
1481 |
|
1481 | |||
1482 | c.InlineBackend.figure_formats = {'png', 'jpeg'} |
|
1482 | c.InlineBackend.figure_formats = {'png', 'jpeg'} | |
1483 | c.InlineBackend.print_figure_kwargs.update({'quality' : 90}) |
|
1483 | c.InlineBackend.print_figure_kwargs.update({'quality' : 90}) | |
1484 |
|
1484 | |||
1485 | Parameters |
|
1485 | Parameters | |
1486 | ---------- |
|
1486 | ---------- | |
1487 | *formats : strs |
|
1487 | *formats : strs | |
1488 | One or more figure formats to enable: 'png', 'retina', 'jpeg', 'svg', 'pdf'. |
|
1488 | One or more figure formats to enable: 'png', 'retina', 'jpeg', 'svg', 'pdf'. | |
1489 | **kwargs : |
|
1489 | **kwargs : | |
1490 | Keyword args will be relayed to ``figure.canvas.print_figure``. |
|
1490 | Keyword args will be relayed to ``figure.canvas.print_figure``. | |
1491 | """ |
|
1491 | """ | |
1492 | from IPython.core.interactiveshell import InteractiveShell |
|
1492 | from IPython.core.interactiveshell import InteractiveShell | |
1493 | from IPython.core.pylabtools import select_figure_formats |
|
1493 | from IPython.core.pylabtools import select_figure_formats | |
1494 | # build kwargs, starting with InlineBackend config |
|
1494 | # build kwargs, starting with InlineBackend config | |
1495 | kw = {} |
|
1495 | kw = {} | |
1496 | from ipykernel.pylab.config import InlineBackend |
|
1496 | from ipykernel.pylab.config import InlineBackend | |
1497 | cfg = InlineBackend.instance() |
|
1497 | cfg = InlineBackend.instance() | |
1498 | kw.update(cfg.print_figure_kwargs) |
|
1498 | kw.update(cfg.print_figure_kwargs) | |
1499 | kw.update(**kwargs) |
|
1499 | kw.update(**kwargs) | |
1500 | shell = InteractiveShell.instance() |
|
1500 | shell = InteractiveShell.instance() | |
1501 | select_figure_formats(shell, formats, **kw) |
|
1501 | select_figure_formats(shell, formats, **kw) | |
1502 |
|
1502 | |||
1503 | @skip_doctest |
|
1503 | @skip_doctest | |
1504 | def set_matplotlib_close(close=True): |
|
1504 | def set_matplotlib_close(close=True): | |
1505 | """Set whether the inline backend closes all figures automatically or not. |
|
1505 | """Set whether the inline backend closes all figures automatically or not. | |
1506 |
|
1506 | |||
1507 | By default, the inline backend used in the IPython Notebook will close all |
|
1507 | By default, the inline backend used in the IPython Notebook will close all | |
1508 | matplotlib figures automatically after each cell is run. This means that |
|
1508 | matplotlib figures automatically after each cell is run. This means that | |
1509 | plots in different cells won't interfere. Sometimes, you may want to make |
|
1509 | plots in different cells won't interfere. Sometimes, you may want to make | |
1510 | a plot in one cell and then refine it in later cells. This can be accomplished |
|
1510 | a plot in one cell and then refine it in later cells. This can be accomplished | |
1511 | by:: |
|
1511 | by:: | |
1512 |
|
1512 | |||
1513 | In [1]: set_matplotlib_close(False) |
|
1513 | In [1]: set_matplotlib_close(False) | |
1514 |
|
1514 | |||
1515 | To set this in your config files use the following:: |
|
1515 | To set this in your config files use the following:: | |
1516 |
|
1516 | |||
1517 | c.InlineBackend.close_figures = False |
|
1517 | c.InlineBackend.close_figures = False | |
1518 |
|
1518 | |||
1519 | Parameters |
|
1519 | Parameters | |
1520 | ---------- |
|
1520 | ---------- | |
1521 | close : bool |
|
1521 | close : bool | |
1522 | Should all matplotlib figures be automatically closed after each cell is |
|
1522 | Should all matplotlib figures be automatically closed after each cell is | |
1523 | run? |
|
1523 | run? | |
1524 | """ |
|
1524 | """ | |
1525 | from ipykernel.pylab.config import InlineBackend |
|
1525 | from ipykernel.pylab.config import InlineBackend | |
1526 | cfg = InlineBackend.instance() |
|
1526 | cfg = InlineBackend.instance() | |
1527 | cfg.close_figures = close |
|
1527 | cfg.close_figures = close |
General Comments 0
You need to be logged in to leave comments.
Login now