Show More
@@ -0,0 +1,4 b'' | |||||
|
1 | Terminal IPython will now show the signature of the function while completing. | |||
|
2 | Only the currently highlighted function will show its signature on the line | |||
|
3 | below the completer by default. The functionality is recent so might be | |||
|
4 | limited, we welcome bug report and enhancement request on it. |
@@ -1,1953 +1,2017 b'' | |||||
1 | # encoding: utf-8 |
|
|||
2 |
|
|
1 | """Completion for IPython. | |
3 |
|
2 | |||
4 | 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 | |
5 | library. The original enhancements made to rlcompleter have been sent |
|
4 | library. The original enhancements made to rlcompleter have been sent | |
6 | upstream and were accepted as of Python 2.3, |
|
5 | upstream and were accepted as of Python 2.3, | |
7 |
|
6 | |||
8 | 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 | |
9 | 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 | |
10 | Syntax like magics. |
|
9 | Syntax like magics. | |
11 |
|
10 | |||
12 | Latex and Unicode completion |
|
11 | Latex and Unicode completion | |
13 | ============================ |
|
12 | ============================ | |
14 |
|
13 | |||
15 | 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 | |
16 | 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 | |
17 | a unicode character using the tab completion mechanism. |
|
16 | a unicode character using the tab completion mechanism. | |
18 |
|
17 | |||
19 | Forward latex/unicode completion |
|
18 | Forward latex/unicode completion | |
20 | -------------------------------- |
|
19 | -------------------------------- | |
21 |
|
20 | |||
22 | 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 | |
23 | 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 | |
24 | relevant name and press tab: |
|
23 | relevant name and press tab: | |
25 |
|
24 | |||
26 |
|
25 | |||
27 | Using latex completion: |
|
26 | Using latex completion: | |
28 |
|
27 | |||
29 | .. code:: |
|
28 | .. code:: | |
30 |
|
29 | |||
31 | \\alpha<tab> |
|
30 | \\alpha<tab> | |
32 | Ξ± |
|
31 | Ξ± | |
33 |
|
32 | |||
34 | or using unicode completion: |
|
33 | or using unicode completion: | |
35 |
|
34 | |||
36 |
|
35 | |||
37 | .. code:: |
|
36 | .. code:: | |
38 |
|
37 | |||
39 | \\greek small letter alpha<tab> |
|
38 | \\greek small letter alpha<tab> | |
40 | Ξ± |
|
39 | Ξ± | |
41 |
|
40 | |||
42 |
|
41 | |||
43 | Only valid Python identifiers will complete. Combining characters (like arrow or |
|
42 | Only valid Python identifiers will complete. Combining characters (like arrow or | |
44 | 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 | |
45 | 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`. | |
46 |
|
45 | |||
47 | Some browsers are known to display combining characters incorrectly. |
|
46 | Some browsers are known to display combining characters incorrectly. | |
48 |
|
47 | |||
49 | Backward latex completion |
|
48 | Backward latex completion | |
50 | ------------------------- |
|
49 | ------------------------- | |
51 |
|
50 | |||
52 | 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 | |
53 | 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 | |
54 | and press `<tab>` to expand it to its latex form. |
|
53 | and press `<tab>` to expand it to its latex form. | |
55 |
|
54 | |||
56 | .. code:: |
|
55 | .. code:: | |
57 |
|
56 | |||
58 | \\Ξ±<tab> |
|
57 | \\Ξ±<tab> | |
59 | \\alpha |
|
58 | \\alpha | |
60 |
|
59 | |||
61 |
|
60 | |||
62 | Both forward and backward completions can be deactivated by setting the |
|
61 | Both forward and backward completions can be deactivated by setting the | |
63 | ``Completer.backslash_combining_completions`` option to ``False``. |
|
62 | ``Completer.backslash_combining_completions`` option to ``False``. | |
64 |
|
63 | |||
65 |
|
64 | |||
66 | Experimental |
|
65 | Experimental | |
67 | ============ |
|
66 | ============ | |
68 |
|
67 | |||
69 | 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 | |
70 | generate completions both using static analysis of the code, and dynamically |
|
69 | generate completions both using static analysis of the code, and dynamically | |
71 | inspecting multiple namespaces. The APIs attached to this new mechanism is |
|
70 | inspecting multiple namespaces. The APIs attached to this new mechanism is | |
72 | unstable and will raise unless use in an :any:`provisionalcompleter` context |
|
71 | unstable and will raise unless use in an :any:`provisionalcompleter` context | |
73 | manager. |
|
72 | manager. | |
74 |
|
73 | |||
75 | You will find that the following are experimental: |
|
74 | You will find that the following are experimental: | |
76 |
|
75 | |||
77 | - :any:`provisionalcompleter` |
|
76 | - :any:`provisionalcompleter` | |
78 | - :any:`IPCompleter.completions` |
|
77 | - :any:`IPCompleter.completions` | |
79 | - :any:`Completion` |
|
78 | - :any:`Completion` | |
80 | - :any:`rectify_completions` |
|
79 | - :any:`rectify_completions` | |
81 |
|
80 | |||
82 | .. note:: |
|
81 | .. note:: | |
83 |
|
82 | |||
84 | better name for :any:`rectify_completions` ? |
|
83 | better name for :any:`rectify_completions` ? | |
85 |
|
84 | |||
86 | 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 | |
87 | 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 | |
88 | to have extra logging information is :any:`jedi` is crashing, or if current |
|
87 | to have extra logging information is :any:`jedi` is crashing, or if current | |
89 | IPython completer pending deprecations are returning results not yet handled |
|
88 | IPython completer pending deprecations are returning results not yet handled | |
90 |
by :any:`jedi` |
|
89 | by :any:`jedi` | |
91 |
|
90 | |||
92 | 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 | |
93 | having to execute any code: |
|
92 | having to execute any code: | |
94 |
|
93 | |||
95 | >>> myvar = ['hello', 42] |
|
94 | >>> myvar = ['hello', 42] | |
96 | ... myvar[1].bi<tab> |
|
95 | ... myvar[1].bi<tab> | |
97 |
|
96 | |||
98 | 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 | |
99 | executing any code unlike the previously available ``IPCompleter.greedy`` |
|
98 | executing any code unlike the previously available ``IPCompleter.greedy`` | |
100 | option. |
|
99 | option. | |
101 |
|
100 | |||
102 | 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 | |
103 | current development version to get better completions. |
|
102 | current development version to get better completions. | |
104 | """ |
|
103 | """ | |
105 |
|
104 | |||
106 | # skip module docstests |
|
|||
107 | skip_doctest = True |
|
|||
108 |
|
105 | |||
109 | # Copyright (c) IPython Development Team. |
|
106 | # Copyright (c) IPython Development Team. | |
110 | # Distributed under the terms of the Modified BSD License. |
|
107 | # Distributed under the terms of the Modified BSD License. | |
111 | # |
|
108 | # | |
112 | # 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 | |
113 | # Copyright (C) 2001 Python Software Foundation, www.python.org |
|
110 | # Copyright (C) 2001 Python Software Foundation, www.python.org | |
114 |
|
111 | |||
115 |
|
112 | |||
116 | import __main__ |
|
113 | import __main__ | |
117 | import builtins as builtin_mod |
|
114 | import builtins as builtin_mod | |
118 | import glob |
|
115 | import glob | |
119 | import time |
|
116 | import time | |
120 | import inspect |
|
117 | import inspect | |
121 | import itertools |
|
118 | import itertools | |
122 | import keyword |
|
119 | import keyword | |
123 | import os |
|
120 | import os | |
124 | import re |
|
121 | import re | |
125 | import sys |
|
122 | import sys | |
126 | import unicodedata |
|
123 | import unicodedata | |
127 | import string |
|
124 | import string | |
128 | import warnings |
|
125 | import warnings | |
129 |
|
126 | |||
130 | from contextlib import contextmanager |
|
127 | from contextlib import contextmanager | |
131 | from importlib import import_module |
|
128 | from importlib import import_module | |
132 | from typing import Iterator, List, Tuple, Iterable, Union |
|
129 | from typing import Iterator, List, Tuple, Iterable, Union | |
133 | from types import SimpleNamespace |
|
130 | from types import SimpleNamespace | |
134 |
|
131 | |||
135 | from traitlets.config.configurable import Configurable |
|
132 | from traitlets.config.configurable import Configurable | |
136 | from IPython.core.error import TryNext |
|
133 | from IPython.core.error import TryNext | |
137 | from IPython.core.inputsplitter import ESC_MAGIC |
|
134 | from IPython.core.inputsplitter import ESC_MAGIC | |
138 | from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol |
|
135 | from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol | |
139 | from IPython.core.oinspect import InspectColors |
|
136 | from IPython.core.oinspect import InspectColors | |
140 | from IPython.utils import generics |
|
137 | from IPython.utils import generics | |
141 | from IPython.utils.dir2 import dir2, get_real_method |
|
138 | from IPython.utils.dir2 import dir2, get_real_method | |
142 | from IPython.utils.process import arg_split |
|
139 | from IPython.utils.process import arg_split | |
143 | from traitlets import Bool, Enum, observe, Int |
|
140 | from traitlets import Bool, Enum, observe, Int | |
144 |
|
141 | |||
|
142 | # skip module docstests | |||
|
143 | skip_doctest = True | |||
|
144 | ||||
145 | try: |
|
145 | try: | |
146 | import jedi |
|
146 | import jedi | |
147 | import jedi.api.helpers |
|
147 | import jedi.api.helpers | |
|
148 | import jedi.api.classes | |||
148 | JEDI_INSTALLED = True |
|
149 | JEDI_INSTALLED = True | |
149 | except ImportError: |
|
150 | except ImportError: | |
150 | JEDI_INSTALLED = False |
|
151 | JEDI_INSTALLED = False | |
151 | #----------------------------------------------------------------------------- |
|
152 | #----------------------------------------------------------------------------- | |
152 | # Globals |
|
153 | # Globals | |
153 | #----------------------------------------------------------------------------- |
|
154 | #----------------------------------------------------------------------------- | |
154 |
|
155 | |||
155 | # Public API |
|
156 | # Public API | |
156 | __all__ = ['Completer','IPCompleter'] |
|
157 | __all__ = ['Completer','IPCompleter'] | |
157 |
|
158 | |||
158 | if sys.platform == 'win32': |
|
159 | if sys.platform == 'win32': | |
159 | PROTECTABLES = ' ' |
|
160 | PROTECTABLES = ' ' | |
160 | else: |
|
161 | else: | |
161 | PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&' |
|
162 | PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&' | |
162 |
|
163 | |||
163 |
|
164 | |||
164 | _deprecation_readline_sentinel = object() |
|
165 | _deprecation_readline_sentinel = object() | |
165 |
|
166 | |||
166 |
|
167 | |||
167 | class ProvisionalCompleterWarning(FutureWarning): |
|
168 | class ProvisionalCompleterWarning(FutureWarning): | |
168 | """ |
|
169 | """ | |
169 | Exception raise by an experimental feature in this module. |
|
170 | Exception raise by an experimental feature in this module. | |
170 |
|
171 | |||
171 | Wrap code in :any:`provisionalcompleter` context manager if you |
|
172 | Wrap code in :any:`provisionalcompleter` context manager if you | |
172 | are certain you want to use an unstable feature. |
|
173 | are certain you want to use an unstable feature. | |
173 | """ |
|
174 | """ | |
174 | pass |
|
175 | pass | |
175 |
|
176 | |||
176 | warnings.filterwarnings('error', category=ProvisionalCompleterWarning) |
|
177 | warnings.filterwarnings('error', category=ProvisionalCompleterWarning) | |
177 |
|
178 | |||
178 | @contextmanager |
|
179 | @contextmanager | |
179 | def provisionalcompleter(action='ignore'): |
|
180 | def provisionalcompleter(action='ignore'): | |
180 | """ |
|
181 | """ | |
181 |
|
182 | |||
182 |
|
183 | |||
183 | This contest manager has to be used in any place where unstable completer |
|
184 | This contest manager has to be used in any place where unstable completer | |
184 | behavior and API may be called. |
|
185 | behavior and API may be called. | |
185 |
|
186 | |||
186 | >>> with provisionalcompleter(): |
|
187 | >>> with provisionalcompleter(): | |
187 | ... completer.do_experimetal_things() # works |
|
188 | ... completer.do_experimetal_things() # works | |
188 |
|
189 | |||
189 | >>> completer.do_experimental_things() # raises. |
|
190 | >>> completer.do_experimental_things() # raises. | |
190 |
|
191 | |||
191 | .. note:: Unstable |
|
192 | .. note:: Unstable | |
192 |
|
193 | |||
193 | By using this context manager you agree that the API in use may change |
|
194 | By using this context manager you agree that the API in use may change | |
194 | without warning, and that you won't complain if they do so. |
|
195 | without warning, and that you won't complain if they do so. | |
195 |
|
196 | |||
196 | You also understand that if the API is not to you liking you should report |
|
197 | You also understand that if the API is not to you liking you should report | |
197 | a bug to explain your use case upstream and improve the API and will loose |
|
198 | a bug to explain your use case upstream and improve the API and will loose | |
198 | credibility if you complain after the API is make stable. |
|
199 | credibility if you complain after the API is make stable. | |
199 |
|
200 | |||
200 | We'll be happy to get your feedback , feature request and improvement on |
|
201 | We'll be happy to get your feedback , feature request and improvement on | |
201 | any of the unstable APIs ! |
|
202 | any of the unstable APIs ! | |
202 | """ |
|
203 | """ | |
203 | with warnings.catch_warnings(): |
|
204 | with warnings.catch_warnings(): | |
204 | warnings.filterwarnings(action, category=ProvisionalCompleterWarning) |
|
205 | warnings.filterwarnings(action, category=ProvisionalCompleterWarning) | |
205 | yield |
|
206 | yield | |
206 |
|
207 | |||
207 |
|
208 | |||
208 | def has_open_quotes(s): |
|
209 | def has_open_quotes(s): | |
209 | """Return whether a string has open quotes. |
|
210 | """Return whether a string has open quotes. | |
210 |
|
211 | |||
211 | This simply counts whether the number of quote characters of either type in |
|
212 | This simply counts whether the number of quote characters of either type in | |
212 | the string is odd. |
|
213 | the string is odd. | |
213 |
|
214 | |||
214 | Returns |
|
215 | Returns | |
215 | ------- |
|
216 | ------- | |
216 | If there is an open quote, the quote character is returned. Else, return |
|
217 | If there is an open quote, the quote character is returned. Else, return | |
217 | False. |
|
218 | False. | |
218 | """ |
|
219 | """ | |
219 | # We check " first, then ', so complex cases with nested quotes will get |
|
220 | # We check " first, then ', so complex cases with nested quotes will get | |
220 | # the " to take precedence. |
|
221 | # the " to take precedence. | |
221 | if s.count('"') % 2: |
|
222 | if s.count('"') % 2: | |
222 | return '"' |
|
223 | return '"' | |
223 | elif s.count("'") % 2: |
|
224 | elif s.count("'") % 2: | |
224 | return "'" |
|
225 | return "'" | |
225 | else: |
|
226 | else: | |
226 | return False |
|
227 | return False | |
227 |
|
228 | |||
228 |
|
229 | |||
229 | def protect_filename(s, protectables=PROTECTABLES): |
|
230 | def protect_filename(s, protectables=PROTECTABLES): | |
230 | """Escape a string to protect certain characters.""" |
|
231 | """Escape a string to protect certain characters.""" | |
231 | if set(s) & set(protectables): |
|
232 | if set(s) & set(protectables): | |
232 | if sys.platform == "win32": |
|
233 | if sys.platform == "win32": | |
233 | return '"' + s + '"' |
|
234 | return '"' + s + '"' | |
234 | else: |
|
235 | else: | |
235 | return "".join(("\\" + c if c in protectables else c) for c in s) |
|
236 | return "".join(("\\" + c if c in protectables else c) for c in s) | |
236 | else: |
|
237 | else: | |
237 | return s |
|
238 | return s | |
238 |
|
239 | |||
239 |
|
240 | |||
240 | def expand_user(path): |
|
241 | def expand_user(path:str) -> Tuple[str, bool, str]: | |
241 | """Expand ``~``-style usernames in strings. |
|
242 | """Expand ``~``-style usernames in strings. | |
242 |
|
243 | |||
243 | This is similar to :func:`os.path.expanduser`, but it computes and returns |
|
244 | This is similar to :func:`os.path.expanduser`, but it computes and returns | |
244 | extra information that will be useful if the input was being used in |
|
245 | extra information that will be useful if the input was being used in | |
245 | computing completions, and you wish to return the completions with the |
|
246 | computing completions, and you wish to return the completions with the | |
246 | original '~' instead of its expanded value. |
|
247 | original '~' instead of its expanded value. | |
247 |
|
248 | |||
248 | Parameters |
|
249 | Parameters | |
249 | ---------- |
|
250 | ---------- | |
250 | path : str |
|
251 | path : str | |
251 | String to be expanded. If no ~ is present, the output is the same as the |
|
252 | String to be expanded. If no ~ is present, the output is the same as the | |
252 | input. |
|
253 | input. | |
253 |
|
254 | |||
254 | Returns |
|
255 | Returns | |
255 | ------- |
|
256 | ------- | |
256 | newpath : str |
|
257 | newpath : str | |
257 | Result of ~ expansion in the input path. |
|
258 | Result of ~ expansion in the input path. | |
258 | tilde_expand : bool |
|
259 | tilde_expand : bool | |
259 | Whether any expansion was performed or not. |
|
260 | Whether any expansion was performed or not. | |
260 | tilde_val : str |
|
261 | tilde_val : str | |
261 | The value that ~ was replaced with. |
|
262 | The value that ~ was replaced with. | |
262 | """ |
|
263 | """ | |
263 | # Default values |
|
264 | # Default values | |
264 | tilde_expand = False |
|
265 | tilde_expand = False | |
265 | tilde_val = '' |
|
266 | tilde_val = '' | |
266 | newpath = path |
|
267 | newpath = path | |
267 |
|
268 | |||
268 | if path.startswith('~'): |
|
269 | if path.startswith('~'): | |
269 | tilde_expand = True |
|
270 | tilde_expand = True | |
270 | rest = len(path)-1 |
|
271 | rest = len(path)-1 | |
271 | newpath = os.path.expanduser(path) |
|
272 | newpath = os.path.expanduser(path) | |
272 | if rest: |
|
273 | if rest: | |
273 | tilde_val = newpath[:-rest] |
|
274 | tilde_val = newpath[:-rest] | |
274 | else: |
|
275 | else: | |
275 | tilde_val = newpath |
|
276 | tilde_val = newpath | |
276 |
|
277 | |||
277 | return newpath, tilde_expand, tilde_val |
|
278 | return newpath, tilde_expand, tilde_val | |
278 |
|
279 | |||
279 |
|
280 | |||
280 | def compress_user(path, tilde_expand, tilde_val): |
|
281 | def compress_user(path:str, tilde_expand:bool, tilde_val:str) -> str: | |
281 | """Does the opposite of expand_user, with its outputs. |
|
282 | """Does the opposite of expand_user, with its outputs. | |
282 | """ |
|
283 | """ | |
283 | if tilde_expand: |
|
284 | if tilde_expand: | |
284 | return path.replace(tilde_val, '~') |
|
285 | return path.replace(tilde_val, '~') | |
285 | else: |
|
286 | else: | |
286 | return path |
|
287 | return path | |
287 |
|
288 | |||
288 |
|
289 | |||
289 | def completions_sorting_key(word): |
|
290 | def completions_sorting_key(word): | |
290 | """key for sorting completions |
|
291 | """key for sorting completions | |
291 |
|
292 | |||
292 | This does several things: |
|
293 | This does several things: | |
293 |
|
294 | |||
294 | - Lowercase all completions, so they are sorted alphabetically with |
|
295 | - Lowercase all completions, so they are sorted alphabetically with | |
295 | upper and lower case words mingled |
|
296 | upper and lower case words mingled | |
296 | - Demote any completions starting with underscores to the end |
|
297 | - Demote any completions starting with underscores to the end | |
297 | - Insert any %magic and %%cellmagic completions in the alphabetical order |
|
298 | - Insert any %magic and %%cellmagic completions in the alphabetical order | |
298 | by their name |
|
299 | by their name | |
299 | """ |
|
300 | """ | |
300 | # Case insensitive sort |
|
301 | # Case insensitive sort | |
301 | word = word.lower() |
|
302 | word = word.lower() | |
302 |
|
303 | |||
303 | prio1, prio2 = 0, 0 |
|
304 | prio1, prio2 = 0, 0 | |
304 |
|
305 | |||
305 | if word.startswith('__'): |
|
306 | if word.startswith('__'): | |
306 | prio1 = 2 |
|
307 | prio1 = 2 | |
307 | elif word.startswith('_'): |
|
308 | elif word.startswith('_'): | |
308 | prio1 = 1 |
|
309 | prio1 = 1 | |
309 |
|
310 | |||
310 | if word.endswith('='): |
|
311 | if word.endswith('='): | |
311 | prio1 = -1 |
|
312 | prio1 = -1 | |
312 |
|
313 | |||
313 | if word.startswith('%%'): |
|
314 | if word.startswith('%%'): | |
314 | # 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 | |
315 | if not "%" in word[2:]: |
|
316 | if not "%" in word[2:]: | |
316 | word = word[2:] |
|
317 | word = word[2:] | |
317 | prio2 = 2 |
|
318 | prio2 = 2 | |
318 | elif word.startswith('%'): |
|
319 | elif word.startswith('%'): | |
319 | if not "%" in word[1:]: |
|
320 | if not "%" in word[1:]: | |
320 | word = word[1:] |
|
321 | word = word[1:] | |
321 | prio2 = 1 |
|
322 | prio2 = 1 | |
322 |
|
323 | |||
323 | return prio1, word, prio2 |
|
324 | return prio1, word, prio2 | |
324 |
|
325 | |||
325 |
|
326 | |||
326 | class _FakeJediCompletion: |
|
327 | class _FakeJediCompletion: | |
327 | """ |
|
328 | """ | |
328 | 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 | |
329 | 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. | |
330 |
|
331 | |||
331 | 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 | |
332 |
|
333 | |||
333 | """ |
|
334 | """ | |
334 |
|
335 | |||
335 | def __init__(self, name): |
|
336 | def __init__(self, name): | |
336 |
|
337 | |||
337 | self.name = name |
|
338 | self.name = name | |
338 | self.complete = name |
|
339 | self.complete = name | |
339 | self.type = 'crashed' |
|
340 | self.type = 'crashed' | |
340 | self.name_with_symbols = name |
|
341 | self.name_with_symbols = name | |
|
342 | self.signature = '' | |||
|
343 | self._origin = 'fake' | |||
341 |
|
344 | |||
342 | def __repr__(self): |
|
345 | def __repr__(self): | |
343 | return '<Fake completion object jedi has crashed>' |
|
346 | return '<Fake completion object jedi has crashed>' | |
344 |
|
347 | |||
345 |
|
348 | |||
346 | class Completion: |
|
349 | class Completion: | |
347 | """ |
|
350 | """ | |
348 | Completion object used and return by IPython completers. |
|
351 | Completion object used and return by IPython completers. | |
349 |
|
352 | |||
350 | .. warning:: Unstable |
|
353 | .. warning:: Unstable | |
351 |
|
354 | |||
352 | This function is unstable, API may change without warning. |
|
355 | This function is unstable, API may change without warning. | |
353 | It will also raise unless use in proper context manager. |
|
356 | It will also raise unless use in proper context manager. | |
354 |
|
357 | |||
355 | This act as a middle ground :any:`Completion` object between the |
|
358 | This act as a middle ground :any:`Completion` object between the | |
356 | :any:`jedi.api.classes.Completion` object and the Prompt Toolkit completion |
|
359 | :any:`jedi.api.classes.Completion` object and the Prompt Toolkit completion | |
357 | object. While Jedi need a lot of information about evaluator and how the |
|
360 | object. While Jedi need a lot of information about evaluator and how the | |
358 | code should be ran/inspected, PromptToolkit (and other frontend) mostly |
|
361 | code should be ran/inspected, PromptToolkit (and other frontend) mostly | |
359 | need user facing information. |
|
362 | need user facing information. | |
360 |
|
363 | |||
361 | - Which range should be replaced replaced by what. |
|
364 | - Which range should be replaced replaced by what. | |
362 | - Some metadata (like completion type), or meta informations to displayed to |
|
365 | - Some metadata (like completion type), or meta informations to displayed to | |
363 | the use user. |
|
366 | the use user. | |
364 |
|
367 | |||
365 | For debugging purpose we can also store the origin of the completion (``jedi``, |
|
368 | For debugging purpose we can also store the origin of the completion (``jedi``, | |
366 | ``IPython.python_matches``, ``IPython.magics_matches``...). |
|
369 | ``IPython.python_matches``, ``IPython.magics_matches``...). | |
367 | """ |
|
370 | """ | |
368 |
|
371 | |||
369 | def __init__(self, start: int, end: int, text: str, *, type: str=None, _origin='') -> None: |
|
372 | __slots__ = ['start', 'end', 'text', 'type', 'signature', '_origin'] | |
|
373 | ||||
|
374 | def __init__(self, start: int, end: int, text: str, *, type: str=None, _origin='', signature='') -> None: | |||
370 | warnings.warn("``Completion`` is a provisional API (as of IPython 6.0). " |
|
375 | warnings.warn("``Completion`` is a provisional API (as of IPython 6.0). " | |
371 | "It may change without warnings. " |
|
376 | "It may change without warnings. " | |
372 | "Use in corresponding context manager.", |
|
377 | "Use in corresponding context manager.", | |
373 | category=ProvisionalCompleterWarning, stacklevel=2) |
|
378 | category=ProvisionalCompleterWarning, stacklevel=2) | |
374 |
|
379 | |||
375 | self.start = start |
|
380 | self.start = start | |
376 | self.end = end |
|
381 | self.end = end | |
377 | self.text = text |
|
382 | self.text = text | |
378 | self.type = type |
|
383 | self.type = type | |
|
384 | self.signature = signature | |||
379 | self._origin = _origin |
|
385 | self._origin = _origin | |
380 |
|
386 | |||
381 | def __repr__(self): |
|
387 | def __repr__(self): | |
382 |
return '<Completion start=%s end=%s text=%r type=%r>' % |
|
388 | return '<Completion start=%s end=%s text=%r type=%r, signature=%r,>' % \ | |
|
389 | (self.start, self.end, self.text, self.type or '?', self.signature or '?') | |||
383 |
|
390 | |||
384 | def __eq__(self, other)->Bool: |
|
391 | def __eq__(self, other)->Bool: | |
385 | """ |
|
392 | """ | |
386 | Equality and hash do not hash the type (as some completer may not be |
|
393 | Equality and hash do not hash the type (as some completer may not be | |
387 | able to infer the type), but are use to (partially) de-duplicate |
|
394 | able to infer the type), but are use to (partially) de-duplicate | |
388 | completion. |
|
395 | completion. | |
389 |
|
396 | |||
390 | Completely de-duplicating completion is a bit tricker that just |
|
397 | Completely de-duplicating completion is a bit tricker that just | |
391 | comparing as it depends on surrounding text, which Completions are not |
|
398 | comparing as it depends on surrounding text, which Completions are not | |
392 | aware of. |
|
399 | aware of. | |
393 | """ |
|
400 | """ | |
394 | return self.start == other.start and \ |
|
401 | return self.start == other.start and \ | |
395 | self.end == other.end and \ |
|
402 | self.end == other.end and \ | |
396 | self.text == other.text |
|
403 | self.text == other.text | |
397 |
|
404 | |||
398 | def __hash__(self): |
|
405 | def __hash__(self): | |
399 | return hash((self.start, self.end, self.text)) |
|
406 | return hash((self.start, self.end, self.text)) | |
400 |
|
407 | |||
401 |
|
408 | |||
402 | _IC = Iterable[Completion] |
|
409 | _IC = Iterable[Completion] | |
403 |
|
410 | |||
404 |
|
411 | |||
405 | def _deduplicate_completions(text: str, completions: _IC)-> _IC: |
|
412 | def _deduplicate_completions(text: str, completions: _IC)-> _IC: | |
406 | """ |
|
413 | """ | |
407 | Deduplicate a set of completions. |
|
414 | Deduplicate a set of completions. | |
408 |
|
415 | |||
409 | .. warning:: Unstable |
|
416 | .. warning:: Unstable | |
410 |
|
417 | |||
411 | This function is unstable, API may change without warning. |
|
418 | This function is unstable, API may change without warning. | |
412 |
|
419 | |||
413 | Parameters |
|
420 | Parameters | |
414 | ---------- |
|
421 | ---------- | |
415 | text: str |
|
422 | text: str | |
416 | text that should be completed. |
|
423 | text that should be completed. | |
417 | completions: Iterator[Completion] |
|
424 | completions: Iterator[Completion] | |
418 | iterator over the completions to deduplicate |
|
425 | iterator over the completions to deduplicate | |
419 |
|
426 | |||
|
427 | Yields | |||
|
428 | ------ | |||
|
429 | `Completions` objects | |||
|
430 | ||||
420 |
|
431 | |||
421 | Completions coming from multiple sources, may be different but end up having |
|
432 | Completions coming from multiple sources, may be different but end up having | |
422 | the same effect when applied to ``text``. If this is the case, this will |
|
433 | the same effect when applied to ``text``. If this is the case, this will | |
423 | consider completions as equal and only emit the first encountered. |
|
434 | consider completions as equal and only emit the first encountered. | |
424 |
|
435 | |||
425 | Not folded in `completions()` yet for debugging purpose, and to detect when |
|
436 | Not folded in `completions()` yet for debugging purpose, and to detect when | |
426 | the IPython completer does return things that Jedi does not, but should be |
|
437 | the IPython completer does return things that Jedi does not, but should be | |
427 | at some point. |
|
438 | at some point. | |
428 | """ |
|
439 | """ | |
429 | completions = list(completions) |
|
440 | completions = list(completions) | |
430 | if not completions: |
|
441 | if not completions: | |
431 | return |
|
442 | return | |
432 |
|
443 | |||
433 | new_start = min(c.start for c in completions) |
|
444 | new_start = min(c.start for c in completions) | |
434 | new_end = max(c.end for c in completions) |
|
445 | new_end = max(c.end for c in completions) | |
435 |
|
446 | |||
436 | seen = set() |
|
447 | seen = set() | |
437 | for c in completions: |
|
448 | for c in completions: | |
438 | new_text = text[new_start:c.start] + c.text + text[c.end:new_end] |
|
449 | new_text = text[new_start:c.start] + c.text + text[c.end:new_end] | |
439 | if new_text not in seen: |
|
450 | if new_text not in seen: | |
440 | yield c |
|
451 | yield c | |
441 | seen.add(new_text) |
|
452 | seen.add(new_text) | |
442 |
|
453 | |||
443 |
|
454 | |||
444 | def rectify_completions(text: str, completions: _IC, *, _debug=False)->_IC: |
|
455 | def rectify_completions(text: str, completions: _IC, *, _debug=False)->_IC: | |
445 | """ |
|
456 | """ | |
446 | Rectify a set of completions to all have the same ``start`` and ``end`` |
|
457 | Rectify a set of completions to all have the same ``start`` and ``end`` | |
447 |
|
458 | |||
448 | .. warning:: Unstable |
|
459 | .. warning:: Unstable | |
449 |
|
460 | |||
450 | This function is unstable, API may change without warning. |
|
461 | This function is unstable, API may change without warning. | |
451 | It will also raise unless use in proper context manager. |
|
462 | It will also raise unless use in proper context manager. | |
452 |
|
463 | |||
453 | Parameters |
|
464 | Parameters | |
454 | ---------- |
|
465 | ---------- | |
455 | text: str |
|
466 | text: str | |
456 | text that should be completed. |
|
467 | text that should be completed. | |
457 | completions: Iterator[Completion] |
|
468 | completions: Iterator[Completion] | |
458 | iterator over the completions to rectify |
|
469 | iterator over the completions to rectify | |
459 |
|
470 | |||
460 |
|
471 | |||
461 | :any:`jedi.api.classes.Completion` s returned by Jedi may not have the same start and end, though |
|
472 | :any:`jedi.api.classes.Completion` s returned by Jedi may not have the same start and end, though | |
462 | the Jupyter Protocol requires them to behave like so. This will readjust |
|
473 | the Jupyter Protocol requires them to behave like so. This will readjust | |
463 | the completion to have the same ``start`` and ``end`` by padding both |
|
474 | the completion to have the same ``start`` and ``end`` by padding both | |
464 | extremities with surrounding text. |
|
475 | extremities with surrounding text. | |
465 |
|
476 | |||
466 | During stabilisation should support a ``_debug`` option to log which |
|
477 | During stabilisation should support a ``_debug`` option to log which | |
467 | completion are return by the IPython completer and not found in Jedi in |
|
478 | completion are return by the IPython completer and not found in Jedi in | |
468 | order to make upstream bug report. |
|
479 | order to make upstream bug report. | |
469 | """ |
|
480 | """ | |
470 | warnings.warn("`rectify_completions` is a provisional API (as of IPython 6.0). " |
|
481 | warnings.warn("`rectify_completions` is a provisional API (as of IPython 6.0). " | |
471 | "It may change without warnings. " |
|
482 | "It may change without warnings. " | |
472 | "Use in corresponding context manager.", |
|
483 | "Use in corresponding context manager.", | |
473 | category=ProvisionalCompleterWarning, stacklevel=2) |
|
484 | category=ProvisionalCompleterWarning, stacklevel=2) | |
474 |
|
485 | |||
475 | completions = list(completions) |
|
486 | completions = list(completions) | |
476 | if not completions: |
|
487 | if not completions: | |
477 | return |
|
488 | return | |
478 | starts = (c.start for c in completions) |
|
489 | starts = (c.start for c in completions) | |
479 | ends = (c.end for c in completions) |
|
490 | ends = (c.end for c in completions) | |
480 |
|
491 | |||
481 | new_start = min(starts) |
|
492 | new_start = min(starts) | |
482 | new_end = max(ends) |
|
493 | new_end = max(ends) | |
483 |
|
494 | |||
484 | seen_jedi = set() |
|
495 | seen_jedi = set() | |
485 | seen_python_matches = set() |
|
496 | seen_python_matches = set() | |
486 | for c in completions: |
|
497 | for c in completions: | |
487 | new_text = text[new_start:c.start] + c.text + text[c.end:new_end] |
|
498 | new_text = text[new_start:c.start] + c.text + text[c.end:new_end] | |
488 | if c._origin == 'jedi': |
|
499 | if c._origin == 'jedi': | |
489 | seen_jedi.add(new_text) |
|
500 | seen_jedi.add(new_text) | |
490 | elif c._origin == 'IPCompleter.python_matches': |
|
501 | elif c._origin == 'IPCompleter.python_matches': | |
491 | seen_python_matches.add(new_text) |
|
502 | seen_python_matches.add(new_text) | |
492 | yield Completion(new_start, new_end, new_text, type=c.type, _origin=c._origin) |
|
503 | yield Completion(new_start, new_end, new_text, type=c.type, _origin=c._origin, signature=c.signature) | |
493 | diff = seen_python_matches.difference(seen_jedi) |
|
504 | diff = seen_python_matches.difference(seen_jedi) | |
494 | if diff and _debug: |
|
505 | if diff and _debug: | |
495 | print('IPython.python matches have extras:', diff) |
|
506 | print('IPython.python matches have extras:', diff) | |
496 |
|
507 | |||
497 |
|
508 | |||
498 | if sys.platform == 'win32': |
|
509 | if sys.platform == 'win32': | |
499 | DELIMS = ' \t\n`!@#$^&*()=+[{]}|;\'",<>?' |
|
510 | DELIMS = ' \t\n`!@#$^&*()=+[{]}|;\'",<>?' | |
500 | else: |
|
511 | else: | |
501 | DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?' |
|
512 | DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?' | |
502 |
|
513 | |||
503 | GREEDY_DELIMS = ' =\r\n' |
|
514 | GREEDY_DELIMS = ' =\r\n' | |
504 |
|
515 | |||
505 |
|
516 | |||
506 | class CompletionSplitter(object): |
|
517 | class CompletionSplitter(object): | |
507 | """An object to split an input line in a manner similar to readline. |
|
518 | """An object to split an input line in a manner similar to readline. | |
508 |
|
519 | |||
509 | By having our own implementation, we can expose readline-like completion in |
|
520 | By having our own implementation, we can expose readline-like completion in | |
510 | a uniform manner to all frontends. This object only needs to be given the |
|
521 | a uniform manner to all frontends. This object only needs to be given the | |
511 | line of text to be split and the cursor position on said line, and it |
|
522 | line of text to be split and the cursor position on said line, and it | |
512 | returns the 'word' to be completed on at the cursor after splitting the |
|
523 | returns the 'word' to be completed on at the cursor after splitting the | |
513 | entire line. |
|
524 | entire line. | |
514 |
|
525 | |||
515 | What characters are used as splitting delimiters can be controlled by |
|
526 | What characters are used as splitting delimiters can be controlled by | |
516 | setting the ``delims`` attribute (this is a property that internally |
|
527 | setting the ``delims`` attribute (this is a property that internally | |
517 | automatically builds the necessary regular expression)""" |
|
528 | automatically builds the necessary regular expression)""" | |
518 |
|
529 | |||
519 | # Private interface |
|
530 | # Private interface | |
520 |
|
531 | |||
521 | # A string of delimiter characters. The default value makes sense for |
|
532 | # A string of delimiter characters. The default value makes sense for | |
522 | # IPython's most typical usage patterns. |
|
533 | # IPython's most typical usage patterns. | |
523 | _delims = DELIMS |
|
534 | _delims = DELIMS | |
524 |
|
535 | |||
525 | # The expression (a normal string) to be compiled into a regular expression |
|
536 | # The expression (a normal string) to be compiled into a regular expression | |
526 | # for actual splitting. We store it as an attribute mostly for ease of |
|
537 | # for actual splitting. We store it as an attribute mostly for ease of | |
527 | # debugging, since this type of code can be so tricky to debug. |
|
538 | # debugging, since this type of code can be so tricky to debug. | |
528 | _delim_expr = None |
|
539 | _delim_expr = None | |
529 |
|
540 | |||
530 | # The regular expression that does the actual splitting |
|
541 | # The regular expression that does the actual splitting | |
531 | _delim_re = None |
|
542 | _delim_re = None | |
532 |
|
543 | |||
533 | def __init__(self, delims=None): |
|
544 | def __init__(self, delims=None): | |
534 | delims = CompletionSplitter._delims if delims is None else delims |
|
545 | delims = CompletionSplitter._delims if delims is None else delims | |
535 | self.delims = delims |
|
546 | self.delims = delims | |
536 |
|
547 | |||
537 | @property |
|
548 | @property | |
538 | def delims(self): |
|
549 | def delims(self): | |
539 | """Return the string of delimiter characters.""" |
|
550 | """Return the string of delimiter characters.""" | |
540 | return self._delims |
|
551 | return self._delims | |
541 |
|
552 | |||
542 | @delims.setter |
|
553 | @delims.setter | |
543 | def delims(self, delims): |
|
554 | def delims(self, delims): | |
544 | """Set the delimiters for line splitting.""" |
|
555 | """Set the delimiters for line splitting.""" | |
545 | expr = '[' + ''.join('\\'+ c for c in delims) + ']' |
|
556 | expr = '[' + ''.join('\\'+ c for c in delims) + ']' | |
546 | self._delim_re = re.compile(expr) |
|
557 | self._delim_re = re.compile(expr) | |
547 | self._delims = delims |
|
558 | self._delims = delims | |
548 | self._delim_expr = expr |
|
559 | self._delim_expr = expr | |
549 |
|
560 | |||
550 | def split_line(self, line, cursor_pos=None): |
|
561 | def split_line(self, line, cursor_pos=None): | |
551 | """Split a line of text with a cursor at the given position. |
|
562 | """Split a line of text with a cursor at the given position. | |
552 | """ |
|
563 | """ | |
553 | l = line if cursor_pos is None else line[:cursor_pos] |
|
564 | l = line if cursor_pos is None else line[:cursor_pos] | |
554 | return self._delim_re.split(l)[-1] |
|
565 | return self._delim_re.split(l)[-1] | |
555 |
|
566 | |||
556 |
|
567 | |||
557 |
|
568 | |||
558 | class Completer(Configurable): |
|
569 | class Completer(Configurable): | |
559 |
|
570 | |||
560 | greedy = Bool(False, |
|
571 | greedy = Bool(False, | |
561 | help="""Activate greedy completion |
|
572 | help="""Activate greedy completion | |
562 | PENDING DEPRECTION. this is now mostly taken care of with Jedi. |
|
573 | PENDING DEPRECTION. this is now mostly taken care of with Jedi. | |
563 |
|
574 | |||
564 | This will enable completion on elements of lists, results of function calls, etc., |
|
575 | This will enable completion on elements of lists, results of function calls, etc., | |
565 | but can be unsafe because the code is actually evaluated on TAB. |
|
576 | but can be unsafe because the code is actually evaluated on TAB. | |
566 | """ |
|
577 | """ | |
567 | ).tag(config=True) |
|
578 | ).tag(config=True) | |
568 |
|
579 | |||
569 | use_jedi = Bool(default_value=JEDI_INSTALLED, |
|
580 | use_jedi = Bool(default_value=JEDI_INSTALLED, | |
570 | help="Experimental: Use Jedi to generate autocompletions. " |
|
581 | help="Experimental: Use Jedi to generate autocompletions. " | |
571 | "Default to True if jedi is installed").tag(config=True) |
|
582 | "Default to True if jedi is installed").tag(config=True) | |
572 |
|
583 | |||
573 | jedi_compute_type_timeout = Int(default_value=400, |
|
584 | jedi_compute_type_timeout = Int(default_value=400, | |
574 | help="""Experimental: restrict time (in milliseconds) during which Jedi can compute types. |
|
585 | help="""Experimental: restrict time (in milliseconds) during which Jedi can compute types. | |
575 | Set to 0 to stop computing types. Non-zero value lower than 100ms may hurt |
|
586 | Set to 0 to stop computing types. Non-zero value lower than 100ms may hurt | |
576 | performance by preventing jedi to build its cache. |
|
587 | performance by preventing jedi to build its cache. | |
577 | """).tag(config=True) |
|
588 | """).tag(config=True) | |
578 |
|
589 | |||
579 | debug = Bool(default_value=False, |
|
590 | debug = Bool(default_value=False, | |
580 | help='Enable debug for the Completer. Mostly print extra ' |
|
591 | help='Enable debug for the Completer. Mostly print extra ' | |
581 | 'information for experimental jedi integration.')\ |
|
592 | 'information for experimental jedi integration.')\ | |
582 | .tag(config=True) |
|
593 | .tag(config=True) | |
583 |
|
594 | |||
584 | backslash_combining_completions = Bool(True, |
|
595 | backslash_combining_completions = Bool(True, | |
585 | help="Enable unicode completions, e.g. \\alpha<tab> . " |
|
596 | help="Enable unicode completions, e.g. \\alpha<tab> . " | |
586 | "Includes completion of latex commands, unicode names, and expanding " |
|
597 | "Includes completion of latex commands, unicode names, and expanding " | |
587 | "unicode characters back to latex commands.").tag(config=True) |
|
598 | "unicode characters back to latex commands.").tag(config=True) | |
588 |
|
599 | |||
589 |
|
600 | |||
590 |
|
601 | |||
591 | def __init__(self, namespace=None, global_namespace=None, **kwargs): |
|
602 | def __init__(self, namespace=None, global_namespace=None, **kwargs): | |
592 | """Create a new completer for the command line. |
|
603 | """Create a new completer for the command line. | |
593 |
|
604 | |||
594 | Completer(namespace=ns, global_namespace=ns2) -> completer instance. |
|
605 | Completer(namespace=ns, global_namespace=ns2) -> completer instance. | |
595 |
|
606 | |||
596 | If unspecified, the default namespace where completions are performed |
|
607 | If unspecified, the default namespace where completions are performed | |
597 | is __main__ (technically, __main__.__dict__). Namespaces should be |
|
608 | is __main__ (technically, __main__.__dict__). Namespaces should be | |
598 | given as dictionaries. |
|
609 | given as dictionaries. | |
599 |
|
610 | |||
600 | An optional second namespace can be given. This allows the completer |
|
611 | An optional second namespace can be given. This allows the completer | |
601 | to handle cases where both the local and global scopes need to be |
|
612 | to handle cases where both the local and global scopes need to be | |
602 | distinguished. |
|
613 | distinguished. | |
603 | """ |
|
614 | """ | |
604 |
|
615 | |||
605 | # Don't bind to namespace quite yet, but flag whether the user wants a |
|
616 | # Don't bind to namespace quite yet, but flag whether the user wants a | |
606 | # specific namespace or to use __main__.__dict__. This will allow us |
|
617 | # specific namespace or to use __main__.__dict__. This will allow us | |
607 | # to bind to __main__.__dict__ at completion time, not now. |
|
618 | # to bind to __main__.__dict__ at completion time, not now. | |
608 | if namespace is None: |
|
619 | if namespace is None: | |
609 | self.use_main_ns = True |
|
620 | self.use_main_ns = True | |
610 | else: |
|
621 | else: | |
611 | self.use_main_ns = False |
|
622 | self.use_main_ns = False | |
612 | self.namespace = namespace |
|
623 | self.namespace = namespace | |
613 |
|
624 | |||
614 | # The global namespace, if given, can be bound directly |
|
625 | # The global namespace, if given, can be bound directly | |
615 | if global_namespace is None: |
|
626 | if global_namespace is None: | |
616 | self.global_namespace = {} |
|
627 | self.global_namespace = {} | |
617 | else: |
|
628 | else: | |
618 | self.global_namespace = global_namespace |
|
629 | self.global_namespace = global_namespace | |
619 |
|
630 | |||
620 | super(Completer, self).__init__(**kwargs) |
|
631 | super(Completer, self).__init__(**kwargs) | |
621 |
|
632 | |||
622 | def complete(self, text, state): |
|
633 | def complete(self, text, state): | |
623 | """Return the next possible completion for 'text'. |
|
634 | """Return the next possible completion for 'text'. | |
624 |
|
635 | |||
625 | This is called successively with state == 0, 1, 2, ... until it |
|
636 | This is called successively with state == 0, 1, 2, ... until it | |
626 | returns None. The completion should begin with 'text'. |
|
637 | returns None. The completion should begin with 'text'. | |
627 |
|
638 | |||
628 | """ |
|
639 | """ | |
629 | if self.use_main_ns: |
|
640 | if self.use_main_ns: | |
630 | self.namespace = __main__.__dict__ |
|
641 | self.namespace = __main__.__dict__ | |
631 |
|
642 | |||
632 | if state == 0: |
|
643 | if state == 0: | |
633 | if "." in text: |
|
644 | if "." in text: | |
634 | self.matches = self.attr_matches(text) |
|
645 | self.matches = self.attr_matches(text) | |
635 | else: |
|
646 | else: | |
636 | self.matches = self.global_matches(text) |
|
647 | self.matches = self.global_matches(text) | |
637 | try: |
|
648 | try: | |
638 | return self.matches[state] |
|
649 | return self.matches[state] | |
639 | except IndexError: |
|
650 | except IndexError: | |
640 | return None |
|
651 | return None | |
641 |
|
652 | |||
642 | def global_matches(self, text): |
|
653 | def global_matches(self, text): | |
643 | """Compute matches when text is a simple name. |
|
654 | """Compute matches when text is a simple name. | |
644 |
|
655 | |||
645 | Return a list of all keywords, built-in functions and names currently |
|
656 | Return a list of all keywords, built-in functions and names currently | |
646 | defined in self.namespace or self.global_namespace that match. |
|
657 | defined in self.namespace or self.global_namespace that match. | |
647 |
|
658 | |||
648 | """ |
|
659 | """ | |
649 | matches = [] |
|
660 | matches = [] | |
650 | match_append = matches.append |
|
661 | match_append = matches.append | |
651 | n = len(text) |
|
662 | n = len(text) | |
652 | for lst in [keyword.kwlist, |
|
663 | for lst in [keyword.kwlist, | |
653 | builtin_mod.__dict__.keys(), |
|
664 | builtin_mod.__dict__.keys(), | |
654 | self.namespace.keys(), |
|
665 | self.namespace.keys(), | |
655 | self.global_namespace.keys()]: |
|
666 | self.global_namespace.keys()]: | |
656 | for word in lst: |
|
667 | for word in lst: | |
657 | if word[:n] == text and word != "__builtins__": |
|
668 | if word[:n] == text and word != "__builtins__": | |
658 | match_append(word) |
|
669 | match_append(word) | |
659 |
|
670 | |||
660 | snake_case_re = re.compile(r"[^_]+(_[^_]+)+?\Z") |
|
671 | snake_case_re = re.compile(r"[^_]+(_[^_]+)+?\Z") | |
661 | for lst in [self.namespace.keys(), |
|
672 | for lst in [self.namespace.keys(), | |
662 | self.global_namespace.keys()]: |
|
673 | self.global_namespace.keys()]: | |
663 | shortened = {"_".join([sub[0] for sub in word.split('_')]) : word |
|
674 | shortened = {"_".join([sub[0] for sub in word.split('_')]) : word | |
664 | for word in lst if snake_case_re.match(word)} |
|
675 | for word in lst if snake_case_re.match(word)} | |
665 | for word in shortened.keys(): |
|
676 | for word in shortened.keys(): | |
666 | if word[:n] == text and word != "__builtins__": |
|
677 | if word[:n] == text and word != "__builtins__": | |
667 | match_append(shortened[word]) |
|
678 | match_append(shortened[word]) | |
668 | return matches |
|
679 | return matches | |
669 |
|
680 | |||
670 | def attr_matches(self, text): |
|
681 | def attr_matches(self, text): | |
671 | """Compute matches when text contains a dot. |
|
682 | """Compute matches when text contains a dot. | |
672 |
|
683 | |||
673 | Assuming the text is of the form NAME.NAME....[NAME], and is |
|
684 | Assuming the text is of the form NAME.NAME....[NAME], and is | |
674 | evaluatable in self.namespace or self.global_namespace, it will be |
|
685 | evaluatable in self.namespace or self.global_namespace, it will be | |
675 | evaluated and its attributes (as revealed by dir()) are used as |
|
686 | evaluated and its attributes (as revealed by dir()) are used as | |
676 | possible completions. (For class instances, class members are are |
|
687 | possible completions. (For class instances, class members are are | |
677 | also considered.) |
|
688 | also considered.) | |
678 |
|
689 | |||
679 | WARNING: this can still invoke arbitrary C code, if an object |
|
690 | WARNING: this can still invoke arbitrary C code, if an object | |
680 | with a __getattr__ hook is evaluated. |
|
691 | with a __getattr__ hook is evaluated. | |
681 |
|
692 | |||
682 | """ |
|
693 | """ | |
683 |
|
694 | |||
684 | # Another option, seems to work great. Catches things like ''.<tab> |
|
695 | # Another option, seems to work great. Catches things like ''.<tab> | |
685 | m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text) |
|
696 | m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text) | |
686 |
|
697 | |||
687 | if m: |
|
698 | if m: | |
688 | expr, attr = m.group(1, 3) |
|
699 | expr, attr = m.group(1, 3) | |
689 | elif self.greedy: |
|
700 | elif self.greedy: | |
690 | m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer) |
|
701 | m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer) | |
691 | if not m2: |
|
702 | if not m2: | |
692 | return [] |
|
703 | return [] | |
693 | expr, attr = m2.group(1,2) |
|
704 | expr, attr = m2.group(1,2) | |
694 | else: |
|
705 | else: | |
695 | return [] |
|
706 | return [] | |
696 |
|
707 | |||
697 | try: |
|
708 | try: | |
698 | obj = eval(expr, self.namespace) |
|
709 | obj = eval(expr, self.namespace) | |
699 | except: |
|
710 | except: | |
700 | try: |
|
711 | try: | |
701 | obj = eval(expr, self.global_namespace) |
|
712 | obj = eval(expr, self.global_namespace) | |
702 | except: |
|
713 | except: | |
703 | return [] |
|
714 | return [] | |
704 |
|
715 | |||
705 | if self.limit_to__all__ and hasattr(obj, '__all__'): |
|
716 | if self.limit_to__all__ and hasattr(obj, '__all__'): | |
706 | words = get__all__entries(obj) |
|
717 | words = get__all__entries(obj) | |
707 | else: |
|
718 | else: | |
708 | words = dir2(obj) |
|
719 | words = dir2(obj) | |
709 |
|
720 | |||
710 | try: |
|
721 | try: | |
711 | words = generics.complete_object(obj, words) |
|
722 | words = generics.complete_object(obj, words) | |
712 | except TryNext: |
|
723 | except TryNext: | |
713 | pass |
|
724 | pass | |
714 | except AssertionError: |
|
725 | except AssertionError: | |
715 | raise |
|
726 | raise | |
716 | except Exception: |
|
727 | except Exception: | |
717 | # Silence errors from completion function |
|
728 | # Silence errors from completion function | |
718 | #raise # dbg |
|
729 | #raise # dbg | |
719 | pass |
|
730 | pass | |
720 | # Build match list to return |
|
731 | # Build match list to return | |
721 | n = len(attr) |
|
732 | n = len(attr) | |
722 | return [u"%s.%s" % (expr, w) for w in words if w[:n] == attr ] |
|
733 | return [u"%s.%s" % (expr, w) for w in words if w[:n] == attr ] | |
723 |
|
734 | |||
724 |
|
735 | |||
725 | def get__all__entries(obj): |
|
736 | def get__all__entries(obj): | |
726 | """returns the strings in the __all__ attribute""" |
|
737 | """returns the strings in the __all__ attribute""" | |
727 | try: |
|
738 | try: | |
728 | words = getattr(obj, '__all__') |
|
739 | words = getattr(obj, '__all__') | |
729 | except: |
|
740 | except: | |
730 | return [] |
|
741 | return [] | |
731 |
|
742 | |||
732 | return [w for w in words if isinstance(w, str)] |
|
743 | return [w for w in words if isinstance(w, str)] | |
733 |
|
744 | |||
734 |
|
745 | |||
735 | def match_dict_keys(keys: List[str], prefix: str, delims: str): |
|
746 | def match_dict_keys(keys: List[str], prefix: str, delims: str): | |
736 | """Used by dict_key_matches, matching the prefix to a list of keys |
|
747 | """Used by dict_key_matches, matching the prefix to a list of keys | |
737 |
|
748 | |||
738 | Parameters |
|
749 | Parameters | |
739 | ========== |
|
750 | ========== | |
740 | keys: |
|
751 | keys: | |
741 | list of keys in dictionary currently being completed. |
|
752 | list of keys in dictionary currently being completed. | |
742 | prefix: |
|
753 | prefix: | |
743 | Part of the text already typed by the user. e.g. `mydict[b'fo` |
|
754 | Part of the text already typed by the user. e.g. `mydict[b'fo` | |
744 | delims: |
|
755 | delims: | |
745 | String of delimiters to consider when finding the current key. |
|
756 | String of delimiters to consider when finding the current key. | |
746 |
|
757 | |||
747 | Returns |
|
758 | Returns | |
748 | ======= |
|
759 | ======= | |
749 |
|
760 | |||
750 | A tuple of three elements: ``quote``, ``token_start``, ``matched``, with |
|
761 | A tuple of three elements: ``quote``, ``token_start``, ``matched``, with | |
751 | ``quote`` being the quote that need to be used to close current string. |
|
762 | ``quote`` being the quote that need to be used to close current string. | |
752 | ``token_start`` the position where the replacement should start occurring, |
|
763 | ``token_start`` the position where the replacement should start occurring, | |
753 | ``matches`` a list of replacement/completion |
|
764 | ``matches`` a list of replacement/completion | |
754 |
|
765 | |||
755 | """ |
|
766 | """ | |
756 | if not prefix: |
|
767 | if not prefix: | |
757 | return None, 0, [repr(k) for k in keys |
|
768 | return None, 0, [repr(k) for k in keys | |
758 | if isinstance(k, (str, bytes))] |
|
769 | if isinstance(k, (str, bytes))] | |
759 | quote_match = re.search('["\']', prefix) |
|
770 | quote_match = re.search('["\']', prefix) | |
760 | quote = quote_match.group() |
|
771 | quote = quote_match.group() | |
761 | try: |
|
772 | try: | |
762 | prefix_str = eval(prefix + quote, {}) |
|
773 | prefix_str = eval(prefix + quote, {}) | |
763 | except Exception: |
|
774 | except Exception: | |
764 | return None, 0, [] |
|
775 | return None, 0, [] | |
765 |
|
776 | |||
766 | pattern = '[^' + ''.join('\\' + c for c in delims) + ']*$' |
|
777 | pattern = '[^' + ''.join('\\' + c for c in delims) + ']*$' | |
767 | token_match = re.search(pattern, prefix, re.UNICODE) |
|
778 | token_match = re.search(pattern, prefix, re.UNICODE) | |
768 | token_start = token_match.start() |
|
779 | token_start = token_match.start() | |
769 | token_prefix = token_match.group() |
|
780 | token_prefix = token_match.group() | |
770 |
|
781 | |||
771 | matched = [] |
|
782 | matched = [] | |
772 | for key in keys: |
|
783 | for key in keys: | |
773 | try: |
|
784 | try: | |
774 | if not key.startswith(prefix_str): |
|
785 | if not key.startswith(prefix_str): | |
775 | continue |
|
786 | continue | |
776 | except (AttributeError, TypeError, UnicodeError): |
|
787 | except (AttributeError, TypeError, UnicodeError): | |
777 | # Python 3+ TypeError on b'a'.startswith('a') or vice-versa |
|
788 | # Python 3+ TypeError on b'a'.startswith('a') or vice-versa | |
778 | continue |
|
789 | continue | |
779 |
|
790 | |||
780 | # reformat remainder of key to begin with prefix |
|
791 | # reformat remainder of key to begin with prefix | |
781 | rem = key[len(prefix_str):] |
|
792 | rem = key[len(prefix_str):] | |
782 | # force repr wrapped in ' |
|
793 | # force repr wrapped in ' | |
783 | rem_repr = repr(rem + '"') if isinstance(rem, str) else repr(rem + b'"') |
|
794 | rem_repr = repr(rem + '"') if isinstance(rem, str) else repr(rem + b'"') | |
784 | if rem_repr.startswith('u') and prefix[0] not in 'uU': |
|
795 | if rem_repr.startswith('u') and prefix[0] not in 'uU': | |
785 | # Found key is unicode, but prefix is Py2 string. |
|
796 | # Found key is unicode, but prefix is Py2 string. | |
786 | # Therefore attempt to interpret key as string. |
|
797 | # Therefore attempt to interpret key as string. | |
787 | try: |
|
798 | try: | |
788 | rem_repr = repr(rem.encode('ascii') + '"') |
|
799 | rem_repr = repr(rem.encode('ascii') + '"') | |
789 | except UnicodeEncodeError: |
|
800 | except UnicodeEncodeError: | |
790 | continue |
|
801 | continue | |
791 |
|
802 | |||
792 | rem_repr = rem_repr[1 + rem_repr.index("'"):-2] |
|
803 | rem_repr = rem_repr[1 + rem_repr.index("'"):-2] | |
793 | if quote == '"': |
|
804 | if quote == '"': | |
794 | # The entered prefix is quoted with ", |
|
805 | # The entered prefix is quoted with ", | |
795 | # but the match is quoted with '. |
|
806 | # but the match is quoted with '. | |
796 | # A contained " hence needs escaping for comparison: |
|
807 | # A contained " hence needs escaping for comparison: | |
797 | rem_repr = rem_repr.replace('"', '\\"') |
|
808 | rem_repr = rem_repr.replace('"', '\\"') | |
798 |
|
809 | |||
799 | # then reinsert prefix from start of token |
|
810 | # then reinsert prefix from start of token | |
800 | matched.append('%s%s' % (token_prefix, rem_repr)) |
|
811 | matched.append('%s%s' % (token_prefix, rem_repr)) | |
801 | return quote, token_start, matched |
|
812 | return quote, token_start, matched | |
802 |
|
813 | |||
803 |
|
814 | |||
804 | def cursor_to_position(text:str, line:int, column:int)->int: |
|
815 | def cursor_to_position(text:str, line:int, column:int)->int: | |
805 | """ |
|
816 | """ | |
806 |
|
817 | |||
807 | Convert the (line,column) position of the cursor in text to an offset in a |
|
818 | Convert the (line,column) position of the cursor in text to an offset in a | |
808 | string. |
|
819 | string. | |
809 |
|
820 | |||
810 | Parameters |
|
821 | Parameters | |
811 | ---------- |
|
822 | ---------- | |
812 |
|
823 | |||
813 | text : str |
|
824 | text : str | |
814 | The text in which to calculate the cursor offset |
|
825 | The text in which to calculate the cursor offset | |
815 | line : int |
|
826 | line : int | |
816 | Line of the cursor; 0-indexed |
|
827 | Line of the cursor; 0-indexed | |
817 | column : int |
|
828 | column : int | |
818 | Column of the cursor 0-indexed |
|
829 | Column of the cursor 0-indexed | |
819 |
|
830 | |||
820 | Return |
|
831 | Return | |
821 | ------ |
|
832 | ------ | |
822 | Position of the cursor in ``text``, 0-indexed. |
|
833 | Position of the cursor in ``text``, 0-indexed. | |
823 |
|
834 | |||
824 | See Also |
|
835 | See Also | |
825 | -------- |
|
836 | -------- | |
826 | position_to_cursor: reciprocal of this function |
|
837 | position_to_cursor: reciprocal of this function | |
827 |
|
838 | |||
828 | """ |
|
839 | """ | |
829 | lines = text.split('\n') |
|
840 | lines = text.split('\n') | |
830 | assert line <= len(lines), '{} <= {}'.format(str(line), str(len(lines))) |
|
841 | assert line <= len(lines), '{} <= {}'.format(str(line), str(len(lines))) | |
831 |
|
842 | |||
832 | return sum(len(l) + 1 for l in lines[:line]) + column |
|
843 | return sum(len(l) + 1 for l in lines[:line]) + column | |
833 |
|
844 | |||
834 | def position_to_cursor(text:str, offset:int)->Tuple[int, int]: |
|
845 | def position_to_cursor(text:str, offset:int)->Tuple[int, int]: | |
835 | """ |
|
846 | """ | |
836 | Convert the position of the cursor in text (0 indexed) to a line |
|
847 | Convert the position of the cursor in text (0 indexed) to a line | |
837 | number(0-indexed) and a column number (0-indexed) pair |
|
848 | number(0-indexed) and a column number (0-indexed) pair | |
838 |
|
849 | |||
839 | Position should be a valid position in ``text``. |
|
850 | Position should be a valid position in ``text``. | |
840 |
|
851 | |||
841 | Parameters |
|
852 | Parameters | |
842 | ---------- |
|
853 | ---------- | |
843 |
|
854 | |||
844 | text : str |
|
855 | text : str | |
845 | The text in which to calculate the cursor offset |
|
856 | The text in which to calculate the cursor offset | |
846 | offset : int |
|
857 | offset : int | |
847 | Position of the cursor in ``text``, 0-indexed. |
|
858 | Position of the cursor in ``text``, 0-indexed. | |
848 |
|
859 | |||
849 | Return |
|
860 | Return | |
850 | ------ |
|
861 | ------ | |
851 | (line, column) : (int, int) |
|
862 | (line, column) : (int, int) | |
852 | Line of the cursor; 0-indexed, column of the cursor 0-indexed |
|
863 | Line of the cursor; 0-indexed, column of the cursor 0-indexed | |
853 |
|
864 | |||
854 |
|
865 | |||
855 | See Also |
|
866 | See Also | |
856 | -------- |
|
867 | -------- | |
857 | cursor_to_position : reciprocal of this function |
|
868 | cursor_to_position : reciprocal of this function | |
858 |
|
869 | |||
859 |
|
870 | |||
860 | """ |
|
871 | """ | |
861 |
|
872 | |||
862 | assert 0 < offset <= len(text) , "0 < %s <= %s" % (offset , len(text)) |
|
873 | assert 0 < offset <= len(text) , "0 < %s <= %s" % (offset , len(text)) | |
863 |
|
874 | |||
864 | before = text[:offset] |
|
875 | before = text[:offset] | |
865 | blines = before.split('\n') # ! splitnes trim trailing \n |
|
876 | blines = before.split('\n') # ! splitnes trim trailing \n | |
866 | line = before.count('\n') |
|
877 | line = before.count('\n') | |
867 | col = len(blines[-1]) |
|
878 | col = len(blines[-1]) | |
868 | return line, col |
|
879 | return line, col | |
869 |
|
880 | |||
870 |
|
881 | |||
871 | def _safe_isinstance(obj, module, class_name): |
|
882 | def _safe_isinstance(obj, module, class_name): | |
872 | """Checks if obj is an instance of module.class_name if loaded |
|
883 | """Checks if obj is an instance of module.class_name if loaded | |
873 | """ |
|
884 | """ | |
874 | return (module in sys.modules and |
|
885 | return (module in sys.modules and | |
875 | isinstance(obj, getattr(import_module(module), class_name))) |
|
886 | isinstance(obj, getattr(import_module(module), class_name))) | |
876 |
|
887 | |||
877 |
|
888 | |||
878 | def back_unicode_name_matches(text): |
|
889 | def back_unicode_name_matches(text): | |
879 | u"""Match unicode characters back to unicode name |
|
890 | u"""Match unicode characters back to unicode name | |
880 |
|
891 | |||
881 | This does ``β`` -> ``\\snowman`` |
|
892 | This does ``β`` -> ``\\snowman`` | |
882 |
|
893 | |||
883 | Note that snowman is not a valid python3 combining character but will be expanded. |
|
894 | Note that snowman is not a valid python3 combining character but will be expanded. | |
884 | Though it will not recombine back to the snowman character by the completion machinery. |
|
895 | Though it will not recombine back to the snowman character by the completion machinery. | |
885 |
|
896 | |||
886 | This will not either back-complete standard sequences like \\n, \\b ... |
|
897 | This will not either back-complete standard sequences like \\n, \\b ... | |
887 |
|
898 | |||
888 | Used on Python 3 only. |
|
899 | Used on Python 3 only. | |
889 | """ |
|
900 | """ | |
890 | if len(text)<2: |
|
901 | if len(text)<2: | |
891 | return u'', () |
|
902 | return u'', () | |
892 | maybe_slash = text[-2] |
|
903 | maybe_slash = text[-2] | |
893 | if maybe_slash != '\\': |
|
904 | if maybe_slash != '\\': | |
894 | return u'', () |
|
905 | return u'', () | |
895 |
|
906 | |||
896 | char = text[-1] |
|
907 | char = text[-1] | |
897 | # no expand on quote for completion in strings. |
|
908 | # no expand on quote for completion in strings. | |
898 | # nor backcomplete standard ascii keys |
|
909 | # nor backcomplete standard ascii keys | |
899 | if char in string.ascii_letters or char in ['"',"'"]: |
|
910 | if char in string.ascii_letters or char in ['"',"'"]: | |
900 | return u'', () |
|
911 | return u'', () | |
901 | try : |
|
912 | try : | |
902 | unic = unicodedata.name(char) |
|
913 | unic = unicodedata.name(char) | |
903 | return '\\'+char,['\\'+unic] |
|
914 | return '\\'+char,['\\'+unic] | |
904 | except KeyError: |
|
915 | except KeyError: | |
905 | pass |
|
916 | pass | |
906 | return u'', () |
|
917 | return u'', () | |
907 |
|
918 | |||
908 | def back_latex_name_matches(text:str): |
|
919 | def back_latex_name_matches(text:str): | |
909 | """Match latex characters back to unicode name |
|
920 | """Match latex characters back to unicode name | |
910 |
|
921 | |||
911 | This does ``\\β΅`` -> ``\\aleph`` |
|
922 | This does ``\\β΅`` -> ``\\aleph`` | |
912 |
|
923 | |||
913 | Used on Python 3 only. |
|
924 | Used on Python 3 only. | |
914 | """ |
|
925 | """ | |
915 | if len(text)<2: |
|
926 | if len(text)<2: | |
916 | return u'', () |
|
927 | return u'', () | |
917 | maybe_slash = text[-2] |
|
928 | maybe_slash = text[-2] | |
918 | if maybe_slash != '\\': |
|
929 | if maybe_slash != '\\': | |
919 | return u'', () |
|
930 | return u'', () | |
920 |
|
931 | |||
921 |
|
932 | |||
922 | char = text[-1] |
|
933 | char = text[-1] | |
923 | # no expand on quote for completion in strings. |
|
934 | # no expand on quote for completion in strings. | |
924 | # nor backcomplete standard ascii keys |
|
935 | # nor backcomplete standard ascii keys | |
925 | if char in string.ascii_letters or char in ['"',"'"]: |
|
936 | if char in string.ascii_letters or char in ['"',"'"]: | |
926 | return u'', () |
|
937 | return u'', () | |
927 | try : |
|
938 | try : | |
928 | latex = reverse_latex_symbol[char] |
|
939 | latex = reverse_latex_symbol[char] | |
929 | # '\\' replace the \ as well |
|
940 | # '\\' replace the \ as well | |
930 | return '\\'+char,[latex] |
|
941 | return '\\'+char,[latex] | |
931 | except KeyError: |
|
942 | except KeyError: | |
932 | pass |
|
943 | pass | |
933 | return u'', () |
|
944 | return u'', () | |
934 |
|
945 | |||
935 |
|
946 | |||
|
947 | def _formatparamchildren(parameter) -> str: | |||
|
948 | """ | |||
|
949 | Get parameter name and value from Jedi Private API | |||
|
950 | ||||
|
951 | Jedi does not expose a simple way to get `param=value` from its API. | |||
|
952 | ||||
|
953 | Prameter | |||
|
954 | ======== | |||
|
955 | ||||
|
956 | parameter: | |||
|
957 | Jedi's function `Param` | |||
|
958 | ||||
|
959 | Returns | |||
|
960 | ======= | |||
|
961 | ||||
|
962 | A string like 'a', 'b=1', '*args', '**kwargs' | |||
|
963 | ||||
|
964 | ||||
|
965 | """ | |||
|
966 | description = parameter.description | |||
|
967 | if not description.startswith('param '): | |||
|
968 | raise ValueError('Jedi function parameter description have change format.' | |||
|
969 | 'Expected "param ...", found %r".' % description) | |||
|
970 | return description[6:] | |||
|
971 | ||||
|
972 | def _make_signature(completion)-> str: | |||
|
973 | """ | |||
|
974 | Make the signature from a jedi completion | |||
|
975 | ||||
|
976 | Parameter | |||
|
977 | ========= | |||
|
978 | ||||
|
979 | completion: jedi.Completion | |||
|
980 | object does not complete a function type | |||
|
981 | ||||
|
982 | Returns | |||
|
983 | ======= | |||
|
984 | ||||
|
985 | a string consisting of the function signature, with the parenthesis but | |||
|
986 | without the function name. example: | |||
|
987 | `(a, *args, b=1, **kwargs)` | |||
|
988 | ||||
|
989 | """ | |||
|
990 | ||||
|
991 | return '(%s)'% ', '.join([f for f in (_formatparamchildren(p) for p in completion.params) if f]) | |||
|
992 | ||||
936 | class IPCompleter(Completer): |
|
993 | class IPCompleter(Completer): | |
937 | """Extension of the completer class with IPython-specific features""" |
|
994 | """Extension of the completer class with IPython-specific features""" | |
938 |
|
995 | |||
939 | @observe('greedy') |
|
996 | @observe('greedy') | |
940 | def _greedy_changed(self, change): |
|
997 | def _greedy_changed(self, change): | |
941 | """update the splitter and readline delims when greedy is changed""" |
|
998 | """update the splitter and readline delims when greedy is changed""" | |
942 | if change['new']: |
|
999 | if change['new']: | |
943 | self.splitter.delims = GREEDY_DELIMS |
|
1000 | self.splitter.delims = GREEDY_DELIMS | |
944 | else: |
|
1001 | else: | |
945 | self.splitter.delims = DELIMS |
|
1002 | self.splitter.delims = DELIMS | |
946 |
|
1003 | |||
947 | merge_completions = Bool(True, |
|
1004 | merge_completions = Bool(True, | |
948 | help="""Whether to merge completion results into a single list |
|
1005 | help="""Whether to merge completion results into a single list | |
949 |
|
1006 | |||
950 | If False, only the completion results from the first non-empty |
|
1007 | If False, only the completion results from the first non-empty | |
951 | completer will be returned. |
|
1008 | completer will be returned. | |
952 | """ |
|
1009 | """ | |
953 | ).tag(config=True) |
|
1010 | ).tag(config=True) | |
954 | omit__names = Enum((0,1,2), default_value=2, |
|
1011 | omit__names = Enum((0,1,2), default_value=2, | |
955 | help="""Instruct the completer to omit private method names |
|
1012 | help="""Instruct the completer to omit private method names | |
956 |
|
1013 | |||
957 | Specifically, when completing on ``object.<tab>``. |
|
1014 | Specifically, when completing on ``object.<tab>``. | |
958 |
|
1015 | |||
959 | When 2 [default]: all names that start with '_' will be excluded. |
|
1016 | When 2 [default]: all names that start with '_' will be excluded. | |
960 |
|
1017 | |||
961 | When 1: all 'magic' names (``__foo__``) will be excluded. |
|
1018 | When 1: all 'magic' names (``__foo__``) will be excluded. | |
962 |
|
1019 | |||
963 | When 0: nothing will be excluded. |
|
1020 | When 0: nothing will be excluded. | |
964 | """ |
|
1021 | """ | |
965 | ).tag(config=True) |
|
1022 | ).tag(config=True) | |
966 | limit_to__all__ = Bool(False, |
|
1023 | limit_to__all__ = Bool(False, | |
967 | help=""" |
|
1024 | help=""" | |
968 | DEPRECATED as of version 5.0. |
|
1025 | DEPRECATED as of version 5.0. | |
969 |
|
1026 | |||
970 | Instruct the completer to use __all__ for the completion |
|
1027 | Instruct the completer to use __all__ for the completion | |
971 |
|
1028 | |||
972 | Specifically, when completing on ``object.<tab>``. |
|
1029 | Specifically, when completing on ``object.<tab>``. | |
973 |
|
1030 | |||
974 | When True: only those names in obj.__all__ will be included. |
|
1031 | When True: only those names in obj.__all__ will be included. | |
975 |
|
1032 | |||
976 | When False [default]: the __all__ attribute is ignored |
|
1033 | When False [default]: the __all__ attribute is ignored | |
977 | """, |
|
1034 | """, | |
978 | ).tag(config=True) |
|
1035 | ).tag(config=True) | |
979 |
|
1036 | |||
980 | @observe('limit_to__all__') |
|
1037 | @observe('limit_to__all__') | |
981 | def _limit_to_all_changed(self, change): |
|
1038 | def _limit_to_all_changed(self, change): | |
982 | warnings.warn('`IPython.core.IPCompleter.limit_to__all__` configuration ' |
|
1039 | warnings.warn('`IPython.core.IPCompleter.limit_to__all__` configuration ' | |
983 | 'value has been deprecated since IPython 5.0, will be made to have ' |
|
1040 | 'value has been deprecated since IPython 5.0, will be made to have ' | |
984 | 'no effects and then removed in future version of IPython.', |
|
1041 | 'no effects and then removed in future version of IPython.', | |
985 | UserWarning) |
|
1042 | UserWarning) | |
986 |
|
1043 | |||
987 | def __init__(self, shell=None, namespace=None, global_namespace=None, |
|
1044 | def __init__(self, shell=None, namespace=None, global_namespace=None, | |
988 | use_readline=_deprecation_readline_sentinel, config=None, **kwargs): |
|
1045 | use_readline=_deprecation_readline_sentinel, config=None, **kwargs): | |
989 | """IPCompleter() -> completer |
|
1046 | """IPCompleter() -> completer | |
990 |
|
1047 | |||
991 | Return a completer object. |
|
1048 | Return a completer object. | |
992 |
|
1049 | |||
993 | Parameters |
|
1050 | Parameters | |
994 | ---------- |
|
1051 | ---------- | |
995 |
|
1052 | |||
996 | shell |
|
1053 | shell | |
997 | a pointer to the ipython shell itself. This is needed |
|
1054 | a pointer to the ipython shell itself. This is needed | |
998 | because this completer knows about magic functions, and those can |
|
1055 | because this completer knows about magic functions, and those can | |
999 | only be accessed via the ipython instance. |
|
1056 | only be accessed via the ipython instance. | |
1000 |
|
1057 | |||
1001 | namespace : dict, optional |
|
1058 | namespace : dict, optional | |
1002 | an optional dict where completions are performed. |
|
1059 | an optional dict where completions are performed. | |
1003 |
|
1060 | |||
1004 | global_namespace : dict, optional |
|
1061 | global_namespace : dict, optional | |
1005 | secondary optional dict for completions, to |
|
1062 | secondary optional dict for completions, to | |
1006 | handle cases (such as IPython embedded inside functions) where |
|
1063 | handle cases (such as IPython embedded inside functions) where | |
1007 | both Python scopes are visible. |
|
1064 | both Python scopes are visible. | |
1008 |
|
1065 | |||
1009 | use_readline : bool, optional |
|
1066 | use_readline : bool, optional | |
1010 | DEPRECATED, ignored since IPython 6.0, will have no effects |
|
1067 | DEPRECATED, ignored since IPython 6.0, will have no effects | |
1011 | """ |
|
1068 | """ | |
1012 |
|
1069 | |||
1013 | self.magic_escape = ESC_MAGIC |
|
1070 | self.magic_escape = ESC_MAGIC | |
1014 | self.splitter = CompletionSplitter() |
|
1071 | self.splitter = CompletionSplitter() | |
1015 |
|
1072 | |||
1016 | if use_readline is not _deprecation_readline_sentinel: |
|
1073 | if use_readline is not _deprecation_readline_sentinel: | |
1017 | warnings.warn('The `use_readline` parameter is deprecated and ignored since IPython 6.0.', |
|
1074 | warnings.warn('The `use_readline` parameter is deprecated and ignored since IPython 6.0.', | |
1018 | DeprecationWarning, stacklevel=2) |
|
1075 | DeprecationWarning, stacklevel=2) | |
1019 |
|
1076 | |||
1020 | # _greedy_changed() depends on splitter and readline being defined: |
|
1077 | # _greedy_changed() depends on splitter and readline being defined: | |
1021 | Completer.__init__(self, namespace=namespace, global_namespace=global_namespace, |
|
1078 | Completer.__init__(self, namespace=namespace, global_namespace=global_namespace, | |
1022 | config=config, **kwargs) |
|
1079 | config=config, **kwargs) | |
1023 |
|
1080 | |||
1024 | # List where completion matches will be stored |
|
1081 | # List where completion matches will be stored | |
1025 | self.matches = [] |
|
1082 | self.matches = [] | |
1026 | self.shell = shell |
|
1083 | self.shell = shell | |
1027 | # Regexp to split filenames with spaces in them |
|
1084 | # Regexp to split filenames with spaces in them | |
1028 | self.space_name_re = re.compile(r'([^\\] )') |
|
1085 | self.space_name_re = re.compile(r'([^\\] )') | |
1029 | # Hold a local ref. to glob.glob for speed |
|
1086 | # Hold a local ref. to glob.glob for speed | |
1030 | self.glob = glob.glob |
|
1087 | self.glob = glob.glob | |
1031 |
|
1088 | |||
1032 | # Determine if we are running on 'dumb' terminals, like (X)Emacs |
|
1089 | # Determine if we are running on 'dumb' terminals, like (X)Emacs | |
1033 | # buffers, to avoid completion problems. |
|
1090 | # buffers, to avoid completion problems. | |
1034 | term = os.environ.get('TERM','xterm') |
|
1091 | term = os.environ.get('TERM','xterm') | |
1035 | self.dumb_terminal = term in ['dumb','emacs'] |
|
1092 | self.dumb_terminal = term in ['dumb','emacs'] | |
1036 |
|
1093 | |||
1037 | # Special handling of backslashes needed in win32 platforms |
|
1094 | # Special handling of backslashes needed in win32 platforms | |
1038 | if sys.platform == "win32": |
|
1095 | if sys.platform == "win32": | |
1039 | self.clean_glob = self._clean_glob_win32 |
|
1096 | self.clean_glob = self._clean_glob_win32 | |
1040 | else: |
|
1097 | else: | |
1041 | self.clean_glob = self._clean_glob |
|
1098 | self.clean_glob = self._clean_glob | |
1042 |
|
1099 | |||
1043 | #regexp to parse docstring for function signature |
|
1100 | #regexp to parse docstring for function signature | |
1044 | self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*') |
|
1101 | self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*') | |
1045 | self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)') |
|
1102 | self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)') | |
1046 | #use this if positional argument name is also needed |
|
1103 | #use this if positional argument name is also needed | |
1047 | #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)') |
|
1104 | #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)') | |
1048 |
|
1105 | |||
1049 | # All active matcher routines for completion |
|
1106 | # All active matcher routines for completion | |
1050 | self.matchers = [ |
|
1107 | self.matchers = [ | |
1051 | self.python_matches, |
|
1108 | self.python_matches, | |
1052 | self.file_matches, |
|
1109 | self.file_matches, | |
1053 | self.magic_matches, |
|
1110 | self.magic_matches, | |
1054 | self.python_func_kw_matches, |
|
1111 | self.python_func_kw_matches, | |
1055 | self.dict_key_matches, |
|
1112 | self.dict_key_matches, | |
1056 | ] |
|
1113 | ] | |
1057 | self.magic_arg_matchers = [ |
|
1114 | self.magic_arg_matchers = [ | |
1058 | self.magic_config_matches, |
|
1115 | self.magic_config_matches, | |
1059 | self.magic_color_matches, |
|
1116 | self.magic_color_matches, | |
1060 | ] |
|
1117 | ] | |
1061 |
|
1118 | |||
1062 | # This is set externally by InteractiveShell |
|
1119 | # This is set externally by InteractiveShell | |
1063 | self.custom_completers = None |
|
1120 | self.custom_completers = None | |
1064 |
|
1121 | |||
1065 | def all_completions(self, text): |
|
1122 | def all_completions(self, text): | |
1066 | """ |
|
1123 | """ | |
1067 | Wrapper around the complete method for the benefit of emacs. |
|
1124 | Wrapper around the complete method for the benefit of emacs. | |
1068 | """ |
|
1125 | """ | |
1069 | return self.complete(text)[1] |
|
1126 | return self.complete(text)[1] | |
1070 |
|
1127 | |||
1071 | def _clean_glob(self, text): |
|
1128 | def _clean_glob(self, text): | |
1072 | return self.glob("%s*" % text) |
|
1129 | return self.glob("%s*" % text) | |
1073 |
|
1130 | |||
1074 | def _clean_glob_win32(self,text): |
|
1131 | def _clean_glob_win32(self,text): | |
1075 | return [f.replace("\\","/") |
|
1132 | return [f.replace("\\","/") | |
1076 | for f in self.glob("%s*" % text)] |
|
1133 | for f in self.glob("%s*" % text)] | |
1077 |
|
1134 | |||
1078 | def file_matches(self, text): |
|
1135 | def file_matches(self, text): | |
1079 | """Match filenames, expanding ~USER type strings. |
|
1136 | """Match filenames, expanding ~USER type strings. | |
1080 |
|
1137 | |||
1081 | Most of the seemingly convoluted logic in this completer is an |
|
1138 | Most of the seemingly convoluted logic in this completer is an | |
1082 | attempt to handle filenames with spaces in them. And yet it's not |
|
1139 | attempt to handle filenames with spaces in them. And yet it's not | |
1083 | quite perfect, because Python's readline doesn't expose all of the |
|
1140 | quite perfect, because Python's readline doesn't expose all of the | |
1084 | GNU readline details needed for this to be done correctly. |
|
1141 | GNU readline details needed for this to be done correctly. | |
1085 |
|
1142 | |||
1086 | For a filename with a space in it, the printed completions will be |
|
1143 | For a filename with a space in it, the printed completions will be | |
1087 | only the parts after what's already been typed (instead of the |
|
1144 | only the parts after what's already been typed (instead of the | |
1088 | full completions, as is normally done). I don't think with the |
|
1145 | full completions, as is normally done). I don't think with the | |
1089 | current (as of Python 2.3) Python readline it's possible to do |
|
1146 | current (as of Python 2.3) Python readline it's possible to do | |
1090 | better.""" |
|
1147 | better.""" | |
1091 |
|
1148 | |||
1092 | # chars that require escaping with backslash - i.e. chars |
|
1149 | # chars that require escaping with backslash - i.e. chars | |
1093 | # that readline treats incorrectly as delimiters, but we |
|
1150 | # that readline treats incorrectly as delimiters, but we | |
1094 | # don't want to treat as delimiters in filename matching |
|
1151 | # don't want to treat as delimiters in filename matching | |
1095 | # when escaped with backslash |
|
1152 | # when escaped with backslash | |
1096 | if text.startswith('!'): |
|
1153 | if text.startswith('!'): | |
1097 | text = text[1:] |
|
1154 | text = text[1:] | |
1098 | text_prefix = u'!' |
|
1155 | text_prefix = u'!' | |
1099 | else: |
|
1156 | else: | |
1100 | text_prefix = u'' |
|
1157 | text_prefix = u'' | |
1101 |
|
1158 | |||
1102 | text_until_cursor = self.text_until_cursor |
|
1159 | text_until_cursor = self.text_until_cursor | |
1103 | # track strings with open quotes |
|
1160 | # track strings with open quotes | |
1104 | open_quotes = has_open_quotes(text_until_cursor) |
|
1161 | open_quotes = has_open_quotes(text_until_cursor) | |
1105 |
|
1162 | |||
1106 | if '(' in text_until_cursor or '[' in text_until_cursor: |
|
1163 | if '(' in text_until_cursor or '[' in text_until_cursor: | |
1107 | lsplit = text |
|
1164 | lsplit = text | |
1108 | else: |
|
1165 | else: | |
1109 | try: |
|
1166 | try: | |
1110 | # arg_split ~ shlex.split, but with unicode bugs fixed by us |
|
1167 | # arg_split ~ shlex.split, but with unicode bugs fixed by us | |
1111 | lsplit = arg_split(text_until_cursor)[-1] |
|
1168 | lsplit = arg_split(text_until_cursor)[-1] | |
1112 | except ValueError: |
|
1169 | except ValueError: | |
1113 | # typically an unmatched ", or backslash without escaped char. |
|
1170 | # typically an unmatched ", or backslash without escaped char. | |
1114 | if open_quotes: |
|
1171 | if open_quotes: | |
1115 | lsplit = text_until_cursor.split(open_quotes)[-1] |
|
1172 | lsplit = text_until_cursor.split(open_quotes)[-1] | |
1116 | else: |
|
1173 | else: | |
1117 | return [] |
|
1174 | return [] | |
1118 | except IndexError: |
|
1175 | except IndexError: | |
1119 | # tab pressed on empty line |
|
1176 | # tab pressed on empty line | |
1120 | lsplit = "" |
|
1177 | lsplit = "" | |
1121 |
|
1178 | |||
1122 | if not open_quotes and lsplit != protect_filename(lsplit): |
|
1179 | if not open_quotes and lsplit != protect_filename(lsplit): | |
1123 | # if protectables are found, do matching on the whole escaped name |
|
1180 | # if protectables are found, do matching on the whole escaped name | |
1124 | has_protectables = True |
|
1181 | has_protectables = True | |
1125 | text0,text = text,lsplit |
|
1182 | text0,text = text,lsplit | |
1126 | else: |
|
1183 | else: | |
1127 | has_protectables = False |
|
1184 | has_protectables = False | |
1128 | text = os.path.expanduser(text) |
|
1185 | text = os.path.expanduser(text) | |
1129 |
|
1186 | |||
1130 | if text == "": |
|
1187 | if text == "": | |
1131 | return [text_prefix + protect_filename(f) for f in self.glob("*")] |
|
1188 | return [text_prefix + protect_filename(f) for f in self.glob("*")] | |
1132 |
|
1189 | |||
1133 | # Compute the matches from the filesystem |
|
1190 | # Compute the matches from the filesystem | |
1134 | if sys.platform == 'win32': |
|
1191 | if sys.platform == 'win32': | |
1135 | m0 = self.clean_glob(text) |
|
1192 | m0 = self.clean_glob(text) | |
1136 | else: |
|
1193 | else: | |
1137 | m0 = self.clean_glob(text.replace('\\', '')) |
|
1194 | m0 = self.clean_glob(text.replace('\\', '')) | |
1138 |
|
1195 | |||
1139 | if has_protectables: |
|
1196 | if has_protectables: | |
1140 | # If we had protectables, we need to revert our changes to the |
|
1197 | # If we had protectables, we need to revert our changes to the | |
1141 | # beginning of filename so that we don't double-write the part |
|
1198 | # beginning of filename so that we don't double-write the part | |
1142 | # of the filename we have so far |
|
1199 | # of the filename we have so far | |
1143 | len_lsplit = len(lsplit) |
|
1200 | len_lsplit = len(lsplit) | |
1144 | matches = [text_prefix + text0 + |
|
1201 | matches = [text_prefix + text0 + | |
1145 | protect_filename(f[len_lsplit:]) for f in m0] |
|
1202 | protect_filename(f[len_lsplit:]) for f in m0] | |
1146 | else: |
|
1203 | else: | |
1147 | if open_quotes: |
|
1204 | if open_quotes: | |
1148 | # if we have a string with an open quote, we don't need to |
|
1205 | # if we have a string with an open quote, we don't need to | |
1149 | # protect the names beyond the quote (and we _shouldn't_, as |
|
1206 | # protect the names beyond the quote (and we _shouldn't_, as | |
1150 | # it would cause bugs when the filesystem call is made). |
|
1207 | # it would cause bugs when the filesystem call is made). | |
1151 | matches = m0 if sys.platform == "win32" else\ |
|
1208 | matches = m0 if sys.platform == "win32" else\ | |
1152 | [protect_filename(f, open_quotes) for f in m0] |
|
1209 | [protect_filename(f, open_quotes) for f in m0] | |
1153 | else: |
|
1210 | else: | |
1154 | matches = [text_prefix + |
|
1211 | matches = [text_prefix + | |
1155 | protect_filename(f) for f in m0] |
|
1212 | protect_filename(f) for f in m0] | |
1156 |
|
1213 | |||
1157 | # Mark directories in input list by appending '/' to their names. |
|
1214 | # Mark directories in input list by appending '/' to their names. | |
1158 | return [x+'/' if os.path.isdir(x) else x for x in matches] |
|
1215 | return [x+'/' if os.path.isdir(x) else x for x in matches] | |
1159 |
|
1216 | |||
1160 | def magic_matches(self, text): |
|
1217 | def magic_matches(self, text): | |
1161 | """Match magics""" |
|
1218 | """Match magics""" | |
1162 | # Get all shell magics now rather than statically, so magics loaded at |
|
1219 | # Get all shell magics now rather than statically, so magics loaded at | |
1163 | # runtime show up too. |
|
1220 | # runtime show up too. | |
1164 | lsm = self.shell.magics_manager.lsmagic() |
|
1221 | lsm = self.shell.magics_manager.lsmagic() | |
1165 | line_magics = lsm['line'] |
|
1222 | line_magics = lsm['line'] | |
1166 | cell_magics = lsm['cell'] |
|
1223 | cell_magics = lsm['cell'] | |
1167 | pre = self.magic_escape |
|
1224 | pre = self.magic_escape | |
1168 | pre2 = pre+pre |
|
1225 | pre2 = pre+pre | |
1169 |
|
1226 | |||
1170 | # Completion logic: |
|
1227 | # Completion logic: | |
1171 | # - user gives %%: only do cell magics |
|
1228 | # - user gives %%: only do cell magics | |
1172 | # - user gives %: do both line and cell magics |
|
1229 | # - user gives %: do both line and cell magics | |
1173 | # - no prefix: do both |
|
1230 | # - no prefix: do both | |
1174 | # In other words, line magics are skipped if the user gives %% explicitly |
|
1231 | # In other words, line magics are skipped if the user gives %% explicitly | |
1175 | # |
|
1232 | # | |
1176 | # We also exclude magics that match any currently visible names: |
|
1233 | # We also exclude magics that match any currently visible names: | |
1177 | # https://github.com/ipython/ipython/issues/4877 |
|
1234 | # https://github.com/ipython/ipython/issues/4877 | |
1178 | bare_text = text.lstrip(pre) |
|
1235 | bare_text = text.lstrip(pre) | |
1179 | global_matches = self.global_matches(bare_text) |
|
1236 | global_matches = self.global_matches(bare_text) | |
1180 | matches = lambda magic: magic.startswith(bare_text) \ |
|
1237 | matches = lambda magic: magic.startswith(bare_text) \ | |
1181 | and magic not in global_matches |
|
1238 | and magic not in global_matches | |
1182 | comp = [ pre2+m for m in cell_magics if matches(m)] |
|
1239 | comp = [ pre2+m for m in cell_magics if matches(m)] | |
1183 | if not text.startswith(pre2): |
|
1240 | if not text.startswith(pre2): | |
1184 | comp += [ pre+m for m in line_magics if matches(m)] |
|
1241 | comp += [ pre+m for m in line_magics if matches(m)] | |
1185 |
|
1242 | |||
1186 | return comp |
|
1243 | return comp | |
1187 |
|
1244 | |||
1188 | def magic_config_matches(self, text:str) -> List[str]: |
|
1245 | def magic_config_matches(self, text:str) -> List[str]: | |
1189 | """ Match class names and attributes for %config magic """ |
|
1246 | """ Match class names and attributes for %config magic """ | |
1190 | texts = text.strip().split() |
|
1247 | texts = text.strip().split() | |
1191 |
|
1248 | |||
1192 | if len(texts) > 0 and (texts[0] == 'config' or texts[0] == '%config'): |
|
1249 | if len(texts) > 0 and (texts[0] == 'config' or texts[0] == '%config'): | |
1193 | # get all configuration classes |
|
1250 | # get all configuration classes | |
1194 | classes = sorted(set([ c for c in self.shell.configurables |
|
1251 | classes = sorted(set([ c for c in self.shell.configurables | |
1195 | if c.__class__.class_traits(config=True) |
|
1252 | if c.__class__.class_traits(config=True) | |
1196 | ]), key=lambda x: x.__class__.__name__) |
|
1253 | ]), key=lambda x: x.__class__.__name__) | |
1197 | classnames = [ c.__class__.__name__ for c in classes ] |
|
1254 | classnames = [ c.__class__.__name__ for c in classes ] | |
1198 |
|
1255 | |||
1199 | # return all classnames if config or %config is given |
|
1256 | # return all classnames if config or %config is given | |
1200 | if len(texts) == 1: |
|
1257 | if len(texts) == 1: | |
1201 | return classnames |
|
1258 | return classnames | |
1202 |
|
1259 | |||
1203 | # match classname |
|
1260 | # match classname | |
1204 | classname_texts = texts[1].split('.') |
|
1261 | classname_texts = texts[1].split('.') | |
1205 | classname = classname_texts[0] |
|
1262 | classname = classname_texts[0] | |
1206 | classname_matches = [ c for c in classnames |
|
1263 | classname_matches = [ c for c in classnames | |
1207 | if c.startswith(classname) ] |
|
1264 | if c.startswith(classname) ] | |
1208 |
|
1265 | |||
1209 | # return matched classes or the matched class with attributes |
|
1266 | # return matched classes or the matched class with attributes | |
1210 | if texts[1].find('.') < 0: |
|
1267 | if texts[1].find('.') < 0: | |
1211 | return classname_matches |
|
1268 | return classname_matches | |
1212 | elif len(classname_matches) == 1 and \ |
|
1269 | elif len(classname_matches) == 1 and \ | |
1213 | classname_matches[0] == classname: |
|
1270 | classname_matches[0] == classname: | |
1214 | cls = classes[classnames.index(classname)].__class__ |
|
1271 | cls = classes[classnames.index(classname)].__class__ | |
1215 | help = cls.class_get_help() |
|
1272 | help = cls.class_get_help() | |
1216 | # strip leading '--' from cl-args: |
|
1273 | # strip leading '--' from cl-args: | |
1217 | help = re.sub(re.compile(r'^--', re.MULTILINE), '', help) |
|
1274 | help = re.sub(re.compile(r'^--', re.MULTILINE), '', help) | |
1218 | return [ attr.split('=')[0] |
|
1275 | return [ attr.split('=')[0] | |
1219 | for attr in help.strip().splitlines() |
|
1276 | for attr in help.strip().splitlines() | |
1220 | if attr.startswith(texts[1]) ] |
|
1277 | if attr.startswith(texts[1]) ] | |
1221 | return [] |
|
1278 | return [] | |
1222 |
|
1279 | |||
1223 | def magic_color_matches(self, text:str) -> List[str] : |
|
1280 | def magic_color_matches(self, text:str) -> List[str] : | |
1224 | """ Match color schemes for %colors magic""" |
|
1281 | """ Match color schemes for %colors magic""" | |
1225 | texts = text.strip().split() |
|
1282 | texts = text.strip().split() | |
1226 |
|
1283 | |||
1227 | if len(texts) > 0 and (texts[0] == 'colors' or texts[0] == '%colors'): |
|
1284 | if len(texts) > 0 and (texts[0] == 'colors' or texts[0] == '%colors'): | |
1228 | prefix = texts[1] if len(texts) > 1 else '' |
|
1285 | prefix = texts[1] if len(texts) > 1 else '' | |
1229 | return [ color for color in InspectColors.keys() |
|
1286 | return [ color for color in InspectColors.keys() | |
1230 | if color.startswith(prefix) ] |
|
1287 | if color.startswith(prefix) ] | |
1231 | return [] |
|
1288 | return [] | |
1232 |
|
1289 | |||
1233 | def _jedi_matches(self, cursor_column:int, cursor_line:int, text:str): |
|
1290 | def _jedi_matches(self, cursor_column:int, cursor_line:int, text:str): | |
1234 | """ |
|
1291 | """ | |
1235 |
|
1292 | |||
1236 | Return a list of :any:`jedi.api.Completions` object from a ``text`` and |
|
1293 | Return a list of :any:`jedi.api.Completions` object from a ``text`` and | |
1237 | cursor position. |
|
1294 | cursor position. | |
1238 |
|
1295 | |||
1239 | Parameters |
|
1296 | Parameters | |
1240 | ---------- |
|
1297 | ---------- | |
1241 | cursor_column : int |
|
1298 | cursor_column : int | |
1242 | column position of the cursor in ``text``, 0-indexed. |
|
1299 | column position of the cursor in ``text``, 0-indexed. | |
1243 | cursor_line : int |
|
1300 | cursor_line : int | |
1244 | line position of the cursor in ``text``, 0-indexed |
|
1301 | line position of the cursor in ``text``, 0-indexed | |
1245 | text : str |
|
1302 | text : str | |
1246 | text to complete |
|
1303 | text to complete | |
1247 |
|
1304 | |||
1248 | Debugging |
|
1305 | Debugging | |
1249 | --------- |
|
1306 | --------- | |
1250 |
|
1307 | |||
1251 | If ``IPCompleter.debug`` is ``True`` may return a :any:`_FakeJediCompletion` |
|
1308 | If ``IPCompleter.debug`` is ``True`` may return a :any:`_FakeJediCompletion` | |
1252 | object containing a string with the Jedi debug information attached. |
|
1309 | object containing a string with the Jedi debug information attached. | |
1253 | """ |
|
1310 | """ | |
1254 | namespaces = [self.namespace] |
|
1311 | namespaces = [self.namespace] | |
1255 | if self.global_namespace is not None: |
|
1312 | if self.global_namespace is not None: | |
1256 | namespaces.append(self.global_namespace) |
|
1313 | namespaces.append(self.global_namespace) | |
1257 |
|
1314 | |||
1258 | completion_filter = lambda x:x |
|
1315 | completion_filter = lambda x:x | |
1259 | # cursor_pos is an it, jedi wants line and column |
|
1316 | # cursor_pos is an it, jedi wants line and column | |
1260 | offset = cursor_to_position(text, cursor_line, cursor_column) |
|
1317 | offset = cursor_to_position(text, cursor_line, cursor_column) | |
1261 | # filter output if we are completing for object members |
|
1318 | # filter output if we are completing for object members | |
1262 | if offset: |
|
1319 | if offset: | |
1263 | pre = text[offset-1] |
|
1320 | pre = text[offset-1] | |
1264 | if pre == '.': |
|
1321 | if pre == '.': | |
1265 | if self.omit__names == 2: |
|
1322 | if self.omit__names == 2: | |
1266 | completion_filter = lambda c:not c.name.startswith('_') |
|
1323 | completion_filter = lambda c:not c.name.startswith('_') | |
1267 | elif self.omit__names == 1: |
|
1324 | elif self.omit__names == 1: | |
1268 | completion_filter = lambda c:not (c.name.startswith('__') and c.name.endswith('__')) |
|
1325 | completion_filter = lambda c:not (c.name.startswith('__') and c.name.endswith('__')) | |
1269 | elif self.omit__names == 0: |
|
1326 | elif self.omit__names == 0: | |
1270 | completion_filter = lambda x:x |
|
1327 | completion_filter = lambda x:x | |
1271 | else: |
|
1328 | else: | |
1272 | raise ValueError("Don't understand self.omit__names == {}".format(self.omit__names)) |
|
1329 | raise ValueError("Don't understand self.omit__names == {}".format(self.omit__names)) | |
1273 |
|
1330 | |||
1274 | interpreter = jedi.Interpreter( |
|
1331 | interpreter = jedi.Interpreter( | |
1275 | text, namespaces, column=cursor_column, line=cursor_line + 1) |
|
1332 | text, namespaces, column=cursor_column, line=cursor_line + 1) | |
1276 |
|
1333 | |||
1277 | try_jedi = False |
|
1334 | try_jedi = False | |
1278 |
|
1335 | |||
1279 | try: |
|
1336 | try: | |
1280 | # should we check the type of the node is Error ? |
|
1337 | # should we check the type of the node is Error ? | |
1281 | from jedi.parser.tree import ErrorLeaf |
|
1338 | from jedi.parser.tree import ErrorLeaf | |
1282 | next_to_last_tree = interpreter._get_module().tree_node.children[-2] |
|
1339 | next_to_last_tree = interpreter._get_module().tree_node.children[-2] | |
1283 | completing_string = False |
|
1340 | completing_string = False | |
1284 | if isinstance(next_to_last_tree, ErrorLeaf): |
|
1341 | if isinstance(next_to_last_tree, ErrorLeaf): | |
1285 | completing_string = interpreter._get_module().tree_node.children[-2].value[0] in {'"', "'"} |
|
1342 | completing_string = interpreter._get_module().tree_node.children[-2].value[0] in {'"', "'"} | |
1286 | # if we are in a string jedi is likely not the right candidate for |
|
1343 | # if we are in a string jedi is likely not the right candidate for | |
1287 | # now. Skip it. |
|
1344 | # now. Skip it. | |
1288 | try_jedi = not completing_string |
|
1345 | try_jedi = not completing_string | |
1289 | except Exception as e: |
|
1346 | except Exception as e: | |
1290 | # many of things can go wrong, we are using private API just don't crash. |
|
1347 | # many of things can go wrong, we are using private API just don't crash. | |
1291 | if self.debug: |
|
1348 | if self.debug: | |
1292 | print("Error detecting if completing a non-finished string :", e, '|') |
|
1349 | print("Error detecting if completing a non-finished string :", e, '|') | |
1293 |
|
1350 | |||
1294 | if not try_jedi: |
|
1351 | if not try_jedi: | |
1295 | return [] |
|
1352 | return [] | |
1296 | try: |
|
1353 | try: | |
1297 | return filter(completion_filter, interpreter.completions()) |
|
1354 | return filter(completion_filter, interpreter.completions()) | |
1298 | except Exception as e: |
|
1355 | except Exception as e: | |
1299 | if self.debug: |
|
1356 | if self.debug: | |
1300 | return [_FakeJediCompletion('Oops Jedi has crashed, please report a bug with the following:\n"""\n%s\ns"""' % (e))] |
|
1357 | return [_FakeJediCompletion('Oops Jedi has crashed, please report a bug with the following:\n"""\n%s\ns"""' % (e))] | |
1301 | else: |
|
1358 | else: | |
1302 | return [] |
|
1359 | return [] | |
1303 |
|
1360 | |||
1304 | def python_matches(self, text): |
|
1361 | def python_matches(self, text): | |
1305 | """Match attributes or global python names""" |
|
1362 | """Match attributes or global python names""" | |
1306 | if "." in text: |
|
1363 | if "." in text: | |
1307 | try: |
|
1364 | try: | |
1308 | matches = self.attr_matches(text) |
|
1365 | matches = self.attr_matches(text) | |
1309 | if text.endswith('.') and self.omit__names: |
|
1366 | if text.endswith('.') and self.omit__names: | |
1310 | if self.omit__names == 1: |
|
1367 | if self.omit__names == 1: | |
1311 | # true if txt is _not_ a __ name, false otherwise: |
|
1368 | # true if txt is _not_ a __ name, false otherwise: | |
1312 | no__name = (lambda txt: |
|
1369 | no__name = (lambda txt: | |
1313 | re.match(r'.*\.__.*?__',txt) is None) |
|
1370 | re.match(r'.*\.__.*?__',txt) is None) | |
1314 | else: |
|
1371 | else: | |
1315 | # true if txt is _not_ a _ name, false otherwise: |
|
1372 | # true if txt is _not_ a _ name, false otherwise: | |
1316 | no__name = (lambda txt: |
|
1373 | no__name = (lambda txt: | |
1317 | re.match(r'\._.*?',txt[txt.rindex('.'):]) is None) |
|
1374 | re.match(r'\._.*?',txt[txt.rindex('.'):]) is None) | |
1318 | matches = filter(no__name, matches) |
|
1375 | matches = filter(no__name, matches) | |
1319 | except NameError: |
|
1376 | except NameError: | |
1320 | # catches <undefined attributes>.<tab> |
|
1377 | # catches <undefined attributes>.<tab> | |
1321 | matches = [] |
|
1378 | matches = [] | |
1322 | else: |
|
1379 | else: | |
1323 | matches = self.global_matches(text) |
|
1380 | matches = self.global_matches(text) | |
1324 | return matches |
|
1381 | return matches | |
1325 |
|
1382 | |||
1326 | def _default_arguments_from_docstring(self, doc): |
|
1383 | def _default_arguments_from_docstring(self, doc): | |
1327 | """Parse the first line of docstring for call signature. |
|
1384 | """Parse the first line of docstring for call signature. | |
1328 |
|
1385 | |||
1329 | Docstring should be of the form 'min(iterable[, key=func])\n'. |
|
1386 | Docstring should be of the form 'min(iterable[, key=func])\n'. | |
1330 | It can also parse cython docstring of the form |
|
1387 | It can also parse cython docstring of the form | |
1331 | 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'. |
|
1388 | 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'. | |
1332 | """ |
|
1389 | """ | |
1333 | if doc is None: |
|
1390 | if doc is None: | |
1334 | return [] |
|
1391 | return [] | |
1335 |
|
1392 | |||
1336 | #care only the firstline |
|
1393 | #care only the firstline | |
1337 | line = doc.lstrip().splitlines()[0] |
|
1394 | line = doc.lstrip().splitlines()[0] | |
1338 |
|
1395 | |||
1339 | #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*') |
|
1396 | #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*') | |
1340 | #'min(iterable[, key=func])\n' -> 'iterable[, key=func]' |
|
1397 | #'min(iterable[, key=func])\n' -> 'iterable[, key=func]' | |
1341 | sig = self.docstring_sig_re.search(line) |
|
1398 | sig = self.docstring_sig_re.search(line) | |
1342 | if sig is None: |
|
1399 | if sig is None: | |
1343 | return [] |
|
1400 | return [] | |
1344 | # iterable[, key=func]' -> ['iterable[' ,' key=func]'] |
|
1401 | # iterable[, key=func]' -> ['iterable[' ,' key=func]'] | |
1345 | sig = sig.groups()[0].split(',') |
|
1402 | sig = sig.groups()[0].split(',') | |
1346 | ret = [] |
|
1403 | ret = [] | |
1347 | for s in sig: |
|
1404 | for s in sig: | |
1348 | #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)') |
|
1405 | #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)') | |
1349 | ret += self.docstring_kwd_re.findall(s) |
|
1406 | ret += self.docstring_kwd_re.findall(s) | |
1350 | return ret |
|
1407 | return ret | |
1351 |
|
1408 | |||
1352 | def _default_arguments(self, obj): |
|
1409 | def _default_arguments(self, obj): | |
1353 | """Return the list of default arguments of obj if it is callable, |
|
1410 | """Return the list of default arguments of obj if it is callable, | |
1354 | or empty list otherwise.""" |
|
1411 | or empty list otherwise.""" | |
1355 | call_obj = obj |
|
1412 | call_obj = obj | |
1356 | ret = [] |
|
1413 | ret = [] | |
1357 | if inspect.isbuiltin(obj): |
|
1414 | if inspect.isbuiltin(obj): | |
1358 | pass |
|
1415 | pass | |
1359 | elif not (inspect.isfunction(obj) or inspect.ismethod(obj)): |
|
1416 | elif not (inspect.isfunction(obj) or inspect.ismethod(obj)): | |
1360 | if inspect.isclass(obj): |
|
1417 | if inspect.isclass(obj): | |
1361 | #for cython embededsignature=True the constructor docstring |
|
1418 | #for cython embededsignature=True the constructor docstring | |
1362 | #belongs to the object itself not __init__ |
|
1419 | #belongs to the object itself not __init__ | |
1363 | ret += self._default_arguments_from_docstring( |
|
1420 | ret += self._default_arguments_from_docstring( | |
1364 | getattr(obj, '__doc__', '')) |
|
1421 | getattr(obj, '__doc__', '')) | |
1365 | # for classes, check for __init__,__new__ |
|
1422 | # for classes, check for __init__,__new__ | |
1366 | call_obj = (getattr(obj, '__init__', None) or |
|
1423 | call_obj = (getattr(obj, '__init__', None) or | |
1367 | getattr(obj, '__new__', None)) |
|
1424 | getattr(obj, '__new__', None)) | |
1368 | # for all others, check if they are __call__able |
|
1425 | # for all others, check if they are __call__able | |
1369 | elif hasattr(obj, '__call__'): |
|
1426 | elif hasattr(obj, '__call__'): | |
1370 | call_obj = obj.__call__ |
|
1427 | call_obj = obj.__call__ | |
1371 | ret += self._default_arguments_from_docstring( |
|
1428 | ret += self._default_arguments_from_docstring( | |
1372 | getattr(call_obj, '__doc__', '')) |
|
1429 | getattr(call_obj, '__doc__', '')) | |
1373 |
|
1430 | |||
1374 | _keeps = (inspect.Parameter.KEYWORD_ONLY, |
|
1431 | _keeps = (inspect.Parameter.KEYWORD_ONLY, | |
1375 | inspect.Parameter.POSITIONAL_OR_KEYWORD) |
|
1432 | inspect.Parameter.POSITIONAL_OR_KEYWORD) | |
1376 |
|
1433 | |||
1377 | try: |
|
1434 | try: | |
1378 | sig = inspect.signature(call_obj) |
|
1435 | sig = inspect.signature(call_obj) | |
1379 | ret.extend(k for k, v in sig.parameters.items() if |
|
1436 | ret.extend(k for k, v in sig.parameters.items() if | |
1380 | v.kind in _keeps) |
|
1437 | v.kind in _keeps) | |
1381 | except ValueError: |
|
1438 | except ValueError: | |
1382 | pass |
|
1439 | pass | |
1383 |
|
1440 | |||
1384 | return list(set(ret)) |
|
1441 | return list(set(ret)) | |
1385 |
|
1442 | |||
1386 | def python_func_kw_matches(self,text): |
|
1443 | def python_func_kw_matches(self,text): | |
1387 | """Match named parameters (kwargs) of the last open function""" |
|
1444 | """Match named parameters (kwargs) of the last open function""" | |
1388 |
|
1445 | |||
1389 | if "." in text: # a parameter cannot be dotted |
|
1446 | if "." in text: # a parameter cannot be dotted | |
1390 | return [] |
|
1447 | return [] | |
1391 | try: regexp = self.__funcParamsRegex |
|
1448 | try: regexp = self.__funcParamsRegex | |
1392 | except AttributeError: |
|
1449 | except AttributeError: | |
1393 | regexp = self.__funcParamsRegex = re.compile(r''' |
|
1450 | regexp = self.__funcParamsRegex = re.compile(r''' | |
1394 | '.*?(?<!\\)' | # single quoted strings or |
|
1451 | '.*?(?<!\\)' | # single quoted strings or | |
1395 | ".*?(?<!\\)" | # double quoted strings or |
|
1452 | ".*?(?<!\\)" | # double quoted strings or | |
1396 | \w+ | # identifier |
|
1453 | \w+ | # identifier | |
1397 | \S # other characters |
|
1454 | \S # other characters | |
1398 | ''', re.VERBOSE | re.DOTALL) |
|
1455 | ''', re.VERBOSE | re.DOTALL) | |
1399 | # 1. find the nearest identifier that comes before an unclosed |
|
1456 | # 1. find the nearest identifier that comes before an unclosed | |
1400 | # parenthesis before the cursor |
|
1457 | # parenthesis before the cursor | |
1401 | # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo" |
|
1458 | # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo" | |
1402 | tokens = regexp.findall(self.text_until_cursor) |
|
1459 | tokens = regexp.findall(self.text_until_cursor) | |
1403 | iterTokens = reversed(tokens); openPar = 0 |
|
1460 | iterTokens = reversed(tokens); openPar = 0 | |
1404 |
|
1461 | |||
1405 | for token in iterTokens: |
|
1462 | for token in iterTokens: | |
1406 | if token == ')': |
|
1463 | if token == ')': | |
1407 | openPar -= 1 |
|
1464 | openPar -= 1 | |
1408 | elif token == '(': |
|
1465 | elif token == '(': | |
1409 | openPar += 1 |
|
1466 | openPar += 1 | |
1410 | if openPar > 0: |
|
1467 | if openPar > 0: | |
1411 | # found the last unclosed parenthesis |
|
1468 | # found the last unclosed parenthesis | |
1412 | break |
|
1469 | break | |
1413 | else: |
|
1470 | else: | |
1414 | return [] |
|
1471 | return [] | |
1415 | # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" ) |
|
1472 | # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" ) | |
1416 | ids = [] |
|
1473 | ids = [] | |
1417 | isId = re.compile(r'\w+$').match |
|
1474 | isId = re.compile(r'\w+$').match | |
1418 |
|
1475 | |||
1419 | while True: |
|
1476 | while True: | |
1420 | try: |
|
1477 | try: | |
1421 | ids.append(next(iterTokens)) |
|
1478 | ids.append(next(iterTokens)) | |
1422 | if not isId(ids[-1]): |
|
1479 | if not isId(ids[-1]): | |
1423 | ids.pop(); break |
|
1480 | ids.pop(); break | |
1424 | if not next(iterTokens) == '.': |
|
1481 | if not next(iterTokens) == '.': | |
1425 | break |
|
1482 | break | |
1426 | except StopIteration: |
|
1483 | except StopIteration: | |
1427 | break |
|
1484 | break | |
1428 |
|
1485 | |||
1429 | # Find all named arguments already assigned to, as to avoid suggesting |
|
1486 | # Find all named arguments already assigned to, as to avoid suggesting | |
1430 | # them again |
|
1487 | # them again | |
1431 | usedNamedArgs = set() |
|
1488 | usedNamedArgs = set() | |
1432 | par_level = -1 |
|
1489 | par_level = -1 | |
1433 | for token, next_token in zip(tokens, tokens[1:]): |
|
1490 | for token, next_token in zip(tokens, tokens[1:]): | |
1434 | if token == '(': |
|
1491 | if token == '(': | |
1435 | par_level += 1 |
|
1492 | par_level += 1 | |
1436 | elif token == ')': |
|
1493 | elif token == ')': | |
1437 | par_level -= 1 |
|
1494 | par_level -= 1 | |
1438 |
|
1495 | |||
1439 | if par_level != 0: |
|
1496 | if par_level != 0: | |
1440 | continue |
|
1497 | continue | |
1441 |
|
1498 | |||
1442 | if next_token != '=': |
|
1499 | if next_token != '=': | |
1443 | continue |
|
1500 | continue | |
1444 |
|
1501 | |||
1445 | usedNamedArgs.add(token) |
|
1502 | usedNamedArgs.add(token) | |
1446 |
|
1503 | |||
1447 | # lookup the candidate callable matches either using global_matches |
|
1504 | # lookup the candidate callable matches either using global_matches | |
1448 | # or attr_matches for dotted names |
|
1505 | # or attr_matches for dotted names | |
1449 | if len(ids) == 1: |
|
1506 | if len(ids) == 1: | |
1450 | callableMatches = self.global_matches(ids[0]) |
|
1507 | callableMatches = self.global_matches(ids[0]) | |
1451 | else: |
|
1508 | else: | |
1452 | callableMatches = self.attr_matches('.'.join(ids[::-1])) |
|
1509 | callableMatches = self.attr_matches('.'.join(ids[::-1])) | |
1453 | argMatches = [] |
|
1510 | argMatches = [] | |
1454 | for callableMatch in callableMatches: |
|
1511 | for callableMatch in callableMatches: | |
1455 | try: |
|
1512 | try: | |
1456 | namedArgs = self._default_arguments(eval(callableMatch, |
|
1513 | namedArgs = self._default_arguments(eval(callableMatch, | |
1457 | self.namespace)) |
|
1514 | self.namespace)) | |
1458 | except: |
|
1515 | except: | |
1459 | continue |
|
1516 | continue | |
1460 |
|
1517 | |||
1461 | # Remove used named arguments from the list, no need to show twice |
|
1518 | # Remove used named arguments from the list, no need to show twice | |
1462 | for namedArg in set(namedArgs) - usedNamedArgs: |
|
1519 | for namedArg in set(namedArgs) - usedNamedArgs: | |
1463 | if namedArg.startswith(text): |
|
1520 | if namedArg.startswith(text): | |
1464 | argMatches.append(u"%s=" %namedArg) |
|
1521 | argMatches.append(u"%s=" %namedArg) | |
1465 | return argMatches |
|
1522 | return argMatches | |
1466 |
|
1523 | |||
1467 | def dict_key_matches(self, text): |
|
1524 | def dict_key_matches(self, text): | |
1468 | "Match string keys in a dictionary, after e.g. 'foo[' " |
|
1525 | "Match string keys in a dictionary, after e.g. 'foo[' " | |
1469 | def get_keys(obj): |
|
1526 | def get_keys(obj): | |
1470 | # Objects can define their own completions by defining an |
|
1527 | # Objects can define their own completions by defining an | |
1471 | # _ipy_key_completions_() method. |
|
1528 | # _ipy_key_completions_() method. | |
1472 | method = get_real_method(obj, '_ipython_key_completions_') |
|
1529 | method = get_real_method(obj, '_ipython_key_completions_') | |
1473 | if method is not None: |
|
1530 | if method is not None: | |
1474 | return method() |
|
1531 | return method() | |
1475 |
|
1532 | |||
1476 | # Special case some common in-memory dict-like types |
|
1533 | # Special case some common in-memory dict-like types | |
1477 | if isinstance(obj, dict) or\ |
|
1534 | if isinstance(obj, dict) or\ | |
1478 | _safe_isinstance(obj, 'pandas', 'DataFrame'): |
|
1535 | _safe_isinstance(obj, 'pandas', 'DataFrame'): | |
1479 | try: |
|
1536 | try: | |
1480 | return list(obj.keys()) |
|
1537 | return list(obj.keys()) | |
1481 | except Exception: |
|
1538 | except Exception: | |
1482 | return [] |
|
1539 | return [] | |
1483 | elif _safe_isinstance(obj, 'numpy', 'ndarray') or\ |
|
1540 | elif _safe_isinstance(obj, 'numpy', 'ndarray') or\ | |
1484 | _safe_isinstance(obj, 'numpy', 'void'): |
|
1541 | _safe_isinstance(obj, 'numpy', 'void'): | |
1485 | return obj.dtype.names or [] |
|
1542 | return obj.dtype.names or [] | |
1486 | return [] |
|
1543 | return [] | |
1487 |
|
1544 | |||
1488 | try: |
|
1545 | try: | |
1489 | regexps = self.__dict_key_regexps |
|
1546 | regexps = self.__dict_key_regexps | |
1490 | except AttributeError: |
|
1547 | except AttributeError: | |
1491 | dict_key_re_fmt = r'''(?x) |
|
1548 | dict_key_re_fmt = r'''(?x) | |
1492 | ( # match dict-referring expression wrt greedy setting |
|
1549 | ( # match dict-referring expression wrt greedy setting | |
1493 | %s |
|
1550 | %s | |
1494 | ) |
|
1551 | ) | |
1495 | \[ # open bracket |
|
1552 | \[ # open bracket | |
1496 | \s* # and optional whitespace |
|
1553 | \s* # and optional whitespace | |
1497 | ([uUbB]? # string prefix (r not handled) |
|
1554 | ([uUbB]? # string prefix (r not handled) | |
1498 | (?: # unclosed string |
|
1555 | (?: # unclosed string | |
1499 | '(?:[^']|(?<!\\)\\')* |
|
1556 | '(?:[^']|(?<!\\)\\')* | |
1500 | | |
|
1557 | | | |
1501 | "(?:[^"]|(?<!\\)\\")* |
|
1558 | "(?:[^"]|(?<!\\)\\")* | |
1502 | ) |
|
1559 | ) | |
1503 | )? |
|
1560 | )? | |
1504 | $ |
|
1561 | $ | |
1505 | ''' |
|
1562 | ''' | |
1506 | regexps = self.__dict_key_regexps = { |
|
1563 | regexps = self.__dict_key_regexps = { | |
1507 | False: re.compile(dict_key_re_fmt % ''' |
|
1564 | False: re.compile(dict_key_re_fmt % ''' | |
1508 | # identifiers separated by . |
|
1565 | # identifiers separated by . | |
1509 | (?!\d)\w+ |
|
1566 | (?!\d)\w+ | |
1510 | (?:\.(?!\d)\w+)* |
|
1567 | (?:\.(?!\d)\w+)* | |
1511 | '''), |
|
1568 | '''), | |
1512 | True: re.compile(dict_key_re_fmt % ''' |
|
1569 | True: re.compile(dict_key_re_fmt % ''' | |
1513 | .+ |
|
1570 | .+ | |
1514 | ''') |
|
1571 | ''') | |
1515 | } |
|
1572 | } | |
1516 |
|
1573 | |||
1517 | match = regexps[self.greedy].search(self.text_until_cursor) |
|
1574 | match = regexps[self.greedy].search(self.text_until_cursor) | |
1518 | if match is None: |
|
1575 | if match is None: | |
1519 | return [] |
|
1576 | return [] | |
1520 |
|
1577 | |||
1521 | expr, prefix = match.groups() |
|
1578 | expr, prefix = match.groups() | |
1522 | try: |
|
1579 | try: | |
1523 | obj = eval(expr, self.namespace) |
|
1580 | obj = eval(expr, self.namespace) | |
1524 | except Exception: |
|
1581 | except Exception: | |
1525 | try: |
|
1582 | try: | |
1526 | obj = eval(expr, self.global_namespace) |
|
1583 | obj = eval(expr, self.global_namespace) | |
1527 | except Exception: |
|
1584 | except Exception: | |
1528 | return [] |
|
1585 | return [] | |
1529 |
|
1586 | |||
1530 | keys = get_keys(obj) |
|
1587 | keys = get_keys(obj) | |
1531 | if not keys: |
|
1588 | if not keys: | |
1532 | return keys |
|
1589 | return keys | |
1533 | closing_quote, token_offset, matches = match_dict_keys(keys, prefix, self.splitter.delims) |
|
1590 | closing_quote, token_offset, matches = match_dict_keys(keys, prefix, self.splitter.delims) | |
1534 | if not matches: |
|
1591 | if not matches: | |
1535 | return matches |
|
1592 | return matches | |
1536 |
|
1593 | |||
1537 | # get the cursor position of |
|
1594 | # get the cursor position of | |
1538 | # - the text being completed |
|
1595 | # - the text being completed | |
1539 | # - the start of the key text |
|
1596 | # - the start of the key text | |
1540 | # - the start of the completion |
|
1597 | # - the start of the completion | |
1541 | text_start = len(self.text_until_cursor) - len(text) |
|
1598 | text_start = len(self.text_until_cursor) - len(text) | |
1542 | if prefix: |
|
1599 | if prefix: | |
1543 | key_start = match.start(2) |
|
1600 | key_start = match.start(2) | |
1544 | completion_start = key_start + token_offset |
|
1601 | completion_start = key_start + token_offset | |
1545 | else: |
|
1602 | else: | |
1546 | key_start = completion_start = match.end() |
|
1603 | key_start = completion_start = match.end() | |
1547 |
|
1604 | |||
1548 | # grab the leading prefix, to make sure all completions start with `text` |
|
1605 | # grab the leading prefix, to make sure all completions start with `text` | |
1549 | if text_start > key_start: |
|
1606 | if text_start > key_start: | |
1550 | leading = '' |
|
1607 | leading = '' | |
1551 | else: |
|
1608 | else: | |
1552 | leading = text[text_start:completion_start] |
|
1609 | leading = text[text_start:completion_start] | |
1553 |
|
1610 | |||
1554 | # the index of the `[` character |
|
1611 | # the index of the `[` character | |
1555 | bracket_idx = match.end(1) |
|
1612 | bracket_idx = match.end(1) | |
1556 |
|
1613 | |||
1557 | # append closing quote and bracket as appropriate |
|
1614 | # append closing quote and bracket as appropriate | |
1558 | # this is *not* appropriate if the opening quote or bracket is outside |
|
1615 | # this is *not* appropriate if the opening quote or bracket is outside | |
1559 | # the text given to this method |
|
1616 | # the text given to this method | |
1560 | suf = '' |
|
1617 | suf = '' | |
1561 | continuation = self.line_buffer[len(self.text_until_cursor):] |
|
1618 | continuation = self.line_buffer[len(self.text_until_cursor):] | |
1562 | if key_start > text_start and closing_quote: |
|
1619 | if key_start > text_start and closing_quote: | |
1563 | # quotes were opened inside text, maybe close them |
|
1620 | # quotes were opened inside text, maybe close them | |
1564 | if continuation.startswith(closing_quote): |
|
1621 | if continuation.startswith(closing_quote): | |
1565 | continuation = continuation[len(closing_quote):] |
|
1622 | continuation = continuation[len(closing_quote):] | |
1566 | else: |
|
1623 | else: | |
1567 | suf += closing_quote |
|
1624 | suf += closing_quote | |
1568 | if bracket_idx > text_start: |
|
1625 | if bracket_idx > text_start: | |
1569 | # brackets were opened inside text, maybe close them |
|
1626 | # brackets were opened inside text, maybe close them | |
1570 | if not continuation.startswith(']'): |
|
1627 | if not continuation.startswith(']'): | |
1571 | suf += ']' |
|
1628 | suf += ']' | |
1572 |
|
1629 | |||
1573 | return [leading + k + suf for k in matches] |
|
1630 | return [leading + k + suf for k in matches] | |
1574 |
|
1631 | |||
1575 | def unicode_name_matches(self, text): |
|
1632 | def unicode_name_matches(self, text): | |
1576 | u"""Match Latex-like syntax for unicode characters base |
|
1633 | u"""Match Latex-like syntax for unicode characters base | |
1577 | on the name of the character. |
|
1634 | on the name of the character. | |
1578 |
|
1635 | |||
1579 | This does ``\\GREEK SMALL LETTER ETA`` -> ``Ξ·`` |
|
1636 | This does ``\\GREEK SMALL LETTER ETA`` -> ``Ξ·`` | |
1580 |
|
1637 | |||
1581 | Works only on valid python 3 identifier, or on combining characters that |
|
1638 | Works only on valid python 3 identifier, or on combining characters that | |
1582 | will combine to form a valid identifier. |
|
1639 | will combine to form a valid identifier. | |
1583 |
|
1640 | |||
1584 | Used on Python 3 only. |
|
1641 | Used on Python 3 only. | |
1585 | """ |
|
1642 | """ | |
1586 | slashpos = text.rfind('\\') |
|
1643 | slashpos = text.rfind('\\') | |
1587 | if slashpos > -1: |
|
1644 | if slashpos > -1: | |
1588 | s = text[slashpos+1:] |
|
1645 | s = text[slashpos+1:] | |
1589 | try : |
|
1646 | try : | |
1590 | unic = unicodedata.lookup(s) |
|
1647 | unic = unicodedata.lookup(s) | |
1591 | # allow combining chars |
|
1648 | # allow combining chars | |
1592 | if ('a'+unic).isidentifier(): |
|
1649 | if ('a'+unic).isidentifier(): | |
1593 | return '\\'+s,[unic] |
|
1650 | return '\\'+s,[unic] | |
1594 | except KeyError: |
|
1651 | except KeyError: | |
1595 | pass |
|
1652 | pass | |
1596 | return u'', [] |
|
1653 | return u'', [] | |
1597 |
|
1654 | |||
1598 |
|
1655 | |||
1599 | def latex_matches(self, text): |
|
1656 | def latex_matches(self, text): | |
1600 | u"""Match Latex syntax for unicode characters. |
|
1657 | u"""Match Latex syntax for unicode characters. | |
1601 |
|
1658 | |||
1602 | This does both ``\\alp`` -> ``\\alpha`` and ``\\alpha`` -> ``Ξ±`` |
|
1659 | This does both ``\\alp`` -> ``\\alpha`` and ``\\alpha`` -> ``Ξ±`` | |
1603 |
|
1660 | |||
1604 | Used on Python 3 only. |
|
1661 | Used on Python 3 only. | |
1605 | """ |
|
1662 | """ | |
1606 | slashpos = text.rfind('\\') |
|
1663 | slashpos = text.rfind('\\') | |
1607 | if slashpos > -1: |
|
1664 | if slashpos > -1: | |
1608 | s = text[slashpos:] |
|
1665 | s = text[slashpos:] | |
1609 | if s in latex_symbols: |
|
1666 | if s in latex_symbols: | |
1610 | # Try to complete a full latex symbol to unicode |
|
1667 | # Try to complete a full latex symbol to unicode | |
1611 | # \\alpha -> Ξ± |
|
1668 | # \\alpha -> Ξ± | |
1612 | return s, [latex_symbols[s]] |
|
1669 | return s, [latex_symbols[s]] | |
1613 | else: |
|
1670 | else: | |
1614 | # If a user has partially typed a latex symbol, give them |
|
1671 | # If a user has partially typed a latex symbol, give them | |
1615 | # a full list of options \al -> [\aleph, \alpha] |
|
1672 | # a full list of options \al -> [\aleph, \alpha] | |
1616 | matches = [k for k in latex_symbols if k.startswith(s)] |
|
1673 | matches = [k for k in latex_symbols if k.startswith(s)] | |
1617 | return s, matches |
|
1674 | return s, matches | |
1618 | return u'', [] |
|
1675 | return u'', [] | |
1619 |
|
1676 | |||
1620 | def dispatch_custom_completer(self, text): |
|
1677 | def dispatch_custom_completer(self, text): | |
1621 | if not self.custom_completers: |
|
1678 | if not self.custom_completers: | |
1622 | return |
|
1679 | return | |
1623 |
|
1680 | |||
1624 | line = self.line_buffer |
|
1681 | line = self.line_buffer | |
1625 | if not line.strip(): |
|
1682 | if not line.strip(): | |
1626 | return None |
|
1683 | return None | |
1627 |
|
1684 | |||
1628 | # Create a little structure to pass all the relevant information about |
|
1685 | # Create a little structure to pass all the relevant information about | |
1629 | # the current completion to any custom completer. |
|
1686 | # the current completion to any custom completer. | |
1630 | event = SimpleNamespace() |
|
1687 | event = SimpleNamespace() | |
1631 | event.line = line |
|
1688 | event.line = line | |
1632 | event.symbol = text |
|
1689 | event.symbol = text | |
1633 | cmd = line.split(None,1)[0] |
|
1690 | cmd = line.split(None,1)[0] | |
1634 | event.command = cmd |
|
1691 | event.command = cmd | |
1635 | event.text_until_cursor = self.text_until_cursor |
|
1692 | event.text_until_cursor = self.text_until_cursor | |
1636 |
|
1693 | |||
1637 | # for foo etc, try also to find completer for %foo |
|
1694 | # for foo etc, try also to find completer for %foo | |
1638 | if not cmd.startswith(self.magic_escape): |
|
1695 | if not cmd.startswith(self.magic_escape): | |
1639 | try_magic = self.custom_completers.s_matches( |
|
1696 | try_magic = self.custom_completers.s_matches( | |
1640 | self.magic_escape + cmd) |
|
1697 | self.magic_escape + cmd) | |
1641 | else: |
|
1698 | else: | |
1642 | try_magic = [] |
|
1699 | try_magic = [] | |
1643 |
|
1700 | |||
1644 | for c in itertools.chain(self.custom_completers.s_matches(cmd), |
|
1701 | for c in itertools.chain(self.custom_completers.s_matches(cmd), | |
1645 | try_magic, |
|
1702 | try_magic, | |
1646 | self.custom_completers.flat_matches(self.text_until_cursor)): |
|
1703 | self.custom_completers.flat_matches(self.text_until_cursor)): | |
1647 | try: |
|
1704 | try: | |
1648 | res = c(event) |
|
1705 | res = c(event) | |
1649 | if res: |
|
1706 | if res: | |
1650 | # first, try case sensitive match |
|
1707 | # first, try case sensitive match | |
1651 | withcase = [r for r in res if r.startswith(text)] |
|
1708 | withcase = [r for r in res if r.startswith(text)] | |
1652 | if withcase: |
|
1709 | if withcase: | |
1653 | return withcase |
|
1710 | return withcase | |
1654 | # if none, then case insensitive ones are ok too |
|
1711 | # if none, then case insensitive ones are ok too | |
1655 | text_low = text.lower() |
|
1712 | text_low = text.lower() | |
1656 | return [r for r in res if r.lower().startswith(text_low)] |
|
1713 | return [r for r in res if r.lower().startswith(text_low)] | |
1657 | except TryNext: |
|
1714 | except TryNext: | |
1658 | pass |
|
1715 | pass | |
1659 |
|
1716 | |||
1660 | return None |
|
1717 | return None | |
1661 |
|
1718 | |||
1662 | def completions(self, text: str, offset: int)->Iterator[Completion]: |
|
1719 | def completions(self, text: str, offset: int)->Iterator[Completion]: | |
1663 | """ |
|
1720 | """ | |
1664 | Returns an iterator over the possible completions |
|
1721 | Returns an iterator over the possible completions | |
1665 |
|
1722 | |||
1666 | .. warning:: Unstable |
|
1723 | .. warning:: Unstable | |
1667 |
|
1724 | |||
1668 | This function is unstable, API may change without warning. |
|
1725 | This function is unstable, API may change without warning. | |
1669 | It will also raise unless use in proper context manager. |
|
1726 | It will also raise unless use in proper context manager. | |
1670 |
|
1727 | |||
1671 | Parameters |
|
1728 | Parameters | |
1672 | ---------- |
|
1729 | ---------- | |
1673 |
|
1730 | |||
1674 | text:str |
|
1731 | text:str | |
1675 | Full text of the current input, multi line string. |
|
1732 | Full text of the current input, multi line string. | |
1676 | offset:int |
|
1733 | offset:int | |
1677 | Integer representing the position of the cursor in ``text``. Offset |
|
1734 | Integer representing the position of the cursor in ``text``. Offset | |
1678 | is 0-based indexed. |
|
1735 | is 0-based indexed. | |
1679 |
|
1736 | |||
1680 | Yields |
|
1737 | Yields | |
1681 | ------ |
|
1738 | ------ | |
1682 | :any:`Completion` object |
|
1739 | :any:`Completion` object | |
1683 |
|
1740 | |||
1684 |
|
1741 | |||
1685 | The cursor on a text can either be seen as being "in between" |
|
1742 | The cursor on a text can either be seen as being "in between" | |
1686 | characters or "On" a character depending on the interface visible to |
|
1743 | characters or "On" a character depending on the interface visible to | |
1687 | the user. For consistency the cursor being on "in between" characters X |
|
1744 | the user. For consistency the cursor being on "in between" characters X | |
1688 | and Y is equivalent to the cursor being "on" character Y, that is to say |
|
1745 | and Y is equivalent to the cursor being "on" character Y, that is to say | |
1689 | the character the cursor is on is considered as being after the cursor. |
|
1746 | the character the cursor is on is considered as being after the cursor. | |
1690 |
|
1747 | |||
1691 | Combining characters may span more that one position in the |
|
1748 | Combining characters may span more that one position in the | |
1692 | text. |
|
1749 | text. | |
1693 |
|
1750 | |||
1694 |
|
1751 | |||
1695 | .. note:: |
|
1752 | .. note:: | |
1696 |
|
1753 | |||
1697 | If ``IPCompleter.debug`` is :any:`True` will yield a ``--jedi/ipython--`` |
|
1754 | If ``IPCompleter.debug`` is :any:`True` will yield a ``--jedi/ipython--`` | |
1698 | fake Completion token to distinguish completion returned by Jedi |
|
1755 | fake Completion token to distinguish completion returned by Jedi | |
1699 | and usual IPython completion. |
|
1756 | and usual IPython completion. | |
1700 |
|
1757 | |||
1701 | .. note:: |
|
1758 | .. note:: | |
1702 |
|
1759 | |||
1703 | Completions are not completely deduplicated yet. If identical |
|
1760 | Completions are not completely deduplicated yet. If identical | |
1704 | completions are coming from different sources this function does not |
|
1761 | completions are coming from different sources this function does not | |
1705 | ensure that each completion object will only be present once. |
|
1762 | ensure that each completion object will only be present once. | |
1706 | """ |
|
1763 | """ | |
1707 | warnings.warn("_complete is a provisional API (as of IPython 6.0). " |
|
1764 | warnings.warn("_complete is a provisional API (as of IPython 6.0). " | |
1708 | "It may change without warnings. " |
|
1765 | "It may change without warnings. " | |
1709 | "Use in corresponding context manager.", |
|
1766 | "Use in corresponding context manager.", | |
1710 | category=ProvisionalCompleterWarning, stacklevel=2) |
|
1767 | category=ProvisionalCompleterWarning, stacklevel=2) | |
1711 |
|
1768 | |||
1712 | seen = set() |
|
1769 | seen = set() | |
1713 | for c in self._completions(text, offset, _timeout=self.jedi_compute_type_timeout/1000): |
|
1770 | for c in self._completions(text, offset, _timeout=self.jedi_compute_type_timeout/1000): | |
1714 | if c and (c in seen): |
|
1771 | if c and (c in seen): | |
1715 | continue |
|
1772 | continue | |
1716 | yield c |
|
1773 | yield c | |
1717 | seen.add(c) |
|
1774 | seen.add(c) | |
1718 |
|
1775 | |||
1719 | def _completions(self, full_text: str, offset: int, *, _timeout)->Iterator[Completion]: |
|
1776 | def _completions(self, full_text: str, offset: int, *, _timeout)->Iterator[Completion]: | |
1720 | """ |
|
1777 | """ | |
1721 | Core completion module.Same signature as :any:`completions`, with the |
|
1778 | Core completion module.Same signature as :any:`completions`, with the | |
1722 | extra `timeout` parameter (in seconds). |
|
1779 | extra `timeout` parameter (in seconds). | |
1723 |
|
1780 | |||
1724 |
|
1781 | |||
1725 | Computing jedi's completion ``.type`` can be quite expensive (it is a |
|
1782 | Computing jedi's completion ``.type`` can be quite expensive (it is a | |
1726 | lazy property) and can require some warm-up, more warm up than just |
|
1783 | lazy property) and can require some warm-up, more warm up than just | |
1727 | computing the ``name`` of a completion. The warm-up can be : |
|
1784 | computing the ``name`` of a completion. The warm-up can be : | |
1728 |
|
1785 | |||
1729 | - Long warm-up the first time a module is encountered after |
|
1786 | - Long warm-up the first time a module is encountered after | |
1730 | install/update: actually build parse/inference tree. |
|
1787 | install/update: actually build parse/inference tree. | |
1731 |
|
1788 | |||
1732 | - first time the module is encountered in a session: load tree from |
|
1789 | - first time the module is encountered in a session: load tree from | |
1733 | disk. |
|
1790 | disk. | |
1734 |
|
1791 | |||
1735 | We don't want to block completions for tens of seconds so we give the |
|
1792 | We don't want to block completions for tens of seconds so we give the | |
1736 | completer a "budget" of ``_timeout`` seconds per invocation to compute |
|
1793 | completer a "budget" of ``_timeout`` seconds per invocation to compute | |
1737 | completions types, the completions that have not yet been computed will |
|
1794 | completions types, the completions that have not yet been computed will | |
1738 | be marked as "unknown" an will have a chance to be computed next round |
|
1795 | be marked as "unknown" an will have a chance to be computed next round | |
1739 | are things get cached. |
|
1796 | are things get cached. | |
1740 |
|
1797 | |||
1741 | Keep in mind that Jedi is not the only thing treating the completion so |
|
1798 | Keep in mind that Jedi is not the only thing treating the completion so | |
1742 | keep the timeout short-ish as if we take more than 0.3 second we still |
|
1799 | keep the timeout short-ish as if we take more than 0.3 second we still | |
1743 | have lots of processing to do. |
|
1800 | have lots of processing to do. | |
1744 |
|
1801 | |||
1745 | """ |
|
1802 | """ | |
1746 | deadline = time.monotonic() + _timeout |
|
1803 | deadline = time.monotonic() + _timeout | |
1747 |
|
1804 | |||
1748 |
|
1805 | |||
1749 | before = full_text[:offset] |
|
1806 | before = full_text[:offset] | |
1750 | cursor_line, cursor_column = position_to_cursor(full_text, offset) |
|
1807 | cursor_line, cursor_column = position_to_cursor(full_text, offset) | |
1751 |
|
1808 | |||
1752 | matched_text, matches, matches_origin, jedi_matches = self._complete( |
|
1809 | matched_text, matches, matches_origin, jedi_matches = self._complete( | |
1753 | full_text=full_text, cursor_line=cursor_line, cursor_pos=cursor_column) |
|
1810 | full_text=full_text, cursor_line=cursor_line, cursor_pos=cursor_column) | |
1754 |
|
1811 | |||
1755 | iter_jm = iter(jedi_matches) |
|
1812 | iter_jm = iter(jedi_matches) | |
1756 | if _timeout: |
|
1813 | if _timeout: | |
1757 | for jm in iter_jm: |
|
1814 | for jm in iter_jm: | |
1758 | try: |
|
1815 | try: | |
1759 | type_ = jm.type |
|
1816 | type_ = jm.type | |
1760 | except Exception: |
|
1817 | except Exception: | |
1761 | if self.debug: |
|
1818 | if self.debug: | |
1762 | print("Error in Jedi getting type of ", jm) |
|
1819 | print("Error in Jedi getting type of ", jm) | |
1763 | type_ = None |
|
1820 | type_ = None | |
1764 | delta = len(jm.name_with_symbols) - len(jm.complete) |
|
1821 | delta = len(jm.name_with_symbols) - len(jm.complete) | |
|
1822 | if type_ == 'function': | |||
|
1823 | signature = _make_signature(jm) | |||
|
1824 | else: | |||
|
1825 | signature = '' | |||
1765 | yield Completion(start=offset - delta, |
|
1826 | yield Completion(start=offset - delta, | |
1766 | end=offset, |
|
1827 | end=offset, | |
1767 | text=jm.name_with_symbols, |
|
1828 | text=jm.name_with_symbols, | |
1768 | type=type_, |
|
1829 | type=type_, | |
|
1830 | signature=signature, | |||
1769 | _origin='jedi') |
|
1831 | _origin='jedi') | |
1770 |
|
1832 | |||
1771 | if time.monotonic() > deadline: |
|
1833 | if time.monotonic() > deadline: | |
1772 | break |
|
1834 | break | |
1773 |
|
1835 | |||
1774 | for jm in iter_jm: |
|
1836 | for jm in iter_jm: | |
1775 | delta = len(jm.name_with_symbols) - len(jm.complete) |
|
1837 | delta = len(jm.name_with_symbols) - len(jm.complete) | |
1776 | yield Completion(start=offset - delta, |
|
1838 | yield Completion(start=offset - delta, | |
1777 | end=offset, |
|
1839 | end=offset, | |
1778 | text=jm.name_with_symbols, |
|
1840 | text=jm.name_with_symbols, | |
1779 | type='<unknown>', # don't compute type for speed |
|
1841 | type='<unknown>', # don't compute type for speed | |
1780 |
_origin='jedi' |
|
1842 | _origin='jedi', | |
|
1843 | signature='') | |||
1781 |
|
1844 | |||
1782 |
|
1845 | |||
1783 | start_offset = before.rfind(matched_text) |
|
1846 | start_offset = before.rfind(matched_text) | |
1784 |
|
1847 | |||
1785 | # TODO: |
|
1848 | # TODO: | |
1786 | # Supress this, right now just for debug. |
|
1849 | # Supress this, right now just for debug. | |
1787 | if jedi_matches and matches and self.debug: |
|
1850 | if jedi_matches and matches and self.debug: | |
1788 |
yield Completion(start=start_offset, end=offset, text='--jedi/ipython--', |
|
1851 | yield Completion(start=start_offset, end=offset, text='--jedi/ipython--', | |
|
1852 | _origin='debug', type='none', signature='') | |||
1789 |
|
1853 | |||
1790 | # I'm unsure if this is always true, so let's assert and see if it |
|
1854 | # I'm unsure if this is always true, so let's assert and see if it | |
1791 | # crash |
|
1855 | # crash | |
1792 | assert before.endswith(matched_text) |
|
1856 | assert before.endswith(matched_text) | |
1793 | for m, t in zip(matches, matches_origin): |
|
1857 | for m, t in zip(matches, matches_origin): | |
1794 | yield Completion(start=start_offset, end=offset, text=m, _origin=t) |
|
1858 | yield Completion(start=start_offset, end=offset, text=m, _origin=t, signature='', type='<unknown>') | |
1795 |
|
1859 | |||
1796 |
|
1860 | |||
1797 | def complete(self, text=None, line_buffer=None, cursor_pos=None): |
|
1861 | def complete(self, text=None, line_buffer=None, cursor_pos=None): | |
1798 | """Find completions for the given text and line context. |
|
1862 | """Find completions for the given text and line context. | |
1799 |
|
1863 | |||
1800 | Note that both the text and the line_buffer are optional, but at least |
|
1864 | Note that both the text and the line_buffer are optional, but at least | |
1801 | one of them must be given. |
|
1865 | one of them must be given. | |
1802 |
|
1866 | |||
1803 | Parameters |
|
1867 | Parameters | |
1804 | ---------- |
|
1868 | ---------- | |
1805 | text : string, optional |
|
1869 | text : string, optional | |
1806 | Text to perform the completion on. If not given, the line buffer |
|
1870 | Text to perform the completion on. If not given, the line buffer | |
1807 | is split using the instance's CompletionSplitter object. |
|
1871 | is split using the instance's CompletionSplitter object. | |
1808 |
|
1872 | |||
1809 | line_buffer : string, optional |
|
1873 | line_buffer : string, optional | |
1810 | If not given, the completer attempts to obtain the current line |
|
1874 | If not given, the completer attempts to obtain the current line | |
1811 | buffer via readline. This keyword allows clients which are |
|
1875 | buffer via readline. This keyword allows clients which are | |
1812 | requesting for text completions in non-readline contexts to inform |
|
1876 | requesting for text completions in non-readline contexts to inform | |
1813 | the completer of the entire text. |
|
1877 | the completer of the entire text. | |
1814 |
|
1878 | |||
1815 | cursor_pos : int, optional |
|
1879 | cursor_pos : int, optional | |
1816 | Index of the cursor in the full line buffer. Should be provided by |
|
1880 | Index of the cursor in the full line buffer. Should be provided by | |
1817 | remote frontends where kernel has no access to frontend state. |
|
1881 | remote frontends where kernel has no access to frontend state. | |
1818 |
|
1882 | |||
1819 | Returns |
|
1883 | Returns | |
1820 | ------- |
|
1884 | ------- | |
1821 | text : str |
|
1885 | text : str | |
1822 | Text that was actually used in the completion. |
|
1886 | Text that was actually used in the completion. | |
1823 |
|
1887 | |||
1824 | matches : list |
|
1888 | matches : list | |
1825 | A list of completion matches. |
|
1889 | A list of completion matches. | |
1826 |
|
1890 | |||
1827 |
|
1891 | |||
1828 | .. note:: |
|
1892 | .. note:: | |
1829 |
|
1893 | |||
1830 | This API is likely to be deprecated and replaced by |
|
1894 | This API is likely to be deprecated and replaced by | |
1831 | :any:`IPCompleter.completions` in the future. |
|
1895 | :any:`IPCompleter.completions` in the future. | |
1832 |
|
1896 | |||
1833 |
|
1897 | |||
1834 | """ |
|
1898 | """ | |
1835 | warnings.warn('`Completer.complete` is pending deprecation since ' |
|
1899 | warnings.warn('`Completer.complete` is pending deprecation since ' | |
1836 | 'IPython 6.0 and will be replaced by `Completer.completions`.', |
|
1900 | 'IPython 6.0 and will be replaced by `Completer.completions`.', | |
1837 | PendingDeprecationWarning) |
|
1901 | PendingDeprecationWarning) | |
1838 | # potential todo, FOLD the 3rd throw away argument of _complete |
|
1902 | # potential todo, FOLD the 3rd throw away argument of _complete | |
1839 | # into the first 2 one. |
|
1903 | # into the first 2 one. | |
1840 | return self._complete(line_buffer=line_buffer, cursor_pos=cursor_pos, text=text, cursor_line=0)[:2] |
|
1904 | return self._complete(line_buffer=line_buffer, cursor_pos=cursor_pos, text=text, cursor_line=0)[:2] | |
1841 |
|
1905 | |||
1842 | def _complete(self, *, cursor_line, cursor_pos, line_buffer=None, text=None, |
|
1906 | def _complete(self, *, cursor_line, cursor_pos, line_buffer=None, text=None, | |
1843 | full_text=None, return_jedi_results=True) -> Tuple[str, List[str], List[str], Iterable[_FakeJediCompletion]]: |
|
1907 | full_text=None, return_jedi_results=True) -> Tuple[str, List[str], List[str], Iterable[_FakeJediCompletion]]: | |
1844 | """ |
|
1908 | """ | |
1845 |
|
1909 | |||
1846 | Like complete but can also returns raw jedi completions as well as the |
|
1910 | Like complete but can also returns raw jedi completions as well as the | |
1847 | origin of the completion text. This could (and should) be made much |
|
1911 | origin of the completion text. This could (and should) be made much | |
1848 | cleaner but that will be simpler once we drop the old (and stateful) |
|
1912 | cleaner but that will be simpler once we drop the old (and stateful) | |
1849 | :any:`complete` API. |
|
1913 | :any:`complete` API. | |
1850 |
|
1914 | |||
1851 |
|
1915 | |||
1852 | With current provisional API, cursor_pos act both (depending on the |
|
1916 | With current provisional API, cursor_pos act both (depending on the | |
1853 | caller) as the offset in the ``text`` or ``line_buffer``, or as the |
|
1917 | caller) as the offset in the ``text`` or ``line_buffer``, or as the | |
1854 | ``column`` when passing multiline strings this could/should be renamed |
|
1918 | ``column`` when passing multiline strings this could/should be renamed | |
1855 | but would add extra noise. |
|
1919 | but would add extra noise. | |
1856 | """ |
|
1920 | """ | |
1857 |
|
1921 | |||
1858 | # if the cursor position isn't given, the only sane assumption we can |
|
1922 | # if the cursor position isn't given, the only sane assumption we can | |
1859 | # make is that it's at the end of the line (the common case) |
|
1923 | # make is that it's at the end of the line (the common case) | |
1860 | if cursor_pos is None: |
|
1924 | if cursor_pos is None: | |
1861 | cursor_pos = len(line_buffer) if text is None else len(text) |
|
1925 | cursor_pos = len(line_buffer) if text is None else len(text) | |
1862 |
|
1926 | |||
1863 | if self.use_main_ns: |
|
1927 | if self.use_main_ns: | |
1864 | self.namespace = __main__.__dict__ |
|
1928 | self.namespace = __main__.__dict__ | |
1865 |
|
1929 | |||
1866 | # if text is either None or an empty string, rely on the line buffer |
|
1930 | # if text is either None or an empty string, rely on the line buffer | |
1867 | if (not line_buffer) and full_text: |
|
1931 | if (not line_buffer) and full_text: | |
1868 | line_buffer = full_text.split('\n')[cursor_line] |
|
1932 | line_buffer = full_text.split('\n')[cursor_line] | |
1869 | if not text: |
|
1933 | if not text: | |
1870 | text = self.splitter.split_line(line_buffer, cursor_pos) |
|
1934 | text = self.splitter.split_line(line_buffer, cursor_pos) | |
1871 |
|
1935 | |||
1872 | if self.backslash_combining_completions: |
|
1936 | if self.backslash_combining_completions: | |
1873 | # allow deactivation of these on windows. |
|
1937 | # allow deactivation of these on windows. | |
1874 | base_text = text if not line_buffer else line_buffer[:cursor_pos] |
|
1938 | base_text = text if not line_buffer else line_buffer[:cursor_pos] | |
1875 | latex_text, latex_matches = self.latex_matches(base_text) |
|
1939 | latex_text, latex_matches = self.latex_matches(base_text) | |
1876 | if latex_matches: |
|
1940 | if latex_matches: | |
1877 | return latex_text, latex_matches, ['latex_matches']*len(latex_matches), () |
|
1941 | return latex_text, latex_matches, ['latex_matches']*len(latex_matches), () | |
1878 | name_text = '' |
|
1942 | name_text = '' | |
1879 | name_matches = [] |
|
1943 | name_matches = [] | |
1880 | for meth in (self.unicode_name_matches, back_latex_name_matches, back_unicode_name_matches): |
|
1944 | for meth in (self.unicode_name_matches, back_latex_name_matches, back_unicode_name_matches): | |
1881 | name_text, name_matches = meth(base_text) |
|
1945 | name_text, name_matches = meth(base_text) | |
1882 | if name_text: |
|
1946 | if name_text: | |
1883 | return name_text, name_matches, [meth.__qualname__]*len(name_matches), () |
|
1947 | return name_text, name_matches, [meth.__qualname__]*len(name_matches), () | |
1884 |
|
1948 | |||
1885 |
|
1949 | |||
1886 | # If no line buffer is given, assume the input text is all there was |
|
1950 | # If no line buffer is given, assume the input text is all there was | |
1887 | if line_buffer is None: |
|
1951 | if line_buffer is None: | |
1888 | line_buffer = text |
|
1952 | line_buffer = text | |
1889 |
|
1953 | |||
1890 | self.line_buffer = line_buffer |
|
1954 | self.line_buffer = line_buffer | |
1891 | self.text_until_cursor = self.line_buffer[:cursor_pos] |
|
1955 | self.text_until_cursor = self.line_buffer[:cursor_pos] | |
1892 |
|
1956 | |||
1893 | # Do magic arg matches |
|
1957 | # Do magic arg matches | |
1894 | for matcher in self.magic_arg_matchers: |
|
1958 | for matcher in self.magic_arg_matchers: | |
1895 | matches = [(m, matcher.__qualname__) for m in matcher(line_buffer)] |
|
1959 | matches = [(m, matcher.__qualname__) for m in matcher(line_buffer)] | |
1896 | if matches: |
|
1960 | if matches: | |
1897 | matches2 = [m[0] for m in matches] |
|
1961 | matches2 = [m[0] for m in matches] | |
1898 | origins = [m[1] for m in matches] |
|
1962 | origins = [m[1] for m in matches] | |
1899 | return text, matches2, origins, () |
|
1963 | return text, matches2, origins, () | |
1900 |
|
1964 | |||
1901 | # Start with a clean slate of completions |
|
1965 | # Start with a clean slate of completions | |
1902 | matches = [] |
|
1966 | matches = [] | |
1903 | custom_res = self.dispatch_custom_completer(text) |
|
1967 | custom_res = self.dispatch_custom_completer(text) | |
1904 | # FIXME: we should extend our api to return a dict with completions for |
|
1968 | # FIXME: we should extend our api to return a dict with completions for | |
1905 | # different types of objects. The rlcomplete() method could then |
|
1969 | # different types of objects. The rlcomplete() method could then | |
1906 | # simply collapse the dict into a list for readline, but we'd have |
|
1970 | # simply collapse the dict into a list for readline, but we'd have | |
1907 | # richer completion semantics in other evironments. |
|
1971 | # richer completion semantics in other evironments. | |
1908 | completions = () |
|
1972 | completions = () | |
1909 | if self.use_jedi and return_jedi_results: |
|
1973 | if self.use_jedi and return_jedi_results: | |
1910 | if not full_text: |
|
1974 | if not full_text: | |
1911 | full_text = line_buffer |
|
1975 | full_text = line_buffer | |
1912 | completions = self._jedi_matches( |
|
1976 | completions = self._jedi_matches( | |
1913 | cursor_pos, cursor_line, full_text) |
|
1977 | cursor_pos, cursor_line, full_text) | |
1914 | if custom_res is not None: |
|
1978 | if custom_res is not None: | |
1915 | # did custom completers produce something? |
|
1979 | # did custom completers produce something? | |
1916 | matches = [(m, 'custom') for m in custom_res] |
|
1980 | matches = [(m, 'custom') for m in custom_res] | |
1917 | else: |
|
1981 | else: | |
1918 | # Extend the list of completions with the results of each |
|
1982 | # Extend the list of completions with the results of each | |
1919 | # matcher, so we return results to the user from all |
|
1983 | # matcher, so we return results to the user from all | |
1920 | # namespaces. |
|
1984 | # namespaces. | |
1921 | if self.merge_completions: |
|
1985 | if self.merge_completions: | |
1922 | matches = [] |
|
1986 | matches = [] | |
1923 | for matcher in self.matchers: |
|
1987 | for matcher in self.matchers: | |
1924 | try: |
|
1988 | try: | |
1925 | matches.extend([(m, matcher.__qualname__) |
|
1989 | matches.extend([(m, matcher.__qualname__) | |
1926 | for m in matcher(text)]) |
|
1990 | for m in matcher(text)]) | |
1927 | except: |
|
1991 | except: | |
1928 | # Show the ugly traceback if the matcher causes an |
|
1992 | # Show the ugly traceback if the matcher causes an | |
1929 | # exception, but do NOT crash the kernel! |
|
1993 | # exception, but do NOT crash the kernel! | |
1930 | sys.excepthook(*sys.exc_info()) |
|
1994 | sys.excepthook(*sys.exc_info()) | |
1931 | else: |
|
1995 | else: | |
1932 | for matcher in self.matchers: |
|
1996 | for matcher in self.matchers: | |
1933 | matches = [(m, matcher.__qualname__) |
|
1997 | matches = [(m, matcher.__qualname__) | |
1934 | for m in matcher(text)] |
|
1998 | for m in matcher(text)] | |
1935 | if matches: |
|
1999 | if matches: | |
1936 | break |
|
2000 | break | |
1937 | seen = set() |
|
2001 | seen = set() | |
1938 | filtered_matches = set() |
|
2002 | filtered_matches = set() | |
1939 | for m in matches: |
|
2003 | for m in matches: | |
1940 | t, c = m |
|
2004 | t, c = m | |
1941 | if t not in seen: |
|
2005 | if t not in seen: | |
1942 | filtered_matches.add(m) |
|
2006 | filtered_matches.add(m) | |
1943 | seen.add(t) |
|
2007 | seen.add(t) | |
1944 |
|
2008 | |||
1945 | _filtered_matches = sorted( |
|
2009 | _filtered_matches = sorted( | |
1946 | set(filtered_matches), key=lambda x: completions_sorting_key(x[0])) |
|
2010 | set(filtered_matches), key=lambda x: completions_sorting_key(x[0])) | |
1947 |
|
2011 | |||
1948 | _matches = [m[0] for m in _filtered_matches] |
|
2012 | _matches = [m[0] for m in _filtered_matches] | |
1949 | origins = [m[1] for m in _filtered_matches] |
|
2013 | origins = [m[1] for m in _filtered_matches] | |
1950 |
|
2014 | |||
1951 | self.matches = _matches |
|
2015 | self.matches = _matches | |
1952 |
|
2016 | |||
1953 | return text, _matches, origins, completions |
|
2017 | return text, _matches, origins, completions |
@@ -1,352 +1,354 b'' | |||||
1 | # encoding: utf-8 |
|
1 | # encoding: utf-8 | |
2 | """Implementations for various useful completers. |
|
2 | """Implementations for various useful completers. | |
3 |
|
3 | |||
4 | These are all loaded by default by IPython. |
|
4 | These are all loaded by default by IPython. | |
5 | """ |
|
5 | """ | |
6 | #----------------------------------------------------------------------------- |
|
6 | #----------------------------------------------------------------------------- | |
7 | # Copyright (C) 2010-2011 The IPython Development Team. |
|
7 | # Copyright (C) 2010-2011 The IPython Development Team. | |
8 | # |
|
8 | # | |
9 | # Distributed under the terms of the BSD License. |
|
9 | # Distributed under the terms of the BSD License. | |
10 | # |
|
10 | # | |
11 | # The full license is in the file COPYING.txt, distributed with this software. |
|
11 | # The full license is in the file COPYING.txt, distributed with this software. | |
12 | #----------------------------------------------------------------------------- |
|
12 | #----------------------------------------------------------------------------- | |
13 |
|
13 | |||
14 | #----------------------------------------------------------------------------- |
|
14 | #----------------------------------------------------------------------------- | |
15 | # Imports |
|
15 | # Imports | |
16 | #----------------------------------------------------------------------------- |
|
16 | #----------------------------------------------------------------------------- | |
17 |
|
17 | |||
18 | # Stdlib imports |
|
18 | # Stdlib imports | |
19 | import glob |
|
19 | import glob | |
20 | import inspect |
|
20 | import inspect | |
21 | import os |
|
21 | import os | |
22 | import re |
|
22 | import re | |
23 | import sys |
|
23 | import sys | |
24 | from importlib import import_module |
|
24 | from importlib import import_module | |
25 | from importlib.machinery import all_suffixes |
|
25 | from importlib.machinery import all_suffixes | |
26 |
|
26 | |||
27 |
|
27 | |||
28 | # Third-party imports |
|
28 | # Third-party imports | |
29 | from time import time |
|
29 | from time import time | |
30 | from zipimport import zipimporter |
|
30 | from zipimport import zipimporter | |
31 |
|
31 | |||
32 | # Our own imports |
|
32 | # Our own imports | |
33 | from IPython.core.completer import expand_user, compress_user |
|
33 | from IPython.core.completer import expand_user, compress_user | |
34 | from IPython.core.error import TryNext |
|
34 | from IPython.core.error import TryNext | |
35 | from IPython.utils._process_common import arg_split |
|
35 | from IPython.utils._process_common import arg_split | |
36 |
|
36 | |||
37 | # FIXME: this should be pulled in with the right call via the component system |
|
37 | # FIXME: this should be pulled in with the right call via the component system | |
38 | from IPython import get_ipython |
|
38 | from IPython import get_ipython | |
39 |
|
39 | |||
|
40 | from typing import List | |||
|
41 | ||||
40 | #----------------------------------------------------------------------------- |
|
42 | #----------------------------------------------------------------------------- | |
41 | # Globals and constants |
|
43 | # Globals and constants | |
42 | #----------------------------------------------------------------------------- |
|
44 | #----------------------------------------------------------------------------- | |
43 | _suffixes = all_suffixes() |
|
45 | _suffixes = all_suffixes() | |
44 |
|
46 | |||
45 | # Time in seconds after which the rootmodules will be stored permanently in the |
|
47 | # Time in seconds after which the rootmodules will be stored permanently in the | |
46 | # ipython ip.db database (kept in the user's .ipython dir). |
|
48 | # ipython ip.db database (kept in the user's .ipython dir). | |
47 | TIMEOUT_STORAGE = 2 |
|
49 | TIMEOUT_STORAGE = 2 | |
48 |
|
50 | |||
49 | # Time in seconds after which we give up |
|
51 | # Time in seconds after which we give up | |
50 | TIMEOUT_GIVEUP = 20 |
|
52 | TIMEOUT_GIVEUP = 20 | |
51 |
|
53 | |||
52 | # Regular expression for the python import statement |
|
54 | # Regular expression for the python import statement | |
53 | import_re = re.compile(r'(?P<name>[a-zA-Z_][a-zA-Z0-9_]*?)' |
|
55 | import_re = re.compile(r'(?P<name>[a-zA-Z_][a-zA-Z0-9_]*?)' | |
54 | r'(?P<package>[/\\]__init__)?' |
|
56 | r'(?P<package>[/\\]__init__)?' | |
55 | r'(?P<suffix>%s)$' % |
|
57 | r'(?P<suffix>%s)$' % | |
56 | r'|'.join(re.escape(s) for s in _suffixes)) |
|
58 | r'|'.join(re.escape(s) for s in _suffixes)) | |
57 |
|
59 | |||
58 | # RE for the ipython %run command (python + ipython scripts) |
|
60 | # RE for the ipython %run command (python + ipython scripts) | |
59 | magic_run_re = re.compile(r'.*(\.ipy|\.ipynb|\.py[w]?)$') |
|
61 | magic_run_re = re.compile(r'.*(\.ipy|\.ipynb|\.py[w]?)$') | |
60 |
|
62 | |||
61 | #----------------------------------------------------------------------------- |
|
63 | #----------------------------------------------------------------------------- | |
62 | # Local utilities |
|
64 | # Local utilities | |
63 | #----------------------------------------------------------------------------- |
|
65 | #----------------------------------------------------------------------------- | |
64 |
|
66 | |||
65 | def module_list(path): |
|
67 | def module_list(path): | |
66 | """ |
|
68 | """ | |
67 | Return the list containing the names of the modules available in the given |
|
69 | Return the list containing the names of the modules available in the given | |
68 | folder. |
|
70 | folder. | |
69 | """ |
|
71 | """ | |
70 | # sys.path has the cwd as an empty string, but isdir/listdir need it as '.' |
|
72 | # sys.path has the cwd as an empty string, but isdir/listdir need it as '.' | |
71 | if path == '': |
|
73 | if path == '': | |
72 | path = '.' |
|
74 | path = '.' | |
73 |
|
75 | |||
74 | # A few local constants to be used in loops below |
|
76 | # A few local constants to be used in loops below | |
75 | pjoin = os.path.join |
|
77 | pjoin = os.path.join | |
76 |
|
78 | |||
77 | if os.path.isdir(path): |
|
79 | if os.path.isdir(path): | |
78 | # Build a list of all files in the directory and all files |
|
80 | # Build a list of all files in the directory and all files | |
79 | # in its subdirectories. For performance reasons, do not |
|
81 | # in its subdirectories. For performance reasons, do not | |
80 | # recurse more than one level into subdirectories. |
|
82 | # recurse more than one level into subdirectories. | |
81 | files = [] |
|
83 | files = [] | |
82 | for root, dirs, nondirs in os.walk(path, followlinks=True): |
|
84 | for root, dirs, nondirs in os.walk(path, followlinks=True): | |
83 | subdir = root[len(path)+1:] |
|
85 | subdir = root[len(path)+1:] | |
84 | if subdir: |
|
86 | if subdir: | |
85 | files.extend(pjoin(subdir, f) for f in nondirs) |
|
87 | files.extend(pjoin(subdir, f) for f in nondirs) | |
86 | dirs[:] = [] # Do not recurse into additional subdirectories. |
|
88 | dirs[:] = [] # Do not recurse into additional subdirectories. | |
87 | else: |
|
89 | else: | |
88 | files.extend(nondirs) |
|
90 | files.extend(nondirs) | |
89 |
|
91 | |||
90 | else: |
|
92 | else: | |
91 | try: |
|
93 | try: | |
92 | files = list(zipimporter(path)._files.keys()) |
|
94 | files = list(zipimporter(path)._files.keys()) | |
93 | except: |
|
95 | except: | |
94 | files = [] |
|
96 | files = [] | |
95 |
|
97 | |||
96 | # Build a list of modules which match the import_re regex. |
|
98 | # Build a list of modules which match the import_re regex. | |
97 | modules = [] |
|
99 | modules = [] | |
98 | for f in files: |
|
100 | for f in files: | |
99 | m = import_re.match(f) |
|
101 | m = import_re.match(f) | |
100 | if m: |
|
102 | if m: | |
101 | modules.append(m.group('name')) |
|
103 | modules.append(m.group('name')) | |
102 | return list(set(modules)) |
|
104 | return list(set(modules)) | |
103 |
|
105 | |||
104 |
|
106 | |||
105 | def get_root_modules(): |
|
107 | def get_root_modules(): | |
106 | """ |
|
108 | """ | |
107 | Returns a list containing the names of all the modules available in the |
|
109 | Returns a list containing the names of all the modules available in the | |
108 | folders of the pythonpath. |
|
110 | folders of the pythonpath. | |
109 |
|
111 | |||
110 | ip.db['rootmodules_cache'] maps sys.path entries to list of modules. |
|
112 | ip.db['rootmodules_cache'] maps sys.path entries to list of modules. | |
111 | """ |
|
113 | """ | |
112 | ip = get_ipython() |
|
114 | ip = get_ipython() | |
113 | if ip is None: |
|
115 | if ip is None: | |
114 | # No global shell instance to store cached list of modules. |
|
116 | # No global shell instance to store cached list of modules. | |
115 | # Don't try to scan for modules every time. |
|
117 | # Don't try to scan for modules every time. | |
116 | return list(sys.builtin_module_names) |
|
118 | return list(sys.builtin_module_names) | |
117 |
|
119 | |||
118 | rootmodules_cache = ip.db.get('rootmodules_cache', {}) |
|
120 | rootmodules_cache = ip.db.get('rootmodules_cache', {}) | |
119 | rootmodules = list(sys.builtin_module_names) |
|
121 | rootmodules = list(sys.builtin_module_names) | |
120 | start_time = time() |
|
122 | start_time = time() | |
121 | store = False |
|
123 | store = False | |
122 | for path in sys.path: |
|
124 | for path in sys.path: | |
123 | try: |
|
125 | try: | |
124 | modules = rootmodules_cache[path] |
|
126 | modules = rootmodules_cache[path] | |
125 | except KeyError: |
|
127 | except KeyError: | |
126 | modules = module_list(path) |
|
128 | modules = module_list(path) | |
127 | try: |
|
129 | try: | |
128 | modules.remove('__init__') |
|
130 | modules.remove('__init__') | |
129 | except ValueError: |
|
131 | except ValueError: | |
130 | pass |
|
132 | pass | |
131 | if path not in ('', '.'): # cwd modules should not be cached |
|
133 | if path not in ('', '.'): # cwd modules should not be cached | |
132 | rootmodules_cache[path] = modules |
|
134 | rootmodules_cache[path] = modules | |
133 | if time() - start_time > TIMEOUT_STORAGE and not store: |
|
135 | if time() - start_time > TIMEOUT_STORAGE and not store: | |
134 | store = True |
|
136 | store = True | |
135 | print("\nCaching the list of root modules, please wait!") |
|
137 | print("\nCaching the list of root modules, please wait!") | |
136 | print("(This will only be done once - type '%rehashx' to " |
|
138 | print("(This will only be done once - type '%rehashx' to " | |
137 | "reset cache!)\n") |
|
139 | "reset cache!)\n") | |
138 | sys.stdout.flush() |
|
140 | sys.stdout.flush() | |
139 | if time() - start_time > TIMEOUT_GIVEUP: |
|
141 | if time() - start_time > TIMEOUT_GIVEUP: | |
140 | print("This is taking too long, we give up.\n") |
|
142 | print("This is taking too long, we give up.\n") | |
141 | return [] |
|
143 | return [] | |
142 | rootmodules.extend(modules) |
|
144 | rootmodules.extend(modules) | |
143 | if store: |
|
145 | if store: | |
144 | ip.db['rootmodules_cache'] = rootmodules_cache |
|
146 | ip.db['rootmodules_cache'] = rootmodules_cache | |
145 | rootmodules = list(set(rootmodules)) |
|
147 | rootmodules = list(set(rootmodules)) | |
146 | return rootmodules |
|
148 | return rootmodules | |
147 |
|
149 | |||
148 |
|
150 | |||
149 | def is_importable(module, attr, only_modules): |
|
151 | def is_importable(module, attr, only_modules): | |
150 | if only_modules: |
|
152 | if only_modules: | |
151 | return inspect.ismodule(getattr(module, attr)) |
|
153 | return inspect.ismodule(getattr(module, attr)) | |
152 | else: |
|
154 | else: | |
153 | return not(attr[:2] == '__' and attr[-2:] == '__') |
|
155 | return not(attr[:2] == '__' and attr[-2:] == '__') | |
154 |
|
156 | |||
155 |
|
157 | |||
156 | def try_import(mod: str, only_modules=False): |
|
158 | def try_import(mod: str, only_modules=False) -> List[str]: | |
157 | """ |
|
159 | """ | |
158 | Try to import given module and return list of potential completions. |
|
160 | Try to import given module and return list of potential completions. | |
159 | """ |
|
161 | """ | |
160 | mod = mod.rstrip('.') |
|
162 | mod = mod.rstrip('.') | |
161 | try: |
|
163 | try: | |
162 | m = import_module(mod) |
|
164 | m = import_module(mod) | |
163 | except: |
|
165 | except: | |
164 | return [] |
|
166 | return [] | |
165 |
|
167 | |||
166 | m_is_init = hasattr(m, '__file__') and '__init__' in m.__file__ |
|
168 | m_is_init = hasattr(m, '__file__') and '__init__' in m.__file__ | |
167 |
|
169 | |||
168 | completions = [] |
|
170 | completions = [] | |
169 | if (not hasattr(m, '__file__')) or (not only_modules) or m_is_init: |
|
171 | if (not hasattr(m, '__file__')) or (not only_modules) or m_is_init: | |
170 | completions.extend( [attr for attr in dir(m) if |
|
172 | completions.extend( [attr for attr in dir(m) if | |
171 | is_importable(m, attr, only_modules)]) |
|
173 | is_importable(m, attr, only_modules)]) | |
172 |
|
174 | |||
173 | completions.extend(getattr(m, '__all__', [])) |
|
175 | completions.extend(getattr(m, '__all__', [])) | |
174 | if m_is_init: |
|
176 | if m_is_init: | |
175 | completions.extend(module_list(os.path.dirname(m.__file__))) |
|
177 | completions.extend(module_list(os.path.dirname(m.__file__))) | |
176 | completions = {c for c in completions if isinstance(c, str)} |
|
178 | completions_set = {c for c in completions if isinstance(c, str)} | |
177 | completions.discard('__init__') |
|
179 | completions_set.discard('__init__') | |
178 | return list(completions) |
|
180 | return list(completions_set) | |
179 |
|
181 | |||
180 |
|
182 | |||
181 | #----------------------------------------------------------------------------- |
|
183 | #----------------------------------------------------------------------------- | |
182 | # Completion-related functions. |
|
184 | # Completion-related functions. | |
183 | #----------------------------------------------------------------------------- |
|
185 | #----------------------------------------------------------------------------- | |
184 |
|
186 | |||
185 | def quick_completer(cmd, completions): |
|
187 | def quick_completer(cmd, completions): | |
186 | """ Easily create a trivial completer for a command. |
|
188 | """ Easily create a trivial completer for a command. | |
187 |
|
189 | |||
188 | Takes either a list of completions, or all completions in string (that will |
|
190 | Takes either a list of completions, or all completions in string (that will | |
189 | be split on whitespace). |
|
191 | be split on whitespace). | |
190 |
|
192 | |||
191 | Example:: |
|
193 | Example:: | |
192 |
|
194 | |||
193 | [d:\ipython]|1> import ipy_completers |
|
195 | [d:\ipython]|1> import ipy_completers | |
194 | [d:\ipython]|2> ipy_completers.quick_completer('foo', ['bar','baz']) |
|
196 | [d:\ipython]|2> ipy_completers.quick_completer('foo', ['bar','baz']) | |
195 | [d:\ipython]|3> foo b<TAB> |
|
197 | [d:\ipython]|3> foo b<TAB> | |
196 | bar baz |
|
198 | bar baz | |
197 | [d:\ipython]|3> foo ba |
|
199 | [d:\ipython]|3> foo ba | |
198 | """ |
|
200 | """ | |
199 |
|
201 | |||
200 | if isinstance(completions, str): |
|
202 | if isinstance(completions, str): | |
201 | completions = completions.split() |
|
203 | completions = completions.split() | |
202 |
|
204 | |||
203 | def do_complete(self, event): |
|
205 | def do_complete(self, event): | |
204 | return completions |
|
206 | return completions | |
205 |
|
207 | |||
206 | get_ipython().set_hook('complete_command',do_complete, str_key = cmd) |
|
208 | get_ipython().set_hook('complete_command',do_complete, str_key = cmd) | |
207 |
|
209 | |||
208 | def module_completion(line): |
|
210 | def module_completion(line): | |
209 | """ |
|
211 | """ | |
210 | Returns a list containing the completion possibilities for an import line. |
|
212 | Returns a list containing the completion possibilities for an import line. | |
211 |
|
213 | |||
212 | The line looks like this : |
|
214 | The line looks like this : | |
213 | 'import xml.d' |
|
215 | 'import xml.d' | |
214 | 'from xml.dom import' |
|
216 | 'from xml.dom import' | |
215 | """ |
|
217 | """ | |
216 |
|
218 | |||
217 | words = line.split(' ') |
|
219 | words = line.split(' ') | |
218 | nwords = len(words) |
|
220 | nwords = len(words) | |
219 |
|
221 | |||
220 | # from whatever <tab> -> 'import ' |
|
222 | # from whatever <tab> -> 'import ' | |
221 | if nwords == 3 and words[0] == 'from': |
|
223 | if nwords == 3 and words[0] == 'from': | |
222 | return ['import '] |
|
224 | return ['import '] | |
223 |
|
225 | |||
224 | # 'from xy<tab>' or 'import xy<tab>' |
|
226 | # 'from xy<tab>' or 'import xy<tab>' | |
225 | if nwords < 3 and (words[0] in {'%aimport', 'import', 'from'}) : |
|
227 | if nwords < 3 and (words[0] in {'%aimport', 'import', 'from'}) : | |
226 | if nwords == 1: |
|
228 | if nwords == 1: | |
227 | return get_root_modules() |
|
229 | return get_root_modules() | |
228 | mod = words[1].split('.') |
|
230 | mod = words[1].split('.') | |
229 | if len(mod) < 2: |
|
231 | if len(mod) < 2: | |
230 | return get_root_modules() |
|
232 | return get_root_modules() | |
231 | completion_list = try_import('.'.join(mod[:-1]), True) |
|
233 | completion_list = try_import('.'.join(mod[:-1]), True) | |
232 | return ['.'.join(mod[:-1] + [el]) for el in completion_list] |
|
234 | return ['.'.join(mod[:-1] + [el]) for el in completion_list] | |
233 |
|
235 | |||
234 | # 'from xyz import abc<tab>' |
|
236 | # 'from xyz import abc<tab>' | |
235 | if nwords >= 3 and words[0] == 'from': |
|
237 | if nwords >= 3 and words[0] == 'from': | |
236 | mod = words[1] |
|
238 | mod = words[1] | |
237 | return try_import(mod) |
|
239 | return try_import(mod) | |
238 |
|
240 | |||
239 | #----------------------------------------------------------------------------- |
|
241 | #----------------------------------------------------------------------------- | |
240 | # Completers |
|
242 | # Completers | |
241 | #----------------------------------------------------------------------------- |
|
243 | #----------------------------------------------------------------------------- | |
242 | # These all have the func(self, event) signature to be used as custom |
|
244 | # These all have the func(self, event) signature to be used as custom | |
243 | # completers |
|
245 | # completers | |
244 |
|
246 | |||
245 | def module_completer(self,event): |
|
247 | def module_completer(self,event): | |
246 | """Give completions after user has typed 'import ...' or 'from ...'""" |
|
248 | """Give completions after user has typed 'import ...' or 'from ...'""" | |
247 |
|
249 | |||
248 | # This works in all versions of python. While 2.5 has |
|
250 | # This works in all versions of python. While 2.5 has | |
249 | # pkgutil.walk_packages(), that particular routine is fairly dangerous, |
|
251 | # pkgutil.walk_packages(), that particular routine is fairly dangerous, | |
250 | # since it imports *EVERYTHING* on sys.path. That is: a) very slow b) full |
|
252 | # since it imports *EVERYTHING* on sys.path. That is: a) very slow b) full | |
251 | # of possibly problematic side effects. |
|
253 | # of possibly problematic side effects. | |
252 | # This search the folders in the sys.path for available modules. |
|
254 | # This search the folders in the sys.path for available modules. | |
253 |
|
255 | |||
254 | return module_completion(event.line) |
|
256 | return module_completion(event.line) | |
255 |
|
257 | |||
256 | # FIXME: there's a lot of logic common to the run, cd and builtin file |
|
258 | # FIXME: there's a lot of logic common to the run, cd and builtin file | |
257 | # completers, that is currently reimplemented in each. |
|
259 | # completers, that is currently reimplemented in each. | |
258 |
|
260 | |||
259 | def magic_run_completer(self, event): |
|
261 | def magic_run_completer(self, event): | |
260 | """Complete files that end in .py or .ipy or .ipynb for the %run command. |
|
262 | """Complete files that end in .py or .ipy or .ipynb for the %run command. | |
261 | """ |
|
263 | """ | |
262 | comps = arg_split(event.line, strict=False) |
|
264 | comps = arg_split(event.line, strict=False) | |
263 | # relpath should be the current token that we need to complete. |
|
265 | # relpath should be the current token that we need to complete. | |
264 | if (len(comps) > 1) and (not event.line.endswith(' ')): |
|
266 | if (len(comps) > 1) and (not event.line.endswith(' ')): | |
265 | relpath = comps[-1].strip("'\"") |
|
267 | relpath = comps[-1].strip("'\"") | |
266 | else: |
|
268 | else: | |
267 | relpath = '' |
|
269 | relpath = '' | |
268 |
|
270 | |||
269 | #print("\nev=", event) # dbg |
|
271 | #print("\nev=", event) # dbg | |
270 | #print("rp=", relpath) # dbg |
|
272 | #print("rp=", relpath) # dbg | |
271 | #print('comps=', comps) # dbg |
|
273 | #print('comps=', comps) # dbg | |
272 |
|
274 | |||
273 | lglob = glob.glob |
|
275 | lglob = glob.glob | |
274 | isdir = os.path.isdir |
|
276 | isdir = os.path.isdir | |
275 | relpath, tilde_expand, tilde_val = expand_user(relpath) |
|
277 | relpath, tilde_expand, tilde_val = expand_user(relpath) | |
276 |
|
278 | |||
277 | # Find if the user has already typed the first filename, after which we |
|
279 | # Find if the user has already typed the first filename, after which we | |
278 | # should complete on all files, since after the first one other files may |
|
280 | # should complete on all files, since after the first one other files may | |
279 | # be arguments to the input script. |
|
281 | # be arguments to the input script. | |
280 |
|
282 | |||
281 | if any(magic_run_re.match(c) for c in comps): |
|
283 | if any(magic_run_re.match(c) for c in comps): | |
282 | matches = [f.replace('\\','/') + ('/' if isdir(f) else '') |
|
284 | matches = [f.replace('\\','/') + ('/' if isdir(f) else '') | |
283 | for f in lglob(relpath+'*')] |
|
285 | for f in lglob(relpath+'*')] | |
284 | else: |
|
286 | else: | |
285 | dirs = [f.replace('\\','/') + "/" for f in lglob(relpath+'*') if isdir(f)] |
|
287 | dirs = [f.replace('\\','/') + "/" for f in lglob(relpath+'*') if isdir(f)] | |
286 | pys = [f.replace('\\','/') |
|
288 | pys = [f.replace('\\','/') | |
287 | for f in lglob(relpath+'*.py') + lglob(relpath+'*.ipy') + |
|
289 | for f in lglob(relpath+'*.py') + lglob(relpath+'*.ipy') + | |
288 | lglob(relpath+'*.ipynb') + lglob(relpath + '*.pyw')] |
|
290 | lglob(relpath+'*.ipynb') + lglob(relpath + '*.pyw')] | |
289 |
|
291 | |||
290 | matches = dirs + pys |
|
292 | matches = dirs + pys | |
291 |
|
293 | |||
292 | #print('run comp:', dirs+pys) # dbg |
|
294 | #print('run comp:', dirs+pys) # dbg | |
293 | return [compress_user(p, tilde_expand, tilde_val) for p in matches] |
|
295 | return [compress_user(p, tilde_expand, tilde_val) for p in matches] | |
294 |
|
296 | |||
295 |
|
297 | |||
296 | def cd_completer(self, event): |
|
298 | def cd_completer(self, event): | |
297 | """Completer function for cd, which only returns directories.""" |
|
299 | """Completer function for cd, which only returns directories.""" | |
298 | ip = get_ipython() |
|
300 | ip = get_ipython() | |
299 | relpath = event.symbol |
|
301 | relpath = event.symbol | |
300 |
|
302 | |||
301 | #print(event) # dbg |
|
303 | #print(event) # dbg | |
302 | if event.line.endswith('-b') or ' -b ' in event.line: |
|
304 | if event.line.endswith('-b') or ' -b ' in event.line: | |
303 | # return only bookmark completions |
|
305 | # return only bookmark completions | |
304 | bkms = self.db.get('bookmarks', None) |
|
306 | bkms = self.db.get('bookmarks', None) | |
305 | if bkms: |
|
307 | if bkms: | |
306 | return bkms.keys() |
|
308 | return bkms.keys() | |
307 | else: |
|
309 | else: | |
308 | return [] |
|
310 | return [] | |
309 |
|
311 | |||
310 | if event.symbol == '-': |
|
312 | if event.symbol == '-': | |
311 | width_dh = str(len(str(len(ip.user_ns['_dh']) + 1))) |
|
313 | width_dh = str(len(str(len(ip.user_ns['_dh']) + 1))) | |
312 | # jump in directory history by number |
|
314 | # jump in directory history by number | |
313 | fmt = '-%0' + width_dh +'d [%s]' |
|
315 | fmt = '-%0' + width_dh +'d [%s]' | |
314 | ents = [ fmt % (i,s) for i,s in enumerate(ip.user_ns['_dh'])] |
|
316 | ents = [ fmt % (i,s) for i,s in enumerate(ip.user_ns['_dh'])] | |
315 | if len(ents) > 1: |
|
317 | if len(ents) > 1: | |
316 | return ents |
|
318 | return ents | |
317 | return [] |
|
319 | return [] | |
318 |
|
320 | |||
319 | if event.symbol.startswith('--'): |
|
321 | if event.symbol.startswith('--'): | |
320 | return ["--" + os.path.basename(d) for d in ip.user_ns['_dh']] |
|
322 | return ["--" + os.path.basename(d) for d in ip.user_ns['_dh']] | |
321 |
|
323 | |||
322 | # Expand ~ in path and normalize directory separators. |
|
324 | # Expand ~ in path and normalize directory separators. | |
323 | relpath, tilde_expand, tilde_val = expand_user(relpath) |
|
325 | relpath, tilde_expand, tilde_val = expand_user(relpath) | |
324 | relpath = relpath.replace('\\','/') |
|
326 | relpath = relpath.replace('\\','/') | |
325 |
|
327 | |||
326 | found = [] |
|
328 | found = [] | |
327 | for d in [f.replace('\\','/') + '/' for f in glob.glob(relpath+'*') |
|
329 | for d in [f.replace('\\','/') + '/' for f in glob.glob(relpath+'*') | |
328 | if os.path.isdir(f)]: |
|
330 | if os.path.isdir(f)]: | |
329 | if ' ' in d: |
|
331 | if ' ' in d: | |
330 | # we don't want to deal with any of that, complex code |
|
332 | # we don't want to deal with any of that, complex code | |
331 | # for this is elsewhere |
|
333 | # for this is elsewhere | |
332 | raise TryNext |
|
334 | raise TryNext | |
333 |
|
335 | |||
334 | found.append(d) |
|
336 | found.append(d) | |
335 |
|
337 | |||
336 | if not found: |
|
338 | if not found: | |
337 | if os.path.isdir(relpath): |
|
339 | if os.path.isdir(relpath): | |
338 | return [compress_user(relpath, tilde_expand, tilde_val)] |
|
340 | return [compress_user(relpath, tilde_expand, tilde_val)] | |
339 |
|
341 | |||
340 | # if no completions so far, try bookmarks |
|
342 | # if no completions so far, try bookmarks | |
341 | bks = self.db.get('bookmarks',{}) |
|
343 | bks = self.db.get('bookmarks',{}) | |
342 | bkmatches = [s for s in bks if s.startswith(event.symbol)] |
|
344 | bkmatches = [s for s in bks if s.startswith(event.symbol)] | |
343 | if bkmatches: |
|
345 | if bkmatches: | |
344 | return bkmatches |
|
346 | return bkmatches | |
345 |
|
347 | |||
346 | raise TryNext |
|
348 | raise TryNext | |
347 |
|
349 | |||
348 | return [compress_user(p, tilde_expand, tilde_val) for p in found] |
|
350 | return [compress_user(p, tilde_expand, tilde_val) for p in found] | |
349 |
|
351 | |||
350 | def reset_completer(self, event): |
|
352 | def reset_completer(self, event): | |
351 | "A completer for %reset magic" |
|
353 | "A completer for %reset magic" | |
352 | return '-f -s in out array dhist'.split() |
|
354 | return '-f -s in out array dhist'.split() |
@@ -1,949 +1,961 b'' | |||||
1 | # encoding: utf-8 |
|
1 | # encoding: utf-8 | |
2 | """Tests for the IPython tab-completion machinery.""" |
|
2 | """Tests for the IPython tab-completion machinery.""" | |
3 |
|
3 | |||
4 | # Copyright (c) IPython Development Team. |
|
4 | # Copyright (c) IPython Development Team. | |
5 | # Distributed under the terms of the Modified BSD License. |
|
5 | # Distributed under the terms of the Modified BSD License. | |
6 |
|
6 | |||
7 | import os |
|
7 | import os | |
8 | import sys |
|
8 | import sys | |
9 | import textwrap |
|
9 | import textwrap | |
10 | import unittest |
|
10 | import unittest | |
11 |
|
11 | |||
12 | from contextlib import contextmanager |
|
12 | from contextlib import contextmanager | |
13 |
|
13 | |||
14 | import nose.tools as nt |
|
14 | import nose.tools as nt | |
15 |
|
15 | |||
16 | from traitlets.config.loader import Config |
|
16 | from traitlets.config.loader import Config | |
17 | from IPython import get_ipython |
|
17 | from IPython import get_ipython | |
18 | from IPython.core import completer |
|
18 | from IPython.core import completer | |
19 | from IPython.external.decorators import knownfailureif |
|
19 | from IPython.external.decorators import knownfailureif | |
20 | from IPython.utils.tempdir import TemporaryDirectory, TemporaryWorkingDirectory |
|
20 | from IPython.utils.tempdir import TemporaryDirectory, TemporaryWorkingDirectory | |
21 | from IPython.utils.generics import complete_object |
|
21 | from IPython.utils.generics import complete_object | |
22 | from IPython.testing import decorators as dec |
|
22 | from IPython.testing import decorators as dec | |
23 |
|
23 | |||
24 | from IPython.core.completer import ( |
|
24 | from IPython.core.completer import ( | |
25 | Completion, provisionalcompleter, match_dict_keys, _deduplicate_completions) |
|
25 | Completion, provisionalcompleter, match_dict_keys, _deduplicate_completions) | |
26 | from nose.tools import assert_in, assert_not_in |
|
26 | from nose.tools import assert_in, assert_not_in | |
27 |
|
27 | |||
28 | #----------------------------------------------------------------------------- |
|
28 | #----------------------------------------------------------------------------- | |
29 | # Test functions |
|
29 | # Test functions | |
30 | #----------------------------------------------------------------------------- |
|
30 | #----------------------------------------------------------------------------- | |
31 |
|
31 | |||
32 | @contextmanager |
|
32 | @contextmanager | |
33 | def greedy_completion(): |
|
33 | def greedy_completion(): | |
34 | ip = get_ipython() |
|
34 | ip = get_ipython() | |
35 | greedy_original = ip.Completer.greedy |
|
35 | greedy_original = ip.Completer.greedy | |
36 | try: |
|
36 | try: | |
37 | ip.Completer.greedy = True |
|
37 | ip.Completer.greedy = True | |
38 | yield |
|
38 | yield | |
39 | finally: |
|
39 | finally: | |
40 | ip.Completer.greedy = greedy_original |
|
40 | ip.Completer.greedy = greedy_original | |
41 |
|
41 | |||
42 | def test_protect_filename(): |
|
42 | def test_protect_filename(): | |
43 | if sys.platform == 'win32': |
|
43 | if sys.platform == 'win32': | |
44 | pairs = [('abc','abc'), |
|
44 | pairs = [('abc','abc'), | |
45 | (' abc','" abc"'), |
|
45 | (' abc','" abc"'), | |
46 | ('a bc','"a bc"'), |
|
46 | ('a bc','"a bc"'), | |
47 | ('a bc','"a bc"'), |
|
47 | ('a bc','"a bc"'), | |
48 | (' bc','" bc"'), |
|
48 | (' bc','" bc"'), | |
49 | ] |
|
49 | ] | |
50 | else: |
|
50 | else: | |
51 | pairs = [('abc','abc'), |
|
51 | pairs = [('abc','abc'), | |
52 | (' abc',r'\ abc'), |
|
52 | (' abc',r'\ abc'), | |
53 | ('a bc',r'a\ bc'), |
|
53 | ('a bc',r'a\ bc'), | |
54 | ('a bc',r'a\ \ bc'), |
|
54 | ('a bc',r'a\ \ bc'), | |
55 | (' bc',r'\ \ bc'), |
|
55 | (' bc',r'\ \ bc'), | |
56 | # On posix, we also protect parens and other special characters. |
|
56 | # On posix, we also protect parens and other special characters. | |
57 | ('a(bc',r'a\(bc'), |
|
57 | ('a(bc',r'a\(bc'), | |
58 | ('a)bc',r'a\)bc'), |
|
58 | ('a)bc',r'a\)bc'), | |
59 | ('a( )bc',r'a\(\ \)bc'), |
|
59 | ('a( )bc',r'a\(\ \)bc'), | |
60 | ('a[1]bc', r'a\[1\]bc'), |
|
60 | ('a[1]bc', r'a\[1\]bc'), | |
61 | ('a{1}bc', r'a\{1\}bc'), |
|
61 | ('a{1}bc', r'a\{1\}bc'), | |
62 | ('a#bc', r'a\#bc'), |
|
62 | ('a#bc', r'a\#bc'), | |
63 | ('a?bc', r'a\?bc'), |
|
63 | ('a?bc', r'a\?bc'), | |
64 | ('a=bc', r'a\=bc'), |
|
64 | ('a=bc', r'a\=bc'), | |
65 | ('a\\bc', r'a\\bc'), |
|
65 | ('a\\bc', r'a\\bc'), | |
66 | ('a|bc', r'a\|bc'), |
|
66 | ('a|bc', r'a\|bc'), | |
67 | ('a;bc', r'a\;bc'), |
|
67 | ('a;bc', r'a\;bc'), | |
68 | ('a:bc', r'a\:bc'), |
|
68 | ('a:bc', r'a\:bc'), | |
69 | ("a'bc", r"a\'bc"), |
|
69 | ("a'bc", r"a\'bc"), | |
70 | ('a*bc', r'a\*bc'), |
|
70 | ('a*bc', r'a\*bc'), | |
71 | ('a"bc', r'a\"bc'), |
|
71 | ('a"bc', r'a\"bc'), | |
72 | ('a^bc', r'a\^bc'), |
|
72 | ('a^bc', r'a\^bc'), | |
73 | ('a&bc', r'a\&bc'), |
|
73 | ('a&bc', r'a\&bc'), | |
74 | ] |
|
74 | ] | |
75 | # run the actual tests |
|
75 | # run the actual tests | |
76 | for s1, s2 in pairs: |
|
76 | for s1, s2 in pairs: | |
77 | s1p = completer.protect_filename(s1) |
|
77 | s1p = completer.protect_filename(s1) | |
78 | nt.assert_equal(s1p, s2) |
|
78 | nt.assert_equal(s1p, s2) | |
79 |
|
79 | |||
80 |
|
80 | |||
81 | def check_line_split(splitter, test_specs): |
|
81 | def check_line_split(splitter, test_specs): | |
82 | for part1, part2, split in test_specs: |
|
82 | for part1, part2, split in test_specs: | |
83 | cursor_pos = len(part1) |
|
83 | cursor_pos = len(part1) | |
84 | line = part1+part2 |
|
84 | line = part1+part2 | |
85 | out = splitter.split_line(line, cursor_pos) |
|
85 | out = splitter.split_line(line, cursor_pos) | |
86 | nt.assert_equal(out, split) |
|
86 | nt.assert_equal(out, split) | |
87 |
|
87 | |||
88 |
|
88 | |||
89 | def test_line_split(): |
|
89 | def test_line_split(): | |
90 | """Basic line splitter test with default specs.""" |
|
90 | """Basic line splitter test with default specs.""" | |
91 | sp = completer.CompletionSplitter() |
|
91 | sp = completer.CompletionSplitter() | |
92 | # The format of the test specs is: part1, part2, expected answer. Parts 1 |
|
92 | # The format of the test specs is: part1, part2, expected answer. Parts 1 | |
93 | # and 2 are joined into the 'line' sent to the splitter, as if the cursor |
|
93 | # and 2 are joined into the 'line' sent to the splitter, as if the cursor | |
94 | # was at the end of part1. So an empty part2 represents someone hitting |
|
94 | # was at the end of part1. So an empty part2 represents someone hitting | |
95 | # tab at the end of the line, the most common case. |
|
95 | # tab at the end of the line, the most common case. | |
96 | t = [('run some/scrip', '', 'some/scrip'), |
|
96 | t = [('run some/scrip', '', 'some/scrip'), | |
97 | ('run scripts/er', 'ror.py foo', 'scripts/er'), |
|
97 | ('run scripts/er', 'ror.py foo', 'scripts/er'), | |
98 | ('echo $HOM', '', 'HOM'), |
|
98 | ('echo $HOM', '', 'HOM'), | |
99 | ('print sys.pa', '', 'sys.pa'), |
|
99 | ('print sys.pa', '', 'sys.pa'), | |
100 | ('print(sys.pa', '', 'sys.pa'), |
|
100 | ('print(sys.pa', '', 'sys.pa'), | |
101 | ("execfile('scripts/er", '', 'scripts/er'), |
|
101 | ("execfile('scripts/er", '', 'scripts/er'), | |
102 | ('a[x.', '', 'x.'), |
|
102 | ('a[x.', '', 'x.'), | |
103 | ('a[x.', 'y', 'x.'), |
|
103 | ('a[x.', 'y', 'x.'), | |
104 | ('cd "some_file/', '', 'some_file/'), |
|
104 | ('cd "some_file/', '', 'some_file/'), | |
105 | ] |
|
105 | ] | |
106 | check_line_split(sp, t) |
|
106 | check_line_split(sp, t) | |
107 | # Ensure splitting works OK with unicode by re-running the tests with |
|
107 | # Ensure splitting works OK with unicode by re-running the tests with | |
108 | # all inputs turned into unicode |
|
108 | # all inputs turned into unicode | |
109 | check_line_split(sp, [ map(str, p) for p in t] ) |
|
109 | check_line_split(sp, [ map(str, p) for p in t] ) | |
110 |
|
110 | |||
111 |
|
111 | |||
112 | def test_custom_completion_error(): |
|
112 | def test_custom_completion_error(): | |
113 | """Test that errors from custom attribute completers are silenced.""" |
|
113 | """Test that errors from custom attribute completers are silenced.""" | |
114 | ip = get_ipython() |
|
114 | ip = get_ipython() | |
115 | class A(object): pass |
|
115 | class A(object): pass | |
116 | ip.user_ns['a'] = A() |
|
116 | ip.user_ns['a'] = A() | |
117 |
|
117 | |||
118 | @complete_object.when_type(A) |
|
118 | @complete_object.when_type(A) | |
119 | def complete_A(a, existing_completions): |
|
119 | def complete_A(a, existing_completions): | |
120 | raise TypeError("this should be silenced") |
|
120 | raise TypeError("this should be silenced") | |
121 |
|
121 | |||
122 | ip.complete("a.") |
|
122 | ip.complete("a.") | |
123 |
|
123 | |||
124 |
|
124 | |||
125 | def test_unicode_completions(): |
|
125 | def test_unicode_completions(): | |
126 | ip = get_ipython() |
|
126 | ip = get_ipython() | |
127 | # Some strings that trigger different types of completion. Check them both |
|
127 | # Some strings that trigger different types of completion. Check them both | |
128 | # in str and unicode forms |
|
128 | # in str and unicode forms | |
129 | s = ['ru', '%ru', 'cd /', 'floa', 'float(x)/'] |
|
129 | s = ['ru', '%ru', 'cd /', 'floa', 'float(x)/'] | |
130 | for t in s + list(map(str, s)): |
|
130 | for t in s + list(map(str, s)): | |
131 | # We don't need to check exact completion values (they may change |
|
131 | # We don't need to check exact completion values (they may change | |
132 | # depending on the state of the namespace, but at least no exceptions |
|
132 | # depending on the state of the namespace, but at least no exceptions | |
133 | # should be thrown and the return value should be a pair of text, list |
|
133 | # should be thrown and the return value should be a pair of text, list | |
134 | # values. |
|
134 | # values. | |
135 | text, matches = ip.complete(t) |
|
135 | text, matches = ip.complete(t) | |
136 | nt.assert_true(isinstance(text, str)) |
|
136 | nt.assert_true(isinstance(text, str)) | |
137 | nt.assert_true(isinstance(matches, list)) |
|
137 | nt.assert_true(isinstance(matches, list)) | |
138 |
|
138 | |||
139 | def test_latex_completions(): |
|
139 | def test_latex_completions(): | |
140 | from IPython.core.latex_symbols import latex_symbols |
|
140 | from IPython.core.latex_symbols import latex_symbols | |
141 | import random |
|
141 | import random | |
142 | ip = get_ipython() |
|
142 | ip = get_ipython() | |
143 | # Test some random unicode symbols |
|
143 | # Test some random unicode symbols | |
144 | keys = random.sample(latex_symbols.keys(), 10) |
|
144 | keys = random.sample(latex_symbols.keys(), 10) | |
145 | for k in keys: |
|
145 | for k in keys: | |
146 | text, matches = ip.complete(k) |
|
146 | text, matches = ip.complete(k) | |
147 | nt.assert_equal(len(matches),1) |
|
147 | nt.assert_equal(len(matches),1) | |
148 | nt.assert_equal(text, k) |
|
148 | nt.assert_equal(text, k) | |
149 | nt.assert_equal(matches[0], latex_symbols[k]) |
|
149 | nt.assert_equal(matches[0], latex_symbols[k]) | |
150 | # Test a more complex line |
|
150 | # Test a more complex line | |
151 | text, matches = ip.complete(u'print(\\alpha') |
|
151 | text, matches = ip.complete(u'print(\\alpha') | |
152 | nt.assert_equal(text, u'\\alpha') |
|
152 | nt.assert_equal(text, u'\\alpha') | |
153 | nt.assert_equal(matches[0], latex_symbols['\\alpha']) |
|
153 | nt.assert_equal(matches[0], latex_symbols['\\alpha']) | |
154 | # Test multiple matching latex symbols |
|
154 | # Test multiple matching latex symbols | |
155 | text, matches = ip.complete(u'\\al') |
|
155 | text, matches = ip.complete(u'\\al') | |
156 | nt.assert_in('\\alpha', matches) |
|
156 | nt.assert_in('\\alpha', matches) | |
157 | nt.assert_in('\\aleph', matches) |
|
157 | nt.assert_in('\\aleph', matches) | |
158 |
|
158 | |||
159 |
|
159 | |||
160 |
|
160 | |||
161 |
|
161 | |||
162 | def test_back_latex_completion(): |
|
162 | def test_back_latex_completion(): | |
163 | ip = get_ipython() |
|
163 | ip = get_ipython() | |
164 |
|
164 | |||
165 | # do not return more than 1 matches fro \beta, only the latex one. |
|
165 | # do not return more than 1 matches fro \beta, only the latex one. | |
166 | name, matches = ip.complete('\\Ξ²') |
|
166 | name, matches = ip.complete('\\Ξ²') | |
167 | nt.assert_equal(len(matches), 1) |
|
167 | nt.assert_equal(len(matches), 1) | |
168 | nt.assert_equal(matches[0], '\\beta') |
|
168 | nt.assert_equal(matches[0], '\\beta') | |
169 |
|
169 | |||
170 | def test_back_unicode_completion(): |
|
170 | def test_back_unicode_completion(): | |
171 | ip = get_ipython() |
|
171 | ip = get_ipython() | |
172 |
|
172 | |||
173 | name, matches = ip.complete('\\β €') |
|
173 | name, matches = ip.complete('\\β €') | |
174 | nt.assert_equal(len(matches), 1) |
|
174 | nt.assert_equal(len(matches), 1) | |
175 | nt.assert_equal(matches[0], '\\ROMAN NUMERAL FIVE') |
|
175 | nt.assert_equal(matches[0], '\\ROMAN NUMERAL FIVE') | |
176 |
|
176 | |||
177 |
|
177 | |||
178 | def test_forward_unicode_completion(): |
|
178 | def test_forward_unicode_completion(): | |
179 | ip = get_ipython() |
|
179 | ip = get_ipython() | |
180 |
|
180 | |||
181 | name, matches = ip.complete('\\ROMAN NUMERAL FIVE') |
|
181 | name, matches = ip.complete('\\ROMAN NUMERAL FIVE') | |
182 | nt.assert_equal(len(matches), 1) |
|
182 | nt.assert_equal(len(matches), 1) | |
183 | nt.assert_equal(matches[0], 'β €') |
|
183 | nt.assert_equal(matches[0], 'β €') | |
184 |
|
184 | |||
185 | @dec.knownfailureif(sys.platform == 'win32', 'Fails if there is a C:\\j... path') |
|
185 | @dec.knownfailureif(sys.platform == 'win32', 'Fails if there is a C:\\j... path') | |
186 | def test_no_ascii_back_completion(): |
|
186 | def test_no_ascii_back_completion(): | |
187 | ip = get_ipython() |
|
187 | ip = get_ipython() | |
188 | with TemporaryWorkingDirectory(): # Avoid any filename completions |
|
188 | with TemporaryWorkingDirectory(): # Avoid any filename completions | |
189 | # single ascii letter that don't have yet completions |
|
189 | # single ascii letter that don't have yet completions | |
190 | for letter in 'jJ' : |
|
190 | for letter in 'jJ' : | |
191 | name, matches = ip.complete('\\'+letter) |
|
191 | name, matches = ip.complete('\\'+letter) | |
192 | nt.assert_equal(matches, []) |
|
192 | nt.assert_equal(matches, []) | |
193 |
|
193 | |||
194 |
|
194 | |||
195 |
|
195 | |||
196 |
|
196 | |||
197 | class CompletionSplitterTestCase(unittest.TestCase): |
|
197 | class CompletionSplitterTestCase(unittest.TestCase): | |
198 | def setUp(self): |
|
198 | def setUp(self): | |
199 | self.sp = completer.CompletionSplitter() |
|
199 | self.sp = completer.CompletionSplitter() | |
200 |
|
200 | |||
201 | def test_delim_setting(self): |
|
201 | def test_delim_setting(self): | |
202 | self.sp.delims = ' ' |
|
202 | self.sp.delims = ' ' | |
203 | nt.assert_equal(self.sp.delims, ' ') |
|
203 | nt.assert_equal(self.sp.delims, ' ') | |
204 | nt.assert_equal(self.sp._delim_expr, '[\ ]') |
|
204 | nt.assert_equal(self.sp._delim_expr, '[\ ]') | |
205 |
|
205 | |||
206 | def test_spaces(self): |
|
206 | def test_spaces(self): | |
207 | """Test with only spaces as split chars.""" |
|
207 | """Test with only spaces as split chars.""" | |
208 | self.sp.delims = ' ' |
|
208 | self.sp.delims = ' ' | |
209 | t = [('foo', '', 'foo'), |
|
209 | t = [('foo', '', 'foo'), | |
210 | ('run foo', '', 'foo'), |
|
210 | ('run foo', '', 'foo'), | |
211 | ('run foo', 'bar', 'foo'), |
|
211 | ('run foo', 'bar', 'foo'), | |
212 | ] |
|
212 | ] | |
213 | check_line_split(self.sp, t) |
|
213 | check_line_split(self.sp, t) | |
214 |
|
214 | |||
215 |
|
215 | |||
216 | def test_has_open_quotes1(): |
|
216 | def test_has_open_quotes1(): | |
217 | for s in ["'", "'''", "'hi' '"]: |
|
217 | for s in ["'", "'''", "'hi' '"]: | |
218 | nt.assert_equal(completer.has_open_quotes(s), "'") |
|
218 | nt.assert_equal(completer.has_open_quotes(s), "'") | |
219 |
|
219 | |||
220 |
|
220 | |||
221 | def test_has_open_quotes2(): |
|
221 | def test_has_open_quotes2(): | |
222 | for s in ['"', '"""', '"hi" "']: |
|
222 | for s in ['"', '"""', '"hi" "']: | |
223 | nt.assert_equal(completer.has_open_quotes(s), '"') |
|
223 | nt.assert_equal(completer.has_open_quotes(s), '"') | |
224 |
|
224 | |||
225 |
|
225 | |||
226 | def test_has_open_quotes3(): |
|
226 | def test_has_open_quotes3(): | |
227 | for s in ["''", "''' '''", "'hi' 'ipython'"]: |
|
227 | for s in ["''", "''' '''", "'hi' 'ipython'"]: | |
228 | nt.assert_false(completer.has_open_quotes(s)) |
|
228 | nt.assert_false(completer.has_open_quotes(s)) | |
229 |
|
229 | |||
230 |
|
230 | |||
231 | def test_has_open_quotes4(): |
|
231 | def test_has_open_quotes4(): | |
232 | for s in ['""', '""" """', '"hi" "ipython"']: |
|
232 | for s in ['""', '""" """', '"hi" "ipython"']: | |
233 | nt.assert_false(completer.has_open_quotes(s)) |
|
233 | nt.assert_false(completer.has_open_quotes(s)) | |
234 |
|
234 | |||
235 |
|
235 | |||
236 | @knownfailureif(sys.platform == 'win32', "abspath completions fail on Windows") |
|
236 | @knownfailureif(sys.platform == 'win32', "abspath completions fail on Windows") | |
237 | def test_abspath_file_completions(): |
|
237 | def test_abspath_file_completions(): | |
238 | ip = get_ipython() |
|
238 | ip = get_ipython() | |
239 | with TemporaryDirectory() as tmpdir: |
|
239 | with TemporaryDirectory() as tmpdir: | |
240 | prefix = os.path.join(tmpdir, 'foo') |
|
240 | prefix = os.path.join(tmpdir, 'foo') | |
241 | suffixes = ['1', '2'] |
|
241 | suffixes = ['1', '2'] | |
242 | names = [prefix+s for s in suffixes] |
|
242 | names = [prefix+s for s in suffixes] | |
243 | for n in names: |
|
243 | for n in names: | |
244 | open(n, 'w').close() |
|
244 | open(n, 'w').close() | |
245 |
|
245 | |||
246 | # Check simple completion |
|
246 | # Check simple completion | |
247 | c = ip.complete(prefix)[1] |
|
247 | c = ip.complete(prefix)[1] | |
248 | nt.assert_equal(c, names) |
|
248 | nt.assert_equal(c, names) | |
249 |
|
249 | |||
250 | # Now check with a function call |
|
250 | # Now check with a function call | |
251 | cmd = 'a = f("%s' % prefix |
|
251 | cmd = 'a = f("%s' % prefix | |
252 | c = ip.complete(prefix, cmd)[1] |
|
252 | c = ip.complete(prefix, cmd)[1] | |
253 | comp = [prefix+s for s in suffixes] |
|
253 | comp = [prefix+s for s in suffixes] | |
254 | nt.assert_equal(c, comp) |
|
254 | nt.assert_equal(c, comp) | |
255 |
|
255 | |||
256 |
|
256 | |||
257 | def test_local_file_completions(): |
|
257 | def test_local_file_completions(): | |
258 | ip = get_ipython() |
|
258 | ip = get_ipython() | |
259 | with TemporaryWorkingDirectory(): |
|
259 | with TemporaryWorkingDirectory(): | |
260 | prefix = './foo' |
|
260 | prefix = './foo' | |
261 | suffixes = ['1', '2'] |
|
261 | suffixes = ['1', '2'] | |
262 | names = [prefix+s for s in suffixes] |
|
262 | names = [prefix+s for s in suffixes] | |
263 | for n in names: |
|
263 | for n in names: | |
264 | open(n, 'w').close() |
|
264 | open(n, 'w').close() | |
265 |
|
265 | |||
266 | # Check simple completion |
|
266 | # Check simple completion | |
267 | c = ip.complete(prefix)[1] |
|
267 | c = ip.complete(prefix)[1] | |
268 | nt.assert_equal(c, names) |
|
268 | nt.assert_equal(c, names) | |
269 |
|
269 | |||
270 | # Now check with a function call |
|
270 | # Now check with a function call | |
271 | cmd = 'a = f("%s' % prefix |
|
271 | cmd = 'a = f("%s' % prefix | |
272 | c = ip.complete(prefix, cmd)[1] |
|
272 | c = ip.complete(prefix, cmd)[1] | |
273 | comp = set(prefix+s for s in suffixes) |
|
273 | comp = set(prefix+s for s in suffixes) | |
274 | nt.assert_true(comp.issubset(set(c))) |
|
274 | nt.assert_true(comp.issubset(set(c))) | |
275 |
|
275 | |||
276 |
|
276 | |||
277 | def test_quoted_file_completions(): |
|
277 | def test_quoted_file_completions(): | |
278 | ip = get_ipython() |
|
278 | ip = get_ipython() | |
279 | with TemporaryWorkingDirectory(): |
|
279 | with TemporaryWorkingDirectory(): | |
280 | name = "foo'bar" |
|
280 | name = "foo'bar" | |
281 | open(name, 'w').close() |
|
281 | open(name, 'w').close() | |
282 |
|
282 | |||
283 | # Don't escape Windows |
|
283 | # Don't escape Windows | |
284 | escaped = name if sys.platform == "win32" else "foo\\'bar" |
|
284 | escaped = name if sys.platform == "win32" else "foo\\'bar" | |
285 |
|
285 | |||
286 | # Single quote matches embedded single quote |
|
286 | # Single quote matches embedded single quote | |
287 | text = "open('foo" |
|
287 | text = "open('foo" | |
288 | c = ip.Completer._complete(cursor_line=0, |
|
288 | c = ip.Completer._complete(cursor_line=0, | |
289 | cursor_pos=len(text), |
|
289 | cursor_pos=len(text), | |
290 | full_text=text)[1] |
|
290 | full_text=text)[1] | |
291 | nt.assert_equal(c, [escaped]) |
|
291 | nt.assert_equal(c, [escaped]) | |
292 |
|
292 | |||
293 | # Double quote requires no escape |
|
293 | # Double quote requires no escape | |
294 | text = 'open("foo' |
|
294 | text = 'open("foo' | |
295 | c = ip.Completer._complete(cursor_line=0, |
|
295 | c = ip.Completer._complete(cursor_line=0, | |
296 | cursor_pos=len(text), |
|
296 | cursor_pos=len(text), | |
297 | full_text=text)[1] |
|
297 | full_text=text)[1] | |
298 | nt.assert_equal(c, [name]) |
|
298 | nt.assert_equal(c, [name]) | |
299 |
|
299 | |||
300 | # No quote requires an escape |
|
300 | # No quote requires an escape | |
301 | text = '%ls foo' |
|
301 | text = '%ls foo' | |
302 | c = ip.Completer._complete(cursor_line=0, |
|
302 | c = ip.Completer._complete(cursor_line=0, | |
303 | cursor_pos=len(text), |
|
303 | cursor_pos=len(text), | |
304 | full_text=text)[1] |
|
304 | full_text=text)[1] | |
305 | nt.assert_equal(c, [escaped]) |
|
305 | nt.assert_equal(c, [escaped]) | |
306 |
|
306 | |||
307 |
|
307 | |||
308 | def test_jedi(): |
|
308 | def test_jedi(): | |
309 | """ |
|
309 | """ | |
310 | A couple of issue we had with Jedi |
|
310 | A couple of issue we had with Jedi | |
311 | """ |
|
311 | """ | |
312 | ip = get_ipython() |
|
312 | ip = get_ipython() | |
313 |
|
313 | |||
314 | def _test_complete(reason, s, comp, start=None, end=None): |
|
314 | def _test_complete(reason, s, comp, start=None, end=None): | |
315 | l = len(s) |
|
315 | l = len(s) | |
316 | start = start if start is not None else l |
|
316 | start = start if start is not None else l | |
317 | end = end if end is not None else l |
|
317 | end = end if end is not None else l | |
318 | with provisionalcompleter(): |
|
318 | with provisionalcompleter(): | |
319 | completions = set(ip.Completer.completions(s, l)) |
|
319 | completions = set(ip.Completer.completions(s, l)) | |
320 | assert_in(Completion(start, end, comp), completions, reason) |
|
320 | assert_in(Completion(start, end, comp), completions, reason) | |
321 |
|
321 | |||
322 | def _test_not_complete(reason, s, comp): |
|
322 | def _test_not_complete(reason, s, comp): | |
323 | l = len(s) |
|
323 | l = len(s) | |
324 | with provisionalcompleter(): |
|
324 | with provisionalcompleter(): | |
325 | completions = set(ip.Completer.completions(s, l)) |
|
325 | completions = set(ip.Completer.completions(s, l)) | |
326 | assert_not_in(Completion(l, l, comp), completions, reason) |
|
326 | assert_not_in(Completion(l, l, comp), completions, reason) | |
327 |
|
327 | |||
328 | import jedi |
|
328 | import jedi | |
329 | jedi_version = tuple(int(i) for i in jedi.__version__.split('.')[:3]) |
|
329 | jedi_version = tuple(int(i) for i in jedi.__version__.split('.')[:3]) | |
330 | if jedi_version > (0, 10): |
|
330 | if jedi_version > (0, 10): | |
331 | yield _test_complete, 'jedi >0.9 should complete and not crash', 'a=1;a.', 'real' |
|
331 | yield _test_complete, 'jedi >0.9 should complete and not crash', 'a=1;a.', 'real' | |
332 | yield _test_complete, 'can infer first argument', 'a=(1,"foo");a[0].', 'real' |
|
332 | yield _test_complete, 'can infer first argument', 'a=(1,"foo");a[0].', 'real' | |
333 | yield _test_complete, 'can infer second argument', 'a=(1,"foo");a[1].', 'capitalize' |
|
333 | yield _test_complete, 'can infer second argument', 'a=(1,"foo");a[1].', 'capitalize' | |
334 | yield _test_complete, 'cover duplicate completions', 'im', 'import', 0, 2 |
|
334 | yield _test_complete, 'cover duplicate completions', 'im', 'import', 0, 2 | |
335 |
|
335 | |||
336 | yield _test_not_complete, 'does not mix types', 'a=(1,"foo");a[0].', 'capitalize' |
|
336 | yield _test_not_complete, 'does not mix types', 'a=(1,"foo");a[0].', 'capitalize' | |
337 |
|
337 | |||
|
338 | def test_completion_have_signature(): | |||
|
339 | """ | |||
|
340 | Lets make sure jedi is capable of pulling out the signature of the function we are completing. | |||
|
341 | """ | |||
|
342 | ip = get_ipython() | |||
|
343 | with provisionalcompleter(): | |||
|
344 | completions = ip.Completer.completions('ope', 3) | |||
|
345 | c = next(completions) # should be `open` | |||
|
346 | assert 'file' in c.signature, "Signature of function was not found by completer" | |||
|
347 | assert 'encoding' in c.signature, "Signature of function was not found by completer" | |||
|
348 | ||||
|
349 | ||||
338 | def test_deduplicate_completions(): |
|
350 | def test_deduplicate_completions(): | |
339 | """ |
|
351 | """ | |
340 | Test that completions are correctly deduplicated (even if ranges are not the same) |
|
352 | Test that completions are correctly deduplicated (even if ranges are not the same) | |
341 | """ |
|
353 | """ | |
342 | ip = get_ipython() |
|
354 | ip = get_ipython() | |
343 | ip.ex(textwrap.dedent(''' |
|
355 | ip.ex(textwrap.dedent(''' | |
344 | class Z: |
|
356 | class Z: | |
345 | zoo = 1 |
|
357 | zoo = 1 | |
346 | ''')) |
|
358 | ''')) | |
347 | with provisionalcompleter(): |
|
359 | with provisionalcompleter(): | |
348 | l = list(_deduplicate_completions('Z.z', ip.Completer.completions('Z.z', 3))) |
|
360 | l = list(_deduplicate_completions('Z.z', ip.Completer.completions('Z.z', 3))) | |
349 |
|
361 | |||
350 | assert len(l) == 1, 'Completions (Z.z<tab>) correctly deduplicate: %s ' % l |
|
362 | assert len(l) == 1, 'Completions (Z.z<tab>) correctly deduplicate: %s ' % l | |
351 | assert l[0].text == 'zoo' # and not `it.accumulate` |
|
363 | assert l[0].text == 'zoo' # and not `it.accumulate` | |
352 |
|
364 | |||
353 |
|
365 | |||
354 | def test_greedy_completions(): |
|
366 | def test_greedy_completions(): | |
355 | """ |
|
367 | """ | |
356 | Test the capability of the Greedy completer. |
|
368 | Test the capability of the Greedy completer. | |
357 |
|
369 | |||
358 | Most of the test here do not really show off the greedy completer, for proof |
|
370 | Most of the test here do not really show off the greedy completer, for proof | |
359 | each of the text bellow now pass with Jedi. The greedy completer is capable of more. |
|
371 | each of the text bellow now pass with Jedi. The greedy completer is capable of more. | |
360 |
|
372 | |||
361 | See the :any:`test_dict_key_completion_contexts` |
|
373 | See the :any:`test_dict_key_completion_contexts` | |
362 |
|
374 | |||
363 | """ |
|
375 | """ | |
364 | ip = get_ipython() |
|
376 | ip = get_ipython() | |
365 | ip.ex('a=list(range(5))') |
|
377 | ip.ex('a=list(range(5))') | |
366 | _,c = ip.complete('.',line='a[0].') |
|
378 | _,c = ip.complete('.',line='a[0].') | |
367 | nt.assert_false('.real' in c, |
|
379 | nt.assert_false('.real' in c, | |
368 | "Shouldn't have completed on a[0]: %s"%c) |
|
380 | "Shouldn't have completed on a[0]: %s"%c) | |
369 | with greedy_completion(), provisionalcompleter(): |
|
381 | with greedy_completion(), provisionalcompleter(): | |
370 | def _(line, cursor_pos, expect, message, completion): |
|
382 | def _(line, cursor_pos, expect, message, completion): | |
371 | _,c = ip.complete('.', line=line, cursor_pos=cursor_pos) |
|
383 | _,c = ip.complete('.', line=line, cursor_pos=cursor_pos) | |
372 | with provisionalcompleter(): |
|
384 | with provisionalcompleter(): | |
373 | completions = ip.Completer.completions(line, cursor_pos) |
|
385 | completions = ip.Completer.completions(line, cursor_pos) | |
374 | nt.assert_in(expect, c, message%c) |
|
386 | nt.assert_in(expect, c, message%c) | |
375 | nt.assert_in(completion, completions) |
|
387 | nt.assert_in(completion, completions) | |
376 |
|
388 | |||
377 | yield _, 'a[0].', 5, 'a[0].real', "Should have completed on a[0].: %s", Completion(5,5, 'real') |
|
389 | yield _, 'a[0].', 5, 'a[0].real', "Should have completed on a[0].: %s", Completion(5,5, 'real') | |
378 | yield _, 'a[0].r', 6, 'a[0].real', "Should have completed on a[0].r: %s", Completion(5,6, 'real') |
|
390 | yield _, 'a[0].r', 6, 'a[0].real', "Should have completed on a[0].r: %s", Completion(5,6, 'real') | |
379 |
|
391 | |||
380 | if sys.version_info > (3, 4): |
|
392 | if sys.version_info > (3, 4): | |
381 | yield _, 'a[0].from_', 10, 'a[0].from_bytes', "Should have completed on a[0].from_: %s", Completion(5, 10, 'from_bytes') |
|
393 | yield _, 'a[0].from_', 10, 'a[0].from_bytes', "Should have completed on a[0].from_: %s", Completion(5, 10, 'from_bytes') | |
382 |
|
394 | |||
383 |
|
395 | |||
384 | def test_omit__names(): |
|
396 | def test_omit__names(): | |
385 | # also happens to test IPCompleter as a configurable |
|
397 | # also happens to test IPCompleter as a configurable | |
386 | ip = get_ipython() |
|
398 | ip = get_ipython() | |
387 | ip._hidden_attr = 1 |
|
399 | ip._hidden_attr = 1 | |
388 | ip._x = {} |
|
400 | ip._x = {} | |
389 | c = ip.Completer |
|
401 | c = ip.Completer | |
390 | ip.ex('ip=get_ipython()') |
|
402 | ip.ex('ip=get_ipython()') | |
391 | cfg = Config() |
|
403 | cfg = Config() | |
392 | cfg.IPCompleter.omit__names = 0 |
|
404 | cfg.IPCompleter.omit__names = 0 | |
393 | c.update_config(cfg) |
|
405 | c.update_config(cfg) | |
394 | with provisionalcompleter(): |
|
406 | with provisionalcompleter(): | |
395 | s,matches = c.complete('ip.') |
|
407 | s,matches = c.complete('ip.') | |
396 | completions = set(c.completions('ip.', 3)) |
|
408 | completions = set(c.completions('ip.', 3)) | |
397 |
|
409 | |||
398 | nt.assert_in('ip.__str__', matches) |
|
410 | nt.assert_in('ip.__str__', matches) | |
399 | nt.assert_in(Completion(3, 3, '__str__'), completions) |
|
411 | nt.assert_in(Completion(3, 3, '__str__'), completions) | |
400 |
|
412 | |||
401 | nt.assert_in('ip._hidden_attr', matches) |
|
413 | nt.assert_in('ip._hidden_attr', matches) | |
402 | nt.assert_in(Completion(3,3, "_hidden_attr"), completions) |
|
414 | nt.assert_in(Completion(3,3, "_hidden_attr"), completions) | |
403 |
|
415 | |||
404 |
|
416 | |||
405 | cfg = Config() |
|
417 | cfg = Config() | |
406 | cfg.IPCompleter.omit__names = 1 |
|
418 | cfg.IPCompleter.omit__names = 1 | |
407 | c.update_config(cfg) |
|
419 | c.update_config(cfg) | |
408 | with provisionalcompleter(): |
|
420 | with provisionalcompleter(): | |
409 | s,matches = c.complete('ip.') |
|
421 | s,matches = c.complete('ip.') | |
410 | completions = set(c.completions('ip.', 3)) |
|
422 | completions = set(c.completions('ip.', 3)) | |
411 |
|
423 | |||
412 | nt.assert_not_in('ip.__str__', matches) |
|
424 | nt.assert_not_in('ip.__str__', matches) | |
413 | nt.assert_not_in(Completion(3,3,'__str__'), completions) |
|
425 | nt.assert_not_in(Completion(3,3,'__str__'), completions) | |
414 |
|
426 | |||
415 | # nt.assert_in('ip._hidden_attr', matches) |
|
427 | # nt.assert_in('ip._hidden_attr', matches) | |
416 | nt.assert_in(Completion(3,3, "_hidden_attr"), completions) |
|
428 | nt.assert_in(Completion(3,3, "_hidden_attr"), completions) | |
417 |
|
429 | |||
418 | cfg = Config() |
|
430 | cfg = Config() | |
419 | cfg.IPCompleter.omit__names = 2 |
|
431 | cfg.IPCompleter.omit__names = 2 | |
420 | c.update_config(cfg) |
|
432 | c.update_config(cfg) | |
421 | with provisionalcompleter(): |
|
433 | with provisionalcompleter(): | |
422 | s,matches = c.complete('ip.') |
|
434 | s,matches = c.complete('ip.') | |
423 | completions = set(c.completions('ip.', 3)) |
|
435 | completions = set(c.completions('ip.', 3)) | |
424 |
|
436 | |||
425 | nt.assert_not_in('ip.__str__', matches) |
|
437 | nt.assert_not_in('ip.__str__', matches) | |
426 | nt.assert_not_in(Completion(3,3,'__str__'), completions) |
|
438 | nt.assert_not_in(Completion(3,3,'__str__'), completions) | |
427 |
|
439 | |||
428 | nt.assert_not_in('ip._hidden_attr', matches) |
|
440 | nt.assert_not_in('ip._hidden_attr', matches) | |
429 | nt.assert_not_in(Completion(3,3, "_hidden_attr"), completions) |
|
441 | nt.assert_not_in(Completion(3,3, "_hidden_attr"), completions) | |
430 |
|
442 | |||
431 | with provisionalcompleter(): |
|
443 | with provisionalcompleter(): | |
432 | s,matches = c.complete('ip._x.') |
|
444 | s,matches = c.complete('ip._x.') | |
433 | completions = set(c.completions('ip._x.', 6)) |
|
445 | completions = set(c.completions('ip._x.', 6)) | |
434 |
|
446 | |||
435 | nt.assert_in('ip._x.keys', matches) |
|
447 | nt.assert_in('ip._x.keys', matches) | |
436 | nt.assert_in(Completion(6,6, "keys"), completions) |
|
448 | nt.assert_in(Completion(6,6, "keys"), completions) | |
437 |
|
449 | |||
438 | del ip._hidden_attr |
|
450 | del ip._hidden_attr | |
439 | del ip._x |
|
451 | del ip._x | |
440 |
|
452 | |||
441 |
|
453 | |||
442 | def test_limit_to__all__False_ok(): |
|
454 | def test_limit_to__all__False_ok(): | |
443 | """ |
|
455 | """ | |
444 | Limit to all is deprecated, once we remove it this test can go away. |
|
456 | Limit to all is deprecated, once we remove it this test can go away. | |
445 | """ |
|
457 | """ | |
446 | ip = get_ipython() |
|
458 | ip = get_ipython() | |
447 | c = ip.Completer |
|
459 | c = ip.Completer | |
448 | ip.ex('class D: x=24') |
|
460 | ip.ex('class D: x=24') | |
449 | ip.ex('d=D()') |
|
461 | ip.ex('d=D()') | |
450 | cfg = Config() |
|
462 | cfg = Config() | |
451 | cfg.IPCompleter.limit_to__all__ = False |
|
463 | cfg.IPCompleter.limit_to__all__ = False | |
452 | c.update_config(cfg) |
|
464 | c.update_config(cfg) | |
453 | s, matches = c.complete('d.') |
|
465 | s, matches = c.complete('d.') | |
454 | nt.assert_in('d.x', matches) |
|
466 | nt.assert_in('d.x', matches) | |
455 |
|
467 | |||
456 |
|
468 | |||
457 | def test_get__all__entries_ok(): |
|
469 | def test_get__all__entries_ok(): | |
458 | class A(object): |
|
470 | class A(object): | |
459 | __all__ = ['x', 1] |
|
471 | __all__ = ['x', 1] | |
460 | words = completer.get__all__entries(A()) |
|
472 | words = completer.get__all__entries(A()) | |
461 | nt.assert_equal(words, ['x']) |
|
473 | nt.assert_equal(words, ['x']) | |
462 |
|
474 | |||
463 |
|
475 | |||
464 | def test_get__all__entries_no__all__ok(): |
|
476 | def test_get__all__entries_no__all__ok(): | |
465 | class A(object): |
|
477 | class A(object): | |
466 | pass |
|
478 | pass | |
467 | words = completer.get__all__entries(A()) |
|
479 | words = completer.get__all__entries(A()) | |
468 | nt.assert_equal(words, []) |
|
480 | nt.assert_equal(words, []) | |
469 |
|
481 | |||
470 |
|
482 | |||
471 | def test_func_kw_completions(): |
|
483 | def test_func_kw_completions(): | |
472 | ip = get_ipython() |
|
484 | ip = get_ipython() | |
473 | c = ip.Completer |
|
485 | c = ip.Completer | |
474 | ip.ex('def myfunc(a=1,b=2): return a+b') |
|
486 | ip.ex('def myfunc(a=1,b=2): return a+b') | |
475 | s, matches = c.complete(None, 'myfunc(1,b') |
|
487 | s, matches = c.complete(None, 'myfunc(1,b') | |
476 | nt.assert_in('b=', matches) |
|
488 | nt.assert_in('b=', matches) | |
477 | # Simulate completing with cursor right after b (pos==10): |
|
489 | # Simulate completing with cursor right after b (pos==10): | |
478 | s, matches = c.complete(None, 'myfunc(1,b)', 10) |
|
490 | s, matches = c.complete(None, 'myfunc(1,b)', 10) | |
479 | nt.assert_in('b=', matches) |
|
491 | nt.assert_in('b=', matches) | |
480 | s, matches = c.complete(None, 'myfunc(a="escaped\\")string",b') |
|
492 | s, matches = c.complete(None, 'myfunc(a="escaped\\")string",b') | |
481 | nt.assert_in('b=', matches) |
|
493 | nt.assert_in('b=', matches) | |
482 | #builtin function |
|
494 | #builtin function | |
483 | s, matches = c.complete(None, 'min(k, k') |
|
495 | s, matches = c.complete(None, 'min(k, k') | |
484 | nt.assert_in('key=', matches) |
|
496 | nt.assert_in('key=', matches) | |
485 |
|
497 | |||
486 |
|
498 | |||
487 | def test_default_arguments_from_docstring(): |
|
499 | def test_default_arguments_from_docstring(): | |
488 | ip = get_ipython() |
|
500 | ip = get_ipython() | |
489 | c = ip.Completer |
|
501 | c = ip.Completer | |
490 | kwd = c._default_arguments_from_docstring( |
|
502 | kwd = c._default_arguments_from_docstring( | |
491 | 'min(iterable[, key=func]) -> value') |
|
503 | 'min(iterable[, key=func]) -> value') | |
492 | nt.assert_equal(kwd, ['key']) |
|
504 | nt.assert_equal(kwd, ['key']) | |
493 | #with cython type etc |
|
505 | #with cython type etc | |
494 | kwd = c._default_arguments_from_docstring( |
|
506 | kwd = c._default_arguments_from_docstring( | |
495 | 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)\n') |
|
507 | 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)\n') | |
496 | nt.assert_equal(kwd, ['ncall', 'resume', 'nsplit']) |
|
508 | nt.assert_equal(kwd, ['ncall', 'resume', 'nsplit']) | |
497 | #white spaces |
|
509 | #white spaces | |
498 | kwd = c._default_arguments_from_docstring( |
|
510 | kwd = c._default_arguments_from_docstring( | |
499 | '\n Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)\n') |
|
511 | '\n Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)\n') | |
500 | nt.assert_equal(kwd, ['ncall', 'resume', 'nsplit']) |
|
512 | nt.assert_equal(kwd, ['ncall', 'resume', 'nsplit']) | |
501 |
|
513 | |||
502 | def test_line_magics(): |
|
514 | def test_line_magics(): | |
503 | ip = get_ipython() |
|
515 | ip = get_ipython() | |
504 | c = ip.Completer |
|
516 | c = ip.Completer | |
505 | s, matches = c.complete(None, 'lsmag') |
|
517 | s, matches = c.complete(None, 'lsmag') | |
506 | nt.assert_in('%lsmagic', matches) |
|
518 | nt.assert_in('%lsmagic', matches) | |
507 | s, matches = c.complete(None, '%lsmag') |
|
519 | s, matches = c.complete(None, '%lsmag') | |
508 | nt.assert_in('%lsmagic', matches) |
|
520 | nt.assert_in('%lsmagic', matches) | |
509 |
|
521 | |||
510 |
|
522 | |||
511 | def test_cell_magics(): |
|
523 | def test_cell_magics(): | |
512 | from IPython.core.magic import register_cell_magic |
|
524 | from IPython.core.magic import register_cell_magic | |
513 |
|
525 | |||
514 | @register_cell_magic |
|
526 | @register_cell_magic | |
515 | def _foo_cellm(line, cell): |
|
527 | def _foo_cellm(line, cell): | |
516 | pass |
|
528 | pass | |
517 |
|
529 | |||
518 | ip = get_ipython() |
|
530 | ip = get_ipython() | |
519 | c = ip.Completer |
|
531 | c = ip.Completer | |
520 |
|
532 | |||
521 | s, matches = c.complete(None, '_foo_ce') |
|
533 | s, matches = c.complete(None, '_foo_ce') | |
522 | nt.assert_in('%%_foo_cellm', matches) |
|
534 | nt.assert_in('%%_foo_cellm', matches) | |
523 | s, matches = c.complete(None, '%%_foo_ce') |
|
535 | s, matches = c.complete(None, '%%_foo_ce') | |
524 | nt.assert_in('%%_foo_cellm', matches) |
|
536 | nt.assert_in('%%_foo_cellm', matches) | |
525 |
|
537 | |||
526 |
|
538 | |||
527 | def test_line_cell_magics(): |
|
539 | def test_line_cell_magics(): | |
528 | from IPython.core.magic import register_line_cell_magic |
|
540 | from IPython.core.magic import register_line_cell_magic | |
529 |
|
541 | |||
530 | @register_line_cell_magic |
|
542 | @register_line_cell_magic | |
531 | def _bar_cellm(line, cell): |
|
543 | def _bar_cellm(line, cell): | |
532 | pass |
|
544 | pass | |
533 |
|
545 | |||
534 | ip = get_ipython() |
|
546 | ip = get_ipython() | |
535 | c = ip.Completer |
|
547 | c = ip.Completer | |
536 |
|
548 | |||
537 | # The policy here is trickier, see comments in completion code. The |
|
549 | # The policy here is trickier, see comments in completion code. The | |
538 | # returned values depend on whether the user passes %% or not explicitly, |
|
550 | # returned values depend on whether the user passes %% or not explicitly, | |
539 | # and this will show a difference if the same name is both a line and cell |
|
551 | # and this will show a difference if the same name is both a line and cell | |
540 | # magic. |
|
552 | # magic. | |
541 | s, matches = c.complete(None, '_bar_ce') |
|
553 | s, matches = c.complete(None, '_bar_ce') | |
542 | nt.assert_in('%_bar_cellm', matches) |
|
554 | nt.assert_in('%_bar_cellm', matches) | |
543 | nt.assert_in('%%_bar_cellm', matches) |
|
555 | nt.assert_in('%%_bar_cellm', matches) | |
544 | s, matches = c.complete(None, '%_bar_ce') |
|
556 | s, matches = c.complete(None, '%_bar_ce') | |
545 | nt.assert_in('%_bar_cellm', matches) |
|
557 | nt.assert_in('%_bar_cellm', matches) | |
546 | nt.assert_in('%%_bar_cellm', matches) |
|
558 | nt.assert_in('%%_bar_cellm', matches) | |
547 | s, matches = c.complete(None, '%%_bar_ce') |
|
559 | s, matches = c.complete(None, '%%_bar_ce') | |
548 | nt.assert_not_in('%_bar_cellm', matches) |
|
560 | nt.assert_not_in('%_bar_cellm', matches) | |
549 | nt.assert_in('%%_bar_cellm', matches) |
|
561 | nt.assert_in('%%_bar_cellm', matches) | |
550 |
|
562 | |||
551 |
|
563 | |||
552 | def test_magic_completion_order(): |
|
564 | def test_magic_completion_order(): | |
553 | ip = get_ipython() |
|
565 | ip = get_ipython() | |
554 | c = ip.Completer |
|
566 | c = ip.Completer | |
555 |
|
567 | |||
556 | # Test ordering of line and cell magics. |
|
568 | # Test ordering of line and cell magics. | |
557 | text, matches = c.complete("timeit") |
|
569 | text, matches = c.complete("timeit") | |
558 | nt.assert_equal(matches, ["%timeit", "%%timeit"]) |
|
570 | nt.assert_equal(matches, ["%timeit", "%%timeit"]) | |
559 |
|
571 | |||
560 |
|
572 | |||
561 | def test_magic_completion_shadowing(): |
|
573 | def test_magic_completion_shadowing(): | |
562 | ip = get_ipython() |
|
574 | ip = get_ipython() | |
563 | c = ip.Completer |
|
575 | c = ip.Completer | |
564 |
|
576 | |||
565 | # Before importing matplotlib, %matplotlib magic should be the only option. |
|
577 | # Before importing matplotlib, %matplotlib magic should be the only option. | |
566 | text, matches = c.complete("mat") |
|
578 | text, matches = c.complete("mat") | |
567 | nt.assert_equal(matches, ["%matplotlib"]) |
|
579 | nt.assert_equal(matches, ["%matplotlib"]) | |
568 |
|
580 | |||
569 | # The newly introduced name should shadow the magic. |
|
581 | # The newly introduced name should shadow the magic. | |
570 | ip.run_cell("matplotlib = 1") |
|
582 | ip.run_cell("matplotlib = 1") | |
571 | text, matches = c.complete("mat") |
|
583 | text, matches = c.complete("mat") | |
572 | nt.assert_equal(matches, ["matplotlib"]) |
|
584 | nt.assert_equal(matches, ["matplotlib"]) | |
573 |
|
585 | |||
574 | # After removing matplotlib from namespace, the magic should again be |
|
586 | # After removing matplotlib from namespace, the magic should again be | |
575 | # the only option. |
|
587 | # the only option. | |
576 | del ip.user_ns["matplotlib"] |
|
588 | del ip.user_ns["matplotlib"] | |
577 | text, matches = c.complete("mat") |
|
589 | text, matches = c.complete("mat") | |
578 | nt.assert_equal(matches, ["%matplotlib"]) |
|
590 | nt.assert_equal(matches, ["%matplotlib"]) | |
579 |
|
591 | |||
580 |
|
592 | |||
581 | def test_magic_config(): |
|
593 | def test_magic_config(): | |
582 | ip = get_ipython() |
|
594 | ip = get_ipython() | |
583 | c = ip.Completer |
|
595 | c = ip.Completer | |
584 |
|
596 | |||
585 | s, matches = c.complete(None, 'conf') |
|
597 | s, matches = c.complete(None, 'conf') | |
586 | nt.assert_in('%config', matches) |
|
598 | nt.assert_in('%config', matches) | |
587 | s, matches = c.complete(None, 'conf') |
|
599 | s, matches = c.complete(None, 'conf') | |
588 | nt.assert_not_in('AliasManager', matches) |
|
600 | nt.assert_not_in('AliasManager', matches) | |
589 | s, matches = c.complete(None, 'config ') |
|
601 | s, matches = c.complete(None, 'config ') | |
590 | nt.assert_in('AliasManager', matches) |
|
602 | nt.assert_in('AliasManager', matches) | |
591 | s, matches = c.complete(None, '%config ') |
|
603 | s, matches = c.complete(None, '%config ') | |
592 | nt.assert_in('AliasManager', matches) |
|
604 | nt.assert_in('AliasManager', matches) | |
593 | s, matches = c.complete(None, 'config Ali') |
|
605 | s, matches = c.complete(None, 'config Ali') | |
594 | nt.assert_list_equal(['AliasManager'], matches) |
|
606 | nt.assert_list_equal(['AliasManager'], matches) | |
595 | s, matches = c.complete(None, '%config Ali') |
|
607 | s, matches = c.complete(None, '%config Ali') | |
596 | nt.assert_list_equal(['AliasManager'], matches) |
|
608 | nt.assert_list_equal(['AliasManager'], matches) | |
597 | s, matches = c.complete(None, 'config AliasManager') |
|
609 | s, matches = c.complete(None, 'config AliasManager') | |
598 | nt.assert_list_equal(['AliasManager'], matches) |
|
610 | nt.assert_list_equal(['AliasManager'], matches) | |
599 | s, matches = c.complete(None, '%config AliasManager') |
|
611 | s, matches = c.complete(None, '%config AliasManager') | |
600 | nt.assert_list_equal(['AliasManager'], matches) |
|
612 | nt.assert_list_equal(['AliasManager'], matches) | |
601 | s, matches = c.complete(None, 'config AliasManager.') |
|
613 | s, matches = c.complete(None, 'config AliasManager.') | |
602 | nt.assert_in('AliasManager.default_aliases', matches) |
|
614 | nt.assert_in('AliasManager.default_aliases', matches) | |
603 | s, matches = c.complete(None, '%config AliasManager.') |
|
615 | s, matches = c.complete(None, '%config AliasManager.') | |
604 | nt.assert_in('AliasManager.default_aliases', matches) |
|
616 | nt.assert_in('AliasManager.default_aliases', matches) | |
605 | s, matches = c.complete(None, 'config AliasManager.de') |
|
617 | s, matches = c.complete(None, 'config AliasManager.de') | |
606 | nt.assert_list_equal(['AliasManager.default_aliases'], matches) |
|
618 | nt.assert_list_equal(['AliasManager.default_aliases'], matches) | |
607 | s, matches = c.complete(None, 'config AliasManager.de') |
|
619 | s, matches = c.complete(None, 'config AliasManager.de') | |
608 | nt.assert_list_equal(['AliasManager.default_aliases'], matches) |
|
620 | nt.assert_list_equal(['AliasManager.default_aliases'], matches) | |
609 |
|
621 | |||
610 |
|
622 | |||
611 | def test_magic_color(): |
|
623 | def test_magic_color(): | |
612 | ip = get_ipython() |
|
624 | ip = get_ipython() | |
613 | c = ip.Completer |
|
625 | c = ip.Completer | |
614 |
|
626 | |||
615 | s, matches = c.complete(None, 'colo') |
|
627 | s, matches = c.complete(None, 'colo') | |
616 | nt.assert_in('%colors', matches) |
|
628 | nt.assert_in('%colors', matches) | |
617 | s, matches = c.complete(None, 'colo') |
|
629 | s, matches = c.complete(None, 'colo') | |
618 | nt.assert_not_in('NoColor', matches) |
|
630 | nt.assert_not_in('NoColor', matches) | |
619 | s, matches = c.complete(None, 'colors ') |
|
631 | s, matches = c.complete(None, 'colors ') | |
620 | nt.assert_in('NoColor', matches) |
|
632 | nt.assert_in('NoColor', matches) | |
621 | s, matches = c.complete(None, '%colors ') |
|
633 | s, matches = c.complete(None, '%colors ') | |
622 | nt.assert_in('NoColor', matches) |
|
634 | nt.assert_in('NoColor', matches) | |
623 | s, matches = c.complete(None, 'colors NoCo') |
|
635 | s, matches = c.complete(None, 'colors NoCo') | |
624 | nt.assert_list_equal(['NoColor'], matches) |
|
636 | nt.assert_list_equal(['NoColor'], matches) | |
625 | s, matches = c.complete(None, '%colors NoCo') |
|
637 | s, matches = c.complete(None, '%colors NoCo') | |
626 | nt.assert_list_equal(['NoColor'], matches) |
|
638 | nt.assert_list_equal(['NoColor'], matches) | |
627 |
|
639 | |||
628 |
|
640 | |||
629 | def test_match_dict_keys(): |
|
641 | def test_match_dict_keys(): | |
630 | """ |
|
642 | """ | |
631 | Test that match_dict_keys works on a couple of use case does return what |
|
643 | Test that match_dict_keys works on a couple of use case does return what | |
632 | expected, and does not crash |
|
644 | expected, and does not crash | |
633 | """ |
|
645 | """ | |
634 | delims = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?' |
|
646 | delims = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?' | |
635 |
|
647 | |||
636 |
|
648 | |||
637 | keys = ['foo', b'far'] |
|
649 | keys = ['foo', b'far'] | |
638 | assert match_dict_keys(keys, "b'", delims=delims) == ("'", 2 ,['far']) |
|
650 | assert match_dict_keys(keys, "b'", delims=delims) == ("'", 2 ,['far']) | |
639 | assert match_dict_keys(keys, "b'f", delims=delims) == ("'", 2 ,['far']) |
|
651 | assert match_dict_keys(keys, "b'f", delims=delims) == ("'", 2 ,['far']) | |
640 | assert match_dict_keys(keys, 'b"', delims=delims) == ('"', 2 ,['far']) |
|
652 | assert match_dict_keys(keys, 'b"', delims=delims) == ('"', 2 ,['far']) | |
641 | assert match_dict_keys(keys, 'b"f', delims=delims) == ('"', 2 ,['far']) |
|
653 | assert match_dict_keys(keys, 'b"f', delims=delims) == ('"', 2 ,['far']) | |
642 |
|
654 | |||
643 | assert match_dict_keys(keys, "'", delims=delims) == ("'", 1 ,['foo']) |
|
655 | assert match_dict_keys(keys, "'", delims=delims) == ("'", 1 ,['foo']) | |
644 | assert match_dict_keys(keys, "'f", delims=delims) == ("'", 1 ,['foo']) |
|
656 | assert match_dict_keys(keys, "'f", delims=delims) == ("'", 1 ,['foo']) | |
645 | assert match_dict_keys(keys, '"', delims=delims) == ('"', 1 ,['foo']) |
|
657 | assert match_dict_keys(keys, '"', delims=delims) == ('"', 1 ,['foo']) | |
646 | assert match_dict_keys(keys, '"f', delims=delims) == ('"', 1 ,['foo']) |
|
658 | assert match_dict_keys(keys, '"f', delims=delims) == ('"', 1 ,['foo']) | |
647 |
|
659 | |||
648 | match_dict_keys |
|
660 | match_dict_keys | |
649 |
|
661 | |||
650 |
|
662 | |||
651 | def test_dict_key_completion_string(): |
|
663 | def test_dict_key_completion_string(): | |
652 | """Test dictionary key completion for string keys""" |
|
664 | """Test dictionary key completion for string keys""" | |
653 | ip = get_ipython() |
|
665 | ip = get_ipython() | |
654 | complete = ip.Completer.complete |
|
666 | complete = ip.Completer.complete | |
655 |
|
667 | |||
656 | ip.user_ns['d'] = {'abc': None} |
|
668 | ip.user_ns['d'] = {'abc': None} | |
657 |
|
669 | |||
658 | # check completion at different stages |
|
670 | # check completion at different stages | |
659 | _, matches = complete(line_buffer="d[") |
|
671 | _, matches = complete(line_buffer="d[") | |
660 | nt.assert_in("'abc'", matches) |
|
672 | nt.assert_in("'abc'", matches) | |
661 | nt.assert_not_in("'abc']", matches) |
|
673 | nt.assert_not_in("'abc']", matches) | |
662 |
|
674 | |||
663 | _, matches = complete(line_buffer="d['") |
|
675 | _, matches = complete(line_buffer="d['") | |
664 | nt.assert_in("abc", matches) |
|
676 | nt.assert_in("abc", matches) | |
665 | nt.assert_not_in("abc']", matches) |
|
677 | nt.assert_not_in("abc']", matches) | |
666 |
|
678 | |||
667 | _, matches = complete(line_buffer="d['a") |
|
679 | _, matches = complete(line_buffer="d['a") | |
668 | nt.assert_in("abc", matches) |
|
680 | nt.assert_in("abc", matches) | |
669 | nt.assert_not_in("abc']", matches) |
|
681 | nt.assert_not_in("abc']", matches) | |
670 |
|
682 | |||
671 | # check use of different quoting |
|
683 | # check use of different quoting | |
672 | _, matches = complete(line_buffer="d[\"") |
|
684 | _, matches = complete(line_buffer="d[\"") | |
673 | nt.assert_in("abc", matches) |
|
685 | nt.assert_in("abc", matches) | |
674 | nt.assert_not_in('abc\"]', matches) |
|
686 | nt.assert_not_in('abc\"]', matches) | |
675 |
|
687 | |||
676 | _, matches = complete(line_buffer="d[\"a") |
|
688 | _, matches = complete(line_buffer="d[\"a") | |
677 | nt.assert_in("abc", matches) |
|
689 | nt.assert_in("abc", matches) | |
678 | nt.assert_not_in('abc\"]', matches) |
|
690 | nt.assert_not_in('abc\"]', matches) | |
679 |
|
691 | |||
680 | # check sensitivity to following context |
|
692 | # check sensitivity to following context | |
681 | _, matches = complete(line_buffer="d[]", cursor_pos=2) |
|
693 | _, matches = complete(line_buffer="d[]", cursor_pos=2) | |
682 | nt.assert_in("'abc'", matches) |
|
694 | nt.assert_in("'abc'", matches) | |
683 |
|
695 | |||
684 | _, matches = complete(line_buffer="d['']", cursor_pos=3) |
|
696 | _, matches = complete(line_buffer="d['']", cursor_pos=3) | |
685 | nt.assert_in("abc", matches) |
|
697 | nt.assert_in("abc", matches) | |
686 | nt.assert_not_in("abc'", matches) |
|
698 | nt.assert_not_in("abc'", matches) | |
687 | nt.assert_not_in("abc']", matches) |
|
699 | nt.assert_not_in("abc']", matches) | |
688 |
|
700 | |||
689 | # check multiple solutions are correctly returned and that noise is not |
|
701 | # check multiple solutions are correctly returned and that noise is not | |
690 | ip.user_ns['d'] = {'abc': None, 'abd': None, 'bad': None, object(): None, |
|
702 | ip.user_ns['d'] = {'abc': None, 'abd': None, 'bad': None, object(): None, | |
691 | 5: None} |
|
703 | 5: None} | |
692 |
|
704 | |||
693 | _, matches = complete(line_buffer="d['a") |
|
705 | _, matches = complete(line_buffer="d['a") | |
694 | nt.assert_in("abc", matches) |
|
706 | nt.assert_in("abc", matches) | |
695 | nt.assert_in("abd", matches) |
|
707 | nt.assert_in("abd", matches) | |
696 | nt.assert_not_in("bad", matches) |
|
708 | nt.assert_not_in("bad", matches) | |
697 | assert not any(m.endswith((']', '"', "'")) for m in matches), matches |
|
709 | assert not any(m.endswith((']', '"', "'")) for m in matches), matches | |
698 |
|
710 | |||
699 | # check escaping and whitespace |
|
711 | # check escaping and whitespace | |
700 | ip.user_ns['d'] = {'a\nb': None, 'a\'b': None, 'a"b': None, 'a word': None} |
|
712 | ip.user_ns['d'] = {'a\nb': None, 'a\'b': None, 'a"b': None, 'a word': None} | |
701 | _, matches = complete(line_buffer="d['a") |
|
713 | _, matches = complete(line_buffer="d['a") | |
702 | nt.assert_in("a\\nb", matches) |
|
714 | nt.assert_in("a\\nb", matches) | |
703 | nt.assert_in("a\\'b", matches) |
|
715 | nt.assert_in("a\\'b", matches) | |
704 | nt.assert_in("a\"b", matches) |
|
716 | nt.assert_in("a\"b", matches) | |
705 | nt.assert_in("a word", matches) |
|
717 | nt.assert_in("a word", matches) | |
706 | assert not any(m.endswith((']', '"', "'")) for m in matches), matches |
|
718 | assert not any(m.endswith((']', '"', "'")) for m in matches), matches | |
707 |
|
719 | |||
708 | # - can complete on non-initial word of the string |
|
720 | # - can complete on non-initial word of the string | |
709 | _, matches = complete(line_buffer="d['a w") |
|
721 | _, matches = complete(line_buffer="d['a w") | |
710 | nt.assert_in("word", matches) |
|
722 | nt.assert_in("word", matches) | |
711 |
|
723 | |||
712 | # - understands quote escaping |
|
724 | # - understands quote escaping | |
713 | _, matches = complete(line_buffer="d['a\\'") |
|
725 | _, matches = complete(line_buffer="d['a\\'") | |
714 | nt.assert_in("b", matches) |
|
726 | nt.assert_in("b", matches) | |
715 |
|
727 | |||
716 | # - default quoting should work like repr |
|
728 | # - default quoting should work like repr | |
717 | _, matches = complete(line_buffer="d[") |
|
729 | _, matches = complete(line_buffer="d[") | |
718 | nt.assert_in("\"a'b\"", matches) |
|
730 | nt.assert_in("\"a'b\"", matches) | |
719 |
|
731 | |||
720 | # - when opening quote with ", possible to match with unescaped apostrophe |
|
732 | # - when opening quote with ", possible to match with unescaped apostrophe | |
721 | _, matches = complete(line_buffer="d[\"a'") |
|
733 | _, matches = complete(line_buffer="d[\"a'") | |
722 | nt.assert_in("b", matches) |
|
734 | nt.assert_in("b", matches) | |
723 |
|
735 | |||
724 | # need to not split at delims that readline won't split at |
|
736 | # need to not split at delims that readline won't split at | |
725 | if '-' not in ip.Completer.splitter.delims: |
|
737 | if '-' not in ip.Completer.splitter.delims: | |
726 | ip.user_ns['d'] = {'before-after': None} |
|
738 | ip.user_ns['d'] = {'before-after': None} | |
727 | _, matches = complete(line_buffer="d['before-af") |
|
739 | _, matches = complete(line_buffer="d['before-af") | |
728 | nt.assert_in('before-after', matches) |
|
740 | nt.assert_in('before-after', matches) | |
729 |
|
741 | |||
730 | def test_dict_key_completion_contexts(): |
|
742 | def test_dict_key_completion_contexts(): | |
731 | """Test expression contexts in which dict key completion occurs""" |
|
743 | """Test expression contexts in which dict key completion occurs""" | |
732 | ip = get_ipython() |
|
744 | ip = get_ipython() | |
733 | complete = ip.Completer.complete |
|
745 | complete = ip.Completer.complete | |
734 | d = {'abc': None} |
|
746 | d = {'abc': None} | |
735 | ip.user_ns['d'] = d |
|
747 | ip.user_ns['d'] = d | |
736 |
|
748 | |||
737 | class C: |
|
749 | class C: | |
738 | data = d |
|
750 | data = d | |
739 | ip.user_ns['C'] = C |
|
751 | ip.user_ns['C'] = C | |
740 | ip.user_ns['get'] = lambda: d |
|
752 | ip.user_ns['get'] = lambda: d | |
741 |
|
753 | |||
742 | def assert_no_completion(**kwargs): |
|
754 | def assert_no_completion(**kwargs): | |
743 | _, matches = complete(**kwargs) |
|
755 | _, matches = complete(**kwargs) | |
744 | nt.assert_not_in('abc', matches) |
|
756 | nt.assert_not_in('abc', matches) | |
745 | nt.assert_not_in('abc\'', matches) |
|
757 | nt.assert_not_in('abc\'', matches) | |
746 | nt.assert_not_in('abc\']', matches) |
|
758 | nt.assert_not_in('abc\']', matches) | |
747 | nt.assert_not_in('\'abc\'', matches) |
|
759 | nt.assert_not_in('\'abc\'', matches) | |
748 | nt.assert_not_in('\'abc\']', matches) |
|
760 | nt.assert_not_in('\'abc\']', matches) | |
749 |
|
761 | |||
750 | def assert_completion(**kwargs): |
|
762 | def assert_completion(**kwargs): | |
751 | _, matches = complete(**kwargs) |
|
763 | _, matches = complete(**kwargs) | |
752 | nt.assert_in("'abc'", matches) |
|
764 | nt.assert_in("'abc'", matches) | |
753 | nt.assert_not_in("'abc']", matches) |
|
765 | nt.assert_not_in("'abc']", matches) | |
754 |
|
766 | |||
755 | # no completion after string closed, even if reopened |
|
767 | # no completion after string closed, even if reopened | |
756 | assert_no_completion(line_buffer="d['a'") |
|
768 | assert_no_completion(line_buffer="d['a'") | |
757 | assert_no_completion(line_buffer="d[\"a\"") |
|
769 | assert_no_completion(line_buffer="d[\"a\"") | |
758 | assert_no_completion(line_buffer="d['a' + ") |
|
770 | assert_no_completion(line_buffer="d['a' + ") | |
759 | assert_no_completion(line_buffer="d['a' + '") |
|
771 | assert_no_completion(line_buffer="d['a' + '") | |
760 |
|
772 | |||
761 | # completion in non-trivial expressions |
|
773 | # completion in non-trivial expressions | |
762 | assert_completion(line_buffer="+ d[") |
|
774 | assert_completion(line_buffer="+ d[") | |
763 | assert_completion(line_buffer="(d[") |
|
775 | assert_completion(line_buffer="(d[") | |
764 | assert_completion(line_buffer="C.data[") |
|
776 | assert_completion(line_buffer="C.data[") | |
765 |
|
777 | |||
766 | # greedy flag |
|
778 | # greedy flag | |
767 | def assert_completion(**kwargs): |
|
779 | def assert_completion(**kwargs): | |
768 | _, matches = complete(**kwargs) |
|
780 | _, matches = complete(**kwargs) | |
769 | nt.assert_in("get()['abc']", matches) |
|
781 | nt.assert_in("get()['abc']", matches) | |
770 |
|
782 | |||
771 | assert_no_completion(line_buffer="get()[") |
|
783 | assert_no_completion(line_buffer="get()[") | |
772 | with greedy_completion(): |
|
784 | with greedy_completion(): | |
773 | assert_completion(line_buffer="get()[") |
|
785 | assert_completion(line_buffer="get()[") | |
774 | assert_completion(line_buffer="get()['") |
|
786 | assert_completion(line_buffer="get()['") | |
775 | assert_completion(line_buffer="get()['a") |
|
787 | assert_completion(line_buffer="get()['a") | |
776 | assert_completion(line_buffer="get()['ab") |
|
788 | assert_completion(line_buffer="get()['ab") | |
777 | assert_completion(line_buffer="get()['abc") |
|
789 | assert_completion(line_buffer="get()['abc") | |
778 |
|
790 | |||
779 |
|
791 | |||
780 |
|
792 | |||
781 | def test_dict_key_completion_bytes(): |
|
793 | def test_dict_key_completion_bytes(): | |
782 | """Test handling of bytes in dict key completion""" |
|
794 | """Test handling of bytes in dict key completion""" | |
783 | ip = get_ipython() |
|
795 | ip = get_ipython() | |
784 | complete = ip.Completer.complete |
|
796 | complete = ip.Completer.complete | |
785 |
|
797 | |||
786 | ip.user_ns['d'] = {'abc': None, b'abd': None} |
|
798 | ip.user_ns['d'] = {'abc': None, b'abd': None} | |
787 |
|
799 | |||
788 | _, matches = complete(line_buffer="d[") |
|
800 | _, matches = complete(line_buffer="d[") | |
789 | nt.assert_in("'abc'", matches) |
|
801 | nt.assert_in("'abc'", matches) | |
790 | nt.assert_in("b'abd'", matches) |
|
802 | nt.assert_in("b'abd'", matches) | |
791 |
|
803 | |||
792 | if False: # not currently implemented |
|
804 | if False: # not currently implemented | |
793 | _, matches = complete(line_buffer="d[b") |
|
805 | _, matches = complete(line_buffer="d[b") | |
794 | nt.assert_in("b'abd'", matches) |
|
806 | nt.assert_in("b'abd'", matches) | |
795 | nt.assert_not_in("b'abc'", matches) |
|
807 | nt.assert_not_in("b'abc'", matches) | |
796 |
|
808 | |||
797 | _, matches = complete(line_buffer="d[b'") |
|
809 | _, matches = complete(line_buffer="d[b'") | |
798 | nt.assert_in("abd", matches) |
|
810 | nt.assert_in("abd", matches) | |
799 | nt.assert_not_in("abc", matches) |
|
811 | nt.assert_not_in("abc", matches) | |
800 |
|
812 | |||
801 | _, matches = complete(line_buffer="d[B'") |
|
813 | _, matches = complete(line_buffer="d[B'") | |
802 | nt.assert_in("abd", matches) |
|
814 | nt.assert_in("abd", matches) | |
803 | nt.assert_not_in("abc", matches) |
|
815 | nt.assert_not_in("abc", matches) | |
804 |
|
816 | |||
805 | _, matches = complete(line_buffer="d['") |
|
817 | _, matches = complete(line_buffer="d['") | |
806 | nt.assert_in("abc", matches) |
|
818 | nt.assert_in("abc", matches) | |
807 | nt.assert_not_in("abd", matches) |
|
819 | nt.assert_not_in("abd", matches) | |
808 |
|
820 | |||
809 |
|
821 | |||
810 | def test_dict_key_completion_unicode_py3(): |
|
822 | def test_dict_key_completion_unicode_py3(): | |
811 | """Test handling of unicode in dict key completion""" |
|
823 | """Test handling of unicode in dict key completion""" | |
812 | ip = get_ipython() |
|
824 | ip = get_ipython() | |
813 | complete = ip.Completer.complete |
|
825 | complete = ip.Completer.complete | |
814 |
|
826 | |||
815 | ip.user_ns['d'] = {u'a\u05d0': None} |
|
827 | ip.user_ns['d'] = {u'a\u05d0': None} | |
816 |
|
828 | |||
817 | # query using escape |
|
829 | # query using escape | |
818 | if sys.platform != 'win32': |
|
830 | if sys.platform != 'win32': | |
819 | # Known failure on Windows |
|
831 | # Known failure on Windows | |
820 | _, matches = complete(line_buffer="d['a\\u05d0") |
|
832 | _, matches = complete(line_buffer="d['a\\u05d0") | |
821 | nt.assert_in("u05d0", matches) # tokenized after \\ |
|
833 | nt.assert_in("u05d0", matches) # tokenized after \\ | |
822 |
|
834 | |||
823 | # query using character |
|
835 | # query using character | |
824 | _, matches = complete(line_buffer="d['a\u05d0") |
|
836 | _, matches = complete(line_buffer="d['a\u05d0") | |
825 | nt.assert_in(u"a\u05d0", matches) |
|
837 | nt.assert_in(u"a\u05d0", matches) | |
826 |
|
838 | |||
827 | with greedy_completion(): |
|
839 | with greedy_completion(): | |
828 | # query using escape |
|
840 | # query using escape | |
829 | _, matches = complete(line_buffer="d['a\\u05d0") |
|
841 | _, matches = complete(line_buffer="d['a\\u05d0") | |
830 | nt.assert_in("d['a\\u05d0']", matches) # tokenized after \\ |
|
842 | nt.assert_in("d['a\\u05d0']", matches) # tokenized after \\ | |
831 |
|
843 | |||
832 | # query using character |
|
844 | # query using character | |
833 | _, matches = complete(line_buffer="d['a\u05d0") |
|
845 | _, matches = complete(line_buffer="d['a\u05d0") | |
834 | nt.assert_in(u"d['a\u05d0']", matches) |
|
846 | nt.assert_in(u"d['a\u05d0']", matches) | |
835 |
|
847 | |||
836 |
|
848 | |||
837 |
|
849 | |||
838 | @dec.skip_without('numpy') |
|
850 | @dec.skip_without('numpy') | |
839 | def test_struct_array_key_completion(): |
|
851 | def test_struct_array_key_completion(): | |
840 | """Test dict key completion applies to numpy struct arrays""" |
|
852 | """Test dict key completion applies to numpy struct arrays""" | |
841 | import numpy |
|
853 | import numpy | |
842 | ip = get_ipython() |
|
854 | ip = get_ipython() | |
843 | complete = ip.Completer.complete |
|
855 | complete = ip.Completer.complete | |
844 | ip.user_ns['d'] = numpy.array([], dtype=[('hello', 'f'), ('world', 'f')]) |
|
856 | ip.user_ns['d'] = numpy.array([], dtype=[('hello', 'f'), ('world', 'f')]) | |
845 | _, matches = complete(line_buffer="d['") |
|
857 | _, matches = complete(line_buffer="d['") | |
846 | nt.assert_in("hello", matches) |
|
858 | nt.assert_in("hello", matches) | |
847 | nt.assert_in("world", matches) |
|
859 | nt.assert_in("world", matches) | |
848 | # complete on the numpy struct itself |
|
860 | # complete on the numpy struct itself | |
849 | dt = numpy.dtype([('my_head', [('my_dt', '>u4'), ('my_df', '>u4')]), |
|
861 | dt = numpy.dtype([('my_head', [('my_dt', '>u4'), ('my_df', '>u4')]), | |
850 | ('my_data', '>f4', 5)]) |
|
862 | ('my_data', '>f4', 5)]) | |
851 | x = numpy.zeros(2, dtype=dt) |
|
863 | x = numpy.zeros(2, dtype=dt) | |
852 | ip.user_ns['d'] = x[1] |
|
864 | ip.user_ns['d'] = x[1] | |
853 | _, matches = complete(line_buffer="d['") |
|
865 | _, matches = complete(line_buffer="d['") | |
854 | nt.assert_in("my_head", matches) |
|
866 | nt.assert_in("my_head", matches) | |
855 | nt.assert_in("my_data", matches) |
|
867 | nt.assert_in("my_data", matches) | |
856 | # complete on a nested level |
|
868 | # complete on a nested level | |
857 | with greedy_completion(): |
|
869 | with greedy_completion(): | |
858 | ip.user_ns['d'] = numpy.zeros(2, dtype=dt) |
|
870 | ip.user_ns['d'] = numpy.zeros(2, dtype=dt) | |
859 | _, matches = complete(line_buffer="d[1]['my_head']['") |
|
871 | _, matches = complete(line_buffer="d[1]['my_head']['") | |
860 | nt.assert_true(any(["my_dt" in m for m in matches])) |
|
872 | nt.assert_true(any(["my_dt" in m for m in matches])) | |
861 | nt.assert_true(any(["my_df" in m for m in matches])) |
|
873 | nt.assert_true(any(["my_df" in m for m in matches])) | |
862 |
|
874 | |||
863 |
|
875 | |||
864 | @dec.skip_without('pandas') |
|
876 | @dec.skip_without('pandas') | |
865 | def test_dataframe_key_completion(): |
|
877 | def test_dataframe_key_completion(): | |
866 | """Test dict key completion applies to pandas DataFrames""" |
|
878 | """Test dict key completion applies to pandas DataFrames""" | |
867 | import pandas |
|
879 | import pandas | |
868 | ip = get_ipython() |
|
880 | ip = get_ipython() | |
869 | complete = ip.Completer.complete |
|
881 | complete = ip.Completer.complete | |
870 | ip.user_ns['d'] = pandas.DataFrame({'hello': [1], 'world': [2]}) |
|
882 | ip.user_ns['d'] = pandas.DataFrame({'hello': [1], 'world': [2]}) | |
871 | _, matches = complete(line_buffer="d['") |
|
883 | _, matches = complete(line_buffer="d['") | |
872 | nt.assert_in("hello", matches) |
|
884 | nt.assert_in("hello", matches) | |
873 | nt.assert_in("world", matches) |
|
885 | nt.assert_in("world", matches) | |
874 |
|
886 | |||
875 |
|
887 | |||
876 | def test_dict_key_completion_invalids(): |
|
888 | def test_dict_key_completion_invalids(): | |
877 | """Smoke test cases dict key completion can't handle""" |
|
889 | """Smoke test cases dict key completion can't handle""" | |
878 | ip = get_ipython() |
|
890 | ip = get_ipython() | |
879 | complete = ip.Completer.complete |
|
891 | complete = ip.Completer.complete | |
880 |
|
892 | |||
881 | ip.user_ns['no_getitem'] = None |
|
893 | ip.user_ns['no_getitem'] = None | |
882 | ip.user_ns['no_keys'] = [] |
|
894 | ip.user_ns['no_keys'] = [] | |
883 | ip.user_ns['cant_call_keys'] = dict |
|
895 | ip.user_ns['cant_call_keys'] = dict | |
884 | ip.user_ns['empty'] = {} |
|
896 | ip.user_ns['empty'] = {} | |
885 | ip.user_ns['d'] = {'abc': 5} |
|
897 | ip.user_ns['d'] = {'abc': 5} | |
886 |
|
898 | |||
887 | _, matches = complete(line_buffer="no_getitem['") |
|
899 | _, matches = complete(line_buffer="no_getitem['") | |
888 | _, matches = complete(line_buffer="no_keys['") |
|
900 | _, matches = complete(line_buffer="no_keys['") | |
889 | _, matches = complete(line_buffer="cant_call_keys['") |
|
901 | _, matches = complete(line_buffer="cant_call_keys['") | |
890 | _, matches = complete(line_buffer="empty['") |
|
902 | _, matches = complete(line_buffer="empty['") | |
891 | _, matches = complete(line_buffer="name_error['") |
|
903 | _, matches = complete(line_buffer="name_error['") | |
892 | _, matches = complete(line_buffer="d['\\") # incomplete escape |
|
904 | _, matches = complete(line_buffer="d['\\") # incomplete escape | |
893 |
|
905 | |||
894 | class KeyCompletable(object): |
|
906 | class KeyCompletable(object): | |
895 | def __init__(self, things=()): |
|
907 | def __init__(self, things=()): | |
896 | self.things = things |
|
908 | self.things = things | |
897 |
|
909 | |||
898 | def _ipython_key_completions_(self): |
|
910 | def _ipython_key_completions_(self): | |
899 | return list(self.things) |
|
911 | return list(self.things) | |
900 |
|
912 | |||
901 | def test_object_key_completion(): |
|
913 | def test_object_key_completion(): | |
902 | ip = get_ipython() |
|
914 | ip = get_ipython() | |
903 | ip.user_ns['key_completable'] = KeyCompletable(['qwerty', 'qwick']) |
|
915 | ip.user_ns['key_completable'] = KeyCompletable(['qwerty', 'qwick']) | |
904 |
|
916 | |||
905 | _, matches = ip.Completer.complete(line_buffer="key_completable['qw") |
|
917 | _, matches = ip.Completer.complete(line_buffer="key_completable['qw") | |
906 | nt.assert_in('qwerty', matches) |
|
918 | nt.assert_in('qwerty', matches) | |
907 | nt.assert_in('qwick', matches) |
|
919 | nt.assert_in('qwick', matches) | |
908 |
|
920 | |||
909 |
|
921 | |||
910 | def test_tryimport(): |
|
922 | def test_tryimport(): | |
911 | """ |
|
923 | """ | |
912 | Test that try-import don't crash on trailing dot, and import modules before |
|
924 | Test that try-import don't crash on trailing dot, and import modules before | |
913 | """ |
|
925 | """ | |
914 | from IPython.core.completerlib import try_import |
|
926 | from IPython.core.completerlib import try_import | |
915 | assert(try_import("IPython.")) |
|
927 | assert(try_import("IPython.")) | |
916 |
|
928 | |||
917 |
|
929 | |||
918 | def test_aimport_module_completer(): |
|
930 | def test_aimport_module_completer(): | |
919 | ip = get_ipython() |
|
931 | ip = get_ipython() | |
920 | _, matches = ip.complete('i', '%aimport i') |
|
932 | _, matches = ip.complete('i', '%aimport i') | |
921 | nt.assert_in('io', matches) |
|
933 | nt.assert_in('io', matches) | |
922 | nt.assert_not_in('int', matches) |
|
934 | nt.assert_not_in('int', matches) | |
923 |
|
935 | |||
924 | def test_nested_import_module_completer(): |
|
936 | def test_nested_import_module_completer(): | |
925 | ip = get_ipython() |
|
937 | ip = get_ipython() | |
926 | _, matches = ip.complete(None, 'import IPython.co', 17) |
|
938 | _, matches = ip.complete(None, 'import IPython.co', 17) | |
927 | nt.assert_in('IPython.core', matches) |
|
939 | nt.assert_in('IPython.core', matches) | |
928 | nt.assert_not_in('import IPython.core', matches) |
|
940 | nt.assert_not_in('import IPython.core', matches) | |
929 | nt.assert_not_in('IPython.display', matches) |
|
941 | nt.assert_not_in('IPython.display', matches) | |
930 |
|
942 | |||
931 | def test_import_module_completer(): |
|
943 | def test_import_module_completer(): | |
932 | ip = get_ipython() |
|
944 | ip = get_ipython() | |
933 | _, matches = ip.complete('i', 'import i') |
|
945 | _, matches = ip.complete('i', 'import i') | |
934 | nt.assert_in('io', matches) |
|
946 | nt.assert_in('io', matches) | |
935 | nt.assert_not_in('int', matches) |
|
947 | nt.assert_not_in('int', matches) | |
936 |
|
948 | |||
937 | def test_from_module_completer(): |
|
949 | def test_from_module_completer(): | |
938 | ip = get_ipython() |
|
950 | ip = get_ipython() | |
939 | _, matches = ip.complete('B', 'from io import B', 16) |
|
951 | _, matches = ip.complete('B', 'from io import B', 16) | |
940 | nt.assert_in('BytesIO', matches) |
|
952 | nt.assert_in('BytesIO', matches) | |
941 | nt.assert_not_in('BaseException', matches) |
|
953 | nt.assert_not_in('BaseException', matches) | |
942 |
|
954 | |||
943 | def test_snake_case_completion(): |
|
955 | def test_snake_case_completion(): | |
944 | ip = get_ipython() |
|
956 | ip = get_ipython() | |
945 | ip.user_ns['some_three'] = 3 |
|
957 | ip.user_ns['some_three'] = 3 | |
946 | ip.user_ns['some_four'] = 4 |
|
958 | ip.user_ns['some_four'] = 4 | |
947 | _, matches = ip.complete("s_", "print(s_f") |
|
959 | _, matches = ip.complete("s_", "print(s_f") | |
948 | nt.assert_in('some_three', matches) |
|
960 | nt.assert_in('some_three', matches) | |
949 | nt.assert_in('some_four', matches) No newline at end of file |
|
961 | nt.assert_in('some_four', matches) |
@@ -1,160 +1,160 b'' | |||||
1 | """prompt-toolkit utilities |
|
1 | """prompt-toolkit utilities | |
2 |
|
2 | |||
3 | Everything in this module is a private API, |
|
3 | Everything in this module is a private API, | |
4 | not to be used outside IPython. |
|
4 | not to be used outside IPython. | |
5 | """ |
|
5 | """ | |
6 |
|
6 | |||
7 | # Copyright (c) IPython Development Team. |
|
7 | # Copyright (c) IPython Development Team. | |
8 | # Distributed under the terms of the Modified BSD License. |
|
8 | # Distributed under the terms of the Modified BSD License. | |
9 |
|
9 | |||
10 | import unicodedata |
|
10 | import unicodedata | |
11 | from wcwidth import wcwidth |
|
11 | from wcwidth import wcwidth | |
12 |
|
12 | |||
13 | from IPython.core.completer import ( |
|
13 | from IPython.core.completer import ( | |
14 | provisionalcompleter, cursor_to_position, |
|
14 | provisionalcompleter, cursor_to_position, | |
15 | _deduplicate_completions) |
|
15 | _deduplicate_completions) | |
16 | from prompt_toolkit.completion import Completer, Completion |
|
16 | from prompt_toolkit.completion import Completer, Completion | |
17 | from prompt_toolkit.layout.lexers import Lexer |
|
17 | from prompt_toolkit.layout.lexers import Lexer | |
18 | from prompt_toolkit.layout.lexers import PygmentsLexer |
|
18 | from prompt_toolkit.layout.lexers import PygmentsLexer | |
19 |
|
19 | |||
20 | import pygments.lexers as pygments_lexers |
|
20 | import pygments.lexers as pygments_lexers | |
21 |
|
21 | |||
22 | _completion_sentinel = object() |
|
22 | _completion_sentinel = object() | |
23 |
|
23 | |||
24 | def _elide(string, *, min_elide=30): |
|
24 | def _elide(string, *, min_elide=30): | |
25 | """ |
|
25 | """ | |
26 | If a string is long enough, and has at least 2 dots, |
|
26 | If a string is long enough, and has at least 2 dots, | |
27 | replace the middle part with ellipses. |
|
27 | replace the middle part with ellipses. | |
28 |
|
28 | |||
29 | If three consecutive dots, or two consecutive dots are encountered these are |
|
29 | If three consecutive dots, or two consecutive dots are encountered these are | |
30 | replaced by the equivalents HORIZONTAL ELLIPSIS or TWO DOT LEADER unicode |
|
30 | replaced by the equivalents HORIZONTAL ELLIPSIS or TWO DOT LEADER unicode | |
31 | equivalents |
|
31 | equivalents | |
32 | """ |
|
32 | """ | |
33 | string = string.replace('...','\N{HORIZONTAL ELLIPSIS}') |
|
33 | string = string.replace('...','\N{HORIZONTAL ELLIPSIS}') | |
34 | string = string.replace('..','\N{TWO DOT LEADER}') |
|
34 | string = string.replace('..','\N{TWO DOT LEADER}') | |
35 | if len(string) < min_elide: |
|
35 | if len(string) < min_elide: | |
36 | return string |
|
36 | return string | |
37 |
|
37 | |||
38 | parts = string.split('.') |
|
38 | parts = string.split('.') | |
39 |
|
39 | |||
40 | if len(parts) <= 3: |
|
40 | if len(parts) <= 3: | |
41 | return string |
|
41 | return string | |
42 |
|
42 | |||
43 | return '{}.{}\N{HORIZONTAL ELLIPSIS}{}.{}'.format(parts[0], parts[1][0], parts[-2][-1], parts[-1]) |
|
43 | return '{}.{}\N{HORIZONTAL ELLIPSIS}{}.{}'.format(parts[0], parts[1][0], parts[-2][-1], parts[-1]) | |
44 |
|
44 | |||
45 |
|
45 | |||
46 | def _adjust_completion_text_based_on_context(text, body, offset): |
|
46 | def _adjust_completion_text_based_on_context(text, body, offset): | |
47 | if text.endswith('=') and len(body) > offset and body[offset] is '=': |
|
47 | if text.endswith('=') and len(body) > offset and body[offset] is '=': | |
48 | return text[:-1] |
|
48 | return text[:-1] | |
49 | else: |
|
49 | else: | |
50 | return text |
|
50 | return text | |
51 |
|
51 | |||
52 |
|
52 | |||
53 | class IPythonPTCompleter(Completer): |
|
53 | class IPythonPTCompleter(Completer): | |
54 | """Adaptor to provide IPython completions to prompt_toolkit""" |
|
54 | """Adaptor to provide IPython completions to prompt_toolkit""" | |
55 | def __init__(self, ipy_completer=None, shell=None, patch_stdout=None): |
|
55 | def __init__(self, ipy_completer=None, shell=None, patch_stdout=None): | |
56 | if shell is None and ipy_completer is None: |
|
56 | if shell is None and ipy_completer is None: | |
57 | raise TypeError("Please pass shell=an InteractiveShell instance.") |
|
57 | raise TypeError("Please pass shell=an InteractiveShell instance.") | |
58 | self._ipy_completer = ipy_completer |
|
58 | self._ipy_completer = ipy_completer | |
59 | self.shell = shell |
|
59 | self.shell = shell | |
60 | if patch_stdout is None: |
|
60 | if patch_stdout is None: | |
61 | raise TypeError("Please pass patch_stdout") |
|
61 | raise TypeError("Please pass patch_stdout") | |
62 | self.patch_stdout = patch_stdout |
|
62 | self.patch_stdout = patch_stdout | |
63 |
|
63 | |||
64 | @property |
|
64 | @property | |
65 | def ipy_completer(self): |
|
65 | def ipy_completer(self): | |
66 | if self._ipy_completer: |
|
66 | if self._ipy_completer: | |
67 | return self._ipy_completer |
|
67 | return self._ipy_completer | |
68 | else: |
|
68 | else: | |
69 | return self.shell.Completer |
|
69 | return self.shell.Completer | |
70 |
|
70 | |||
71 | def get_completions(self, document, complete_event): |
|
71 | def get_completions(self, document, complete_event): | |
72 | if not document.current_line.strip(): |
|
72 | if not document.current_line.strip(): | |
73 | return |
|
73 | return | |
74 | # Some bits of our completion system may print stuff (e.g. if a module |
|
74 | # Some bits of our completion system may print stuff (e.g. if a module | |
75 | # is imported). This context manager ensures that doesn't interfere with |
|
75 | # is imported). This context manager ensures that doesn't interfere with | |
76 | # the prompt. |
|
76 | # the prompt. | |
77 |
|
77 | |||
78 | with self.patch_stdout(), provisionalcompleter(): |
|
78 | with self.patch_stdout(), provisionalcompleter(): | |
79 | body = document.text |
|
79 | body = document.text | |
80 | cursor_row = document.cursor_position_row |
|
80 | cursor_row = document.cursor_position_row | |
81 | cursor_col = document.cursor_position_col |
|
81 | cursor_col = document.cursor_position_col | |
82 | cursor_position = document.cursor_position |
|
82 | cursor_position = document.cursor_position | |
83 | offset = cursor_to_position(body, cursor_row, cursor_col) |
|
83 | offset = cursor_to_position(body, cursor_row, cursor_col) | |
84 | yield from self._get_completions(body, offset, cursor_position, self.ipy_completer) |
|
84 | yield from self._get_completions(body, offset, cursor_position, self.ipy_completer) | |
85 |
|
85 | |||
86 | @staticmethod |
|
86 | @staticmethod | |
87 | def _get_completions(body, offset, cursor_position, ipyc): |
|
87 | def _get_completions(body, offset, cursor_position, ipyc): | |
88 | """ |
|
88 | """ | |
89 | Private equivalent of get_completions() use only for unit_testing. |
|
89 | Private equivalent of get_completions() use only for unit_testing. | |
90 | """ |
|
90 | """ | |
91 | debug = getattr(ipyc, 'debug', False) |
|
91 | debug = getattr(ipyc, 'debug', False) | |
92 | completions = _deduplicate_completions( |
|
92 | completions = _deduplicate_completions( | |
93 | body, ipyc.completions(body, offset)) |
|
93 | body, ipyc.completions(body, offset)) | |
94 | for c in completions: |
|
94 | for c in completions: | |
95 | if not c.text: |
|
95 | if not c.text: | |
96 | # Guard against completion machinery giving us an empty string. |
|
96 | # Guard against completion machinery giving us an empty string. | |
97 | continue |
|
97 | continue | |
98 | text = unicodedata.normalize('NFC', c.text) |
|
98 | text = unicodedata.normalize('NFC', c.text) | |
99 | # When the first character of the completion has a zero length, |
|
99 | # When the first character of the completion has a zero length, | |
100 | # then it's probably a decomposed unicode character. E.g. caused by |
|
100 | # then it's probably a decomposed unicode character. E.g. caused by | |
101 | # the "\dot" completion. Try to compose again with the previous |
|
101 | # the "\dot" completion. Try to compose again with the previous | |
102 | # character. |
|
102 | # character. | |
103 | if wcwidth(text[0]) == 0: |
|
103 | if wcwidth(text[0]) == 0: | |
104 | if cursor_position + c.start > 0: |
|
104 | if cursor_position + c.start > 0: | |
105 | char_before = body[c.start - 1] |
|
105 | char_before = body[c.start - 1] | |
106 | fixed_text = unicodedata.normalize( |
|
106 | fixed_text = unicodedata.normalize( | |
107 | 'NFC', char_before + text) |
|
107 | 'NFC', char_before + text) | |
108 |
|
108 | |||
109 | # Yield the modified completion instead, if this worked. |
|
109 | # Yield the modified completion instead, if this worked. | |
110 | if wcwidth(text[0:1]) == 1: |
|
110 | if wcwidth(text[0:1]) == 1: | |
111 | yield Completion(fixed_text, start_position=c.start - offset - 1) |
|
111 | yield Completion(fixed_text, start_position=c.start - offset - 1) | |
112 | continue |
|
112 | continue | |
113 |
|
113 | |||
114 | # TODO: Use Jedi to determine meta_text |
|
114 | # TODO: Use Jedi to determine meta_text | |
115 | # (Jedi currently has a bug that results in incorrect information.) |
|
115 | # (Jedi currently has a bug that results in incorrect information.) | |
116 | # meta_text = '' |
|
116 | # meta_text = '' | |
117 | # yield Completion(m, start_position=start_pos, |
|
117 | # yield Completion(m, start_position=start_pos, | |
118 | # display_meta=meta_text) |
|
118 | # display_meta=meta_text) | |
119 | display_text = c.text |
|
119 | display_text = c.text | |
120 |
|
120 | |||
121 | adjusted_text = _adjust_completion_text_based_on_context(c.text, body, offset) |
|
121 | adjusted_text = _adjust_completion_text_based_on_context(c.text, body, offset) | |
122 | if c.type == 'function': |
|
122 | if c.type == 'function': | |
123 | display_text = display_text + '()' |
|
123 | yield Completion(adjusted_text, start_position=c.start - offset, display=_elide(display_text+'()'), display_meta=c.type+c.signature) | |
124 |
|
124 | else: | ||
125 | yield Completion(adjusted_text, start_position=c.start - offset, display=_elide(display_text), display_meta=c.type) |
|
125 | yield Completion(adjusted_text, start_position=c.start - offset, display=_elide(display_text), display_meta=c.type) | |
126 |
|
126 | |||
127 | class IPythonPTLexer(Lexer): |
|
127 | class IPythonPTLexer(Lexer): | |
128 | """ |
|
128 | """ | |
129 | Wrapper around PythonLexer and BashLexer. |
|
129 | Wrapper around PythonLexer and BashLexer. | |
130 | """ |
|
130 | """ | |
131 | def __init__(self): |
|
131 | def __init__(self): | |
132 | l = pygments_lexers |
|
132 | l = pygments_lexers | |
133 | self.python_lexer = PygmentsLexer(l.Python3Lexer) |
|
133 | self.python_lexer = PygmentsLexer(l.Python3Lexer) | |
134 | self.shell_lexer = PygmentsLexer(l.BashLexer) |
|
134 | self.shell_lexer = PygmentsLexer(l.BashLexer) | |
135 |
|
135 | |||
136 | self.magic_lexers = { |
|
136 | self.magic_lexers = { | |
137 | 'HTML': PygmentsLexer(l.HtmlLexer), |
|
137 | 'HTML': PygmentsLexer(l.HtmlLexer), | |
138 | 'html': PygmentsLexer(l.HtmlLexer), |
|
138 | 'html': PygmentsLexer(l.HtmlLexer), | |
139 | 'javascript': PygmentsLexer(l.JavascriptLexer), |
|
139 | 'javascript': PygmentsLexer(l.JavascriptLexer), | |
140 | 'js': PygmentsLexer(l.JavascriptLexer), |
|
140 | 'js': PygmentsLexer(l.JavascriptLexer), | |
141 | 'perl': PygmentsLexer(l.PerlLexer), |
|
141 | 'perl': PygmentsLexer(l.PerlLexer), | |
142 | 'ruby': PygmentsLexer(l.RubyLexer), |
|
142 | 'ruby': PygmentsLexer(l.RubyLexer), | |
143 | 'latex': PygmentsLexer(l.TexLexer), |
|
143 | 'latex': PygmentsLexer(l.TexLexer), | |
144 | } |
|
144 | } | |
145 |
|
145 | |||
146 | def lex_document(self, cli, document): |
|
146 | def lex_document(self, cli, document): | |
147 | text = document.text.lstrip() |
|
147 | text = document.text.lstrip() | |
148 |
|
148 | |||
149 | lexer = self.python_lexer |
|
149 | lexer = self.python_lexer | |
150 |
|
150 | |||
151 | if text.startswith('!') or text.startswith('%%bash'): |
|
151 | if text.startswith('!') or text.startswith('%%bash'): | |
152 | lexer = self.shell_lexer |
|
152 | lexer = self.shell_lexer | |
153 |
|
153 | |||
154 | elif text.startswith('%%'): |
|
154 | elif text.startswith('%%'): | |
155 | for magic, l in self.magic_lexers.items(): |
|
155 | for magic, l in self.magic_lexers.items(): | |
156 | if text.startswith('%%' + magic): |
|
156 | if text.startswith('%%' + magic): | |
157 | lexer = l |
|
157 | lexer = l | |
158 | break |
|
158 | break | |
159 |
|
159 | |||
160 | return lexer.lex_document(cli, document) |
|
160 | return lexer.lex_document(cli, document) |
@@ -1,280 +1,282 b'' | |||||
1 | .. _tutorial: |
|
1 | .. _tutorial: | |
2 |
|
2 | |||
3 | ====================== |
|
3 | ====================== | |
4 | Introducing IPython |
|
4 | Introducing IPython | |
5 | ====================== |
|
5 | ====================== | |
6 |
|
6 | |||
7 | You don't need to know anything beyond Python to start using IPython β just type |
|
7 | You don't need to know anything beyond Python to start using IPython β just type | |
8 | commands as you would at the standard Python prompt. But IPython can do much |
|
8 | commands as you would at the standard Python prompt. But IPython can do much | |
9 | more than the standard prompt. Some key features are described here. For more |
|
9 | more than the standard prompt. Some key features are described here. For more | |
10 | information, check the :ref:`tips page <tips>`, or look at examples in the |
|
10 | information, check the :ref:`tips page <tips>`, or look at examples in the | |
11 | `IPython cookbook <https://github.com/ipython/ipython/wiki/Cookbook%3A-Index>`_. |
|
11 | `IPython cookbook <https://github.com/ipython/ipython/wiki/Cookbook%3A-Index>`_. | |
12 |
|
12 | |||
13 | If you haven't done that yet see `how to install ipython <install>`_ . |
|
13 | If you haven't done that yet see `how to install ipython <install>`_ . | |
14 |
|
14 | |||
15 | If you've never used Python before, you might want to look at `the official |
|
15 | If you've never used Python before, you might want to look at `the official | |
16 | tutorial <http://docs.python.org/tutorial/>`_ or an alternative, `Dive into |
|
16 | tutorial <http://docs.python.org/tutorial/>`_ or an alternative, `Dive into | |
17 | Python <http://diveintopython.net/toc/index.html>`_. |
|
17 | Python <http://diveintopython.net/toc/index.html>`_. | |
18 |
|
18 | |||
19 | Start IPython by issuing the ``ipython`` command from your shell, you should be |
|
19 | Start IPython by issuing the ``ipython`` command from your shell, you should be | |
20 | greeted by the following:: |
|
20 | greeted by the following:: | |
21 |
|
21 | |||
22 | Python 3.6.0 |
|
22 | Python 3.6.0 | |
23 | Type 'copyright', 'credits' or 'license' for more information |
|
23 | Type 'copyright', 'credits' or 'license' for more information | |
24 | IPython 6.0.0.dev -- An enhanced Interactive Python. Type '?' for help. |
|
24 | IPython 6.0.0.dev -- An enhanced Interactive Python. Type '?' for help. | |
25 |
|
25 | |||
26 | In [1]: |
|
26 | In [1]: | |
27 |
|
27 | |||
28 |
|
28 | |||
29 | Unlike the Python REPL, you will see that the input prompt is ``In [N]:`` |
|
29 | Unlike the Python REPL, you will see that the input prompt is ``In [N]:`` | |
30 | instead of ``>>>``. The number ``N`` in the prompt will be used later in this |
|
30 | instead of ``>>>``. The number ``N`` in the prompt will be used later in this | |
31 | tutorial but should usually not impact the computation. |
|
31 | tutorial but should usually not impact the computation. | |
32 |
|
32 | |||
33 | You should be able to type single line expressions and press enter to evaluate |
|
33 | You should be able to type single line expressions and press enter to evaluate | |
34 | them. If an expression is incomplete, IPython will automatically detect this and |
|
34 | them. If an expression is incomplete, IPython will automatically detect this and | |
35 | add a new line when you press :kbd:`Enter` instead of executing right away. |
|
35 | add a new line when you press :kbd:`Enter` instead of executing right away. | |
36 |
|
36 | |||
37 | Feel free to explore multi-line text input. Unlike many other REPLs, with |
|
37 | Feel free to explore multi-line text input. Unlike many other REPLs, with | |
38 | IPython you can use the up and down arrow keys when editing multi-line |
|
38 | IPython you can use the up and down arrow keys when editing multi-line | |
39 | code blocks. |
|
39 | code blocks. | |
40 |
|
40 | |||
41 | Here is an example of a longer interaction with the IPython REPL, |
|
41 | Here is an example of a longer interaction with the IPython REPL, | |
42 | which we often refer to as an IPython *session* :: |
|
42 | which we often refer to as an IPython *session* :: | |
43 |
|
43 | |||
44 | In [1]: print('Hello IPython') |
|
44 | In [1]: print('Hello IPython') | |
45 | Hello IPython |
|
45 | Hello IPython | |
46 |
|
46 | |||
47 | In [2]: 21 * 2 |
|
47 | In [2]: 21 * 2 | |
48 | Out[2]: 42 |
|
48 | Out[2]: 42 | |
49 |
|
49 | |||
50 | In [3]: def say_hello(name): |
|
50 | In [3]: def say_hello(name): | |
51 | ...: print('Hello {name}'.format(name=name)) |
|
51 | ...: print('Hello {name}'.format(name=name)) | |
52 | ...: |
|
52 | ...: | |
53 |
|
53 | |||
54 | We won't get into details right now, but you may notice a few differences to |
|
54 | We won't get into details right now, but you may notice a few differences to | |
55 | the standard Python REPL. First, your code should be syntax-highlighted as you |
|
55 | the standard Python REPL. First, your code should be syntax-highlighted as you | |
56 | type. Second, you will see that some results will have an ``Out[N]:`` prompt, |
|
56 | type. Second, you will see that some results will have an ``Out[N]:`` prompt, | |
57 | while some other do not. We'll come to this later. |
|
57 | while some other do not. We'll come to this later. | |
58 |
|
58 | |||
59 | Depending on the exact command you are typing you might realize that sometimes |
|
59 | Depending on the exact command you are typing you might realize that sometimes | |
60 | :kbd:`Enter` will add a new line, and sometimes it will execute the current |
|
60 | :kbd:`Enter` will add a new line, and sometimes it will execute the current | |
61 | statement. IPython tries to guess what you are doing, so most of the time you |
|
61 | statement. IPython tries to guess what you are doing, so most of the time you | |
62 | should not have to care. Though if by any chance IPython does not the right |
|
62 | should not have to care. Though if by any chance IPython does not the right | |
63 | thing you can force execution of the current code block by pressing in sequence |
|
63 | thing you can force execution of the current code block by pressing in sequence | |
64 | :kbd:`Esc` and :kbd:`Enter`. You can also force the insertion of a new line at |
|
64 | :kbd:`Esc` and :kbd:`Enter`. You can also force the insertion of a new line at | |
65 | the position of the cursor by using :kbd:`Ctrl-o`. |
|
65 | the position of the cursor by using :kbd:`Ctrl-o`. | |
66 |
|
66 | |||
67 | The four most helpful commands |
|
67 | The four most helpful commands | |
68 | ============================== |
|
68 | ============================== | |
69 |
|
69 | |||
70 | The four most helpful commands, as well as their brief description, is shown |
|
70 | The four most helpful commands, as well as their brief description, is shown | |
71 | to you in a banner, every time you start IPython: |
|
71 | to you in a banner, every time you start IPython: | |
72 |
|
72 | |||
73 | ========== ========================================================= |
|
73 | ========== ========================================================= | |
74 | command description |
|
74 | command description | |
75 | ========== ========================================================= |
|
75 | ========== ========================================================= | |
76 | ? Introduction and overview of IPython's features. |
|
76 | ? Introduction and overview of IPython's features. | |
77 | %quickref Quick reference. |
|
77 | %quickref Quick reference. | |
78 | help Python's own help system. |
|
78 | help Python's own help system. | |
79 | object? Details about 'object', use 'object??' for extra details. |
|
79 | object? Details about 'object', use 'object??' for extra details. | |
80 | ========== ========================================================= |
|
80 | ========== ========================================================= | |
81 |
|
81 | |||
82 | Tab completion |
|
82 | Tab completion | |
83 | ============== |
|
83 | ============== | |
84 |
|
84 | |||
85 | Tab completion, especially for attributes, is a convenient way to explore the |
|
85 | Tab completion, especially for attributes, is a convenient way to explore the | |
86 | structure of any object you're dealing with. Simply type ``object_name.<TAB>`` |
|
86 | structure of any object you're dealing with. Simply type ``object_name.<TAB>`` | |
87 | to view the object's attributes. Besides Python objects and keywords, tab |
|
87 | to view the object's attributes. Besides Python objects and keywords, tab | |
88 | completion also works on file and directory names. |
|
88 | completion also works on file and directory names. | |
89 |
|
89 | |||
90 | Starting with IPython 6.0, if ``jedi`` is installed, IPython will try to pull |
|
90 | Starting with IPython 6.0, if ``jedi`` is installed, IPython will try to pull | |
91 | completions from Jedi as well. This allows to not only inspect currently |
|
91 | completions from Jedi as well. This allows to not only inspect currently | |
92 | existing objects, but also to infer completion statically without executing |
|
92 | existing objects, but also to infer completion statically without executing | |
93 | code. There is nothing particular need to get this to work, simply use tab |
|
93 | code. There is nothing particular need to get this to work, simply use tab | |
94 | completion on more complex expressions like the following:: |
|
94 | completion on more complex expressions like the following:: | |
95 |
|
95 | |||
96 | >>> data = ['Number of users', 123_456] |
|
96 | >>> data = ['Number of users', 123_456] | |
97 | ... data[0].<tab> |
|
97 | ... data[0].<tab> | |
98 |
|
98 | |||
99 | IPython and Jedi will be able to infer that ``data[0]`` is actually a string |
|
99 | IPython and Jedi will be able to infer that ``data[0]`` is actually a string | |
100 | and should show relevant completions like ``upper()``, ``lower()`` and other |
|
100 | and should show relevant completions like ``upper()``, ``lower()`` and other | |
101 | string methods. You can use the :kbd:`Tab` key to cycle through completions, |
|
101 | string methods. You can use the :kbd:`Tab` key to cycle through completions, | |
102 | and while a completion is highlighted, its type will be shown as well. |
|
102 | and while a completion is highlighted, its type will be shown as well. | |
|
103 | When the type of the completion is a function, the completer will also show the | |||
|
104 | signature of the function when highlighted. | |||
103 |
|
105 | |||
104 | Exploring your objects |
|
106 | Exploring your objects | |
105 | ====================== |
|
107 | ====================== | |
106 |
|
108 | |||
107 | Typing ``object_name?`` will print all sorts of details about any object, |
|
109 | Typing ``object_name?`` will print all sorts of details about any object, | |
108 | including docstrings, function definition lines (for call arguments) and |
|
110 | including docstrings, function definition lines (for call arguments) and | |
109 | constructor details for classes. To get specific information on an object, you |
|
111 | constructor details for classes. To get specific information on an object, you | |
110 | can use the magic commands ``%pdoc``, ``%pdef``, ``%psource`` and ``%pfile`` |
|
112 | can use the magic commands ``%pdoc``, ``%pdef``, ``%psource`` and ``%pfile`` | |
111 |
|
113 | |||
112 | .. _magics_explained: |
|
114 | .. _magics_explained: | |
113 |
|
115 | |||
114 | Magic functions |
|
116 | Magic functions | |
115 | =============== |
|
117 | =============== | |
116 |
|
118 | |||
117 | IPython has a set of predefined 'magic functions' that you can call with a |
|
119 | IPython has a set of predefined 'magic functions' that you can call with a | |
118 | command line style syntax. There are two kinds of magics, line-oriented and |
|
120 | command line style syntax. There are two kinds of magics, line-oriented and | |
119 | cell-oriented. **Line magics** are prefixed with the ``%`` character and work |
|
121 | cell-oriented. **Line magics** are prefixed with the ``%`` character and work | |
120 | much like OS command-line calls: they get as an argument the rest of the line, |
|
122 | much like OS command-line calls: they get as an argument the rest of the line, | |
121 | where arguments are passed without parentheses or quotes. **Lines magics** can |
|
123 | where arguments are passed without parentheses or quotes. **Lines magics** can | |
122 | return results and can be used in the right hand side of an assignment. **Cell |
|
124 | return results and can be used in the right hand side of an assignment. **Cell | |
123 | magics** are prefixed with a double ``%%``, and they are functions that get as |
|
125 | magics** are prefixed with a double ``%%``, and they are functions that get as | |
124 | an argument not only the rest of the line, but also the lines below it in a |
|
126 | an argument not only the rest of the line, but also the lines below it in a | |
125 | separate argument. |
|
127 | separate argument. | |
126 |
|
128 | |||
127 | Magics are useful as convenient functions where Python syntax is not the most |
|
129 | Magics are useful as convenient functions where Python syntax is not the most | |
128 | natural one, or when one want to embed invalid python syntax in their work flow. |
|
130 | natural one, or when one want to embed invalid python syntax in their work flow. | |
129 |
|
131 | |||
130 | The following examples show how to call the built-in :magic:`timeit` magic, both |
|
132 | The following examples show how to call the built-in :magic:`timeit` magic, both | |
131 | in line and cell mode:: |
|
133 | in line and cell mode:: | |
132 |
|
134 | |||
133 | In [1]: %timeit range(1000) |
|
135 | In [1]: %timeit range(1000) | |
134 | 100000 loops, best of 3: 7.76 us per loop |
|
136 | 100000 loops, best of 3: 7.76 us per loop | |
135 |
|
137 | |||
136 | In [2]: %%timeit x = range(10000) |
|
138 | In [2]: %%timeit x = range(10000) | |
137 | ...: max(x) |
|
139 | ...: max(x) | |
138 | ...: |
|
140 | ...: | |
139 | 1000 loops, best of 3: 223 us per loop |
|
141 | 1000 loops, best of 3: 223 us per loop | |
140 |
|
142 | |||
141 | The built-in magics include: |
|
143 | The built-in magics include: | |
142 |
|
144 | |||
143 | - Functions that work with code: :magic:`run`, :magic:`edit`, :magic:`save`, |
|
145 | - Functions that work with code: :magic:`run`, :magic:`edit`, :magic:`save`, | |
144 | :magic:`macro`, :magic:`recall`, etc. |
|
146 | :magic:`macro`, :magic:`recall`, etc. | |
145 |
|
147 | |||
146 | - Functions which affect the shell: :magic:`colors`, :magic:`xmode`, |
|
148 | - Functions which affect the shell: :magic:`colors`, :magic:`xmode`, | |
147 | :magic:`autoindent`, :magic:`automagic`, etc. |
|
149 | :magic:`autoindent`, :magic:`automagic`, etc. | |
148 |
|
150 | |||
149 | - Other functions such as :magic:`reset`, :magic:`timeit`, |
|
151 | - Other functions such as :magic:`reset`, :magic:`timeit`, | |
150 | :cellmagic:`writefile`, :magic:`load`, or :magic:`paste`. |
|
152 | :cellmagic:`writefile`, :magic:`load`, or :magic:`paste`. | |
151 |
|
153 | |||
152 | You can always call magics using the ``%`` prefix, and if you're calling a line |
|
154 | You can always call magics using the ``%`` prefix, and if you're calling a line | |
153 | magic on a line by itself, as long as the identifier is not defined in your |
|
155 | magic on a line by itself, as long as the identifier is not defined in your | |
154 | namespace, you can omit even that:: |
|
156 | namespace, you can omit even that:: | |
155 |
|
157 | |||
156 | run thescript.py |
|
158 | run thescript.py | |
157 |
|
159 | |||
158 | You can toggle this behavior by running the :magic:`automagic` magic. Cell |
|
160 | You can toggle this behavior by running the :magic:`automagic` magic. Cell | |
159 | magics must always have the ``%%`` prefix. |
|
161 | magics must always have the ``%%`` prefix. | |
160 |
|
162 | |||
161 | A more detailed explanation of the magic system can be obtained by calling |
|
163 | A more detailed explanation of the magic system can be obtained by calling | |
162 | ``%magic``, and for more details on any magic function, call ``%somemagic?`` to |
|
164 | ``%magic``, and for more details on any magic function, call ``%somemagic?`` to | |
163 | read its docstring. To see all the available magic functions, call |
|
165 | read its docstring. To see all the available magic functions, call | |
164 | ``%lsmagic``. |
|
166 | ``%lsmagic``. | |
165 |
|
167 | |||
166 | .. seealso:: |
|
168 | .. seealso:: | |
167 |
|
169 | |||
168 | The :ref:`magic` section of the documentation goes more in depth into how |
|
170 | The :ref:`magic` section of the documentation goes more in depth into how | |
169 | the magics works and how to define your own, and :doc:`magics` for a list of |
|
171 | the magics works and how to define your own, and :doc:`magics` for a list of | |
170 | built-in magics. |
|
172 | built-in magics. | |
171 |
|
173 | |||
172 | `Cell magics`_ example notebook |
|
174 | `Cell magics`_ example notebook | |
173 |
|
175 | |||
174 | Running and Editing |
|
176 | Running and Editing | |
175 | ------------------- |
|
177 | ------------------- | |
176 |
|
178 | |||
177 | The :magic:`run` magic command allows you to run any python script and load all |
|
179 | The :magic:`run` magic command allows you to run any python script and load all | |
178 | of its data directly into the interactive namespace. Since the file is re-read |
|
180 | of its data directly into the interactive namespace. Since the file is re-read | |
179 | from disk each time, changes you make to it are reflected immediately (unlike |
|
181 | from disk each time, changes you make to it are reflected immediately (unlike | |
180 | imported modules, which have to be specifically reloaded). IPython also includes |
|
182 | imported modules, which have to be specifically reloaded). IPython also includes | |
181 | :ref:`dreload <dreload>`, a recursive reload function. |
|
183 | :ref:`dreload <dreload>`, a recursive reload function. | |
182 |
|
184 | |||
183 | ``%run`` has special flags for timing the execution of your scripts (-t), or |
|
185 | ``%run`` has special flags for timing the execution of your scripts (-t), or | |
184 | for running them under the control of either Python's pdb debugger (-d) or |
|
186 | for running them under the control of either Python's pdb debugger (-d) or | |
185 | profiler (-p). |
|
187 | profiler (-p). | |
186 |
|
188 | |||
187 | The :magic:`edit` command gives a reasonable approximation of multi-line editing, |
|
189 | The :magic:`edit` command gives a reasonable approximation of multi-line editing, | |
188 | by invoking your favorite editor on the spot. IPython will execute the |
|
190 | by invoking your favorite editor on the spot. IPython will execute the | |
189 | code you type in there as if it were typed interactively. Note that for |
|
191 | code you type in there as if it were typed interactively. Note that for | |
190 | :magic:`edit` to work, the call to startup your editor has to be a blocking |
|
192 | :magic:`edit` to work, the call to startup your editor has to be a blocking | |
191 | call. In a GUI environment, your editor likely will have such an option. |
|
193 | call. In a GUI environment, your editor likely will have such an option. | |
192 |
|
194 | |||
193 | Debugging |
|
195 | Debugging | |
194 | --------- |
|
196 | --------- | |
195 |
|
197 | |||
196 | After an exception occurs, you can call :magic:`debug` to jump into the Python |
|
198 | After an exception occurs, you can call :magic:`debug` to jump into the Python | |
197 | debugger (pdb) and examine the problem. Alternatively, if you call :magic:`pdb`, |
|
199 | debugger (pdb) and examine the problem. Alternatively, if you call :magic:`pdb`, | |
198 | IPython will automatically start the debugger on any uncaught exception. You can |
|
200 | IPython will automatically start the debugger on any uncaught exception. You can | |
199 | print variables, see code, execute statements and even walk up and down the call |
|
201 | print variables, see code, execute statements and even walk up and down the call | |
200 | stack to track down the true source of the problem. This can be an efficient way |
|
202 | stack to track down the true source of the problem. This can be an efficient way | |
201 | to develop and debug code, in many cases eliminating the need for print |
|
203 | to develop and debug code, in many cases eliminating the need for print | |
202 | statements or external debugging tools. |
|
204 | statements or external debugging tools. | |
203 |
|
205 | |||
204 | You can also step through a program from the beginning by calling |
|
206 | You can also step through a program from the beginning by calling | |
205 | ``%run -d theprogram.py``. |
|
207 | ``%run -d theprogram.py``. | |
206 |
|
208 | |||
207 | History |
|
209 | History | |
208 | ======= |
|
210 | ======= | |
209 |
|
211 | |||
210 | IPython stores both the commands you enter, and the results it produces. You |
|
212 | IPython stores both the commands you enter, and the results it produces. You | |
211 | can easily go through previous commands with the up- and down-arrow keys, or |
|
213 | can easily go through previous commands with the up- and down-arrow keys, or | |
212 | access your history in more sophisticated ways. |
|
214 | access your history in more sophisticated ways. | |
213 |
|
215 | |||
214 | Input and output history are kept in variables called ``In`` and ``Out``, keyed |
|
216 | Input and output history are kept in variables called ``In`` and ``Out``, keyed | |
215 | by the prompt numbers, e.g. ``In[4]``. The last three objects in output history |
|
217 | by the prompt numbers, e.g. ``In[4]``. The last three objects in output history | |
216 | are also kept in variables named ``_``, ``__`` and ``___``. |
|
218 | are also kept in variables named ``_``, ``__`` and ``___``. | |
217 |
|
219 | |||
218 | You can use the ``%history`` magic function to examine past input and output. |
|
220 | You can use the ``%history`` magic function to examine past input and output. | |
219 | Input history from previous sessions is saved in a database, and IPython can be |
|
221 | Input history from previous sessions is saved in a database, and IPython can be | |
220 | configured to save output history. |
|
222 | configured to save output history. | |
221 |
|
223 | |||
222 | Several other magic functions can use your input history, including ``%edit``, |
|
224 | Several other magic functions can use your input history, including ``%edit``, | |
223 | ``%rerun``, ``%recall``, ``%macro``, ``%save`` and ``%pastebin``. You can use a |
|
225 | ``%rerun``, ``%recall``, ``%macro``, ``%save`` and ``%pastebin``. You can use a | |
224 | standard format to refer to lines:: |
|
226 | standard format to refer to lines:: | |
225 |
|
227 | |||
226 | %pastebin 3 18-20 ~1/1-5 |
|
228 | %pastebin 3 18-20 ~1/1-5 | |
227 |
|
229 | |||
228 | This will take line 3 and lines 18 to 20 from the current session, and lines |
|
230 | This will take line 3 and lines 18 to 20 from the current session, and lines | |
229 | 1-5 from the previous session. |
|
231 | 1-5 from the previous session. | |
230 |
|
232 | |||
231 | System shell commands |
|
233 | System shell commands | |
232 | ===================== |
|
234 | ===================== | |
233 |
|
235 | |||
234 | To run any command at the system shell, simply prefix it with ``!``, e.g.:: |
|
236 | To run any command at the system shell, simply prefix it with ``!``, e.g.:: | |
235 |
|
237 | |||
236 | !ping www.bbc.co.uk |
|
238 | !ping www.bbc.co.uk | |
237 |
|
239 | |||
238 | You can capture the output into a Python list, e.g.: ``files = !ls``. To pass |
|
240 | You can capture the output into a Python list, e.g.: ``files = !ls``. To pass | |
239 | the values of Python variables or expressions to system commands, prefix them |
|
241 | the values of Python variables or expressions to system commands, prefix them | |
240 | with $: ``!grep -rF $pattern ipython/*``. See :ref:`our shell section |
|
242 | with $: ``!grep -rF $pattern ipython/*``. See :ref:`our shell section | |
241 | <system_shell_access>` for more details. |
|
243 | <system_shell_access>` for more details. | |
242 |
|
244 | |||
243 | Define your own system aliases |
|
245 | Define your own system aliases | |
244 | ------------------------------ |
|
246 | ------------------------------ | |
245 |
|
247 | |||
246 | It's convenient to have aliases to the system commands you use most often. This |
|
248 | It's convenient to have aliases to the system commands you use most often. This | |
247 | allows you to work seamlessly from inside IPython with the same commands you are |
|
249 | allows you to work seamlessly from inside IPython with the same commands you are | |
248 | used to in your system shell. IPython comes with some pre-defined aliases and a |
|
250 | used to in your system shell. IPython comes with some pre-defined aliases and a | |
249 | complete system for changing directories, both via a stack (see :magic:`pushd`, |
|
251 | complete system for changing directories, both via a stack (see :magic:`pushd`, | |
250 | :magic:`popd` and :magic:`dhist`) and via direct :magic:`cd`. The latter keeps a |
|
252 | :magic:`popd` and :magic:`dhist`) and via direct :magic:`cd`. The latter keeps a | |
251 | history of visited directories and allows you to go to any previously visited |
|
253 | history of visited directories and allows you to go to any previously visited | |
252 | one. |
|
254 | one. | |
253 |
|
255 | |||
254 |
|
256 | |||
255 | Configuration |
|
257 | Configuration | |
256 | ============= |
|
258 | ============= | |
257 |
|
259 | |||
258 | Much of IPython can be tweaked through :doc:`configuration </config/intro>`. |
|
260 | Much of IPython can be tweaked through :doc:`configuration </config/intro>`. | |
259 | To get started, use the command ``ipython profile create`` to produce the |
|
261 | To get started, use the command ``ipython profile create`` to produce the | |
260 | default config files. These will be placed in |
|
262 | default config files. These will be placed in | |
261 | :file:`~/.ipython/profile_default`, and contain comments explaining |
|
263 | :file:`~/.ipython/profile_default`, and contain comments explaining | |
262 | what the various options do. |
|
264 | what the various options do. | |
263 |
|
265 | |||
264 | Profiles allow you to use IPython for different tasks, keeping separate config |
|
266 | Profiles allow you to use IPython for different tasks, keeping separate config | |
265 | files and history for each one. More details in :ref:`the profiles section |
|
267 | files and history for each one. More details in :ref:`the profiles section | |
266 | <profiles>`. |
|
268 | <profiles>`. | |
267 |
|
269 | |||
268 | .. _startup_files: |
|
270 | .. _startup_files: | |
269 |
|
271 | |||
270 | Startup Files |
|
272 | Startup Files | |
271 | ------------- |
|
273 | ------------- | |
272 |
|
274 | |||
273 | If you want some code to be run at the beginning of every IPython session, the |
|
275 | If you want some code to be run at the beginning of every IPython session, the | |
274 | easiest way is to add Python (.py) or IPython (.ipy) scripts to your |
|
276 | easiest way is to add Python (.py) or IPython (.ipy) scripts to your | |
275 | :file:`profile_default/startup/` directory. Files here will be executed as soon |
|
277 | :file:`profile_default/startup/` directory. Files here will be executed as soon | |
276 | as the IPython shell is constructed, before any other code or scripts you have |
|
278 | as the IPython shell is constructed, before any other code or scripts you have | |
277 | specified. The files will be run in order of their names, so you can control the |
|
279 | specified. The files will be run in order of their names, so you can control the | |
278 | ordering with prefixes, like ``10-myimports.py``. |
|
280 | ordering with prefixes, like ``10-myimports.py``. | |
279 |
|
281 | |||
280 | .. include:: ../links.txt |
|
282 | .. include:: ../links.txt |
General Comments 0
You need to be logged in to leave comments.
Login now