##// END OF EJS Templates
Fix various typos...
luz paz -
Show More
@@ -1,50 +1,50 b''
1 name: Run Downstream tests
1 name: Run Downstream tests
2
2
3 on:
3 on:
4 push:
4 push:
5 pull_request:
5 pull_request:
6 # Run weekly on Monday at 1:23 UTC
6 # Run weekly on Monday at 1:23 UTC
7 schedule:
7 schedule:
8 - cron: '23 1 * * 1'
8 - cron: '23 1 * * 1'
9 workflow_dispatch:
9 workflow_dispatch:
10
10
11
11
12 jobs:
12 jobs:
13 test:
13 test:
14 runs-on: ${{ matrix.os }}
14 runs-on: ${{ matrix.os }}
15 strategy:
15 strategy:
16 matrix:
16 matrix:
17 os: [ubuntu-latest]
17 os: [ubuntu-latest]
18 python-version: ["3.9"]
18 python-version: ["3.9"]
19 include:
19 include:
20 - os: macos-latest
20 - os: macos-latest
21 python-version: "3.9"
21 python-version: "3.9"
22
22
23 steps:
23 steps:
24 - uses: actions/checkout@v2
24 - uses: actions/checkout@v2
25 - name: Set up Python ${{ matrix.python-version }}
25 - name: Set up Python ${{ matrix.python-version }}
26 uses: actions/setup-python@v2
26 uses: actions/setup-python@v2
27 with:
27 with:
28 python-version: ${{ matrix.python-version }}
28 python-version: ${{ matrix.python-version }}
29 - name: Update Python installer
29 - name: Update Python installer
30 run: |
30 run: |
31 python -m pip install --upgrade pip setuptools wheel
31 python -m pip install --upgrade pip setuptools wheel
32 - name: Install ipykernel
32 - name: Install ipykernel
33 run: |
33 run: |
34 cd ..
34 cd ..
35 git clone https://github.com/ipython/ipykernel
35 git clone https://github.com/ipython/ipykernel
36 cd ipykernel
36 cd ipykernel
37 pip install -e .[test]
37 pip install -e .[test]
38 cd ..
38 cd ..
39 - name: Install and update Python dependencies
39 - name: Install and update Python dependencies
40 run: |
40 run: |
41 python -m pip install --upgrade -e file://$PWD#egg=ipython[test]
41 python -m pip install --upgrade -e file://$PWD#egg=ipython[test]
42 # we must instal IPython after ipykernel to get the right versions.
42 # we must install IPython after ipykernel to get the right versions.
43 python -m pip install --upgrade --upgrade-strategy eager flaky ipyparallel
43 python -m pip install --upgrade --upgrade-strategy eager flaky ipyparallel
44 python -m pip install --upgrade 'pytest<7'
44 python -m pip install --upgrade 'pytest<7'
45 - name: pytest
45 - name: pytest
46 env:
46 env:
47 COLUMNS: 120
47 COLUMNS: 120
48 run: |
48 run: |
49 cd ../ipykernel
49 cd ../ipykernel
50 pytest
50 pytest
@@ -1,2271 +1,2271 b''
1 """Completion for IPython.
1 """Completion for IPython.
2
2
3 This module started as fork of the rlcompleter module in the Python standard
3 This module started as fork of the rlcompleter module in the Python standard
4 library. The original enhancements made to rlcompleter have been sent
4 library. The original enhancements made to rlcompleter have been sent
5 upstream and were accepted as of Python 2.3,
5 upstream and were accepted as of Python 2.3,
6
6
7 This module now support a wide variety of completion mechanism both available
7 This module now support a wide variety of completion mechanism both available
8 for normal classic Python code, as well as completer for IPython specific
8 for normal classic Python code, as well as completer for IPython specific
9 Syntax like magics.
9 Syntax like magics.
10
10
11 Latex and Unicode completion
11 Latex and Unicode completion
12 ============================
12 ============================
13
13
14 IPython and compatible frontends not only can complete your code, but can help
14 IPython and compatible frontends not only can complete your code, but can help
15 you to input a wide range of characters. In particular we allow you to insert
15 you to input a wide range of characters. In particular we allow you to insert
16 a unicode character using the tab completion mechanism.
16 a unicode character using the tab completion mechanism.
17
17
18 Forward latex/unicode completion
18 Forward latex/unicode completion
19 --------------------------------
19 --------------------------------
20
20
21 Forward completion allows you to easily type a unicode character using its latex
21 Forward completion allows you to easily type a unicode character using its latex
22 name, or unicode long description. To do so type a backslash follow by the
22 name, or unicode long description. To do so type a backslash follow by the
23 relevant name and press tab:
23 relevant name and press tab:
24
24
25
25
26 Using latex completion:
26 Using latex completion:
27
27
28 .. code::
28 .. code::
29
29
30 \\alpha<tab>
30 \\alpha<tab>
31 Ξ±
31 Ξ±
32
32
33 or using unicode completion:
33 or using unicode completion:
34
34
35
35
36 .. code::
36 .. code::
37
37
38 \\GREEK SMALL LETTER ALPHA<tab>
38 \\GREEK SMALL LETTER ALPHA<tab>
39 Ξ±
39 Ξ±
40
40
41
41
42 Only valid Python identifiers will complete. Combining characters (like arrow or
42 Only valid Python identifiers will complete. Combining characters (like arrow or
43 dots) are also available, unlike latex they need to be put after the their
43 dots) are also available, unlike latex they need to be put after the their
44 counterpart that is to say, `F\\\\vec<tab>` is correct, not `\\\\vec<tab>F`.
44 counterpart that is to say, `F\\\\vec<tab>` is correct, not `\\\\vec<tab>F`.
45
45
46 Some browsers are known to display combining characters incorrectly.
46 Some browsers are known to display combining characters incorrectly.
47
47
48 Backward latex completion
48 Backward latex completion
49 -------------------------
49 -------------------------
50
50
51 It is sometime challenging to know how to type a character, if you are using
51 It is sometime challenging to know how to type a character, if you are using
52 IPython, or any compatible frontend you can prepend backslash to the character
52 IPython, or any compatible frontend you can prepend backslash to the character
53 and press `<tab>` to expand it to its latex form.
53 and press `<tab>` to expand it to its latex form.
54
54
55 .. code::
55 .. code::
56
56
57 \\Ξ±<tab>
57 \\Ξ±<tab>
58 \\alpha
58 \\alpha
59
59
60
60
61 Both forward and backward completions can be deactivated by setting the
61 Both forward and backward completions can be deactivated by setting the
62 ``Completer.backslash_combining_completions`` option to ``False``.
62 ``Completer.backslash_combining_completions`` option to ``False``.
63
63
64
64
65 Experimental
65 Experimental
66 ============
66 ============
67
67
68 Starting with IPython 6.0, this module can make use of the Jedi library to
68 Starting with IPython 6.0, this module can make use of the Jedi library to
69 generate completions both using static analysis of the code, and dynamically
69 generate completions both using static analysis of the code, and dynamically
70 inspecting multiple namespaces. Jedi is an autocompletion and static analysis
70 inspecting multiple namespaces. Jedi is an autocompletion and static analysis
71 for Python. The APIs attached to this new mechanism is unstable and will
71 for Python. The APIs attached to this new mechanism is unstable and will
72 raise unless use in an :any:`provisionalcompleter` context manager.
72 raise unless use in an :any:`provisionalcompleter` context manager.
73
73
74 You will find that the following are experimental:
74 You will find that the following are experimental:
75
75
76 - :any:`provisionalcompleter`
76 - :any:`provisionalcompleter`
77 - :any:`IPCompleter.completions`
77 - :any:`IPCompleter.completions`
78 - :any:`Completion`
78 - :any:`Completion`
79 - :any:`rectify_completions`
79 - :any:`rectify_completions`
80
80
81 .. note::
81 .. note::
82
82
83 better name for :any:`rectify_completions` ?
83 better name for :any:`rectify_completions` ?
84
84
85 We welcome any feedback on these new API, and we also encourage you to try this
85 We welcome any feedback on these new API, and we also encourage you to try this
86 module in debug mode (start IPython with ``--Completer.debug=True``) in order
86 module in debug mode (start IPython with ``--Completer.debug=True``) in order
87 to have extra logging information if :any:`jedi` is crashing, or if current
87 to have extra logging information if :any:`jedi` is crashing, or if current
88 IPython completer pending deprecations are returning results not yet handled
88 IPython completer pending deprecations are returning results not yet handled
89 by :any:`jedi`
89 by :any:`jedi`
90
90
91 Using Jedi for tab completion allow snippets like the following to work without
91 Using Jedi for tab completion allow snippets like the following to work without
92 having to execute any code:
92 having to execute any code:
93
93
94 >>> myvar = ['hello', 42]
94 >>> myvar = ['hello', 42]
95 ... myvar[1].bi<tab>
95 ... myvar[1].bi<tab>
96
96
97 Tab completion will be able to infer that ``myvar[1]`` is a real number without
97 Tab completion will be able to infer that ``myvar[1]`` is a real number without
98 executing any code unlike the previously available ``IPCompleter.greedy``
98 executing any code unlike the previously available ``IPCompleter.greedy``
99 option.
99 option.
100
100
101 Be sure to update :any:`jedi` to the latest stable version or to try the
101 Be sure to update :any:`jedi` to the latest stable version or to try the
102 current development version to get better completions.
102 current development version to get better completions.
103 """
103 """
104
104
105
105
106 # Copyright (c) IPython Development Team.
106 # Copyright (c) IPython Development Team.
107 # Distributed under the terms of the Modified BSD License.
107 # Distributed under the terms of the Modified BSD License.
108 #
108 #
109 # Some of this code originated from rlcompleter in the Python standard library
109 # Some of this code originated from rlcompleter in the Python standard library
110 # Copyright (C) 2001 Python Software Foundation, www.python.org
110 # Copyright (C) 2001 Python Software Foundation, www.python.org
111
111
112
112
113 import builtins as builtin_mod
113 import builtins as builtin_mod
114 import glob
114 import glob
115 import inspect
115 import inspect
116 import itertools
116 import itertools
117 import keyword
117 import keyword
118 import os
118 import os
119 import re
119 import re
120 import string
120 import string
121 import sys
121 import sys
122 import time
122 import time
123 import unicodedata
123 import unicodedata
124 import uuid
124 import uuid
125 import warnings
125 import warnings
126 from contextlib import contextmanager
126 from contextlib import contextmanager
127 from importlib import import_module
127 from importlib import import_module
128 from types import SimpleNamespace
128 from types import SimpleNamespace
129 from typing import Iterable, Iterator, List, Tuple, Union, Any, Sequence, Dict, NamedTuple, Pattern, Optional
129 from typing import Iterable, Iterator, List, Tuple, Union, Any, Sequence, Dict, NamedTuple, Pattern, Optional
130
130
131 from IPython.core.error import TryNext
131 from IPython.core.error import TryNext
132 from IPython.core.inputtransformer2 import ESC_MAGIC
132 from IPython.core.inputtransformer2 import ESC_MAGIC
133 from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol
133 from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol
134 from IPython.core.oinspect import InspectColors
134 from IPython.core.oinspect import InspectColors
135 from IPython.testing.skipdoctest import skip_doctest
135 from IPython.testing.skipdoctest import skip_doctest
136 from IPython.utils import generics
136 from IPython.utils import generics
137 from IPython.utils.dir2 import dir2, get_real_method
137 from IPython.utils.dir2 import dir2, get_real_method
138 from IPython.utils.path import ensure_dir_exists
138 from IPython.utils.path import ensure_dir_exists
139 from IPython.utils.process import arg_split
139 from IPython.utils.process import arg_split
140 from traitlets import Bool, Enum, Int, List as ListTrait, Unicode, default, observe
140 from traitlets import Bool, Enum, Int, List as ListTrait, Unicode, default, observe
141 from traitlets.config.configurable import Configurable
141 from traitlets.config.configurable import Configurable
142
142
143 import __main__
143 import __main__
144
144
145 # skip module docstests
145 # skip module docstests
146 __skip_doctest__ = True
146 __skip_doctest__ = True
147
147
148 try:
148 try:
149 import jedi
149 import jedi
150 jedi.settings.case_insensitive_completion = False
150 jedi.settings.case_insensitive_completion = False
151 import jedi.api.helpers
151 import jedi.api.helpers
152 import jedi.api.classes
152 import jedi.api.classes
153 JEDI_INSTALLED = True
153 JEDI_INSTALLED = True
154 except ImportError:
154 except ImportError:
155 JEDI_INSTALLED = False
155 JEDI_INSTALLED = False
156 #-----------------------------------------------------------------------------
156 #-----------------------------------------------------------------------------
157 # Globals
157 # Globals
158 #-----------------------------------------------------------------------------
158 #-----------------------------------------------------------------------------
159
159
160 # ranges where we have most of the valid unicode names. We could be more finer
160 # ranges where we have most of the valid unicode names. We could be more finer
161 # grained but is it worth it for performance While unicode have character in the
161 # grained but is it worth it for performance While unicode have character in the
162 # range 0, 0x110000, we seem to have name for about 10% of those. (131808 as I
162 # range 0, 0x110000, we seem to have name for about 10% of those. (131808 as I
163 # write this). With below range we cover them all, with a density of ~67%
163 # write this). With below range we cover them all, with a density of ~67%
164 # biggest next gap we consider only adds up about 1% density and there are 600
164 # biggest next gap we consider only adds up about 1% density and there are 600
165 # gaps that would need hard coding.
165 # gaps that would need hard coding.
166 _UNICODE_RANGES = [(32, 0x3134b), (0xe0001, 0xe01f0)]
166 _UNICODE_RANGES = [(32, 0x3134b), (0xe0001, 0xe01f0)]
167
167
168 # Public API
168 # Public API
169 __all__ = ['Completer','IPCompleter']
169 __all__ = ['Completer','IPCompleter']
170
170
171 if sys.platform == 'win32':
171 if sys.platform == 'win32':
172 PROTECTABLES = ' '
172 PROTECTABLES = ' '
173 else:
173 else:
174 PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&'
174 PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&'
175
175
176 # Protect against returning an enormous number of completions which the frontend
176 # Protect against returning an enormous number of completions which the frontend
177 # may have trouble processing.
177 # may have trouble processing.
178 MATCHES_LIMIT = 500
178 MATCHES_LIMIT = 500
179
179
180
180
181 class ProvisionalCompleterWarning(FutureWarning):
181 class ProvisionalCompleterWarning(FutureWarning):
182 """
182 """
183 Exception raise by an experimental feature in this module.
183 Exception raise by an experimental feature in this module.
184
184
185 Wrap code in :any:`provisionalcompleter` context manager if you
185 Wrap code in :any:`provisionalcompleter` context manager if you
186 are certain you want to use an unstable feature.
186 are certain you want to use an unstable feature.
187 """
187 """
188 pass
188 pass
189
189
190 warnings.filterwarnings('error', category=ProvisionalCompleterWarning)
190 warnings.filterwarnings('error', category=ProvisionalCompleterWarning)
191
191
192
192
193 @skip_doctest
193 @skip_doctest
194 @contextmanager
194 @contextmanager
195 def provisionalcompleter(action='ignore'):
195 def provisionalcompleter(action='ignore'):
196 """
196 """
197 This context manager has to be used in any place where unstable completer
197 This context manager has to be used in any place where unstable completer
198 behavior and API may be called.
198 behavior and API may be called.
199
199
200 >>> with provisionalcompleter():
200 >>> with provisionalcompleter():
201 ... completer.do_experimental_things() # works
201 ... completer.do_experimental_things() # works
202
202
203 >>> completer.do_experimental_things() # raises.
203 >>> completer.do_experimental_things() # raises.
204
204
205 .. note::
205 .. note::
206
206
207 Unstable
207 Unstable
208
208
209 By using this context manager you agree that the API in use may change
209 By using this context manager you agree that the API in use may change
210 without warning, and that you won't complain if they do so.
210 without warning, and that you won't complain if they do so.
211
211
212 You also understand that, if the API is not to your liking, you should report
212 You also understand that, if the API is not to your liking, you should report
213 a bug to explain your use case upstream.
213 a bug to explain your use case upstream.
214
214
215 We'll be happy to get your feedback, feature requests, and improvements on
215 We'll be happy to get your feedback, feature requests, and improvements on
216 any of the unstable APIs!
216 any of the unstable APIs!
217 """
217 """
218 with warnings.catch_warnings():
218 with warnings.catch_warnings():
219 warnings.filterwarnings(action, category=ProvisionalCompleterWarning)
219 warnings.filterwarnings(action, category=ProvisionalCompleterWarning)
220 yield
220 yield
221
221
222
222
223 def has_open_quotes(s):
223 def has_open_quotes(s):
224 """Return whether a string has open quotes.
224 """Return whether a string has open quotes.
225
225
226 This simply counts whether the number of quote characters of either type in
226 This simply counts whether the number of quote characters of either type in
227 the string is odd.
227 the string is odd.
228
228
229 Returns
229 Returns
230 -------
230 -------
231 If there is an open quote, the quote character is returned. Else, return
231 If there is an open quote, the quote character is returned. Else, return
232 False.
232 False.
233 """
233 """
234 # We check " first, then ', so complex cases with nested quotes will get
234 # We check " first, then ', so complex cases with nested quotes will get
235 # the " to take precedence.
235 # the " to take precedence.
236 if s.count('"') % 2:
236 if s.count('"') % 2:
237 return '"'
237 return '"'
238 elif s.count("'") % 2:
238 elif s.count("'") % 2:
239 return "'"
239 return "'"
240 else:
240 else:
241 return False
241 return False
242
242
243
243
244 def protect_filename(s, protectables=PROTECTABLES):
244 def protect_filename(s, protectables=PROTECTABLES):
245 """Escape a string to protect certain characters."""
245 """Escape a string to protect certain characters."""
246 if set(s) & set(protectables):
246 if set(s) & set(protectables):
247 if sys.platform == "win32":
247 if sys.platform == "win32":
248 return '"' + s + '"'
248 return '"' + s + '"'
249 else:
249 else:
250 return "".join(("\\" + c if c in protectables else c) for c in s)
250 return "".join(("\\" + c if c in protectables else c) for c in s)
251 else:
251 else:
252 return s
252 return s
253
253
254
254
255 def expand_user(path:str) -> Tuple[str, bool, str]:
255 def expand_user(path:str) -> Tuple[str, bool, str]:
256 """Expand ``~``-style usernames in strings.
256 """Expand ``~``-style usernames in strings.
257
257
258 This is similar to :func:`os.path.expanduser`, but it computes and returns
258 This is similar to :func:`os.path.expanduser`, but it computes and returns
259 extra information that will be useful if the input was being used in
259 extra information that will be useful if the input was being used in
260 computing completions, and you wish to return the completions with the
260 computing completions, and you wish to return the completions with the
261 original '~' instead of its expanded value.
261 original '~' instead of its expanded value.
262
262
263 Parameters
263 Parameters
264 ----------
264 ----------
265 path : str
265 path : str
266 String to be expanded. If no ~ is present, the output is the same as the
266 String to be expanded. If no ~ is present, the output is the same as the
267 input.
267 input.
268
268
269 Returns
269 Returns
270 -------
270 -------
271 newpath : str
271 newpath : str
272 Result of ~ expansion in the input path.
272 Result of ~ expansion in the input path.
273 tilde_expand : bool
273 tilde_expand : bool
274 Whether any expansion was performed or not.
274 Whether any expansion was performed or not.
275 tilde_val : str
275 tilde_val : str
276 The value that ~ was replaced with.
276 The value that ~ was replaced with.
277 """
277 """
278 # Default values
278 # Default values
279 tilde_expand = False
279 tilde_expand = False
280 tilde_val = ''
280 tilde_val = ''
281 newpath = path
281 newpath = path
282
282
283 if path.startswith('~'):
283 if path.startswith('~'):
284 tilde_expand = True
284 tilde_expand = True
285 rest = len(path)-1
285 rest = len(path)-1
286 newpath = os.path.expanduser(path)
286 newpath = os.path.expanduser(path)
287 if rest:
287 if rest:
288 tilde_val = newpath[:-rest]
288 tilde_val = newpath[:-rest]
289 else:
289 else:
290 tilde_val = newpath
290 tilde_val = newpath
291
291
292 return newpath, tilde_expand, tilde_val
292 return newpath, tilde_expand, tilde_val
293
293
294
294
295 def compress_user(path:str, tilde_expand:bool, tilde_val:str) -> str:
295 def compress_user(path:str, tilde_expand:bool, tilde_val:str) -> str:
296 """Does the opposite of expand_user, with its outputs.
296 """Does the opposite of expand_user, with its outputs.
297 """
297 """
298 if tilde_expand:
298 if tilde_expand:
299 return path.replace(tilde_val, '~')
299 return path.replace(tilde_val, '~')
300 else:
300 else:
301 return path
301 return path
302
302
303
303
304 def completions_sorting_key(word):
304 def completions_sorting_key(word):
305 """key for sorting completions
305 """key for sorting completions
306
306
307 This does several things:
307 This does several things:
308
308
309 - Demote any completions starting with underscores to the end
309 - Demote any completions starting with underscores to the end
310 - Insert any %magic and %%cellmagic completions in the alphabetical order
310 - Insert any %magic and %%cellmagic completions in the alphabetical order
311 by their name
311 by their name
312 """
312 """
313 prio1, prio2 = 0, 0
313 prio1, prio2 = 0, 0
314
314
315 if word.startswith('__'):
315 if word.startswith('__'):
316 prio1 = 2
316 prio1 = 2
317 elif word.startswith('_'):
317 elif word.startswith('_'):
318 prio1 = 1
318 prio1 = 1
319
319
320 if word.endswith('='):
320 if word.endswith('='):
321 prio1 = -1
321 prio1 = -1
322
322
323 if word.startswith('%%'):
323 if word.startswith('%%'):
324 # If there's another % in there, this is something else, so leave it alone
324 # If there's another % in there, this is something else, so leave it alone
325 if not "%" in word[2:]:
325 if not "%" in word[2:]:
326 word = word[2:]
326 word = word[2:]
327 prio2 = 2
327 prio2 = 2
328 elif word.startswith('%'):
328 elif word.startswith('%'):
329 if not "%" in word[1:]:
329 if not "%" in word[1:]:
330 word = word[1:]
330 word = word[1:]
331 prio2 = 1
331 prio2 = 1
332
332
333 return prio1, word, prio2
333 return prio1, word, prio2
334
334
335
335
336 class _FakeJediCompletion:
336 class _FakeJediCompletion:
337 """
337 """
338 This is a workaround to communicate to the UI that Jedi has crashed and to
338 This is a workaround to communicate to the UI that Jedi has crashed and to
339 report a bug. Will be used only id :any:`IPCompleter.debug` is set to true.
339 report a bug. Will be used only id :any:`IPCompleter.debug` is set to true.
340
340
341 Added in IPython 6.0 so should likely be removed for 7.0
341 Added in IPython 6.0 so should likely be removed for 7.0
342
342
343 """
343 """
344
344
345 def __init__(self, name):
345 def __init__(self, name):
346
346
347 self.name = name
347 self.name = name
348 self.complete = name
348 self.complete = name
349 self.type = 'crashed'
349 self.type = 'crashed'
350 self.name_with_symbols = name
350 self.name_with_symbols = name
351 self.signature = ''
351 self.signature = ''
352 self._origin = 'fake'
352 self._origin = 'fake'
353
353
354 def __repr__(self):
354 def __repr__(self):
355 return '<Fake completion object jedi has crashed>'
355 return '<Fake completion object jedi has crashed>'
356
356
357
357
358 class Completion:
358 class Completion:
359 """
359 """
360 Completion object used and return by IPython completers.
360 Completion object used and return by IPython completers.
361
361
362 .. warning::
362 .. warning::
363
363
364 Unstable
364 Unstable
365
365
366 This function is unstable, API may change without warning.
366 This function is unstable, API may change without warning.
367 It will also raise unless use in proper context manager.
367 It will also raise unless use in proper context manager.
368
368
369 This act as a middle ground :any:`Completion` object between the
369 This act as a middle ground :any:`Completion` object between the
370 :any:`jedi.api.classes.Completion` object and the Prompt Toolkit completion
370 :any:`jedi.api.classes.Completion` object and the Prompt Toolkit completion
371 object. While Jedi need a lot of information about evaluator and how the
371 object. While Jedi need a lot of information about evaluator and how the
372 code should be ran/inspected, PromptToolkit (and other frontend) mostly
372 code should be ran/inspected, PromptToolkit (and other frontend) mostly
373 need user facing information.
373 need user facing information.
374
374
375 - Which range should be replaced replaced by what.
375 - Which range should be replaced replaced by what.
376 - Some metadata (like completion type), or meta information to displayed to
376 - Some metadata (like completion type), or meta information to displayed to
377 the use user.
377 the use user.
378
378
379 For debugging purpose we can also store the origin of the completion (``jedi``,
379 For debugging purpose we can also store the origin of the completion (``jedi``,
380 ``IPython.python_matches``, ``IPython.magics_matches``...).
380 ``IPython.python_matches``, ``IPython.magics_matches``...).
381 """
381 """
382
382
383 __slots__ = ['start', 'end', 'text', 'type', 'signature', '_origin']
383 __slots__ = ['start', 'end', 'text', 'type', 'signature', '_origin']
384
384
385 def __init__(self, start: int, end: int, text: str, *, type: str=None, _origin='', signature='') -> None:
385 def __init__(self, start: int, end: int, text: str, *, type: str=None, _origin='', signature='') -> None:
386 warnings.warn("``Completion`` is a provisional API (as of IPython 6.0). "
386 warnings.warn("``Completion`` is a provisional API (as of IPython 6.0). "
387 "It may change without warnings. "
387 "It may change without warnings. "
388 "Use in corresponding context manager.",
388 "Use in corresponding context manager.",
389 category=ProvisionalCompleterWarning, stacklevel=2)
389 category=ProvisionalCompleterWarning, stacklevel=2)
390
390
391 self.start = start
391 self.start = start
392 self.end = end
392 self.end = end
393 self.text = text
393 self.text = text
394 self.type = type
394 self.type = type
395 self.signature = signature
395 self.signature = signature
396 self._origin = _origin
396 self._origin = _origin
397
397
398 def __repr__(self):
398 def __repr__(self):
399 return '<Completion start=%s end=%s text=%r type=%r, signature=%r,>' % \
399 return '<Completion start=%s end=%s text=%r type=%r, signature=%r,>' % \
400 (self.start, self.end, self.text, self.type or '?', self.signature or '?')
400 (self.start, self.end, self.text, self.type or '?', self.signature or '?')
401
401
402 def __eq__(self, other)->Bool:
402 def __eq__(self, other)->Bool:
403 """
403 """
404 Equality and hash do not hash the type (as some completer may not be
404 Equality and hash do not hash the type (as some completer may not be
405 able to infer the type), but are use to (partially) de-duplicate
405 able to infer the type), but are use to (partially) de-duplicate
406 completion.
406 completion.
407
407
408 Completely de-duplicating completion is a bit tricker that just
408 Completely de-duplicating completion is a bit tricker that just
409 comparing as it depends on surrounding text, which Completions are not
409 comparing as it depends on surrounding text, which Completions are not
410 aware of.
410 aware of.
411 """
411 """
412 return self.start == other.start and \
412 return self.start == other.start and \
413 self.end == other.end and \
413 self.end == other.end and \
414 self.text == other.text
414 self.text == other.text
415
415
416 def __hash__(self):
416 def __hash__(self):
417 return hash((self.start, self.end, self.text))
417 return hash((self.start, self.end, self.text))
418
418
419
419
420 _IC = Iterable[Completion]
420 _IC = Iterable[Completion]
421
421
422
422
423 def _deduplicate_completions(text: str, completions: _IC)-> _IC:
423 def _deduplicate_completions(text: str, completions: _IC)-> _IC:
424 """
424 """
425 Deduplicate a set of completions.
425 Deduplicate a set of completions.
426
426
427 .. warning::
427 .. warning::
428
428
429 Unstable
429 Unstable
430
430
431 This function is unstable, API may change without warning.
431 This function is unstable, API may change without warning.
432
432
433 Parameters
433 Parameters
434 ----------
434 ----------
435 text : str
435 text : str
436 text that should be completed.
436 text that should be completed.
437 completions : Iterator[Completion]
437 completions : Iterator[Completion]
438 iterator over the completions to deduplicate
438 iterator over the completions to deduplicate
439
439
440 Yields
440 Yields
441 ------
441 ------
442 `Completions` objects
442 `Completions` objects
443 Completions coming from multiple sources, may be different but end up having
443 Completions coming from multiple sources, may be different but end up having
444 the same effect when applied to ``text``. If this is the case, this will
444 the same effect when applied to ``text``. If this is the case, this will
445 consider completions as equal and only emit the first encountered.
445 consider completions as equal and only emit the first encountered.
446 Not folded in `completions()` yet for debugging purpose, and to detect when
446 Not folded in `completions()` yet for debugging purpose, and to detect when
447 the IPython completer does return things that Jedi does not, but should be
447 the IPython completer does return things that Jedi does not, but should be
448 at some point.
448 at some point.
449 """
449 """
450 completions = list(completions)
450 completions = list(completions)
451 if not completions:
451 if not completions:
452 return
452 return
453
453
454 new_start = min(c.start for c in completions)
454 new_start = min(c.start for c in completions)
455 new_end = max(c.end for c in completions)
455 new_end = max(c.end for c in completions)
456
456
457 seen = set()
457 seen = set()
458 for c in completions:
458 for c in completions:
459 new_text = text[new_start:c.start] + c.text + text[c.end:new_end]
459 new_text = text[new_start:c.start] + c.text + text[c.end:new_end]
460 if new_text not in seen:
460 if new_text not in seen:
461 yield c
461 yield c
462 seen.add(new_text)
462 seen.add(new_text)
463
463
464
464
465 def rectify_completions(text: str, completions: _IC, *, _debug: bool = False) -> _IC:
465 def rectify_completions(text: str, completions: _IC, *, _debug: bool = False) -> _IC:
466 """
466 """
467 Rectify a set of completions to all have the same ``start`` and ``end``
467 Rectify a set of completions to all have the same ``start`` and ``end``
468
468
469 .. warning::
469 .. warning::
470
470
471 Unstable
471 Unstable
472
472
473 This function is unstable, API may change without warning.
473 This function is unstable, API may change without warning.
474 It will also raise unless use in proper context manager.
474 It will also raise unless use in proper context manager.
475
475
476 Parameters
476 Parameters
477 ----------
477 ----------
478 text : str
478 text : str
479 text that should be completed.
479 text that should be completed.
480 completions : Iterator[Completion]
480 completions : Iterator[Completion]
481 iterator over the completions to rectify
481 iterator over the completions to rectify
482 _debug : bool
482 _debug : bool
483 Log failed completion
483 Log failed completion
484
484
485 Notes
485 Notes
486 -----
486 -----
487 :any:`jedi.api.classes.Completion` s returned by Jedi may not have the same start and end, though
487 :any:`jedi.api.classes.Completion` s returned by Jedi may not have the same start and end, though
488 the Jupyter Protocol requires them to behave like so. This will readjust
488 the Jupyter Protocol requires them to behave like so. This will readjust
489 the completion to have the same ``start`` and ``end`` by padding both
489 the completion to have the same ``start`` and ``end`` by padding both
490 extremities with surrounding text.
490 extremities with surrounding text.
491
491
492 During stabilisation should support a ``_debug`` option to log which
492 During stabilisation should support a ``_debug`` option to log which
493 completion are return by the IPython completer and not found in Jedi in
493 completion are return by the IPython completer and not found in Jedi in
494 order to make upstream bug report.
494 order to make upstream bug report.
495 """
495 """
496 warnings.warn("`rectify_completions` is a provisional API (as of IPython 6.0). "
496 warnings.warn("`rectify_completions` is a provisional API (as of IPython 6.0). "
497 "It may change without warnings. "
497 "It may change without warnings. "
498 "Use in corresponding context manager.",
498 "Use in corresponding context manager.",
499 category=ProvisionalCompleterWarning, stacklevel=2)
499 category=ProvisionalCompleterWarning, stacklevel=2)
500
500
501 completions = list(completions)
501 completions = list(completions)
502 if not completions:
502 if not completions:
503 return
503 return
504 starts = (c.start for c in completions)
504 starts = (c.start for c in completions)
505 ends = (c.end for c in completions)
505 ends = (c.end for c in completions)
506
506
507 new_start = min(starts)
507 new_start = min(starts)
508 new_end = max(ends)
508 new_end = max(ends)
509
509
510 seen_jedi = set()
510 seen_jedi = set()
511 seen_python_matches = set()
511 seen_python_matches = set()
512 for c in completions:
512 for c in completions:
513 new_text = text[new_start:c.start] + c.text + text[c.end:new_end]
513 new_text = text[new_start:c.start] + c.text + text[c.end:new_end]
514 if c._origin == 'jedi':
514 if c._origin == 'jedi':
515 seen_jedi.add(new_text)
515 seen_jedi.add(new_text)
516 elif c._origin == 'IPCompleter.python_matches':
516 elif c._origin == 'IPCompleter.python_matches':
517 seen_python_matches.add(new_text)
517 seen_python_matches.add(new_text)
518 yield Completion(new_start, new_end, new_text, type=c.type, _origin=c._origin, signature=c.signature)
518 yield Completion(new_start, new_end, new_text, type=c.type, _origin=c._origin, signature=c.signature)
519 diff = seen_python_matches.difference(seen_jedi)
519 diff = seen_python_matches.difference(seen_jedi)
520 if diff and _debug:
520 if diff and _debug:
521 print('IPython.python matches have extras:', diff)
521 print('IPython.python matches have extras:', diff)
522
522
523
523
524 if sys.platform == 'win32':
524 if sys.platform == 'win32':
525 DELIMS = ' \t\n`!@#$^&*()=+[{]}|;\'",<>?'
525 DELIMS = ' \t\n`!@#$^&*()=+[{]}|;\'",<>?'
526 else:
526 else:
527 DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
527 DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
528
528
529 GREEDY_DELIMS = ' =\r\n'
529 GREEDY_DELIMS = ' =\r\n'
530
530
531
531
532 class CompletionSplitter(object):
532 class CompletionSplitter(object):
533 """An object to split an input line in a manner similar to readline.
533 """An object to split an input line in a manner similar to readline.
534
534
535 By having our own implementation, we can expose readline-like completion in
535 By having our own implementation, we can expose readline-like completion in
536 a uniform manner to all frontends. This object only needs to be given the
536 a uniform manner to all frontends. This object only needs to be given the
537 line of text to be split and the cursor position on said line, and it
537 line of text to be split and the cursor position on said line, and it
538 returns the 'word' to be completed on at the cursor after splitting the
538 returns the 'word' to be completed on at the cursor after splitting the
539 entire line.
539 entire line.
540
540
541 What characters are used as splitting delimiters can be controlled by
541 What characters are used as splitting delimiters can be controlled by
542 setting the ``delims`` attribute (this is a property that internally
542 setting the ``delims`` attribute (this is a property that internally
543 automatically builds the necessary regular expression)"""
543 automatically builds the necessary regular expression)"""
544
544
545 # Private interface
545 # Private interface
546
546
547 # A string of delimiter characters. The default value makes sense for
547 # A string of delimiter characters. The default value makes sense for
548 # IPython's most typical usage patterns.
548 # IPython's most typical usage patterns.
549 _delims = DELIMS
549 _delims = DELIMS
550
550
551 # The expression (a normal string) to be compiled into a regular expression
551 # The expression (a normal string) to be compiled into a regular expression
552 # for actual splitting. We store it as an attribute mostly for ease of
552 # for actual splitting. We store it as an attribute mostly for ease of
553 # debugging, since this type of code can be so tricky to debug.
553 # debugging, since this type of code can be so tricky to debug.
554 _delim_expr = None
554 _delim_expr = None
555
555
556 # The regular expression that does the actual splitting
556 # The regular expression that does the actual splitting
557 _delim_re = None
557 _delim_re = None
558
558
559 def __init__(self, delims=None):
559 def __init__(self, delims=None):
560 delims = CompletionSplitter._delims if delims is None else delims
560 delims = CompletionSplitter._delims if delims is None else delims
561 self.delims = delims
561 self.delims = delims
562
562
563 @property
563 @property
564 def delims(self):
564 def delims(self):
565 """Return the string of delimiter characters."""
565 """Return the string of delimiter characters."""
566 return self._delims
566 return self._delims
567
567
568 @delims.setter
568 @delims.setter
569 def delims(self, delims):
569 def delims(self, delims):
570 """Set the delimiters for line splitting."""
570 """Set the delimiters for line splitting."""
571 expr = '[' + ''.join('\\'+ c for c in delims) + ']'
571 expr = '[' + ''.join('\\'+ c for c in delims) + ']'
572 self._delim_re = re.compile(expr)
572 self._delim_re = re.compile(expr)
573 self._delims = delims
573 self._delims = delims
574 self._delim_expr = expr
574 self._delim_expr = expr
575
575
576 def split_line(self, line, cursor_pos=None):
576 def split_line(self, line, cursor_pos=None):
577 """Split a line of text with a cursor at the given position.
577 """Split a line of text with a cursor at the given position.
578 """
578 """
579 l = line if cursor_pos is None else line[:cursor_pos]
579 l = line if cursor_pos is None else line[:cursor_pos]
580 return self._delim_re.split(l)[-1]
580 return self._delim_re.split(l)[-1]
581
581
582
582
583
583
584 class Completer(Configurable):
584 class Completer(Configurable):
585
585
586 greedy = Bool(False,
586 greedy = Bool(False,
587 help="""Activate greedy completion
587 help="""Activate greedy completion
588 PENDING DEPRECATION. this is now mostly taken care of with Jedi.
588 PENDING DEPRECATION. this is now mostly taken care of with Jedi.
589
589
590 This will enable completion on elements of lists, results of function calls, etc.,
590 This will enable completion on elements of lists, results of function calls, etc.,
591 but can be unsafe because the code is actually evaluated on TAB.
591 but can be unsafe because the code is actually evaluated on TAB.
592 """
592 """
593 ).tag(config=True)
593 ).tag(config=True)
594
594
595 use_jedi = Bool(default_value=JEDI_INSTALLED,
595 use_jedi = Bool(default_value=JEDI_INSTALLED,
596 help="Experimental: Use Jedi to generate autocompletions. "
596 help="Experimental: Use Jedi to generate autocompletions. "
597 "Default to True if jedi is installed.").tag(config=True)
597 "Default to True if jedi is installed.").tag(config=True)
598
598
599 jedi_compute_type_timeout = Int(default_value=400,
599 jedi_compute_type_timeout = Int(default_value=400,
600 help="""Experimental: restrict time (in milliseconds) during which Jedi can compute types.
600 help="""Experimental: restrict time (in milliseconds) during which Jedi can compute types.
601 Set to 0 to stop computing types. Non-zero value lower than 100ms may hurt
601 Set to 0 to stop computing types. Non-zero value lower than 100ms may hurt
602 performance by preventing jedi to build its cache.
602 performance by preventing jedi to build its cache.
603 """).tag(config=True)
603 """).tag(config=True)
604
604
605 debug = Bool(default_value=False,
605 debug = Bool(default_value=False,
606 help='Enable debug for the Completer. Mostly print extra '
606 help='Enable debug for the Completer. Mostly print extra '
607 'information for experimental jedi integration.')\
607 'information for experimental jedi integration.')\
608 .tag(config=True)
608 .tag(config=True)
609
609
610 backslash_combining_completions = Bool(True,
610 backslash_combining_completions = Bool(True,
611 help="Enable unicode completions, e.g. \\alpha<tab> . "
611 help="Enable unicode completions, e.g. \\alpha<tab> . "
612 "Includes completion of latex commands, unicode names, and expanding "
612 "Includes completion of latex commands, unicode names, and expanding "
613 "unicode characters back to latex commands.").tag(config=True)
613 "unicode characters back to latex commands.").tag(config=True)
614
614
615 def __init__(self, namespace=None, global_namespace=None, **kwargs):
615 def __init__(self, namespace=None, global_namespace=None, **kwargs):
616 """Create a new completer for the command line.
616 """Create a new completer for the command line.
617
617
618 Completer(namespace=ns, global_namespace=ns2) -> completer instance.
618 Completer(namespace=ns, global_namespace=ns2) -> completer instance.
619
619
620 If unspecified, the default namespace where completions are performed
620 If unspecified, the default namespace where completions are performed
621 is __main__ (technically, __main__.__dict__). Namespaces should be
621 is __main__ (technically, __main__.__dict__). Namespaces should be
622 given as dictionaries.
622 given as dictionaries.
623
623
624 An optional second namespace can be given. This allows the completer
624 An optional second namespace can be given. This allows the completer
625 to handle cases where both the local and global scopes need to be
625 to handle cases where both the local and global scopes need to be
626 distinguished.
626 distinguished.
627 """
627 """
628
628
629 # Don't bind to namespace quite yet, but flag whether the user wants a
629 # Don't bind to namespace quite yet, but flag whether the user wants a
630 # specific namespace or to use __main__.__dict__. This will allow us
630 # specific namespace or to use __main__.__dict__. This will allow us
631 # to bind to __main__.__dict__ at completion time, not now.
631 # to bind to __main__.__dict__ at completion time, not now.
632 if namespace is None:
632 if namespace is None:
633 self.use_main_ns = True
633 self.use_main_ns = True
634 else:
634 else:
635 self.use_main_ns = False
635 self.use_main_ns = False
636 self.namespace = namespace
636 self.namespace = namespace
637
637
638 # The global namespace, if given, can be bound directly
638 # The global namespace, if given, can be bound directly
639 if global_namespace is None:
639 if global_namespace is None:
640 self.global_namespace = {}
640 self.global_namespace = {}
641 else:
641 else:
642 self.global_namespace = global_namespace
642 self.global_namespace = global_namespace
643
643
644 self.custom_matchers = []
644 self.custom_matchers = []
645
645
646 super(Completer, self).__init__(**kwargs)
646 super(Completer, self).__init__(**kwargs)
647
647
648 def complete(self, text, state):
648 def complete(self, text, state):
649 """Return the next possible completion for 'text'.
649 """Return the next possible completion for 'text'.
650
650
651 This is called successively with state == 0, 1, 2, ... until it
651 This is called successively with state == 0, 1, 2, ... until it
652 returns None. The completion should begin with 'text'.
652 returns None. The completion should begin with 'text'.
653
653
654 """
654 """
655 if self.use_main_ns:
655 if self.use_main_ns:
656 self.namespace = __main__.__dict__
656 self.namespace = __main__.__dict__
657
657
658 if state == 0:
658 if state == 0:
659 if "." in text:
659 if "." in text:
660 self.matches = self.attr_matches(text)
660 self.matches = self.attr_matches(text)
661 else:
661 else:
662 self.matches = self.global_matches(text)
662 self.matches = self.global_matches(text)
663 try:
663 try:
664 return self.matches[state]
664 return self.matches[state]
665 except IndexError:
665 except IndexError:
666 return None
666 return None
667
667
668 def global_matches(self, text):
668 def global_matches(self, text):
669 """Compute matches when text is a simple name.
669 """Compute matches when text is a simple name.
670
670
671 Return a list of all keywords, built-in functions and names currently
671 Return a list of all keywords, built-in functions and names currently
672 defined in self.namespace or self.global_namespace that match.
672 defined in self.namespace or self.global_namespace that match.
673
673
674 """
674 """
675 matches = []
675 matches = []
676 match_append = matches.append
676 match_append = matches.append
677 n = len(text)
677 n = len(text)
678 for lst in [keyword.kwlist,
678 for lst in [keyword.kwlist,
679 builtin_mod.__dict__.keys(),
679 builtin_mod.__dict__.keys(),
680 self.namespace.keys(),
680 self.namespace.keys(),
681 self.global_namespace.keys()]:
681 self.global_namespace.keys()]:
682 for word in lst:
682 for word in lst:
683 if word[:n] == text and word != "__builtins__":
683 if word[:n] == text and word != "__builtins__":
684 match_append(word)
684 match_append(word)
685
685
686 snake_case_re = re.compile(r"[^_]+(_[^_]+)+?\Z")
686 snake_case_re = re.compile(r"[^_]+(_[^_]+)+?\Z")
687 for lst in [self.namespace.keys(),
687 for lst in [self.namespace.keys(),
688 self.global_namespace.keys()]:
688 self.global_namespace.keys()]:
689 shortened = {"_".join([sub[0] for sub in word.split('_')]) : word
689 shortened = {"_".join([sub[0] for sub in word.split('_')]) : word
690 for word in lst if snake_case_re.match(word)}
690 for word in lst if snake_case_re.match(word)}
691 for word in shortened.keys():
691 for word in shortened.keys():
692 if word[:n] == text and word != "__builtins__":
692 if word[:n] == text and word != "__builtins__":
693 match_append(shortened[word])
693 match_append(shortened[word])
694 return matches
694 return matches
695
695
696 def attr_matches(self, text):
696 def attr_matches(self, text):
697 """Compute matches when text contains a dot.
697 """Compute matches when text contains a dot.
698
698
699 Assuming the text is of the form NAME.NAME....[NAME], and is
699 Assuming the text is of the form NAME.NAME....[NAME], and is
700 evaluatable in self.namespace or self.global_namespace, it will be
700 evaluatable in self.namespace or self.global_namespace, it will be
701 evaluated and its attributes (as revealed by dir()) are used as
701 evaluated and its attributes (as revealed by dir()) are used as
702 possible completions. (For class instances, class members are
702 possible completions. (For class instances, class members are
703 also considered.)
703 also considered.)
704
704
705 WARNING: this can still invoke arbitrary C code, if an object
705 WARNING: this can still invoke arbitrary C code, if an object
706 with a __getattr__ hook is evaluated.
706 with a __getattr__ hook is evaluated.
707
707
708 """
708 """
709
709
710 # Another option, seems to work great. Catches things like ''.<tab>
710 # Another option, seems to work great. Catches things like ''.<tab>
711 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
711 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
712
712
713 if m:
713 if m:
714 expr, attr = m.group(1, 3)
714 expr, attr = m.group(1, 3)
715 elif self.greedy:
715 elif self.greedy:
716 m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer)
716 m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer)
717 if not m2:
717 if not m2:
718 return []
718 return []
719 expr, attr = m2.group(1,2)
719 expr, attr = m2.group(1,2)
720 else:
720 else:
721 return []
721 return []
722
722
723 try:
723 try:
724 obj = eval(expr, self.namespace)
724 obj = eval(expr, self.namespace)
725 except:
725 except:
726 try:
726 try:
727 obj = eval(expr, self.global_namespace)
727 obj = eval(expr, self.global_namespace)
728 except:
728 except:
729 return []
729 return []
730
730
731 if self.limit_to__all__ and hasattr(obj, '__all__'):
731 if self.limit_to__all__ and hasattr(obj, '__all__'):
732 words = get__all__entries(obj)
732 words = get__all__entries(obj)
733 else:
733 else:
734 words = dir2(obj)
734 words = dir2(obj)
735
735
736 try:
736 try:
737 words = generics.complete_object(obj, words)
737 words = generics.complete_object(obj, words)
738 except TryNext:
738 except TryNext:
739 pass
739 pass
740 except AssertionError:
740 except AssertionError:
741 raise
741 raise
742 except Exception:
742 except Exception:
743 # Silence errors from completion function
743 # Silence errors from completion function
744 #raise # dbg
744 #raise # dbg
745 pass
745 pass
746 # Build match list to return
746 # Build match list to return
747 n = len(attr)
747 n = len(attr)
748 return [u"%s.%s" % (expr, w) for w in words if w[:n] == attr ]
748 return [u"%s.%s" % (expr, w) for w in words if w[:n] == attr ]
749
749
750
750
751 def get__all__entries(obj):
751 def get__all__entries(obj):
752 """returns the strings in the __all__ attribute"""
752 """returns the strings in the __all__ attribute"""
753 try:
753 try:
754 words = getattr(obj, '__all__')
754 words = getattr(obj, '__all__')
755 except:
755 except:
756 return []
756 return []
757
757
758 return [w for w in words if isinstance(w, str)]
758 return [w for w in words if isinstance(w, str)]
759
759
760
760
761 def match_dict_keys(keys: List[Union[str, bytes, Tuple[Union[str, bytes]]]], prefix: str, delims: str,
761 def match_dict_keys(keys: List[Union[str, bytes, Tuple[Union[str, bytes]]]], prefix: str, delims: str,
762 extra_prefix: Optional[Tuple[str, bytes]]=None) -> Tuple[str, int, List[str]]:
762 extra_prefix: Optional[Tuple[str, bytes]]=None) -> Tuple[str, int, List[str]]:
763 """Used by dict_key_matches, matching the prefix to a list of keys
763 """Used by dict_key_matches, matching the prefix to a list of keys
764
764
765 Parameters
765 Parameters
766 ----------
766 ----------
767 keys
767 keys
768 list of keys in dictionary currently being completed.
768 list of keys in dictionary currently being completed.
769 prefix
769 prefix
770 Part of the text already typed by the user. E.g. `mydict[b'fo`
770 Part of the text already typed by the user. E.g. `mydict[b'fo`
771 delims
771 delims
772 String of delimiters to consider when finding the current key.
772 String of delimiters to consider when finding the current key.
773 extra_prefix : optional
773 extra_prefix : optional
774 Part of the text already typed in multi-key index cases. E.g. for
774 Part of the text already typed in multi-key index cases. E.g. for
775 `mydict['foo', "bar", 'b`, this would be `('foo', 'bar')`.
775 `mydict['foo', "bar", 'b`, this would be `('foo', 'bar')`.
776
776
777 Returns
777 Returns
778 -------
778 -------
779 A tuple of three elements: ``quote``, ``token_start``, ``matched``, with
779 A tuple of three elements: ``quote``, ``token_start``, ``matched``, with
780 ``quote`` being the quote that need to be used to close current string.
780 ``quote`` being the quote that need to be used to close current string.
781 ``token_start`` the position where the replacement should start occurring,
781 ``token_start`` the position where the replacement should start occurring,
782 ``matches`` a list of replacement/completion
782 ``matches`` a list of replacement/completion
783
783
784 """
784 """
785 prefix_tuple = extra_prefix if extra_prefix else ()
785 prefix_tuple = extra_prefix if extra_prefix else ()
786 Nprefix = len(prefix_tuple)
786 Nprefix = len(prefix_tuple)
787 def filter_prefix_tuple(key):
787 def filter_prefix_tuple(key):
788 # Reject too short keys
788 # Reject too short keys
789 if len(key) <= Nprefix:
789 if len(key) <= Nprefix:
790 return False
790 return False
791 # Reject keys with non str/bytes in it
791 # Reject keys with non str/bytes in it
792 for k in key:
792 for k in key:
793 if not isinstance(k, (str, bytes)):
793 if not isinstance(k, (str, bytes)):
794 return False
794 return False
795 # Reject keys that do not match the prefix
795 # Reject keys that do not match the prefix
796 for k, pt in zip(key, prefix_tuple):
796 for k, pt in zip(key, prefix_tuple):
797 if k != pt:
797 if k != pt:
798 return False
798 return False
799 # All checks passed!
799 # All checks passed!
800 return True
800 return True
801
801
802 filtered_keys:List[Union[str,bytes]] = []
802 filtered_keys:List[Union[str,bytes]] = []
803 def _add_to_filtered_keys(key):
803 def _add_to_filtered_keys(key):
804 if isinstance(key, (str, bytes)):
804 if isinstance(key, (str, bytes)):
805 filtered_keys.append(key)
805 filtered_keys.append(key)
806
806
807 for k in keys:
807 for k in keys:
808 if isinstance(k, tuple):
808 if isinstance(k, tuple):
809 if filter_prefix_tuple(k):
809 if filter_prefix_tuple(k):
810 _add_to_filtered_keys(k[Nprefix])
810 _add_to_filtered_keys(k[Nprefix])
811 else:
811 else:
812 _add_to_filtered_keys(k)
812 _add_to_filtered_keys(k)
813
813
814 if not prefix:
814 if not prefix:
815 return '', 0, [repr(k) for k in filtered_keys]
815 return '', 0, [repr(k) for k in filtered_keys]
816 quote_match = re.search('["\']', prefix)
816 quote_match = re.search('["\']', prefix)
817 assert quote_match is not None # silence mypy
817 assert quote_match is not None # silence mypy
818 quote = quote_match.group()
818 quote = quote_match.group()
819 try:
819 try:
820 prefix_str = eval(prefix + quote, {})
820 prefix_str = eval(prefix + quote, {})
821 except Exception:
821 except Exception:
822 return '', 0, []
822 return '', 0, []
823
823
824 pattern = '[^' + ''.join('\\' + c for c in delims) + ']*$'
824 pattern = '[^' + ''.join('\\' + c for c in delims) + ']*$'
825 token_match = re.search(pattern, prefix, re.UNICODE)
825 token_match = re.search(pattern, prefix, re.UNICODE)
826 assert token_match is not None # silence mypy
826 assert token_match is not None # silence mypy
827 token_start = token_match.start()
827 token_start = token_match.start()
828 token_prefix = token_match.group()
828 token_prefix = token_match.group()
829
829
830 matched:List[str] = []
830 matched:List[str] = []
831 for key in filtered_keys:
831 for key in filtered_keys:
832 try:
832 try:
833 if not key.startswith(prefix_str):
833 if not key.startswith(prefix_str):
834 continue
834 continue
835 except (AttributeError, TypeError, UnicodeError):
835 except (AttributeError, TypeError, UnicodeError):
836 # Python 3+ TypeError on b'a'.startswith('a') or vice-versa
836 # Python 3+ TypeError on b'a'.startswith('a') or vice-versa
837 continue
837 continue
838
838
839 # reformat remainder of key to begin with prefix
839 # reformat remainder of key to begin with prefix
840 rem = key[len(prefix_str):]
840 rem = key[len(prefix_str):]
841 # force repr wrapped in '
841 # force repr wrapped in '
842 rem_repr = repr(rem + '"') if isinstance(rem, str) else repr(rem + b'"')
842 rem_repr = repr(rem + '"') if isinstance(rem, str) else repr(rem + b'"')
843 rem_repr = rem_repr[1 + rem_repr.index("'"):-2]
843 rem_repr = rem_repr[1 + rem_repr.index("'"):-2]
844 if quote == '"':
844 if quote == '"':
845 # The entered prefix is quoted with ",
845 # The entered prefix is quoted with ",
846 # but the match is quoted with '.
846 # but the match is quoted with '.
847 # A contained " hence needs escaping for comparison:
847 # A contained " hence needs escaping for comparison:
848 rem_repr = rem_repr.replace('"', '\\"')
848 rem_repr = rem_repr.replace('"', '\\"')
849
849
850 # then reinsert prefix from start of token
850 # then reinsert prefix from start of token
851 matched.append('%s%s' % (token_prefix, rem_repr))
851 matched.append('%s%s' % (token_prefix, rem_repr))
852 return quote, token_start, matched
852 return quote, token_start, matched
853
853
854
854
855 def cursor_to_position(text:str, line:int, column:int)->int:
855 def cursor_to_position(text:str, line:int, column:int)->int:
856 """
856 """
857 Convert the (line,column) position of the cursor in text to an offset in a
857 Convert the (line,column) position of the cursor in text to an offset in a
858 string.
858 string.
859
859
860 Parameters
860 Parameters
861 ----------
861 ----------
862 text : str
862 text : str
863 The text in which to calculate the cursor offset
863 The text in which to calculate the cursor offset
864 line : int
864 line : int
865 Line of the cursor; 0-indexed
865 Line of the cursor; 0-indexed
866 column : int
866 column : int
867 Column of the cursor 0-indexed
867 Column of the cursor 0-indexed
868
868
869 Returns
869 Returns
870 -------
870 -------
871 Position of the cursor in ``text``, 0-indexed.
871 Position of the cursor in ``text``, 0-indexed.
872
872
873 See Also
873 See Also
874 --------
874 --------
875 position_to_cursor : reciprocal of this function
875 position_to_cursor : reciprocal of this function
876
876
877 """
877 """
878 lines = text.split('\n')
878 lines = text.split('\n')
879 assert line <= len(lines), '{} <= {}'.format(str(line), str(len(lines)))
879 assert line <= len(lines), '{} <= {}'.format(str(line), str(len(lines)))
880
880
881 return sum(len(l) + 1 for l in lines[:line]) + column
881 return sum(len(l) + 1 for l in lines[:line]) + column
882
882
883 def position_to_cursor(text:str, offset:int)->Tuple[int, int]:
883 def position_to_cursor(text:str, offset:int)->Tuple[int, int]:
884 """
884 """
885 Convert the position of the cursor in text (0 indexed) to a line
885 Convert the position of the cursor in text (0 indexed) to a line
886 number(0-indexed) and a column number (0-indexed) pair
886 number(0-indexed) and a column number (0-indexed) pair
887
887
888 Position should be a valid position in ``text``.
888 Position should be a valid position in ``text``.
889
889
890 Parameters
890 Parameters
891 ----------
891 ----------
892 text : str
892 text : str
893 The text in which to calculate the cursor offset
893 The text in which to calculate the cursor offset
894 offset : int
894 offset : int
895 Position of the cursor in ``text``, 0-indexed.
895 Position of the cursor in ``text``, 0-indexed.
896
896
897 Returns
897 Returns
898 -------
898 -------
899 (line, column) : (int, int)
899 (line, column) : (int, int)
900 Line of the cursor; 0-indexed, column of the cursor 0-indexed
900 Line of the cursor; 0-indexed, column of the cursor 0-indexed
901
901
902 See Also
902 See Also
903 --------
903 --------
904 cursor_to_position : reciprocal of this function
904 cursor_to_position : reciprocal of this function
905
905
906 """
906 """
907
907
908 assert 0 <= offset <= len(text) , "0 <= %s <= %s" % (offset , len(text))
908 assert 0 <= offset <= len(text) , "0 <= %s <= %s" % (offset , len(text))
909
909
910 before = text[:offset]
910 before = text[:offset]
911 blines = before.split('\n') # ! splitnes trim trailing \n
911 blines = before.split('\n') # ! splitnes trim trailing \n
912 line = before.count('\n')
912 line = before.count('\n')
913 col = len(blines[-1])
913 col = len(blines[-1])
914 return line, col
914 return line, col
915
915
916
916
917 def _safe_isinstance(obj, module, class_name):
917 def _safe_isinstance(obj, module, class_name):
918 """Checks if obj is an instance of module.class_name if loaded
918 """Checks if obj is an instance of module.class_name if loaded
919 """
919 """
920 return (module in sys.modules and
920 return (module in sys.modules and
921 isinstance(obj, getattr(import_module(module), class_name)))
921 isinstance(obj, getattr(import_module(module), class_name)))
922
922
923 def back_unicode_name_matches(text:str) -> Tuple[str, Sequence[str]]:
923 def back_unicode_name_matches(text:str) -> Tuple[str, Sequence[str]]:
924 """Match Unicode characters back to Unicode name
924 """Match Unicode characters back to Unicode name
925
925
926 This does ``β˜ƒ`` -> ``\\snowman``
926 This does ``β˜ƒ`` -> ``\\snowman``
927
927
928 Note that snowman is not a valid python3 combining character but will be expanded.
928 Note that snowman is not a valid python3 combining character but will be expanded.
929 Though it will not recombine back to the snowman character by the completion machinery.
929 Though it will not recombine back to the snowman character by the completion machinery.
930
930
931 This will not either back-complete standard sequences like \\n, \\b ...
931 This will not either back-complete standard sequences like \\n, \\b ...
932
932
933 Returns
933 Returns
934 =======
934 =======
935
935
936 Return a tuple with two elements:
936 Return a tuple with two elements:
937
937
938 - The Unicode character that was matched (preceded with a backslash), or
938 - The Unicode character that was matched (preceded with a backslash), or
939 empty string,
939 empty string,
940 - a sequence (of 1), name for the match Unicode character, preceded by
940 - a sequence (of 1), name for the match Unicode character, preceded by
941 backslash, or empty if no match.
941 backslash, or empty if no match.
942
942
943 """
943 """
944 if len(text)<2:
944 if len(text)<2:
945 return '', ()
945 return '', ()
946 maybe_slash = text[-2]
946 maybe_slash = text[-2]
947 if maybe_slash != '\\':
947 if maybe_slash != '\\':
948 return '', ()
948 return '', ()
949
949
950 char = text[-1]
950 char = text[-1]
951 # no expand on quote for completion in strings.
951 # no expand on quote for completion in strings.
952 # nor backcomplete standard ascii keys
952 # nor backcomplete standard ascii keys
953 if char in string.ascii_letters or char in ('"',"'"):
953 if char in string.ascii_letters or char in ('"',"'"):
954 return '', ()
954 return '', ()
955 try :
955 try :
956 unic = unicodedata.name(char)
956 unic = unicodedata.name(char)
957 return '\\'+char,('\\'+unic,)
957 return '\\'+char,('\\'+unic,)
958 except KeyError:
958 except KeyError:
959 pass
959 pass
960 return '', ()
960 return '', ()
961
961
962 def back_latex_name_matches(text:str) -> Tuple[str, Sequence[str]] :
962 def back_latex_name_matches(text:str) -> Tuple[str, Sequence[str]] :
963 """Match latex characters back to unicode name
963 """Match latex characters back to unicode name
964
964
965 This does ``\\β„΅`` -> ``\\aleph``
965 This does ``\\β„΅`` -> ``\\aleph``
966
966
967 """
967 """
968 if len(text)<2:
968 if len(text)<2:
969 return '', ()
969 return '', ()
970 maybe_slash = text[-2]
970 maybe_slash = text[-2]
971 if maybe_slash != '\\':
971 if maybe_slash != '\\':
972 return '', ()
972 return '', ()
973
973
974
974
975 char = text[-1]
975 char = text[-1]
976 # no expand on quote for completion in strings.
976 # no expand on quote for completion in strings.
977 # nor backcomplete standard ascii keys
977 # nor backcomplete standard ascii keys
978 if char in string.ascii_letters or char in ('"',"'"):
978 if char in string.ascii_letters or char in ('"',"'"):
979 return '', ()
979 return '', ()
980 try :
980 try :
981 latex = reverse_latex_symbol[char]
981 latex = reverse_latex_symbol[char]
982 # '\\' replace the \ as well
982 # '\\' replace the \ as well
983 return '\\'+char,[latex]
983 return '\\'+char,[latex]
984 except KeyError:
984 except KeyError:
985 pass
985 pass
986 return '', ()
986 return '', ()
987
987
988
988
989 def _formatparamchildren(parameter) -> str:
989 def _formatparamchildren(parameter) -> str:
990 """
990 """
991 Get parameter name and value from Jedi Private API
991 Get parameter name and value from Jedi Private API
992
992
993 Jedi does not expose a simple way to get `param=value` from its API.
993 Jedi does not expose a simple way to get `param=value` from its API.
994
994
995 Parameters
995 Parameters
996 ----------
996 ----------
997 parameter
997 parameter
998 Jedi's function `Param`
998 Jedi's function `Param`
999
999
1000 Returns
1000 Returns
1001 -------
1001 -------
1002 A string like 'a', 'b=1', '*args', '**kwargs'
1002 A string like 'a', 'b=1', '*args', '**kwargs'
1003
1003
1004 """
1004 """
1005 description = parameter.description
1005 description = parameter.description
1006 if not description.startswith('param '):
1006 if not description.startswith('param '):
1007 raise ValueError('Jedi function parameter description have change format.'
1007 raise ValueError('Jedi function parameter description have change format.'
1008 'Expected "param ...", found %r".' % description)
1008 'Expected "param ...", found %r".' % description)
1009 return description[6:]
1009 return description[6:]
1010
1010
1011 def _make_signature(completion)-> str:
1011 def _make_signature(completion)-> str:
1012 """
1012 """
1013 Make the signature from a jedi completion
1013 Make the signature from a jedi completion
1014
1014
1015 Parameters
1015 Parameters
1016 ----------
1016 ----------
1017 completion : jedi.Completion
1017 completion : jedi.Completion
1018 object does not complete a function type
1018 object does not complete a function type
1019
1019
1020 Returns
1020 Returns
1021 -------
1021 -------
1022 a string consisting of the function signature, with the parenthesis but
1022 a string consisting of the function signature, with the parenthesis but
1023 without the function name. example:
1023 without the function name. example:
1024 `(a, *args, b=1, **kwargs)`
1024 `(a, *args, b=1, **kwargs)`
1025
1025
1026 """
1026 """
1027
1027
1028 # it looks like this might work on jedi 0.17
1028 # it looks like this might work on jedi 0.17
1029 if hasattr(completion, 'get_signatures'):
1029 if hasattr(completion, 'get_signatures'):
1030 signatures = completion.get_signatures()
1030 signatures = completion.get_signatures()
1031 if not signatures:
1031 if not signatures:
1032 return '(?)'
1032 return '(?)'
1033
1033
1034 c0 = completion.get_signatures()[0]
1034 c0 = completion.get_signatures()[0]
1035 return '('+c0.to_string().split('(', maxsplit=1)[1]
1035 return '('+c0.to_string().split('(', maxsplit=1)[1]
1036
1036
1037 return '(%s)'% ', '.join([f for f in (_formatparamchildren(p) for signature in completion.get_signatures()
1037 return '(%s)'% ', '.join([f for f in (_formatparamchildren(p) for signature in completion.get_signatures()
1038 for p in signature.defined_names()) if f])
1038 for p in signature.defined_names()) if f])
1039
1039
1040
1040
1041 class _CompleteResult(NamedTuple):
1041 class _CompleteResult(NamedTuple):
1042 matched_text : str
1042 matched_text : str
1043 matches: Sequence[str]
1043 matches: Sequence[str]
1044 matches_origin: Sequence[str]
1044 matches_origin: Sequence[str]
1045 jedi_matches: Any
1045 jedi_matches: Any
1046
1046
1047
1047
1048 class IPCompleter(Completer):
1048 class IPCompleter(Completer):
1049 """Extension of the completer class with IPython-specific features"""
1049 """Extension of the completer class with IPython-specific features"""
1050
1050
1051 __dict_key_regexps: Optional[Dict[bool,Pattern]] = None
1051 __dict_key_regexps: Optional[Dict[bool,Pattern]] = None
1052
1052
1053 @observe('greedy')
1053 @observe('greedy')
1054 def _greedy_changed(self, change):
1054 def _greedy_changed(self, change):
1055 """update the splitter and readline delims when greedy is changed"""
1055 """update the splitter and readline delims when greedy is changed"""
1056 if change['new']:
1056 if change['new']:
1057 self.splitter.delims = GREEDY_DELIMS
1057 self.splitter.delims = GREEDY_DELIMS
1058 else:
1058 else:
1059 self.splitter.delims = DELIMS
1059 self.splitter.delims = DELIMS
1060
1060
1061 dict_keys_only = Bool(False,
1061 dict_keys_only = Bool(False,
1062 help="""Whether to show dict key matches only""")
1062 help="""Whether to show dict key matches only""")
1063
1063
1064 merge_completions = Bool(True,
1064 merge_completions = Bool(True,
1065 help="""Whether to merge completion results into a single list
1065 help="""Whether to merge completion results into a single list
1066
1066
1067 If False, only the completion results from the first non-empty
1067 If False, only the completion results from the first non-empty
1068 completer will be returned.
1068 completer will be returned.
1069 """
1069 """
1070 ).tag(config=True)
1070 ).tag(config=True)
1071 omit__names = Enum((0,1,2), default_value=2,
1071 omit__names = Enum((0,1,2), default_value=2,
1072 help="""Instruct the completer to omit private method names
1072 help="""Instruct the completer to omit private method names
1073
1073
1074 Specifically, when completing on ``object.<tab>``.
1074 Specifically, when completing on ``object.<tab>``.
1075
1075
1076 When 2 [default]: all names that start with '_' will be excluded.
1076 When 2 [default]: all names that start with '_' will be excluded.
1077
1077
1078 When 1: all 'magic' names (``__foo__``) will be excluded.
1078 When 1: all 'magic' names (``__foo__``) will be excluded.
1079
1079
1080 When 0: nothing will be excluded.
1080 When 0: nothing will be excluded.
1081 """
1081 """
1082 ).tag(config=True)
1082 ).tag(config=True)
1083 limit_to__all__ = Bool(False,
1083 limit_to__all__ = Bool(False,
1084 help="""
1084 help="""
1085 DEPRECATED as of version 5.0.
1085 DEPRECATED as of version 5.0.
1086
1086
1087 Instruct the completer to use __all__ for the completion
1087 Instruct the completer to use __all__ for the completion
1088
1088
1089 Specifically, when completing on ``object.<tab>``.
1089 Specifically, when completing on ``object.<tab>``.
1090
1090
1091 When True: only those names in obj.__all__ will be included.
1091 When True: only those names in obj.__all__ will be included.
1092
1092
1093 When False [default]: the __all__ attribute is ignored
1093 When False [default]: the __all__ attribute is ignored
1094 """,
1094 """,
1095 ).tag(config=True)
1095 ).tag(config=True)
1096
1096
1097 profile_completions = Bool(
1097 profile_completions = Bool(
1098 default_value=False,
1098 default_value=False,
1099 help="If True, emit profiling data for completion subsystem using cProfile."
1099 help="If True, emit profiling data for completion subsystem using cProfile."
1100 ).tag(config=True)
1100 ).tag(config=True)
1101
1101
1102 profiler_output_dir = Unicode(
1102 profiler_output_dir = Unicode(
1103 default_value=".completion_profiles",
1103 default_value=".completion_profiles",
1104 help="Template for path at which to output profile data for completions."
1104 help="Template for path at which to output profile data for completions."
1105 ).tag(config=True)
1105 ).tag(config=True)
1106
1106
1107 @observe('limit_to__all__')
1107 @observe('limit_to__all__')
1108 def _limit_to_all_changed(self, change):
1108 def _limit_to_all_changed(self, change):
1109 warnings.warn('`IPython.core.IPCompleter.limit_to__all__` configuration '
1109 warnings.warn('`IPython.core.IPCompleter.limit_to__all__` configuration '
1110 'value has been deprecated since IPython 5.0, will be made to have '
1110 'value has been deprecated since IPython 5.0, will be made to have '
1111 'no effects and then removed in future version of IPython.',
1111 'no effects and then removed in future version of IPython.',
1112 UserWarning)
1112 UserWarning)
1113
1113
1114 def __init__(
1114 def __init__(
1115 self, shell=None, namespace=None, global_namespace=None, config=None, **kwargs
1115 self, shell=None, namespace=None, global_namespace=None, config=None, **kwargs
1116 ):
1116 ):
1117 """IPCompleter() -> completer
1117 """IPCompleter() -> completer
1118
1118
1119 Return a completer object.
1119 Return a completer object.
1120
1120
1121 Parameters
1121 Parameters
1122 ----------
1122 ----------
1123 shell
1123 shell
1124 a pointer to the ipython shell itself. This is needed
1124 a pointer to the ipython shell itself. This is needed
1125 because this completer knows about magic functions, and those can
1125 because this completer knows about magic functions, and those can
1126 only be accessed via the ipython instance.
1126 only be accessed via the ipython instance.
1127 namespace : dict, optional
1127 namespace : dict, optional
1128 an optional dict where completions are performed.
1128 an optional dict where completions are performed.
1129 global_namespace : dict, optional
1129 global_namespace : dict, optional
1130 secondary optional dict for completions, to
1130 secondary optional dict for completions, to
1131 handle cases (such as IPython embedded inside functions) where
1131 handle cases (such as IPython embedded inside functions) where
1132 both Python scopes are visible.
1132 both Python scopes are visible.
1133 config : Config
1133 config : Config
1134 traitlet's config object
1134 traitlet's config object
1135 **kwargs
1135 **kwargs
1136 passed to super class unmodified.
1136 passed to super class unmodified.
1137 """
1137 """
1138
1138
1139 self.magic_escape = ESC_MAGIC
1139 self.magic_escape = ESC_MAGIC
1140 self.splitter = CompletionSplitter()
1140 self.splitter = CompletionSplitter()
1141
1141
1142 # _greedy_changed() depends on splitter and readline being defined:
1142 # _greedy_changed() depends on splitter and readline being defined:
1143 super().__init__(
1143 super().__init__(
1144 namespace=namespace,
1144 namespace=namespace,
1145 global_namespace=global_namespace,
1145 global_namespace=global_namespace,
1146 config=config,
1146 config=config,
1147 **kwargs
1147 **kwargs
1148 )
1148 )
1149
1149
1150 # List where completion matches will be stored
1150 # List where completion matches will be stored
1151 self.matches = []
1151 self.matches = []
1152 self.shell = shell
1152 self.shell = shell
1153 # Regexp to split filenames with spaces in them
1153 # Regexp to split filenames with spaces in them
1154 self.space_name_re = re.compile(r'([^\\] )')
1154 self.space_name_re = re.compile(r'([^\\] )')
1155 # Hold a local ref. to glob.glob for speed
1155 # Hold a local ref. to glob.glob for speed
1156 self.glob = glob.glob
1156 self.glob = glob.glob
1157
1157
1158 # Determine if we are running on 'dumb' terminals, like (X)Emacs
1158 # Determine if we are running on 'dumb' terminals, like (X)Emacs
1159 # buffers, to avoid completion problems.
1159 # buffers, to avoid completion problems.
1160 term = os.environ.get('TERM','xterm')
1160 term = os.environ.get('TERM','xterm')
1161 self.dumb_terminal = term in ['dumb','emacs']
1161 self.dumb_terminal = term in ['dumb','emacs']
1162
1162
1163 # Special handling of backslashes needed in win32 platforms
1163 # Special handling of backslashes needed in win32 platforms
1164 if sys.platform == "win32":
1164 if sys.platform == "win32":
1165 self.clean_glob = self._clean_glob_win32
1165 self.clean_glob = self._clean_glob_win32
1166 else:
1166 else:
1167 self.clean_glob = self._clean_glob
1167 self.clean_glob = self._clean_glob
1168
1168
1169 #regexp to parse docstring for function signature
1169 #regexp to parse docstring for function signature
1170 self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
1170 self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
1171 self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
1171 self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
1172 #use this if positional argument name is also needed
1172 #use this if positional argument name is also needed
1173 #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)')
1173 #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)')
1174
1174
1175 self.magic_arg_matchers = [
1175 self.magic_arg_matchers = [
1176 self.magic_config_matches,
1176 self.magic_config_matches,
1177 self.magic_color_matches,
1177 self.magic_color_matches,
1178 ]
1178 ]
1179
1179
1180 # This is set externally by InteractiveShell
1180 # This is set externally by InteractiveShell
1181 self.custom_completers = None
1181 self.custom_completers = None
1182
1182
1183 # This is a list of names of unicode characters that can be completed
1183 # This is a list of names of unicode characters that can be completed
1184 # into their corresponding unicode value. The list is large, so we
1184 # into their corresponding unicode value. The list is large, so we
1185 # laziliy initialize it on first use. Consuming code should access this
1185 # lazily initialize it on first use. Consuming code should access this
1186 # attribute through the `@unicode_names` property.
1186 # attribute through the `@unicode_names` property.
1187 self._unicode_names = None
1187 self._unicode_names = None
1188
1188
1189 @property
1189 @property
1190 def matchers(self) -> List[Any]:
1190 def matchers(self) -> List[Any]:
1191 """All active matcher routines for completion"""
1191 """All active matcher routines for completion"""
1192 if self.dict_keys_only:
1192 if self.dict_keys_only:
1193 return [self.dict_key_matches]
1193 return [self.dict_key_matches]
1194
1194
1195 if self.use_jedi:
1195 if self.use_jedi:
1196 return [
1196 return [
1197 *self.custom_matchers,
1197 *self.custom_matchers,
1198 self.dict_key_matches,
1198 self.dict_key_matches,
1199 self.file_matches,
1199 self.file_matches,
1200 self.magic_matches,
1200 self.magic_matches,
1201 ]
1201 ]
1202 else:
1202 else:
1203 return [
1203 return [
1204 *self.custom_matchers,
1204 *self.custom_matchers,
1205 self.dict_key_matches,
1205 self.dict_key_matches,
1206 self.python_matches,
1206 self.python_matches,
1207 self.file_matches,
1207 self.file_matches,
1208 self.magic_matches,
1208 self.magic_matches,
1209 self.python_func_kw_matches,
1209 self.python_func_kw_matches,
1210 ]
1210 ]
1211
1211
1212 def all_completions(self, text:str) -> List[str]:
1212 def all_completions(self, text:str) -> List[str]:
1213 """
1213 """
1214 Wrapper around the completion methods for the benefit of emacs.
1214 Wrapper around the completion methods for the benefit of emacs.
1215 """
1215 """
1216 prefix = text.rpartition('.')[0]
1216 prefix = text.rpartition('.')[0]
1217 with provisionalcompleter():
1217 with provisionalcompleter():
1218 return ['.'.join([prefix, c.text]) if prefix and self.use_jedi else c.text
1218 return ['.'.join([prefix, c.text]) if prefix and self.use_jedi else c.text
1219 for c in self.completions(text, len(text))]
1219 for c in self.completions(text, len(text))]
1220
1220
1221 return self.complete(text)[1]
1221 return self.complete(text)[1]
1222
1222
1223 def _clean_glob(self, text:str):
1223 def _clean_glob(self, text:str):
1224 return self.glob("%s*" % text)
1224 return self.glob("%s*" % text)
1225
1225
1226 def _clean_glob_win32(self, text:str):
1226 def _clean_glob_win32(self, text:str):
1227 return [f.replace("\\","/")
1227 return [f.replace("\\","/")
1228 for f in self.glob("%s*" % text)]
1228 for f in self.glob("%s*" % text)]
1229
1229
1230 def file_matches(self, text:str)->List[str]:
1230 def file_matches(self, text:str)->List[str]:
1231 """Match filenames, expanding ~USER type strings.
1231 """Match filenames, expanding ~USER type strings.
1232
1232
1233 Most of the seemingly convoluted logic in this completer is an
1233 Most of the seemingly convoluted logic in this completer is an
1234 attempt to handle filenames with spaces in them. And yet it's not
1234 attempt to handle filenames with spaces in them. And yet it's not
1235 quite perfect, because Python's readline doesn't expose all of the
1235 quite perfect, because Python's readline doesn't expose all of the
1236 GNU readline details needed for this to be done correctly.
1236 GNU readline details needed for this to be done correctly.
1237
1237
1238 For a filename with a space in it, the printed completions will be
1238 For a filename with a space in it, the printed completions will be
1239 only the parts after what's already been typed (instead of the
1239 only the parts after what's already been typed (instead of the
1240 full completions, as is normally done). I don't think with the
1240 full completions, as is normally done). I don't think with the
1241 current (as of Python 2.3) Python readline it's possible to do
1241 current (as of Python 2.3) Python readline it's possible to do
1242 better."""
1242 better."""
1243
1243
1244 # chars that require escaping with backslash - i.e. chars
1244 # chars that require escaping with backslash - i.e. chars
1245 # that readline treats incorrectly as delimiters, but we
1245 # that readline treats incorrectly as delimiters, but we
1246 # don't want to treat as delimiters in filename matching
1246 # don't want to treat as delimiters in filename matching
1247 # when escaped with backslash
1247 # when escaped with backslash
1248 if text.startswith('!'):
1248 if text.startswith('!'):
1249 text = text[1:]
1249 text = text[1:]
1250 text_prefix = u'!'
1250 text_prefix = u'!'
1251 else:
1251 else:
1252 text_prefix = u''
1252 text_prefix = u''
1253
1253
1254 text_until_cursor = self.text_until_cursor
1254 text_until_cursor = self.text_until_cursor
1255 # track strings with open quotes
1255 # track strings with open quotes
1256 open_quotes = has_open_quotes(text_until_cursor)
1256 open_quotes = has_open_quotes(text_until_cursor)
1257
1257
1258 if '(' in text_until_cursor or '[' in text_until_cursor:
1258 if '(' in text_until_cursor or '[' in text_until_cursor:
1259 lsplit = text
1259 lsplit = text
1260 else:
1260 else:
1261 try:
1261 try:
1262 # arg_split ~ shlex.split, but with unicode bugs fixed by us
1262 # arg_split ~ shlex.split, but with unicode bugs fixed by us
1263 lsplit = arg_split(text_until_cursor)[-1]
1263 lsplit = arg_split(text_until_cursor)[-1]
1264 except ValueError:
1264 except ValueError:
1265 # typically an unmatched ", or backslash without escaped char.
1265 # typically an unmatched ", or backslash without escaped char.
1266 if open_quotes:
1266 if open_quotes:
1267 lsplit = text_until_cursor.split(open_quotes)[-1]
1267 lsplit = text_until_cursor.split(open_quotes)[-1]
1268 else:
1268 else:
1269 return []
1269 return []
1270 except IndexError:
1270 except IndexError:
1271 # tab pressed on empty line
1271 # tab pressed on empty line
1272 lsplit = ""
1272 lsplit = ""
1273
1273
1274 if not open_quotes and lsplit != protect_filename(lsplit):
1274 if not open_quotes and lsplit != protect_filename(lsplit):
1275 # if protectables are found, do matching on the whole escaped name
1275 # if protectables are found, do matching on the whole escaped name
1276 has_protectables = True
1276 has_protectables = True
1277 text0,text = text,lsplit
1277 text0,text = text,lsplit
1278 else:
1278 else:
1279 has_protectables = False
1279 has_protectables = False
1280 text = os.path.expanduser(text)
1280 text = os.path.expanduser(text)
1281
1281
1282 if text == "":
1282 if text == "":
1283 return [text_prefix + protect_filename(f) for f in self.glob("*")]
1283 return [text_prefix + protect_filename(f) for f in self.glob("*")]
1284
1284
1285 # Compute the matches from the filesystem
1285 # Compute the matches from the filesystem
1286 if sys.platform == 'win32':
1286 if sys.platform == 'win32':
1287 m0 = self.clean_glob(text)
1287 m0 = self.clean_glob(text)
1288 else:
1288 else:
1289 m0 = self.clean_glob(text.replace('\\', ''))
1289 m0 = self.clean_glob(text.replace('\\', ''))
1290
1290
1291 if has_protectables:
1291 if has_protectables:
1292 # If we had protectables, we need to revert our changes to the
1292 # If we had protectables, we need to revert our changes to the
1293 # beginning of filename so that we don't double-write the part
1293 # beginning of filename so that we don't double-write the part
1294 # of the filename we have so far
1294 # of the filename we have so far
1295 len_lsplit = len(lsplit)
1295 len_lsplit = len(lsplit)
1296 matches = [text_prefix + text0 +
1296 matches = [text_prefix + text0 +
1297 protect_filename(f[len_lsplit:]) for f in m0]
1297 protect_filename(f[len_lsplit:]) for f in m0]
1298 else:
1298 else:
1299 if open_quotes:
1299 if open_quotes:
1300 # if we have a string with an open quote, we don't need to
1300 # if we have a string with an open quote, we don't need to
1301 # protect the names beyond the quote (and we _shouldn't_, as
1301 # protect the names beyond the quote (and we _shouldn't_, as
1302 # it would cause bugs when the filesystem call is made).
1302 # it would cause bugs when the filesystem call is made).
1303 matches = m0 if sys.platform == "win32" else\
1303 matches = m0 if sys.platform == "win32" else\
1304 [protect_filename(f, open_quotes) for f in m0]
1304 [protect_filename(f, open_quotes) for f in m0]
1305 else:
1305 else:
1306 matches = [text_prefix +
1306 matches = [text_prefix +
1307 protect_filename(f) for f in m0]
1307 protect_filename(f) for f in m0]
1308
1308
1309 # Mark directories in input list by appending '/' to their names.
1309 # Mark directories in input list by appending '/' to their names.
1310 return [x+'/' if os.path.isdir(x) else x for x in matches]
1310 return [x+'/' if os.path.isdir(x) else x for x in matches]
1311
1311
1312 def magic_matches(self, text:str):
1312 def magic_matches(self, text:str):
1313 """Match magics"""
1313 """Match magics"""
1314 # Get all shell magics now rather than statically, so magics loaded at
1314 # Get all shell magics now rather than statically, so magics loaded at
1315 # runtime show up too.
1315 # runtime show up too.
1316 lsm = self.shell.magics_manager.lsmagic()
1316 lsm = self.shell.magics_manager.lsmagic()
1317 line_magics = lsm['line']
1317 line_magics = lsm['line']
1318 cell_magics = lsm['cell']
1318 cell_magics = lsm['cell']
1319 pre = self.magic_escape
1319 pre = self.magic_escape
1320 pre2 = pre+pre
1320 pre2 = pre+pre
1321
1321
1322 explicit_magic = text.startswith(pre)
1322 explicit_magic = text.startswith(pre)
1323
1323
1324 # Completion logic:
1324 # Completion logic:
1325 # - user gives %%: only do cell magics
1325 # - user gives %%: only do cell magics
1326 # - user gives %: do both line and cell magics
1326 # - user gives %: do both line and cell magics
1327 # - no prefix: do both
1327 # - no prefix: do both
1328 # In other words, line magics are skipped if the user gives %% explicitly
1328 # In other words, line magics are skipped if the user gives %% explicitly
1329 #
1329 #
1330 # We also exclude magics that match any currently visible names:
1330 # We also exclude magics that match any currently visible names:
1331 # https://github.com/ipython/ipython/issues/4877, unless the user has
1331 # https://github.com/ipython/ipython/issues/4877, unless the user has
1332 # typed a %:
1332 # typed a %:
1333 # https://github.com/ipython/ipython/issues/10754
1333 # https://github.com/ipython/ipython/issues/10754
1334 bare_text = text.lstrip(pre)
1334 bare_text = text.lstrip(pre)
1335 global_matches = self.global_matches(bare_text)
1335 global_matches = self.global_matches(bare_text)
1336 if not explicit_magic:
1336 if not explicit_magic:
1337 def matches(magic):
1337 def matches(magic):
1338 """
1338 """
1339 Filter magics, in particular remove magics that match
1339 Filter magics, in particular remove magics that match
1340 a name present in global namespace.
1340 a name present in global namespace.
1341 """
1341 """
1342 return ( magic.startswith(bare_text) and
1342 return ( magic.startswith(bare_text) and
1343 magic not in global_matches )
1343 magic not in global_matches )
1344 else:
1344 else:
1345 def matches(magic):
1345 def matches(magic):
1346 return magic.startswith(bare_text)
1346 return magic.startswith(bare_text)
1347
1347
1348 comp = [ pre2+m for m in cell_magics if matches(m)]
1348 comp = [ pre2+m for m in cell_magics if matches(m)]
1349 if not text.startswith(pre2):
1349 if not text.startswith(pre2):
1350 comp += [ pre+m for m in line_magics if matches(m)]
1350 comp += [ pre+m for m in line_magics if matches(m)]
1351
1351
1352 return comp
1352 return comp
1353
1353
1354 def magic_config_matches(self, text:str) -> List[str]:
1354 def magic_config_matches(self, text:str) -> List[str]:
1355 """ Match class names and attributes for %config magic """
1355 """ Match class names and attributes for %config magic """
1356 texts = text.strip().split()
1356 texts = text.strip().split()
1357
1357
1358 if len(texts) > 0 and (texts[0] == 'config' or texts[0] == '%config'):
1358 if len(texts) > 0 and (texts[0] == 'config' or texts[0] == '%config'):
1359 # get all configuration classes
1359 # get all configuration classes
1360 classes = sorted(set([ c for c in self.shell.configurables
1360 classes = sorted(set([ c for c in self.shell.configurables
1361 if c.__class__.class_traits(config=True)
1361 if c.__class__.class_traits(config=True)
1362 ]), key=lambda x: x.__class__.__name__)
1362 ]), key=lambda x: x.__class__.__name__)
1363 classnames = [ c.__class__.__name__ for c in classes ]
1363 classnames = [ c.__class__.__name__ for c in classes ]
1364
1364
1365 # return all classnames if config or %config is given
1365 # return all classnames if config or %config is given
1366 if len(texts) == 1:
1366 if len(texts) == 1:
1367 return classnames
1367 return classnames
1368
1368
1369 # match classname
1369 # match classname
1370 classname_texts = texts[1].split('.')
1370 classname_texts = texts[1].split('.')
1371 classname = classname_texts[0]
1371 classname = classname_texts[0]
1372 classname_matches = [ c for c in classnames
1372 classname_matches = [ c for c in classnames
1373 if c.startswith(classname) ]
1373 if c.startswith(classname) ]
1374
1374
1375 # return matched classes or the matched class with attributes
1375 # return matched classes or the matched class with attributes
1376 if texts[1].find('.') < 0:
1376 if texts[1].find('.') < 0:
1377 return classname_matches
1377 return classname_matches
1378 elif len(classname_matches) == 1 and \
1378 elif len(classname_matches) == 1 and \
1379 classname_matches[0] == classname:
1379 classname_matches[0] == classname:
1380 cls = classes[classnames.index(classname)].__class__
1380 cls = classes[classnames.index(classname)].__class__
1381 help = cls.class_get_help()
1381 help = cls.class_get_help()
1382 # strip leading '--' from cl-args:
1382 # strip leading '--' from cl-args:
1383 help = re.sub(re.compile(r'^--', re.MULTILINE), '', help)
1383 help = re.sub(re.compile(r'^--', re.MULTILINE), '', help)
1384 return [ attr.split('=')[0]
1384 return [ attr.split('=')[0]
1385 for attr in help.strip().splitlines()
1385 for attr in help.strip().splitlines()
1386 if attr.startswith(texts[1]) ]
1386 if attr.startswith(texts[1]) ]
1387 return []
1387 return []
1388
1388
1389 def magic_color_matches(self, text:str) -> List[str] :
1389 def magic_color_matches(self, text:str) -> List[str] :
1390 """ Match color schemes for %colors magic"""
1390 """ Match color schemes for %colors magic"""
1391 texts = text.split()
1391 texts = text.split()
1392 if text.endswith(' '):
1392 if text.endswith(' '):
1393 # .split() strips off the trailing whitespace. Add '' back
1393 # .split() strips off the trailing whitespace. Add '' back
1394 # so that: '%colors ' -> ['%colors', '']
1394 # so that: '%colors ' -> ['%colors', '']
1395 texts.append('')
1395 texts.append('')
1396
1396
1397 if len(texts) == 2 and (texts[0] == 'colors' or texts[0] == '%colors'):
1397 if len(texts) == 2 and (texts[0] == 'colors' or texts[0] == '%colors'):
1398 prefix = texts[1]
1398 prefix = texts[1]
1399 return [ color for color in InspectColors.keys()
1399 return [ color for color in InspectColors.keys()
1400 if color.startswith(prefix) ]
1400 if color.startswith(prefix) ]
1401 return []
1401 return []
1402
1402
1403 def _jedi_matches(self, cursor_column:int, cursor_line:int, text:str) -> Iterable[Any]:
1403 def _jedi_matches(self, cursor_column:int, cursor_line:int, text:str) -> Iterable[Any]:
1404 """
1404 """
1405 Return a list of :any:`jedi.api.Completions` object from a ``text`` and
1405 Return a list of :any:`jedi.api.Completions` object from a ``text`` and
1406 cursor position.
1406 cursor position.
1407
1407
1408 Parameters
1408 Parameters
1409 ----------
1409 ----------
1410 cursor_column : int
1410 cursor_column : int
1411 column position of the cursor in ``text``, 0-indexed.
1411 column position of the cursor in ``text``, 0-indexed.
1412 cursor_line : int
1412 cursor_line : int
1413 line position of the cursor in ``text``, 0-indexed
1413 line position of the cursor in ``text``, 0-indexed
1414 text : str
1414 text : str
1415 text to complete
1415 text to complete
1416
1416
1417 Notes
1417 Notes
1418 -----
1418 -----
1419 If ``IPCompleter.debug`` is ``True`` may return a :any:`_FakeJediCompletion`
1419 If ``IPCompleter.debug`` is ``True`` may return a :any:`_FakeJediCompletion`
1420 object containing a string with the Jedi debug information attached.
1420 object containing a string with the Jedi debug information attached.
1421 """
1421 """
1422 namespaces = [self.namespace]
1422 namespaces = [self.namespace]
1423 if self.global_namespace is not None:
1423 if self.global_namespace is not None:
1424 namespaces.append(self.global_namespace)
1424 namespaces.append(self.global_namespace)
1425
1425
1426 completion_filter = lambda x:x
1426 completion_filter = lambda x:x
1427 offset = cursor_to_position(text, cursor_line, cursor_column)
1427 offset = cursor_to_position(text, cursor_line, cursor_column)
1428 # filter output if we are completing for object members
1428 # filter output if we are completing for object members
1429 if offset:
1429 if offset:
1430 pre = text[offset-1]
1430 pre = text[offset-1]
1431 if pre == '.':
1431 if pre == '.':
1432 if self.omit__names == 2:
1432 if self.omit__names == 2:
1433 completion_filter = lambda c:not c.name.startswith('_')
1433 completion_filter = lambda c:not c.name.startswith('_')
1434 elif self.omit__names == 1:
1434 elif self.omit__names == 1:
1435 completion_filter = lambda c:not (c.name.startswith('__') and c.name.endswith('__'))
1435 completion_filter = lambda c:not (c.name.startswith('__') and c.name.endswith('__'))
1436 elif self.omit__names == 0:
1436 elif self.omit__names == 0:
1437 completion_filter = lambda x:x
1437 completion_filter = lambda x:x
1438 else:
1438 else:
1439 raise ValueError("Don't understand self.omit__names == {}".format(self.omit__names))
1439 raise ValueError("Don't understand self.omit__names == {}".format(self.omit__names))
1440
1440
1441 interpreter = jedi.Interpreter(text[:offset], namespaces)
1441 interpreter = jedi.Interpreter(text[:offset], namespaces)
1442 try_jedi = True
1442 try_jedi = True
1443
1443
1444 try:
1444 try:
1445 # find the first token in the current tree -- if it is a ' or " then we are in a string
1445 # find the first token in the current tree -- if it is a ' or " then we are in a string
1446 completing_string = False
1446 completing_string = False
1447 try:
1447 try:
1448 first_child = next(c for c in interpreter._get_module().tree_node.children if hasattr(c, 'value'))
1448 first_child = next(c for c in interpreter._get_module().tree_node.children if hasattr(c, 'value'))
1449 except StopIteration:
1449 except StopIteration:
1450 pass
1450 pass
1451 else:
1451 else:
1452 # note the value may be ', ", or it may also be ''' or """, or
1452 # note the value may be ', ", or it may also be ''' or """, or
1453 # in some cases, """what/you/typed..., but all of these are
1453 # in some cases, """what/you/typed..., but all of these are
1454 # strings.
1454 # strings.
1455 completing_string = len(first_child.value) > 0 and first_child.value[0] in {"'", '"'}
1455 completing_string = len(first_child.value) > 0 and first_child.value[0] in {"'", '"'}
1456
1456
1457 # if we are in a string jedi is likely not the right candidate for
1457 # if we are in a string jedi is likely not the right candidate for
1458 # now. Skip it.
1458 # now. Skip it.
1459 try_jedi = not completing_string
1459 try_jedi = not completing_string
1460 except Exception as e:
1460 except Exception as e:
1461 # many of things can go wrong, we are using private API just don't crash.
1461 # many of things can go wrong, we are using private API just don't crash.
1462 if self.debug:
1462 if self.debug:
1463 print("Error detecting if completing a non-finished string :", e, '|')
1463 print("Error detecting if completing a non-finished string :", e, '|')
1464
1464
1465 if not try_jedi:
1465 if not try_jedi:
1466 return []
1466 return []
1467 try:
1467 try:
1468 return filter(completion_filter, interpreter.complete(column=cursor_column, line=cursor_line + 1))
1468 return filter(completion_filter, interpreter.complete(column=cursor_column, line=cursor_line + 1))
1469 except Exception as e:
1469 except Exception as e:
1470 if self.debug:
1470 if self.debug:
1471 return [_FakeJediCompletion('Oops Jedi has crashed, please report a bug with the following:\n"""\n%s\ns"""' % (e))]
1471 return [_FakeJediCompletion('Oops Jedi has crashed, please report a bug with the following:\n"""\n%s\ns"""' % (e))]
1472 else:
1472 else:
1473 return []
1473 return []
1474
1474
1475 def python_matches(self, text:str)->List[str]:
1475 def python_matches(self, text:str)->List[str]:
1476 """Match attributes or global python names"""
1476 """Match attributes or global python names"""
1477 if "." in text:
1477 if "." in text:
1478 try:
1478 try:
1479 matches = self.attr_matches(text)
1479 matches = self.attr_matches(text)
1480 if text.endswith('.') and self.omit__names:
1480 if text.endswith('.') and self.omit__names:
1481 if self.omit__names == 1:
1481 if self.omit__names == 1:
1482 # true if txt is _not_ a __ name, false otherwise:
1482 # true if txt is _not_ a __ name, false otherwise:
1483 no__name = (lambda txt:
1483 no__name = (lambda txt:
1484 re.match(r'.*\.__.*?__',txt) is None)
1484 re.match(r'.*\.__.*?__',txt) is None)
1485 else:
1485 else:
1486 # true if txt is _not_ a _ name, false otherwise:
1486 # true if txt is _not_ a _ name, false otherwise:
1487 no__name = (lambda txt:
1487 no__name = (lambda txt:
1488 re.match(r'\._.*?',txt[txt.rindex('.'):]) is None)
1488 re.match(r'\._.*?',txt[txt.rindex('.'):]) is None)
1489 matches = filter(no__name, matches)
1489 matches = filter(no__name, matches)
1490 except NameError:
1490 except NameError:
1491 # catches <undefined attributes>.<tab>
1491 # catches <undefined attributes>.<tab>
1492 matches = []
1492 matches = []
1493 else:
1493 else:
1494 matches = self.global_matches(text)
1494 matches = self.global_matches(text)
1495 return matches
1495 return matches
1496
1496
1497 def _default_arguments_from_docstring(self, doc):
1497 def _default_arguments_from_docstring(self, doc):
1498 """Parse the first line of docstring for call signature.
1498 """Parse the first line of docstring for call signature.
1499
1499
1500 Docstring should be of the form 'min(iterable[, key=func])\n'.
1500 Docstring should be of the form 'min(iterable[, key=func])\n'.
1501 It can also parse cython docstring of the form
1501 It can also parse cython docstring of the form
1502 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'.
1502 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'.
1503 """
1503 """
1504 if doc is None:
1504 if doc is None:
1505 return []
1505 return []
1506
1506
1507 #care only the firstline
1507 #care only the firstline
1508 line = doc.lstrip().splitlines()[0]
1508 line = doc.lstrip().splitlines()[0]
1509
1509
1510 #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
1510 #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
1511 #'min(iterable[, key=func])\n' -> 'iterable[, key=func]'
1511 #'min(iterable[, key=func])\n' -> 'iterable[, key=func]'
1512 sig = self.docstring_sig_re.search(line)
1512 sig = self.docstring_sig_re.search(line)
1513 if sig is None:
1513 if sig is None:
1514 return []
1514 return []
1515 # iterable[, key=func]' -> ['iterable[' ,' key=func]']
1515 # iterable[, key=func]' -> ['iterable[' ,' key=func]']
1516 sig = sig.groups()[0].split(',')
1516 sig = sig.groups()[0].split(',')
1517 ret = []
1517 ret = []
1518 for s in sig:
1518 for s in sig:
1519 #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
1519 #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
1520 ret += self.docstring_kwd_re.findall(s)
1520 ret += self.docstring_kwd_re.findall(s)
1521 return ret
1521 return ret
1522
1522
1523 def _default_arguments(self, obj):
1523 def _default_arguments(self, obj):
1524 """Return the list of default arguments of obj if it is callable,
1524 """Return the list of default arguments of obj if it is callable,
1525 or empty list otherwise."""
1525 or empty list otherwise."""
1526 call_obj = obj
1526 call_obj = obj
1527 ret = []
1527 ret = []
1528 if inspect.isbuiltin(obj):
1528 if inspect.isbuiltin(obj):
1529 pass
1529 pass
1530 elif not (inspect.isfunction(obj) or inspect.ismethod(obj)):
1530 elif not (inspect.isfunction(obj) or inspect.ismethod(obj)):
1531 if inspect.isclass(obj):
1531 if inspect.isclass(obj):
1532 #for cython embedsignature=True the constructor docstring
1532 #for cython embedsignature=True the constructor docstring
1533 #belongs to the object itself not __init__
1533 #belongs to the object itself not __init__
1534 ret += self._default_arguments_from_docstring(
1534 ret += self._default_arguments_from_docstring(
1535 getattr(obj, '__doc__', ''))
1535 getattr(obj, '__doc__', ''))
1536 # for classes, check for __init__,__new__
1536 # for classes, check for __init__,__new__
1537 call_obj = (getattr(obj, '__init__', None) or
1537 call_obj = (getattr(obj, '__init__', None) or
1538 getattr(obj, '__new__', None))
1538 getattr(obj, '__new__', None))
1539 # for all others, check if they are __call__able
1539 # for all others, check if they are __call__able
1540 elif hasattr(obj, '__call__'):
1540 elif hasattr(obj, '__call__'):
1541 call_obj = obj.__call__
1541 call_obj = obj.__call__
1542 ret += self._default_arguments_from_docstring(
1542 ret += self._default_arguments_from_docstring(
1543 getattr(call_obj, '__doc__', ''))
1543 getattr(call_obj, '__doc__', ''))
1544
1544
1545 _keeps = (inspect.Parameter.KEYWORD_ONLY,
1545 _keeps = (inspect.Parameter.KEYWORD_ONLY,
1546 inspect.Parameter.POSITIONAL_OR_KEYWORD)
1546 inspect.Parameter.POSITIONAL_OR_KEYWORD)
1547
1547
1548 try:
1548 try:
1549 sig = inspect.signature(obj)
1549 sig = inspect.signature(obj)
1550 ret.extend(k for k, v in sig.parameters.items() if
1550 ret.extend(k for k, v in sig.parameters.items() if
1551 v.kind in _keeps)
1551 v.kind in _keeps)
1552 except ValueError:
1552 except ValueError:
1553 pass
1553 pass
1554
1554
1555 return list(set(ret))
1555 return list(set(ret))
1556
1556
1557 def python_func_kw_matches(self, text):
1557 def python_func_kw_matches(self, text):
1558 """Match named parameters (kwargs) of the last open function"""
1558 """Match named parameters (kwargs) of the last open function"""
1559
1559
1560 if "." in text: # a parameter cannot be dotted
1560 if "." in text: # a parameter cannot be dotted
1561 return []
1561 return []
1562 try: regexp = self.__funcParamsRegex
1562 try: regexp = self.__funcParamsRegex
1563 except AttributeError:
1563 except AttributeError:
1564 regexp = self.__funcParamsRegex = re.compile(r'''
1564 regexp = self.__funcParamsRegex = re.compile(r'''
1565 '.*?(?<!\\)' | # single quoted strings or
1565 '.*?(?<!\\)' | # single quoted strings or
1566 ".*?(?<!\\)" | # double quoted strings or
1566 ".*?(?<!\\)" | # double quoted strings or
1567 \w+ | # identifier
1567 \w+ | # identifier
1568 \S # other characters
1568 \S # other characters
1569 ''', re.VERBOSE | re.DOTALL)
1569 ''', re.VERBOSE | re.DOTALL)
1570 # 1. find the nearest identifier that comes before an unclosed
1570 # 1. find the nearest identifier that comes before an unclosed
1571 # parenthesis before the cursor
1571 # parenthesis before the cursor
1572 # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo"
1572 # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo"
1573 tokens = regexp.findall(self.text_until_cursor)
1573 tokens = regexp.findall(self.text_until_cursor)
1574 iterTokens = reversed(tokens); openPar = 0
1574 iterTokens = reversed(tokens); openPar = 0
1575
1575
1576 for token in iterTokens:
1576 for token in iterTokens:
1577 if token == ')':
1577 if token == ')':
1578 openPar -= 1
1578 openPar -= 1
1579 elif token == '(':
1579 elif token == '(':
1580 openPar += 1
1580 openPar += 1
1581 if openPar > 0:
1581 if openPar > 0:
1582 # found the last unclosed parenthesis
1582 # found the last unclosed parenthesis
1583 break
1583 break
1584 else:
1584 else:
1585 return []
1585 return []
1586 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
1586 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
1587 ids = []
1587 ids = []
1588 isId = re.compile(r'\w+$').match
1588 isId = re.compile(r'\w+$').match
1589
1589
1590 while True:
1590 while True:
1591 try:
1591 try:
1592 ids.append(next(iterTokens))
1592 ids.append(next(iterTokens))
1593 if not isId(ids[-1]):
1593 if not isId(ids[-1]):
1594 ids.pop(); break
1594 ids.pop(); break
1595 if not next(iterTokens) == '.':
1595 if not next(iterTokens) == '.':
1596 break
1596 break
1597 except StopIteration:
1597 except StopIteration:
1598 break
1598 break
1599
1599
1600 # Find all named arguments already assigned to, as to avoid suggesting
1600 # Find all named arguments already assigned to, as to avoid suggesting
1601 # them again
1601 # them again
1602 usedNamedArgs = set()
1602 usedNamedArgs = set()
1603 par_level = -1
1603 par_level = -1
1604 for token, next_token in zip(tokens, tokens[1:]):
1604 for token, next_token in zip(tokens, tokens[1:]):
1605 if token == '(':
1605 if token == '(':
1606 par_level += 1
1606 par_level += 1
1607 elif token == ')':
1607 elif token == ')':
1608 par_level -= 1
1608 par_level -= 1
1609
1609
1610 if par_level != 0:
1610 if par_level != 0:
1611 continue
1611 continue
1612
1612
1613 if next_token != '=':
1613 if next_token != '=':
1614 continue
1614 continue
1615
1615
1616 usedNamedArgs.add(token)
1616 usedNamedArgs.add(token)
1617
1617
1618 argMatches = []
1618 argMatches = []
1619 try:
1619 try:
1620 callableObj = '.'.join(ids[::-1])
1620 callableObj = '.'.join(ids[::-1])
1621 namedArgs = self._default_arguments(eval(callableObj,
1621 namedArgs = self._default_arguments(eval(callableObj,
1622 self.namespace))
1622 self.namespace))
1623
1623
1624 # Remove used named arguments from the list, no need to show twice
1624 # Remove used named arguments from the list, no need to show twice
1625 for namedArg in set(namedArgs) - usedNamedArgs:
1625 for namedArg in set(namedArgs) - usedNamedArgs:
1626 if namedArg.startswith(text):
1626 if namedArg.startswith(text):
1627 argMatches.append("%s=" %namedArg)
1627 argMatches.append("%s=" %namedArg)
1628 except:
1628 except:
1629 pass
1629 pass
1630
1630
1631 return argMatches
1631 return argMatches
1632
1632
1633 @staticmethod
1633 @staticmethod
1634 def _get_keys(obj: Any) -> List[Any]:
1634 def _get_keys(obj: Any) -> List[Any]:
1635 # Objects can define their own completions by defining an
1635 # Objects can define their own completions by defining an
1636 # _ipy_key_completions_() method.
1636 # _ipy_key_completions_() method.
1637 method = get_real_method(obj, '_ipython_key_completions_')
1637 method = get_real_method(obj, '_ipython_key_completions_')
1638 if method is not None:
1638 if method is not None:
1639 return method()
1639 return method()
1640
1640
1641 # Special case some common in-memory dict-like types
1641 # Special case some common in-memory dict-like types
1642 if isinstance(obj, dict) or\
1642 if isinstance(obj, dict) or\
1643 _safe_isinstance(obj, 'pandas', 'DataFrame'):
1643 _safe_isinstance(obj, 'pandas', 'DataFrame'):
1644 try:
1644 try:
1645 return list(obj.keys())
1645 return list(obj.keys())
1646 except Exception:
1646 except Exception:
1647 return []
1647 return []
1648 elif _safe_isinstance(obj, 'numpy', 'ndarray') or\
1648 elif _safe_isinstance(obj, 'numpy', 'ndarray') or\
1649 _safe_isinstance(obj, 'numpy', 'void'):
1649 _safe_isinstance(obj, 'numpy', 'void'):
1650 return obj.dtype.names or []
1650 return obj.dtype.names or []
1651 return []
1651 return []
1652
1652
1653 def dict_key_matches(self, text:str) -> List[str]:
1653 def dict_key_matches(self, text:str) -> List[str]:
1654 "Match string keys in a dictionary, after e.g. 'foo[' "
1654 "Match string keys in a dictionary, after e.g. 'foo[' "
1655
1655
1656
1656
1657 if self.__dict_key_regexps is not None:
1657 if self.__dict_key_regexps is not None:
1658 regexps = self.__dict_key_regexps
1658 regexps = self.__dict_key_regexps
1659 else:
1659 else:
1660 dict_key_re_fmt = r'''(?x)
1660 dict_key_re_fmt = r'''(?x)
1661 ( # match dict-referring expression wrt greedy setting
1661 ( # match dict-referring expression wrt greedy setting
1662 %s
1662 %s
1663 )
1663 )
1664 \[ # open bracket
1664 \[ # open bracket
1665 \s* # and optional whitespace
1665 \s* # and optional whitespace
1666 # Capture any number of str-like objects (e.g. "a", "b", 'c')
1666 # Capture any number of str-like objects (e.g. "a", "b", 'c')
1667 ((?:[uUbB]? # string prefix (r not handled)
1667 ((?:[uUbB]? # string prefix (r not handled)
1668 (?:
1668 (?:
1669 '(?:[^']|(?<!\\)\\')*'
1669 '(?:[^']|(?<!\\)\\')*'
1670 |
1670 |
1671 "(?:[^"]|(?<!\\)\\")*"
1671 "(?:[^"]|(?<!\\)\\")*"
1672 )
1672 )
1673 \s*,\s*
1673 \s*,\s*
1674 )*)
1674 )*)
1675 ([uUbB]? # string prefix (r not handled)
1675 ([uUbB]? # string prefix (r not handled)
1676 (?: # unclosed string
1676 (?: # unclosed string
1677 '(?:[^']|(?<!\\)\\')*
1677 '(?:[^']|(?<!\\)\\')*
1678 |
1678 |
1679 "(?:[^"]|(?<!\\)\\")*
1679 "(?:[^"]|(?<!\\)\\")*
1680 )
1680 )
1681 )?
1681 )?
1682 $
1682 $
1683 '''
1683 '''
1684 regexps = self.__dict_key_regexps = {
1684 regexps = self.__dict_key_regexps = {
1685 False: re.compile(dict_key_re_fmt % r'''
1685 False: re.compile(dict_key_re_fmt % r'''
1686 # identifiers separated by .
1686 # identifiers separated by .
1687 (?!\d)\w+
1687 (?!\d)\w+
1688 (?:\.(?!\d)\w+)*
1688 (?:\.(?!\d)\w+)*
1689 '''),
1689 '''),
1690 True: re.compile(dict_key_re_fmt % '''
1690 True: re.compile(dict_key_re_fmt % '''
1691 .+
1691 .+
1692 ''')
1692 ''')
1693 }
1693 }
1694
1694
1695 match = regexps[self.greedy].search(self.text_until_cursor)
1695 match = regexps[self.greedy].search(self.text_until_cursor)
1696
1696
1697 if match is None:
1697 if match is None:
1698 return []
1698 return []
1699
1699
1700 expr, prefix0, prefix = match.groups()
1700 expr, prefix0, prefix = match.groups()
1701 try:
1701 try:
1702 obj = eval(expr, self.namespace)
1702 obj = eval(expr, self.namespace)
1703 except Exception:
1703 except Exception:
1704 try:
1704 try:
1705 obj = eval(expr, self.global_namespace)
1705 obj = eval(expr, self.global_namespace)
1706 except Exception:
1706 except Exception:
1707 return []
1707 return []
1708
1708
1709 keys = self._get_keys(obj)
1709 keys = self._get_keys(obj)
1710 if not keys:
1710 if not keys:
1711 return keys
1711 return keys
1712
1712
1713 extra_prefix = eval(prefix0) if prefix0 != '' else None
1713 extra_prefix = eval(prefix0) if prefix0 != '' else None
1714
1714
1715 closing_quote, token_offset, matches = match_dict_keys(keys, prefix, self.splitter.delims, extra_prefix=extra_prefix)
1715 closing_quote, token_offset, matches = match_dict_keys(keys, prefix, self.splitter.delims, extra_prefix=extra_prefix)
1716 if not matches:
1716 if not matches:
1717 return matches
1717 return matches
1718
1718
1719 # get the cursor position of
1719 # get the cursor position of
1720 # - the text being completed
1720 # - the text being completed
1721 # - the start of the key text
1721 # - the start of the key text
1722 # - the start of the completion
1722 # - the start of the completion
1723 text_start = len(self.text_until_cursor) - len(text)
1723 text_start = len(self.text_until_cursor) - len(text)
1724 if prefix:
1724 if prefix:
1725 key_start = match.start(3)
1725 key_start = match.start(3)
1726 completion_start = key_start + token_offset
1726 completion_start = key_start + token_offset
1727 else:
1727 else:
1728 key_start = completion_start = match.end()
1728 key_start = completion_start = match.end()
1729
1729
1730 # grab the leading prefix, to make sure all completions start with `text`
1730 # grab the leading prefix, to make sure all completions start with `text`
1731 if text_start > key_start:
1731 if text_start > key_start:
1732 leading = ''
1732 leading = ''
1733 else:
1733 else:
1734 leading = text[text_start:completion_start]
1734 leading = text[text_start:completion_start]
1735
1735
1736 # the index of the `[` character
1736 # the index of the `[` character
1737 bracket_idx = match.end(1)
1737 bracket_idx = match.end(1)
1738
1738
1739 # append closing quote and bracket as appropriate
1739 # append closing quote and bracket as appropriate
1740 # this is *not* appropriate if the opening quote or bracket is outside
1740 # this is *not* appropriate if the opening quote or bracket is outside
1741 # the text given to this method
1741 # the text given to this method
1742 suf = ''
1742 suf = ''
1743 continuation = self.line_buffer[len(self.text_until_cursor):]
1743 continuation = self.line_buffer[len(self.text_until_cursor):]
1744 if key_start > text_start and closing_quote:
1744 if key_start > text_start and closing_quote:
1745 # quotes were opened inside text, maybe close them
1745 # quotes were opened inside text, maybe close them
1746 if continuation.startswith(closing_quote):
1746 if continuation.startswith(closing_quote):
1747 continuation = continuation[len(closing_quote):]
1747 continuation = continuation[len(closing_quote):]
1748 else:
1748 else:
1749 suf += closing_quote
1749 suf += closing_quote
1750 if bracket_idx > text_start:
1750 if bracket_idx > text_start:
1751 # brackets were opened inside text, maybe close them
1751 # brackets were opened inside text, maybe close them
1752 if not continuation.startswith(']'):
1752 if not continuation.startswith(']'):
1753 suf += ']'
1753 suf += ']'
1754
1754
1755 return [leading + k + suf for k in matches]
1755 return [leading + k + suf for k in matches]
1756
1756
1757 @staticmethod
1757 @staticmethod
1758 def unicode_name_matches(text:str) -> Tuple[str, List[str]] :
1758 def unicode_name_matches(text:str) -> Tuple[str, List[str]] :
1759 """Match Latex-like syntax for unicode characters base
1759 """Match Latex-like syntax for unicode characters base
1760 on the name of the character.
1760 on the name of the character.
1761
1761
1762 This does ``\\GREEK SMALL LETTER ETA`` -> ``Ξ·``
1762 This does ``\\GREEK SMALL LETTER ETA`` -> ``Ξ·``
1763
1763
1764 Works only on valid python 3 identifier, or on combining characters that
1764 Works only on valid python 3 identifier, or on combining characters that
1765 will combine to form a valid identifier.
1765 will combine to form a valid identifier.
1766 """
1766 """
1767 slashpos = text.rfind('\\')
1767 slashpos = text.rfind('\\')
1768 if slashpos > -1:
1768 if slashpos > -1:
1769 s = text[slashpos+1:]
1769 s = text[slashpos+1:]
1770 try :
1770 try :
1771 unic = unicodedata.lookup(s)
1771 unic = unicodedata.lookup(s)
1772 # allow combining chars
1772 # allow combining chars
1773 if ('a'+unic).isidentifier():
1773 if ('a'+unic).isidentifier():
1774 return '\\'+s,[unic]
1774 return '\\'+s,[unic]
1775 except KeyError:
1775 except KeyError:
1776 pass
1776 pass
1777 return '', []
1777 return '', []
1778
1778
1779
1779
1780 def latex_matches(self, text:str) -> Tuple[str, Sequence[str]]:
1780 def latex_matches(self, text:str) -> Tuple[str, Sequence[str]]:
1781 """Match Latex syntax for unicode characters.
1781 """Match Latex syntax for unicode characters.
1782
1782
1783 This does both ``\\alp`` -> ``\\alpha`` and ``\\alpha`` -> ``Ξ±``
1783 This does both ``\\alp`` -> ``\\alpha`` and ``\\alpha`` -> ``Ξ±``
1784 """
1784 """
1785 slashpos = text.rfind('\\')
1785 slashpos = text.rfind('\\')
1786 if slashpos > -1:
1786 if slashpos > -1:
1787 s = text[slashpos:]
1787 s = text[slashpos:]
1788 if s in latex_symbols:
1788 if s in latex_symbols:
1789 # Try to complete a full latex symbol to unicode
1789 # Try to complete a full latex symbol to unicode
1790 # \\alpha -> Ξ±
1790 # \\alpha -> Ξ±
1791 return s, [latex_symbols[s]]
1791 return s, [latex_symbols[s]]
1792 else:
1792 else:
1793 # If a user has partially typed a latex symbol, give them
1793 # If a user has partially typed a latex symbol, give them
1794 # a full list of options \al -> [\aleph, \alpha]
1794 # a full list of options \al -> [\aleph, \alpha]
1795 matches = [k for k in latex_symbols if k.startswith(s)]
1795 matches = [k for k in latex_symbols if k.startswith(s)]
1796 if matches:
1796 if matches:
1797 return s, matches
1797 return s, matches
1798 return '', ()
1798 return '', ()
1799
1799
1800 def dispatch_custom_completer(self, text):
1800 def dispatch_custom_completer(self, text):
1801 if not self.custom_completers:
1801 if not self.custom_completers:
1802 return
1802 return
1803
1803
1804 line = self.line_buffer
1804 line = self.line_buffer
1805 if not line.strip():
1805 if not line.strip():
1806 return None
1806 return None
1807
1807
1808 # Create a little structure to pass all the relevant information about
1808 # Create a little structure to pass all the relevant information about
1809 # the current completion to any custom completer.
1809 # the current completion to any custom completer.
1810 event = SimpleNamespace()
1810 event = SimpleNamespace()
1811 event.line = line
1811 event.line = line
1812 event.symbol = text
1812 event.symbol = text
1813 cmd = line.split(None,1)[0]
1813 cmd = line.split(None,1)[0]
1814 event.command = cmd
1814 event.command = cmd
1815 event.text_until_cursor = self.text_until_cursor
1815 event.text_until_cursor = self.text_until_cursor
1816
1816
1817 # for foo etc, try also to find completer for %foo
1817 # for foo etc, try also to find completer for %foo
1818 if not cmd.startswith(self.magic_escape):
1818 if not cmd.startswith(self.magic_escape):
1819 try_magic = self.custom_completers.s_matches(
1819 try_magic = self.custom_completers.s_matches(
1820 self.magic_escape + cmd)
1820 self.magic_escape + cmd)
1821 else:
1821 else:
1822 try_magic = []
1822 try_magic = []
1823
1823
1824 for c in itertools.chain(self.custom_completers.s_matches(cmd),
1824 for c in itertools.chain(self.custom_completers.s_matches(cmd),
1825 try_magic,
1825 try_magic,
1826 self.custom_completers.flat_matches(self.text_until_cursor)):
1826 self.custom_completers.flat_matches(self.text_until_cursor)):
1827 try:
1827 try:
1828 res = c(event)
1828 res = c(event)
1829 if res:
1829 if res:
1830 # first, try case sensitive match
1830 # first, try case sensitive match
1831 withcase = [r for r in res if r.startswith(text)]
1831 withcase = [r for r in res if r.startswith(text)]
1832 if withcase:
1832 if withcase:
1833 return withcase
1833 return withcase
1834 # if none, then case insensitive ones are ok too
1834 # if none, then case insensitive ones are ok too
1835 text_low = text.lower()
1835 text_low = text.lower()
1836 return [r for r in res if r.lower().startswith(text_low)]
1836 return [r for r in res if r.lower().startswith(text_low)]
1837 except TryNext:
1837 except TryNext:
1838 pass
1838 pass
1839 except KeyboardInterrupt:
1839 except KeyboardInterrupt:
1840 """
1840 """
1841 If custom completer take too long,
1841 If custom completer take too long,
1842 let keyboard interrupt abort and return nothing.
1842 let keyboard interrupt abort and return nothing.
1843 """
1843 """
1844 break
1844 break
1845
1845
1846 return None
1846 return None
1847
1847
1848 def completions(self, text: str, offset: int)->Iterator[Completion]:
1848 def completions(self, text: str, offset: int)->Iterator[Completion]:
1849 """
1849 """
1850 Returns an iterator over the possible completions
1850 Returns an iterator over the possible completions
1851
1851
1852 .. warning::
1852 .. warning::
1853
1853
1854 Unstable
1854 Unstable
1855
1855
1856 This function is unstable, API may change without warning.
1856 This function is unstable, API may change without warning.
1857 It will also raise unless use in proper context manager.
1857 It will also raise unless use in proper context manager.
1858
1858
1859 Parameters
1859 Parameters
1860 ----------
1860 ----------
1861 text : str
1861 text : str
1862 Full text of the current input, multi line string.
1862 Full text of the current input, multi line string.
1863 offset : int
1863 offset : int
1864 Integer representing the position of the cursor in ``text``. Offset
1864 Integer representing the position of the cursor in ``text``. Offset
1865 is 0-based indexed.
1865 is 0-based indexed.
1866
1866
1867 Yields
1867 Yields
1868 ------
1868 ------
1869 Completion
1869 Completion
1870
1870
1871 Notes
1871 Notes
1872 -----
1872 -----
1873 The cursor on a text can either be seen as being "in between"
1873 The cursor on a text can either be seen as being "in between"
1874 characters or "On" a character depending on the interface visible to
1874 characters or "On" a character depending on the interface visible to
1875 the user. For consistency the cursor being on "in between" characters X
1875 the user. For consistency the cursor being on "in between" characters X
1876 and Y is equivalent to the cursor being "on" character Y, that is to say
1876 and Y is equivalent to the cursor being "on" character Y, that is to say
1877 the character the cursor is on is considered as being after the cursor.
1877 the character the cursor is on is considered as being after the cursor.
1878
1878
1879 Combining characters may span more that one position in the
1879 Combining characters may span more that one position in the
1880 text.
1880 text.
1881
1881
1882 .. note::
1882 .. note::
1883
1883
1884 If ``IPCompleter.debug`` is :any:`True` will yield a ``--jedi/ipython--``
1884 If ``IPCompleter.debug`` is :any:`True` will yield a ``--jedi/ipython--``
1885 fake Completion token to distinguish completion returned by Jedi
1885 fake Completion token to distinguish completion returned by Jedi
1886 and usual IPython completion.
1886 and usual IPython completion.
1887
1887
1888 .. note::
1888 .. note::
1889
1889
1890 Completions are not completely deduplicated yet. If identical
1890 Completions are not completely deduplicated yet. If identical
1891 completions are coming from different sources this function does not
1891 completions are coming from different sources this function does not
1892 ensure that each completion object will only be present once.
1892 ensure that each completion object will only be present once.
1893 """
1893 """
1894 warnings.warn("_complete is a provisional API (as of IPython 6.0). "
1894 warnings.warn("_complete is a provisional API (as of IPython 6.0). "
1895 "It may change without warnings. "
1895 "It may change without warnings. "
1896 "Use in corresponding context manager.",
1896 "Use in corresponding context manager.",
1897 category=ProvisionalCompleterWarning, stacklevel=2)
1897 category=ProvisionalCompleterWarning, stacklevel=2)
1898
1898
1899 seen = set()
1899 seen = set()
1900 profiler:Optional[cProfile.Profile]
1900 profiler:Optional[cProfile.Profile]
1901 try:
1901 try:
1902 if self.profile_completions:
1902 if self.profile_completions:
1903 import cProfile
1903 import cProfile
1904 profiler = cProfile.Profile()
1904 profiler = cProfile.Profile()
1905 profiler.enable()
1905 profiler.enable()
1906 else:
1906 else:
1907 profiler = None
1907 profiler = None
1908
1908
1909 for c in self._completions(text, offset, _timeout=self.jedi_compute_type_timeout/1000):
1909 for c in self._completions(text, offset, _timeout=self.jedi_compute_type_timeout/1000):
1910 if c and (c in seen):
1910 if c and (c in seen):
1911 continue
1911 continue
1912 yield c
1912 yield c
1913 seen.add(c)
1913 seen.add(c)
1914 except KeyboardInterrupt:
1914 except KeyboardInterrupt:
1915 """if completions take too long and users send keyboard interrupt,
1915 """if completions take too long and users send keyboard interrupt,
1916 do not crash and return ASAP. """
1916 do not crash and return ASAP. """
1917 pass
1917 pass
1918 finally:
1918 finally:
1919 if profiler is not None:
1919 if profiler is not None:
1920 profiler.disable()
1920 profiler.disable()
1921 ensure_dir_exists(self.profiler_output_dir)
1921 ensure_dir_exists(self.profiler_output_dir)
1922 output_path = os.path.join(self.profiler_output_dir, str(uuid.uuid4()))
1922 output_path = os.path.join(self.profiler_output_dir, str(uuid.uuid4()))
1923 print("Writing profiler output to", output_path)
1923 print("Writing profiler output to", output_path)
1924 profiler.dump_stats(output_path)
1924 profiler.dump_stats(output_path)
1925
1925
1926 def _completions(self, full_text: str, offset: int, *, _timeout) -> Iterator[Completion]:
1926 def _completions(self, full_text: str, offset: int, *, _timeout) -> Iterator[Completion]:
1927 """
1927 """
1928 Core completion module.Same signature as :any:`completions`, with the
1928 Core completion module.Same signature as :any:`completions`, with the
1929 extra `timeout` parameter (in seconds).
1929 extra `timeout` parameter (in seconds).
1930
1930
1931 Computing jedi's completion ``.type`` can be quite expensive (it is a
1931 Computing jedi's completion ``.type`` can be quite expensive (it is a
1932 lazy property) and can require some warm-up, more warm up than just
1932 lazy property) and can require some warm-up, more warm up than just
1933 computing the ``name`` of a completion. The warm-up can be :
1933 computing the ``name`` of a completion. The warm-up can be :
1934
1934
1935 - Long warm-up the first time a module is encountered after
1935 - Long warm-up the first time a module is encountered after
1936 install/update: actually build parse/inference tree.
1936 install/update: actually build parse/inference tree.
1937
1937
1938 - first time the module is encountered in a session: load tree from
1938 - first time the module is encountered in a session: load tree from
1939 disk.
1939 disk.
1940
1940
1941 We don't want to block completions for tens of seconds so we give the
1941 We don't want to block completions for tens of seconds so we give the
1942 completer a "budget" of ``_timeout`` seconds per invocation to compute
1942 completer a "budget" of ``_timeout`` seconds per invocation to compute
1943 completions types, the completions that have not yet been computed will
1943 completions types, the completions that have not yet been computed will
1944 be marked as "unknown" an will have a chance to be computed next round
1944 be marked as "unknown" an will have a chance to be computed next round
1945 are things get cached.
1945 are things get cached.
1946
1946
1947 Keep in mind that Jedi is not the only thing treating the completion so
1947 Keep in mind that Jedi is not the only thing treating the completion so
1948 keep the timeout short-ish as if we take more than 0.3 second we still
1948 keep the timeout short-ish as if we take more than 0.3 second we still
1949 have lots of processing to do.
1949 have lots of processing to do.
1950
1950
1951 """
1951 """
1952 deadline = time.monotonic() + _timeout
1952 deadline = time.monotonic() + _timeout
1953
1953
1954
1954
1955 before = full_text[:offset]
1955 before = full_text[:offset]
1956 cursor_line, cursor_column = position_to_cursor(full_text, offset)
1956 cursor_line, cursor_column = position_to_cursor(full_text, offset)
1957
1957
1958 matched_text, matches, matches_origin, jedi_matches = self._complete(
1958 matched_text, matches, matches_origin, jedi_matches = self._complete(
1959 full_text=full_text, cursor_line=cursor_line, cursor_pos=cursor_column)
1959 full_text=full_text, cursor_line=cursor_line, cursor_pos=cursor_column)
1960
1960
1961 iter_jm = iter(jedi_matches)
1961 iter_jm = iter(jedi_matches)
1962 if _timeout:
1962 if _timeout:
1963 for jm in iter_jm:
1963 for jm in iter_jm:
1964 try:
1964 try:
1965 type_ = jm.type
1965 type_ = jm.type
1966 except Exception:
1966 except Exception:
1967 if self.debug:
1967 if self.debug:
1968 print("Error in Jedi getting type of ", jm)
1968 print("Error in Jedi getting type of ", jm)
1969 type_ = None
1969 type_ = None
1970 delta = len(jm.name_with_symbols) - len(jm.complete)
1970 delta = len(jm.name_with_symbols) - len(jm.complete)
1971 if type_ == 'function':
1971 if type_ == 'function':
1972 signature = _make_signature(jm)
1972 signature = _make_signature(jm)
1973 else:
1973 else:
1974 signature = ''
1974 signature = ''
1975 yield Completion(start=offset - delta,
1975 yield Completion(start=offset - delta,
1976 end=offset,
1976 end=offset,
1977 text=jm.name_with_symbols,
1977 text=jm.name_with_symbols,
1978 type=type_,
1978 type=type_,
1979 signature=signature,
1979 signature=signature,
1980 _origin='jedi')
1980 _origin='jedi')
1981
1981
1982 if time.monotonic() > deadline:
1982 if time.monotonic() > deadline:
1983 break
1983 break
1984
1984
1985 for jm in iter_jm:
1985 for jm in iter_jm:
1986 delta = len(jm.name_with_symbols) - len(jm.complete)
1986 delta = len(jm.name_with_symbols) - len(jm.complete)
1987 yield Completion(start=offset - delta,
1987 yield Completion(start=offset - delta,
1988 end=offset,
1988 end=offset,
1989 text=jm.name_with_symbols,
1989 text=jm.name_with_symbols,
1990 type='<unknown>', # don't compute type for speed
1990 type='<unknown>', # don't compute type for speed
1991 _origin='jedi',
1991 _origin='jedi',
1992 signature='')
1992 signature='')
1993
1993
1994
1994
1995 start_offset = before.rfind(matched_text)
1995 start_offset = before.rfind(matched_text)
1996
1996
1997 # TODO:
1997 # TODO:
1998 # Suppress this, right now just for debug.
1998 # Suppress this, right now just for debug.
1999 if jedi_matches and matches and self.debug:
1999 if jedi_matches and matches and self.debug:
2000 yield Completion(start=start_offset, end=offset, text='--jedi/ipython--',
2000 yield Completion(start=start_offset, end=offset, text='--jedi/ipython--',
2001 _origin='debug', type='none', signature='')
2001 _origin='debug', type='none', signature='')
2002
2002
2003 # I'm unsure if this is always true, so let's assert and see if it
2003 # I'm unsure if this is always true, so let's assert and see if it
2004 # crash
2004 # crash
2005 assert before.endswith(matched_text)
2005 assert before.endswith(matched_text)
2006 for m, t in zip(matches, matches_origin):
2006 for m, t in zip(matches, matches_origin):
2007 yield Completion(start=start_offset, end=offset, text=m, _origin=t, signature='', type='<unknown>')
2007 yield Completion(start=start_offset, end=offset, text=m, _origin=t, signature='', type='<unknown>')
2008
2008
2009
2009
2010 def complete(self, text=None, line_buffer=None, cursor_pos=None) -> Tuple[str, Sequence[str]]:
2010 def complete(self, text=None, line_buffer=None, cursor_pos=None) -> Tuple[str, Sequence[str]]:
2011 """Find completions for the given text and line context.
2011 """Find completions for the given text and line context.
2012
2012
2013 Note that both the text and the line_buffer are optional, but at least
2013 Note that both the text and the line_buffer are optional, but at least
2014 one of them must be given.
2014 one of them must be given.
2015
2015
2016 Parameters
2016 Parameters
2017 ----------
2017 ----------
2018 text : string, optional
2018 text : string, optional
2019 Text to perform the completion on. If not given, the line buffer
2019 Text to perform the completion on. If not given, the line buffer
2020 is split using the instance's CompletionSplitter object.
2020 is split using the instance's CompletionSplitter object.
2021 line_buffer : string, optional
2021 line_buffer : string, optional
2022 If not given, the completer attempts to obtain the current line
2022 If not given, the completer attempts to obtain the current line
2023 buffer via readline. This keyword allows clients which are
2023 buffer via readline. This keyword allows clients which are
2024 requesting for text completions in non-readline contexts to inform
2024 requesting for text completions in non-readline contexts to inform
2025 the completer of the entire text.
2025 the completer of the entire text.
2026 cursor_pos : int, optional
2026 cursor_pos : int, optional
2027 Index of the cursor in the full line buffer. Should be provided by
2027 Index of the cursor in the full line buffer. Should be provided by
2028 remote frontends where kernel has no access to frontend state.
2028 remote frontends where kernel has no access to frontend state.
2029
2029
2030 Returns
2030 Returns
2031 -------
2031 -------
2032 Tuple of two items:
2032 Tuple of two items:
2033 text : str
2033 text : str
2034 Text that was actually used in the completion.
2034 Text that was actually used in the completion.
2035 matches : list
2035 matches : list
2036 A list of completion matches.
2036 A list of completion matches.
2037
2037
2038 Notes
2038 Notes
2039 -----
2039 -----
2040 This API is likely to be deprecated and replaced by
2040 This API is likely to be deprecated and replaced by
2041 :any:`IPCompleter.completions` in the future.
2041 :any:`IPCompleter.completions` in the future.
2042
2042
2043 """
2043 """
2044 warnings.warn('`Completer.complete` is pending deprecation since '
2044 warnings.warn('`Completer.complete` is pending deprecation since '
2045 'IPython 6.0 and will be replaced by `Completer.completions`.',
2045 'IPython 6.0 and will be replaced by `Completer.completions`.',
2046 PendingDeprecationWarning)
2046 PendingDeprecationWarning)
2047 # potential todo, FOLD the 3rd throw away argument of _complete
2047 # potential todo, FOLD the 3rd throw away argument of _complete
2048 # into the first 2 one.
2048 # into the first 2 one.
2049 return self._complete(line_buffer=line_buffer, cursor_pos=cursor_pos, text=text, cursor_line=0)[:2]
2049 return self._complete(line_buffer=line_buffer, cursor_pos=cursor_pos, text=text, cursor_line=0)[:2]
2050
2050
2051 def _complete(self, *, cursor_line, cursor_pos, line_buffer=None, text=None,
2051 def _complete(self, *, cursor_line, cursor_pos, line_buffer=None, text=None,
2052 full_text=None) -> _CompleteResult:
2052 full_text=None) -> _CompleteResult:
2053 """
2053 """
2054 Like complete but can also returns raw jedi completions as well as the
2054 Like complete but can also returns raw jedi completions as well as the
2055 origin of the completion text. This could (and should) be made much
2055 origin of the completion text. This could (and should) be made much
2056 cleaner but that will be simpler once we drop the old (and stateful)
2056 cleaner but that will be simpler once we drop the old (and stateful)
2057 :any:`complete` API.
2057 :any:`complete` API.
2058
2058
2059 With current provisional API, cursor_pos act both (depending on the
2059 With current provisional API, cursor_pos act both (depending on the
2060 caller) as the offset in the ``text`` or ``line_buffer``, or as the
2060 caller) as the offset in the ``text`` or ``line_buffer``, or as the
2061 ``column`` when passing multiline strings this could/should be renamed
2061 ``column`` when passing multiline strings this could/should be renamed
2062 but would add extra noise.
2062 but would add extra noise.
2063
2063
2064 Parameters
2064 Parameters
2065 ----------
2065 ----------
2066 cursor_line
2066 cursor_line
2067 Index of the line the cursor is on. 0 indexed.
2067 Index of the line the cursor is on. 0 indexed.
2068 cursor_pos
2068 cursor_pos
2069 Position of the cursor in the current line/line_buffer/text. 0
2069 Position of the cursor in the current line/line_buffer/text. 0
2070 indexed.
2070 indexed.
2071 line_buffer : optional, str
2071 line_buffer : optional, str
2072 The current line the cursor is in, this is mostly due to legacy
2072 The current line the cursor is in, this is mostly due to legacy
2073 reason that readline coudl only give a us the single current line.
2073 reason that readline could only give a us the single current line.
2074 Prefer `full_text`.
2074 Prefer `full_text`.
2075 text : str
2075 text : str
2076 The current "token" the cursor is in, mostly also for historical
2076 The current "token" the cursor is in, mostly also for historical
2077 reasons. as the completer would trigger only after the current line
2077 reasons. as the completer would trigger only after the current line
2078 was parsed.
2078 was parsed.
2079 full_text : str
2079 full_text : str
2080 Full text of the current cell.
2080 Full text of the current cell.
2081
2081
2082 Returns
2082 Returns
2083 -------
2083 -------
2084 A tuple of N elements which are (likely):
2084 A tuple of N elements which are (likely):
2085 matched_text: ? the text that the complete matched
2085 matched_text: ? the text that the complete matched
2086 matches: list of completions ?
2086 matches: list of completions ?
2087 matches_origin: ? list same length as matches, and where each completion came from
2087 matches_origin: ? list same length as matches, and where each completion came from
2088 jedi_matches: list of Jedi matches, have it's own structure.
2088 jedi_matches: list of Jedi matches, have it's own structure.
2089 """
2089 """
2090
2090
2091
2091
2092 # if the cursor position isn't given, the only sane assumption we can
2092 # if the cursor position isn't given, the only sane assumption we can
2093 # make is that it's at the end of the line (the common case)
2093 # make is that it's at the end of the line (the common case)
2094 if cursor_pos is None:
2094 if cursor_pos is None:
2095 cursor_pos = len(line_buffer) if text is None else len(text)
2095 cursor_pos = len(line_buffer) if text is None else len(text)
2096
2096
2097 if self.use_main_ns:
2097 if self.use_main_ns:
2098 self.namespace = __main__.__dict__
2098 self.namespace = __main__.__dict__
2099
2099
2100 # if text is either None or an empty string, rely on the line buffer
2100 # if text is either None or an empty string, rely on the line buffer
2101 if (not line_buffer) and full_text:
2101 if (not line_buffer) and full_text:
2102 line_buffer = full_text.split('\n')[cursor_line]
2102 line_buffer = full_text.split('\n')[cursor_line]
2103 if not text: # issue #11508: check line_buffer before calling split_line
2103 if not text: # issue #11508: check line_buffer before calling split_line
2104 text = self.splitter.split_line(line_buffer, cursor_pos) if line_buffer else ''
2104 text = self.splitter.split_line(line_buffer, cursor_pos) if line_buffer else ''
2105
2105
2106 if self.backslash_combining_completions:
2106 if self.backslash_combining_completions:
2107 # allow deactivation of these on windows.
2107 # allow deactivation of these on windows.
2108 base_text = text if not line_buffer else line_buffer[:cursor_pos]
2108 base_text = text if not line_buffer else line_buffer[:cursor_pos]
2109
2109
2110 for meth in (self.latex_matches,
2110 for meth in (self.latex_matches,
2111 self.unicode_name_matches,
2111 self.unicode_name_matches,
2112 back_latex_name_matches,
2112 back_latex_name_matches,
2113 back_unicode_name_matches,
2113 back_unicode_name_matches,
2114 self.fwd_unicode_match):
2114 self.fwd_unicode_match):
2115 name_text, name_matches = meth(base_text)
2115 name_text, name_matches = meth(base_text)
2116 if name_text:
2116 if name_text:
2117 return _CompleteResult(name_text, name_matches[:MATCHES_LIMIT], \
2117 return _CompleteResult(name_text, name_matches[:MATCHES_LIMIT], \
2118 [meth.__qualname__]*min(len(name_matches), MATCHES_LIMIT), ())
2118 [meth.__qualname__]*min(len(name_matches), MATCHES_LIMIT), ())
2119
2119
2120
2120
2121 # If no line buffer is given, assume the input text is all there was
2121 # If no line buffer is given, assume the input text is all there was
2122 if line_buffer is None:
2122 if line_buffer is None:
2123 line_buffer = text
2123 line_buffer = text
2124
2124
2125 self.line_buffer = line_buffer
2125 self.line_buffer = line_buffer
2126 self.text_until_cursor = self.line_buffer[:cursor_pos]
2126 self.text_until_cursor = self.line_buffer[:cursor_pos]
2127
2127
2128 # Do magic arg matches
2128 # Do magic arg matches
2129 for matcher in self.magic_arg_matchers:
2129 for matcher in self.magic_arg_matchers:
2130 matches = list(matcher(line_buffer))[:MATCHES_LIMIT]
2130 matches = list(matcher(line_buffer))[:MATCHES_LIMIT]
2131 if matches:
2131 if matches:
2132 origins = [matcher.__qualname__] * len(matches)
2132 origins = [matcher.__qualname__] * len(matches)
2133 return _CompleteResult(text, matches, origins, ())
2133 return _CompleteResult(text, matches, origins, ())
2134
2134
2135 # Start with a clean slate of completions
2135 # Start with a clean slate of completions
2136 matches = []
2136 matches = []
2137
2137
2138 # FIXME: we should extend our api to return a dict with completions for
2138 # FIXME: we should extend our api to return a dict with completions for
2139 # different types of objects. The rlcomplete() method could then
2139 # different types of objects. The rlcomplete() method could then
2140 # simply collapse the dict into a list for readline, but we'd have
2140 # simply collapse the dict into a list for readline, but we'd have
2141 # richer completion semantics in other environments.
2141 # richer completion semantics in other environments.
2142 completions:Iterable[Any] = []
2142 completions:Iterable[Any] = []
2143 if self.use_jedi:
2143 if self.use_jedi:
2144 if not full_text:
2144 if not full_text:
2145 full_text = line_buffer
2145 full_text = line_buffer
2146 completions = self._jedi_matches(
2146 completions = self._jedi_matches(
2147 cursor_pos, cursor_line, full_text)
2147 cursor_pos, cursor_line, full_text)
2148
2148
2149 if self.merge_completions:
2149 if self.merge_completions:
2150 matches = []
2150 matches = []
2151 for matcher in self.matchers:
2151 for matcher in self.matchers:
2152 try:
2152 try:
2153 matches.extend([(m, matcher.__qualname__)
2153 matches.extend([(m, matcher.__qualname__)
2154 for m in matcher(text)])
2154 for m in matcher(text)])
2155 except:
2155 except:
2156 # Show the ugly traceback if the matcher causes an
2156 # Show the ugly traceback if the matcher causes an
2157 # exception, but do NOT crash the kernel!
2157 # exception, but do NOT crash the kernel!
2158 sys.excepthook(*sys.exc_info())
2158 sys.excepthook(*sys.exc_info())
2159 else:
2159 else:
2160 for matcher in self.matchers:
2160 for matcher in self.matchers:
2161 matches = [(m, matcher.__qualname__)
2161 matches = [(m, matcher.__qualname__)
2162 for m in matcher(text)]
2162 for m in matcher(text)]
2163 if matches:
2163 if matches:
2164 break
2164 break
2165
2165
2166 seen = set()
2166 seen = set()
2167 filtered_matches = set()
2167 filtered_matches = set()
2168 for m in matches:
2168 for m in matches:
2169 t, c = m
2169 t, c = m
2170 if t not in seen:
2170 if t not in seen:
2171 filtered_matches.add(m)
2171 filtered_matches.add(m)
2172 seen.add(t)
2172 seen.add(t)
2173
2173
2174 _filtered_matches = sorted(filtered_matches, key=lambda x: completions_sorting_key(x[0]))
2174 _filtered_matches = sorted(filtered_matches, key=lambda x: completions_sorting_key(x[0]))
2175
2175
2176 custom_res = [(m, 'custom') for m in self.dispatch_custom_completer(text) or []]
2176 custom_res = [(m, 'custom') for m in self.dispatch_custom_completer(text) or []]
2177
2177
2178 _filtered_matches = custom_res or _filtered_matches
2178 _filtered_matches = custom_res or _filtered_matches
2179
2179
2180 _filtered_matches = _filtered_matches[:MATCHES_LIMIT]
2180 _filtered_matches = _filtered_matches[:MATCHES_LIMIT]
2181 _matches = [m[0] for m in _filtered_matches]
2181 _matches = [m[0] for m in _filtered_matches]
2182 origins = [m[1] for m in _filtered_matches]
2182 origins = [m[1] for m in _filtered_matches]
2183
2183
2184 self.matches = _matches
2184 self.matches = _matches
2185
2185
2186 return _CompleteResult(text, _matches, origins, completions)
2186 return _CompleteResult(text, _matches, origins, completions)
2187
2187
2188 def fwd_unicode_match(self, text:str) -> Tuple[str, Sequence[str]]:
2188 def fwd_unicode_match(self, text:str) -> Tuple[str, Sequence[str]]:
2189 """
2189 """
2190 Forward match a string starting with a backslash with a list of
2190 Forward match a string starting with a backslash with a list of
2191 potential Unicode completions.
2191 potential Unicode completions.
2192
2192
2193 Will compute list list of Unicode character names on first call and cache it.
2193 Will compute list list of Unicode character names on first call and cache it.
2194
2194
2195 Returns
2195 Returns
2196 -------
2196 -------
2197 At tuple with:
2197 At tuple with:
2198 - matched text (empty if no matches)
2198 - matched text (empty if no matches)
2199 - list of potential completions, empty tuple otherwise)
2199 - list of potential completions, empty tuple otherwise)
2200 """
2200 """
2201 # TODO: self.unicode_names is here a list we traverse each time with ~100k elements.
2201 # TODO: self.unicode_names is here a list we traverse each time with ~100k elements.
2202 # We could do a faster match using a Trie.
2202 # We could do a faster match using a Trie.
2203
2203
2204 # Using pygtrie the following seem to work:
2204 # Using pygtrie the following seem to work:
2205
2205
2206 # s = PrefixSet()
2206 # s = PrefixSet()
2207
2207
2208 # for c in range(0,0x10FFFF + 1):
2208 # for c in range(0,0x10FFFF + 1):
2209 # try:
2209 # try:
2210 # s.add(unicodedata.name(chr(c)))
2210 # s.add(unicodedata.name(chr(c)))
2211 # except ValueError:
2211 # except ValueError:
2212 # pass
2212 # pass
2213 # [''.join(k) for k in s.iter(prefix)]
2213 # [''.join(k) for k in s.iter(prefix)]
2214
2214
2215 # But need to be timed and adds an extra dependency.
2215 # But need to be timed and adds an extra dependency.
2216
2216
2217 slashpos = text.rfind('\\')
2217 slashpos = text.rfind('\\')
2218 # if text starts with slash
2218 # if text starts with slash
2219 if slashpos > -1:
2219 if slashpos > -1:
2220 # PERF: It's important that we don't access self._unicode_names
2220 # PERF: It's important that we don't access self._unicode_names
2221 # until we're inside this if-block. _unicode_names is lazily
2221 # until we're inside this if-block. _unicode_names is lazily
2222 # initialized, and it takes a user-noticeable amount of time to
2222 # initialized, and it takes a user-noticeable amount of time to
2223 # initialize it, so we don't want to initialize it unless we're
2223 # initialize it, so we don't want to initialize it unless we're
2224 # actually going to use it.
2224 # actually going to use it.
2225 s = text[slashpos + 1 :]
2225 s = text[slashpos + 1 :]
2226 sup = s.upper()
2226 sup = s.upper()
2227 candidates = [x for x in self.unicode_names if x.startswith(sup)]
2227 candidates = [x for x in self.unicode_names if x.startswith(sup)]
2228 if candidates:
2228 if candidates:
2229 return s, candidates
2229 return s, candidates
2230 candidates = [x for x in self.unicode_names if sup in x]
2230 candidates = [x for x in self.unicode_names if sup in x]
2231 if candidates:
2231 if candidates:
2232 return s, candidates
2232 return s, candidates
2233 splitsup = sup.split(" ")
2233 splitsup = sup.split(" ")
2234 candidates = [
2234 candidates = [
2235 x for x in self.unicode_names if all(u in x for u in splitsup)
2235 x for x in self.unicode_names if all(u in x for u in splitsup)
2236 ]
2236 ]
2237 if candidates:
2237 if candidates:
2238 return s, candidates
2238 return s, candidates
2239
2239
2240 return "", ()
2240 return "", ()
2241
2241
2242 # if text does not start with slash
2242 # if text does not start with slash
2243 else:
2243 else:
2244 return '', ()
2244 return '', ()
2245
2245
2246 @property
2246 @property
2247 def unicode_names(self) -> List[str]:
2247 def unicode_names(self) -> List[str]:
2248 """List of names of unicode code points that can be completed.
2248 """List of names of unicode code points that can be completed.
2249
2249
2250 The list is lazily initialized on first access.
2250 The list is lazily initialized on first access.
2251 """
2251 """
2252 if self._unicode_names is None:
2252 if self._unicode_names is None:
2253 names = []
2253 names = []
2254 for c in range(0,0x10FFFF + 1):
2254 for c in range(0,0x10FFFF + 1):
2255 try:
2255 try:
2256 names.append(unicodedata.name(chr(c)))
2256 names.append(unicodedata.name(chr(c)))
2257 except ValueError:
2257 except ValueError:
2258 pass
2258 pass
2259 self._unicode_names = _unicode_name_compute(_UNICODE_RANGES)
2259 self._unicode_names = _unicode_name_compute(_UNICODE_RANGES)
2260
2260
2261 return self._unicode_names
2261 return self._unicode_names
2262
2262
2263 def _unicode_name_compute(ranges:List[Tuple[int,int]]) -> List[str]:
2263 def _unicode_name_compute(ranges:List[Tuple[int,int]]) -> List[str]:
2264 names = []
2264 names = []
2265 for start,stop in ranges:
2265 for start,stop in ranges:
2266 for c in range(start, stop) :
2266 for c in range(start, stop) :
2267 try:
2267 try:
2268 names.append(unicodedata.name(chr(c)))
2268 names.append(unicodedata.name(chr(c)))
2269 except ValueError:
2269 except ValueError:
2270 pass
2270 pass
2271 return names
2271 return names
@@ -1,597 +1,597 b''
1 """Tests for autoreload extension.
1 """Tests for autoreload extension.
2 """
2 """
3 # -----------------------------------------------------------------------------
3 # -----------------------------------------------------------------------------
4 # Copyright (c) 2012 IPython Development Team.
4 # Copyright (c) 2012 IPython Development Team.
5 #
5 #
6 # Distributed under the terms of the Modified BSD License.
6 # Distributed under the terms of the Modified BSD License.
7 #
7 #
8 # The full license is in the file COPYING.txt, distributed with this software.
8 # The full license is in the file COPYING.txt, distributed with this software.
9 # -----------------------------------------------------------------------------
9 # -----------------------------------------------------------------------------
10
10
11 # -----------------------------------------------------------------------------
11 # -----------------------------------------------------------------------------
12 # Imports
12 # Imports
13 # -----------------------------------------------------------------------------
13 # -----------------------------------------------------------------------------
14
14
15 import os
15 import os
16 import platform
16 import platform
17 import pytest
17 import pytest
18 import sys
18 import sys
19 import tempfile
19 import tempfile
20 import textwrap
20 import textwrap
21 import shutil
21 import shutil
22 import random
22 import random
23 import time
23 import time
24 from io import StringIO
24 from io import StringIO
25
25
26 import IPython.testing.tools as tt
26 import IPython.testing.tools as tt
27
27
28 from unittest import TestCase
28 from unittest import TestCase
29
29
30 from IPython.extensions.autoreload import AutoreloadMagics
30 from IPython.extensions.autoreload import AutoreloadMagics
31 from IPython.core.events import EventManager, pre_run_cell
31 from IPython.core.events import EventManager, pre_run_cell
32 from IPython.testing.decorators import skipif_not_numpy
32 from IPython.testing.decorators import skipif_not_numpy
33
33
34 if platform.python_implementation() == "PyPy":
34 if platform.python_implementation() == "PyPy":
35 pytest.skip(
35 pytest.skip(
36 "Current autoreload implementation is extremly slow on PyPy",
36 "Current autoreload implementation is extremely slow on PyPy",
37 allow_module_level=True,
37 allow_module_level=True,
38 )
38 )
39
39
40 # -----------------------------------------------------------------------------
40 # -----------------------------------------------------------------------------
41 # Test fixture
41 # Test fixture
42 # -----------------------------------------------------------------------------
42 # -----------------------------------------------------------------------------
43
43
44 noop = lambda *a, **kw: None
44 noop = lambda *a, **kw: None
45
45
46
46
47 class FakeShell:
47 class FakeShell:
48 def __init__(self):
48 def __init__(self):
49 self.ns = {}
49 self.ns = {}
50 self.user_ns = self.ns
50 self.user_ns = self.ns
51 self.user_ns_hidden = {}
51 self.user_ns_hidden = {}
52 self.events = EventManager(self, {"pre_run_cell", pre_run_cell})
52 self.events = EventManager(self, {"pre_run_cell", pre_run_cell})
53 self.auto_magics = AutoreloadMagics(shell=self)
53 self.auto_magics = AutoreloadMagics(shell=self)
54 self.events.register("pre_run_cell", self.auto_magics.pre_run_cell)
54 self.events.register("pre_run_cell", self.auto_magics.pre_run_cell)
55
55
56 register_magics = set_hook = noop
56 register_magics = set_hook = noop
57
57
58 def run_code(self, code):
58 def run_code(self, code):
59 self.events.trigger("pre_run_cell")
59 self.events.trigger("pre_run_cell")
60 exec(code, self.user_ns)
60 exec(code, self.user_ns)
61 self.auto_magics.post_execute_hook()
61 self.auto_magics.post_execute_hook()
62
62
63 def push(self, items):
63 def push(self, items):
64 self.ns.update(items)
64 self.ns.update(items)
65
65
66 def magic_autoreload(self, parameter):
66 def magic_autoreload(self, parameter):
67 self.auto_magics.autoreload(parameter)
67 self.auto_magics.autoreload(parameter)
68
68
69 def magic_aimport(self, parameter, stream=None):
69 def magic_aimport(self, parameter, stream=None):
70 self.auto_magics.aimport(parameter, stream=stream)
70 self.auto_magics.aimport(parameter, stream=stream)
71 self.auto_magics.post_execute_hook()
71 self.auto_magics.post_execute_hook()
72
72
73
73
74 class Fixture(TestCase):
74 class Fixture(TestCase):
75 """Fixture for creating test module files"""
75 """Fixture for creating test module files"""
76
76
77 test_dir = None
77 test_dir = None
78 old_sys_path = None
78 old_sys_path = None
79 filename_chars = "abcdefghijklmopqrstuvwxyz0123456789"
79 filename_chars = "abcdefghijklmopqrstuvwxyz0123456789"
80
80
81 def setUp(self):
81 def setUp(self):
82 self.test_dir = tempfile.mkdtemp()
82 self.test_dir = tempfile.mkdtemp()
83 self.old_sys_path = list(sys.path)
83 self.old_sys_path = list(sys.path)
84 sys.path.insert(0, self.test_dir)
84 sys.path.insert(0, self.test_dir)
85 self.shell = FakeShell()
85 self.shell = FakeShell()
86
86
87 def tearDown(self):
87 def tearDown(self):
88 shutil.rmtree(self.test_dir)
88 shutil.rmtree(self.test_dir)
89 sys.path = self.old_sys_path
89 sys.path = self.old_sys_path
90
90
91 self.test_dir = None
91 self.test_dir = None
92 self.old_sys_path = None
92 self.old_sys_path = None
93 self.shell = None
93 self.shell = None
94
94
95 def get_module(self):
95 def get_module(self):
96 module_name = "tmpmod_" + "".join(random.sample(self.filename_chars, 20))
96 module_name = "tmpmod_" + "".join(random.sample(self.filename_chars, 20))
97 if module_name in sys.modules:
97 if module_name in sys.modules:
98 del sys.modules[module_name]
98 del sys.modules[module_name]
99 file_name = os.path.join(self.test_dir, module_name + ".py")
99 file_name = os.path.join(self.test_dir, module_name + ".py")
100 return module_name, file_name
100 return module_name, file_name
101
101
102 def write_file(self, filename, content):
102 def write_file(self, filename, content):
103 """
103 """
104 Write a file, and force a timestamp difference of at least one second
104 Write a file, and force a timestamp difference of at least one second
105
105
106 Notes
106 Notes
107 -----
107 -----
108 Python's .pyc files record the timestamp of their compilation
108 Python's .pyc files record the timestamp of their compilation
109 with a time resolution of one second.
109 with a time resolution of one second.
110
110
111 Therefore, we need to force a timestamp difference between .py
111 Therefore, we need to force a timestamp difference between .py
112 and .pyc, without having the .py file be timestamped in the
112 and .pyc, without having the .py file be timestamped in the
113 future, and without changing the timestamp of the .pyc file
113 future, and without changing the timestamp of the .pyc file
114 (because that is stored in the file). The only reliable way
114 (because that is stored in the file). The only reliable way
115 to achieve this seems to be to sleep.
115 to achieve this seems to be to sleep.
116 """
116 """
117 content = textwrap.dedent(content)
117 content = textwrap.dedent(content)
118 # Sleep one second + eps
118 # Sleep one second + eps
119 time.sleep(1.05)
119 time.sleep(1.05)
120
120
121 # Write
121 # Write
122 with open(filename, "w", encoding="utf-8") as f:
122 with open(filename, "w", encoding="utf-8") as f:
123 f.write(content)
123 f.write(content)
124
124
125 def new_module(self, code):
125 def new_module(self, code):
126 code = textwrap.dedent(code)
126 code = textwrap.dedent(code)
127 mod_name, mod_fn = self.get_module()
127 mod_name, mod_fn = self.get_module()
128 with open(mod_fn, "w", encoding="utf-8") as f:
128 with open(mod_fn, "w", encoding="utf-8") as f:
129 f.write(code)
129 f.write(code)
130 return mod_name, mod_fn
130 return mod_name, mod_fn
131
131
132
132
133 # -----------------------------------------------------------------------------
133 # -----------------------------------------------------------------------------
134 # Test automatic reloading
134 # Test automatic reloading
135 # -----------------------------------------------------------------------------
135 # -----------------------------------------------------------------------------
136
136
137
137
138 def pickle_get_current_class(obj):
138 def pickle_get_current_class(obj):
139 """
139 """
140 Original issue comes from pickle; hence the name.
140 Original issue comes from pickle; hence the name.
141 """
141 """
142 name = obj.__class__.__name__
142 name = obj.__class__.__name__
143 module_name = getattr(obj, "__module__", None)
143 module_name = getattr(obj, "__module__", None)
144 obj2 = sys.modules[module_name]
144 obj2 = sys.modules[module_name]
145 for subpath in name.split("."):
145 for subpath in name.split("."):
146 obj2 = getattr(obj2, subpath)
146 obj2 = getattr(obj2, subpath)
147 return obj2
147 return obj2
148
148
149
149
150 class TestAutoreload(Fixture):
150 class TestAutoreload(Fixture):
151 def test_reload_enums(self):
151 def test_reload_enums(self):
152 mod_name, mod_fn = self.new_module(
152 mod_name, mod_fn = self.new_module(
153 textwrap.dedent(
153 textwrap.dedent(
154 """
154 """
155 from enum import Enum
155 from enum import Enum
156 class MyEnum(Enum):
156 class MyEnum(Enum):
157 A = 'A'
157 A = 'A'
158 B = 'B'
158 B = 'B'
159 """
159 """
160 )
160 )
161 )
161 )
162 self.shell.magic_autoreload("2")
162 self.shell.magic_autoreload("2")
163 self.shell.magic_aimport(mod_name)
163 self.shell.magic_aimport(mod_name)
164 self.write_file(
164 self.write_file(
165 mod_fn,
165 mod_fn,
166 textwrap.dedent(
166 textwrap.dedent(
167 """
167 """
168 from enum import Enum
168 from enum import Enum
169 class MyEnum(Enum):
169 class MyEnum(Enum):
170 A = 'A'
170 A = 'A'
171 B = 'B'
171 B = 'B'
172 C = 'C'
172 C = 'C'
173 """
173 """
174 ),
174 ),
175 )
175 )
176 with tt.AssertNotPrints(
176 with tt.AssertNotPrints(
177 ("[autoreload of %s failed:" % mod_name), channel="stderr"
177 ("[autoreload of %s failed:" % mod_name), channel="stderr"
178 ):
178 ):
179 self.shell.run_code("pass") # trigger another reload
179 self.shell.run_code("pass") # trigger another reload
180
180
181 def test_reload_class_type(self):
181 def test_reload_class_type(self):
182 self.shell.magic_autoreload("2")
182 self.shell.magic_autoreload("2")
183 mod_name, mod_fn = self.new_module(
183 mod_name, mod_fn = self.new_module(
184 """
184 """
185 class Test():
185 class Test():
186 def meth(self):
186 def meth(self):
187 return "old"
187 return "old"
188 """
188 """
189 )
189 )
190 assert "test" not in self.shell.ns
190 assert "test" not in self.shell.ns
191 assert "result" not in self.shell.ns
191 assert "result" not in self.shell.ns
192
192
193 self.shell.run_code("from %s import Test" % mod_name)
193 self.shell.run_code("from %s import Test" % mod_name)
194 self.shell.run_code("test = Test()")
194 self.shell.run_code("test = Test()")
195
195
196 self.write_file(
196 self.write_file(
197 mod_fn,
197 mod_fn,
198 """
198 """
199 class Test():
199 class Test():
200 def meth(self):
200 def meth(self):
201 return "new"
201 return "new"
202 """,
202 """,
203 )
203 )
204
204
205 test_object = self.shell.ns["test"]
205 test_object = self.shell.ns["test"]
206
206
207 # important to trigger autoreload logic !
207 # important to trigger autoreload logic !
208 self.shell.run_code("pass")
208 self.shell.run_code("pass")
209
209
210 test_class = pickle_get_current_class(test_object)
210 test_class = pickle_get_current_class(test_object)
211 assert isinstance(test_object, test_class)
211 assert isinstance(test_object, test_class)
212
212
213 # extra check.
213 # extra check.
214 self.shell.run_code("import pickle")
214 self.shell.run_code("import pickle")
215 self.shell.run_code("p = pickle.dumps(test)")
215 self.shell.run_code("p = pickle.dumps(test)")
216
216
217 def test_reload_class_attributes(self):
217 def test_reload_class_attributes(self):
218 self.shell.magic_autoreload("2")
218 self.shell.magic_autoreload("2")
219 mod_name, mod_fn = self.new_module(
219 mod_name, mod_fn = self.new_module(
220 textwrap.dedent(
220 textwrap.dedent(
221 """
221 """
222 class MyClass:
222 class MyClass:
223
223
224 def __init__(self, a=10):
224 def __init__(self, a=10):
225 self.a = a
225 self.a = a
226 self.b = 22
226 self.b = 22
227 # self.toto = 33
227 # self.toto = 33
228
228
229 def square(self):
229 def square(self):
230 print('compute square')
230 print('compute square')
231 return self.a*self.a
231 return self.a*self.a
232 """
232 """
233 )
233 )
234 )
234 )
235 self.shell.run_code("from %s import MyClass" % mod_name)
235 self.shell.run_code("from %s import MyClass" % mod_name)
236 self.shell.run_code("first = MyClass(5)")
236 self.shell.run_code("first = MyClass(5)")
237 self.shell.run_code("first.square()")
237 self.shell.run_code("first.square()")
238 with self.assertRaises(AttributeError):
238 with self.assertRaises(AttributeError):
239 self.shell.run_code("first.cube()")
239 self.shell.run_code("first.cube()")
240 with self.assertRaises(AttributeError):
240 with self.assertRaises(AttributeError):
241 self.shell.run_code("first.power(5)")
241 self.shell.run_code("first.power(5)")
242 self.shell.run_code("first.b")
242 self.shell.run_code("first.b")
243 with self.assertRaises(AttributeError):
243 with self.assertRaises(AttributeError):
244 self.shell.run_code("first.toto")
244 self.shell.run_code("first.toto")
245
245
246 # remove square, add power
246 # remove square, add power
247
247
248 self.write_file(
248 self.write_file(
249 mod_fn,
249 mod_fn,
250 textwrap.dedent(
250 textwrap.dedent(
251 """
251 """
252 class MyClass:
252 class MyClass:
253
253
254 def __init__(self, a=10):
254 def __init__(self, a=10):
255 self.a = a
255 self.a = a
256 self.b = 11
256 self.b = 11
257
257
258 def power(self, p):
258 def power(self, p):
259 print('compute power '+str(p))
259 print('compute power '+str(p))
260 return self.a**p
260 return self.a**p
261 """
261 """
262 ),
262 ),
263 )
263 )
264
264
265 self.shell.run_code("second = MyClass(5)")
265 self.shell.run_code("second = MyClass(5)")
266
266
267 for object_name in {"first", "second"}:
267 for object_name in {"first", "second"}:
268 self.shell.run_code(f"{object_name}.power(5)")
268 self.shell.run_code(f"{object_name}.power(5)")
269 with self.assertRaises(AttributeError):
269 with self.assertRaises(AttributeError):
270 self.shell.run_code(f"{object_name}.cube()")
270 self.shell.run_code(f"{object_name}.cube()")
271 with self.assertRaises(AttributeError):
271 with self.assertRaises(AttributeError):
272 self.shell.run_code(f"{object_name}.square()")
272 self.shell.run_code(f"{object_name}.square()")
273 self.shell.run_code(f"{object_name}.b")
273 self.shell.run_code(f"{object_name}.b")
274 self.shell.run_code(f"{object_name}.a")
274 self.shell.run_code(f"{object_name}.a")
275 with self.assertRaises(AttributeError):
275 with self.assertRaises(AttributeError):
276 self.shell.run_code(f"{object_name}.toto")
276 self.shell.run_code(f"{object_name}.toto")
277
277
278 @skipif_not_numpy
278 @skipif_not_numpy
279 def test_comparing_numpy_structures(self):
279 def test_comparing_numpy_structures(self):
280 self.shell.magic_autoreload("2")
280 self.shell.magic_autoreload("2")
281 mod_name, mod_fn = self.new_module(
281 mod_name, mod_fn = self.new_module(
282 textwrap.dedent(
282 textwrap.dedent(
283 """
283 """
284 import numpy as np
284 import numpy as np
285 class MyClass:
285 class MyClass:
286 a = (np.array((.1, .2)),
286 a = (np.array((.1, .2)),
287 np.array((.2, .3)))
287 np.array((.2, .3)))
288 """
288 """
289 )
289 )
290 )
290 )
291 self.shell.run_code("from %s import MyClass" % mod_name)
291 self.shell.run_code("from %s import MyClass" % mod_name)
292 self.shell.run_code("first = MyClass()")
292 self.shell.run_code("first = MyClass()")
293
293
294 # change property `a`
294 # change property `a`
295 self.write_file(
295 self.write_file(
296 mod_fn,
296 mod_fn,
297 textwrap.dedent(
297 textwrap.dedent(
298 """
298 """
299 import numpy as np
299 import numpy as np
300 class MyClass:
300 class MyClass:
301 a = (np.array((.3, .4)),
301 a = (np.array((.3, .4)),
302 np.array((.5, .6)))
302 np.array((.5, .6)))
303 """
303 """
304 ),
304 ),
305 )
305 )
306
306
307 with tt.AssertNotPrints(
307 with tt.AssertNotPrints(
308 ("[autoreload of %s failed:" % mod_name), channel="stderr"
308 ("[autoreload of %s failed:" % mod_name), channel="stderr"
309 ):
309 ):
310 self.shell.run_code("pass") # trigger another reload
310 self.shell.run_code("pass") # trigger another reload
311
311
312 def test_autoload_newly_added_objects(self):
312 def test_autoload_newly_added_objects(self):
313 self.shell.magic_autoreload("3")
313 self.shell.magic_autoreload("3")
314 mod_code = """
314 mod_code = """
315 def func1(): pass
315 def func1(): pass
316 """
316 """
317 mod_name, mod_fn = self.new_module(textwrap.dedent(mod_code))
317 mod_name, mod_fn = self.new_module(textwrap.dedent(mod_code))
318 self.shell.run_code(f"from {mod_name} import *")
318 self.shell.run_code(f"from {mod_name} import *")
319 self.shell.run_code("func1()")
319 self.shell.run_code("func1()")
320 with self.assertRaises(NameError):
320 with self.assertRaises(NameError):
321 self.shell.run_code("func2()")
321 self.shell.run_code("func2()")
322 with self.assertRaises(NameError):
322 with self.assertRaises(NameError):
323 self.shell.run_code("t = Test()")
323 self.shell.run_code("t = Test()")
324 with self.assertRaises(NameError):
324 with self.assertRaises(NameError):
325 self.shell.run_code("number")
325 self.shell.run_code("number")
326
326
327 # ----------- TEST NEW OBJ LOADED --------------------------
327 # ----------- TEST NEW OBJ LOADED --------------------------
328
328
329 new_code = """
329 new_code = """
330 def func1(): pass
330 def func1(): pass
331 def func2(): pass
331 def func2(): pass
332 class Test: pass
332 class Test: pass
333 number = 0
333 number = 0
334 from enum import Enum
334 from enum import Enum
335 class TestEnum(Enum):
335 class TestEnum(Enum):
336 A = 'a'
336 A = 'a'
337 """
337 """
338 self.write_file(mod_fn, textwrap.dedent(new_code))
338 self.write_file(mod_fn, textwrap.dedent(new_code))
339
339
340 # test function now exists in shell's namespace namespace
340 # test function now exists in shell's namespace namespace
341 self.shell.run_code("func2()")
341 self.shell.run_code("func2()")
342 # test function now exists in module's dict
342 # test function now exists in module's dict
343 self.shell.run_code(f"import sys; sys.modules['{mod_name}'].func2()")
343 self.shell.run_code(f"import sys; sys.modules['{mod_name}'].func2()")
344 # test class now exists
344 # test class now exists
345 self.shell.run_code("t = Test()")
345 self.shell.run_code("t = Test()")
346 # test global built-in var now exists
346 # test global built-in var now exists
347 self.shell.run_code("number")
347 self.shell.run_code("number")
348 # test the enumerations gets loaded successfully
348 # test the enumerations gets loaded successfully
349 self.shell.run_code("TestEnum.A")
349 self.shell.run_code("TestEnum.A")
350
350
351 # ----------- TEST NEW OBJ CAN BE CHANGED --------------------
351 # ----------- TEST NEW OBJ CAN BE CHANGED --------------------
352
352
353 new_code = """
353 new_code = """
354 def func1(): return 'changed'
354 def func1(): return 'changed'
355 def func2(): return 'changed'
355 def func2(): return 'changed'
356 class Test:
356 class Test:
357 def new_func(self):
357 def new_func(self):
358 return 'changed'
358 return 'changed'
359 number = 1
359 number = 1
360 from enum import Enum
360 from enum import Enum
361 class TestEnum(Enum):
361 class TestEnum(Enum):
362 A = 'a'
362 A = 'a'
363 B = 'added'
363 B = 'added'
364 """
364 """
365 self.write_file(mod_fn, textwrap.dedent(new_code))
365 self.write_file(mod_fn, textwrap.dedent(new_code))
366 self.shell.run_code("assert func1() == 'changed'")
366 self.shell.run_code("assert func1() == 'changed'")
367 self.shell.run_code("assert func2() == 'changed'")
367 self.shell.run_code("assert func2() == 'changed'")
368 self.shell.run_code("t = Test(); assert t.new_func() == 'changed'")
368 self.shell.run_code("t = Test(); assert t.new_func() == 'changed'")
369 self.shell.run_code("assert number == 1")
369 self.shell.run_code("assert number == 1")
370 self.shell.run_code("assert TestEnum.B.value == 'added'")
370 self.shell.run_code("assert TestEnum.B.value == 'added'")
371
371
372 # ----------- TEST IMPORT FROM MODULE --------------------------
372 # ----------- TEST IMPORT FROM MODULE --------------------------
373
373
374 new_mod_code = """
374 new_mod_code = """
375 from enum import Enum
375 from enum import Enum
376 class Ext(Enum):
376 class Ext(Enum):
377 A = 'ext'
377 A = 'ext'
378 def ext_func():
378 def ext_func():
379 return 'ext'
379 return 'ext'
380 class ExtTest:
380 class ExtTest:
381 def meth(self):
381 def meth(self):
382 return 'ext'
382 return 'ext'
383 ext_int = 2
383 ext_int = 2
384 """
384 """
385 new_mod_name, new_mod_fn = self.new_module(textwrap.dedent(new_mod_code))
385 new_mod_name, new_mod_fn = self.new_module(textwrap.dedent(new_mod_code))
386 current_mod_code = f"""
386 current_mod_code = f"""
387 from {new_mod_name} import *
387 from {new_mod_name} import *
388 """
388 """
389 self.write_file(mod_fn, textwrap.dedent(current_mod_code))
389 self.write_file(mod_fn, textwrap.dedent(current_mod_code))
390 self.shell.run_code("assert Ext.A.value == 'ext'")
390 self.shell.run_code("assert Ext.A.value == 'ext'")
391 self.shell.run_code("assert ext_func() == 'ext'")
391 self.shell.run_code("assert ext_func() == 'ext'")
392 self.shell.run_code("t = ExtTest(); assert t.meth() == 'ext'")
392 self.shell.run_code("t = ExtTest(); assert t.meth() == 'ext'")
393 self.shell.run_code("assert ext_int == 2")
393 self.shell.run_code("assert ext_int == 2")
394
394
395 def _check_smoketest(self, use_aimport=True):
395 def _check_smoketest(self, use_aimport=True):
396 """
396 """
397 Functional test for the automatic reloader using either
397 Functional test for the automatic reloader using either
398 '%autoreload 1' or '%autoreload 2'
398 '%autoreload 1' or '%autoreload 2'
399 """
399 """
400
400
401 mod_name, mod_fn = self.new_module(
401 mod_name, mod_fn = self.new_module(
402 """
402 """
403 x = 9
403 x = 9
404
404
405 z = 123 # this item will be deleted
405 z = 123 # this item will be deleted
406
406
407 def foo(y):
407 def foo(y):
408 return y + 3
408 return y + 3
409
409
410 class Baz(object):
410 class Baz(object):
411 def __init__(self, x):
411 def __init__(self, x):
412 self.x = x
412 self.x = x
413 def bar(self, y):
413 def bar(self, y):
414 return self.x + y
414 return self.x + y
415 @property
415 @property
416 def quux(self):
416 def quux(self):
417 return 42
417 return 42
418 def zzz(self):
418 def zzz(self):
419 '''This method will be deleted below'''
419 '''This method will be deleted below'''
420 return 99
420 return 99
421
421
422 class Bar: # old-style class: weakref doesn't work for it on Python < 2.7
422 class Bar: # old-style class: weakref doesn't work for it on Python < 2.7
423 def foo(self):
423 def foo(self):
424 return 1
424 return 1
425 """
425 """
426 )
426 )
427
427
428 #
428 #
429 # Import module, and mark for reloading
429 # Import module, and mark for reloading
430 #
430 #
431 if use_aimport:
431 if use_aimport:
432 self.shell.magic_autoreload("1")
432 self.shell.magic_autoreload("1")
433 self.shell.magic_aimport(mod_name)
433 self.shell.magic_aimport(mod_name)
434 stream = StringIO()
434 stream = StringIO()
435 self.shell.magic_aimport("", stream=stream)
435 self.shell.magic_aimport("", stream=stream)
436 self.assertIn(("Modules to reload:\n%s" % mod_name), stream.getvalue())
436 self.assertIn(("Modules to reload:\n%s" % mod_name), stream.getvalue())
437
437
438 with self.assertRaises(ImportError):
438 with self.assertRaises(ImportError):
439 self.shell.magic_aimport("tmpmod_as318989e89ds")
439 self.shell.magic_aimport("tmpmod_as318989e89ds")
440 else:
440 else:
441 self.shell.magic_autoreload("2")
441 self.shell.magic_autoreload("2")
442 self.shell.run_code("import %s" % mod_name)
442 self.shell.run_code("import %s" % mod_name)
443 stream = StringIO()
443 stream = StringIO()
444 self.shell.magic_aimport("", stream=stream)
444 self.shell.magic_aimport("", stream=stream)
445 self.assertTrue(
445 self.assertTrue(
446 "Modules to reload:\nall-except-skipped" in stream.getvalue()
446 "Modules to reload:\nall-except-skipped" in stream.getvalue()
447 )
447 )
448 self.assertIn(mod_name, self.shell.ns)
448 self.assertIn(mod_name, self.shell.ns)
449
449
450 mod = sys.modules[mod_name]
450 mod = sys.modules[mod_name]
451
451
452 #
452 #
453 # Test module contents
453 # Test module contents
454 #
454 #
455 old_foo = mod.foo
455 old_foo = mod.foo
456 old_obj = mod.Baz(9)
456 old_obj = mod.Baz(9)
457 old_obj2 = mod.Bar()
457 old_obj2 = mod.Bar()
458
458
459 def check_module_contents():
459 def check_module_contents():
460 self.assertEqual(mod.x, 9)
460 self.assertEqual(mod.x, 9)
461 self.assertEqual(mod.z, 123)
461 self.assertEqual(mod.z, 123)
462
462
463 self.assertEqual(old_foo(0), 3)
463 self.assertEqual(old_foo(0), 3)
464 self.assertEqual(mod.foo(0), 3)
464 self.assertEqual(mod.foo(0), 3)
465
465
466 obj = mod.Baz(9)
466 obj = mod.Baz(9)
467 self.assertEqual(old_obj.bar(1), 10)
467 self.assertEqual(old_obj.bar(1), 10)
468 self.assertEqual(obj.bar(1), 10)
468 self.assertEqual(obj.bar(1), 10)
469 self.assertEqual(obj.quux, 42)
469 self.assertEqual(obj.quux, 42)
470 self.assertEqual(obj.zzz(), 99)
470 self.assertEqual(obj.zzz(), 99)
471
471
472 obj2 = mod.Bar()
472 obj2 = mod.Bar()
473 self.assertEqual(old_obj2.foo(), 1)
473 self.assertEqual(old_obj2.foo(), 1)
474 self.assertEqual(obj2.foo(), 1)
474 self.assertEqual(obj2.foo(), 1)
475
475
476 check_module_contents()
476 check_module_contents()
477
477
478 #
478 #
479 # Simulate a failed reload: no reload should occur and exactly
479 # Simulate a failed reload: no reload should occur and exactly
480 # one error message should be printed
480 # one error message should be printed
481 #
481 #
482 self.write_file(
482 self.write_file(
483 mod_fn,
483 mod_fn,
484 """
484 """
485 a syntax error
485 a syntax error
486 """,
486 """,
487 )
487 )
488
488
489 with tt.AssertPrints(
489 with tt.AssertPrints(
490 ("[autoreload of %s failed:" % mod_name), channel="stderr"
490 ("[autoreload of %s failed:" % mod_name), channel="stderr"
491 ):
491 ):
492 self.shell.run_code("pass") # trigger reload
492 self.shell.run_code("pass") # trigger reload
493 with tt.AssertNotPrints(
493 with tt.AssertNotPrints(
494 ("[autoreload of %s failed:" % mod_name), channel="stderr"
494 ("[autoreload of %s failed:" % mod_name), channel="stderr"
495 ):
495 ):
496 self.shell.run_code("pass") # trigger another reload
496 self.shell.run_code("pass") # trigger another reload
497 check_module_contents()
497 check_module_contents()
498
498
499 #
499 #
500 # Rewrite module (this time reload should succeed)
500 # Rewrite module (this time reload should succeed)
501 #
501 #
502 self.write_file(
502 self.write_file(
503 mod_fn,
503 mod_fn,
504 """
504 """
505 x = 10
505 x = 10
506
506
507 def foo(y):
507 def foo(y):
508 return y + 4
508 return y + 4
509
509
510 class Baz(object):
510 class Baz(object):
511 def __init__(self, x):
511 def __init__(self, x):
512 self.x = x
512 self.x = x
513 def bar(self, y):
513 def bar(self, y):
514 return self.x + y + 1
514 return self.x + y + 1
515 @property
515 @property
516 def quux(self):
516 def quux(self):
517 return 43
517 return 43
518
518
519 class Bar: # old-style class
519 class Bar: # old-style class
520 def foo(self):
520 def foo(self):
521 return 2
521 return 2
522 """,
522 """,
523 )
523 )
524
524
525 def check_module_contents():
525 def check_module_contents():
526 self.assertEqual(mod.x, 10)
526 self.assertEqual(mod.x, 10)
527 self.assertFalse(hasattr(mod, "z"))
527 self.assertFalse(hasattr(mod, "z"))
528
528
529 self.assertEqual(old_foo(0), 4) # superreload magic!
529 self.assertEqual(old_foo(0), 4) # superreload magic!
530 self.assertEqual(mod.foo(0), 4)
530 self.assertEqual(mod.foo(0), 4)
531
531
532 obj = mod.Baz(9)
532 obj = mod.Baz(9)
533 self.assertEqual(old_obj.bar(1), 11) # superreload magic!
533 self.assertEqual(old_obj.bar(1), 11) # superreload magic!
534 self.assertEqual(obj.bar(1), 11)
534 self.assertEqual(obj.bar(1), 11)
535
535
536 self.assertEqual(old_obj.quux, 43)
536 self.assertEqual(old_obj.quux, 43)
537 self.assertEqual(obj.quux, 43)
537 self.assertEqual(obj.quux, 43)
538
538
539 self.assertFalse(hasattr(old_obj, "zzz"))
539 self.assertFalse(hasattr(old_obj, "zzz"))
540 self.assertFalse(hasattr(obj, "zzz"))
540 self.assertFalse(hasattr(obj, "zzz"))
541
541
542 obj2 = mod.Bar()
542 obj2 = mod.Bar()
543 self.assertEqual(old_obj2.foo(), 2)
543 self.assertEqual(old_obj2.foo(), 2)
544 self.assertEqual(obj2.foo(), 2)
544 self.assertEqual(obj2.foo(), 2)
545
545
546 self.shell.run_code("pass") # trigger reload
546 self.shell.run_code("pass") # trigger reload
547 check_module_contents()
547 check_module_contents()
548
548
549 #
549 #
550 # Another failure case: deleted file (shouldn't reload)
550 # Another failure case: deleted file (shouldn't reload)
551 #
551 #
552 os.unlink(mod_fn)
552 os.unlink(mod_fn)
553
553
554 self.shell.run_code("pass") # trigger reload
554 self.shell.run_code("pass") # trigger reload
555 check_module_contents()
555 check_module_contents()
556
556
557 #
557 #
558 # Disable autoreload and rewrite module: no reload should occur
558 # Disable autoreload and rewrite module: no reload should occur
559 #
559 #
560 if use_aimport:
560 if use_aimport:
561 self.shell.magic_aimport("-" + mod_name)
561 self.shell.magic_aimport("-" + mod_name)
562 stream = StringIO()
562 stream = StringIO()
563 self.shell.magic_aimport("", stream=stream)
563 self.shell.magic_aimport("", stream=stream)
564 self.assertTrue(("Modules to skip:\n%s" % mod_name) in stream.getvalue())
564 self.assertTrue(("Modules to skip:\n%s" % mod_name) in stream.getvalue())
565
565
566 # This should succeed, although no such module exists
566 # This should succeed, although no such module exists
567 self.shell.magic_aimport("-tmpmod_as318989e89ds")
567 self.shell.magic_aimport("-tmpmod_as318989e89ds")
568 else:
568 else:
569 self.shell.magic_autoreload("0")
569 self.shell.magic_autoreload("0")
570
570
571 self.write_file(
571 self.write_file(
572 mod_fn,
572 mod_fn,
573 """
573 """
574 x = -99
574 x = -99
575 """,
575 """,
576 )
576 )
577
577
578 self.shell.run_code("pass") # trigger reload
578 self.shell.run_code("pass") # trigger reload
579 self.shell.run_code("pass")
579 self.shell.run_code("pass")
580 check_module_contents()
580 check_module_contents()
581
581
582 #
582 #
583 # Re-enable autoreload: reload should now occur
583 # Re-enable autoreload: reload should now occur
584 #
584 #
585 if use_aimport:
585 if use_aimport:
586 self.shell.magic_aimport(mod_name)
586 self.shell.magic_aimport(mod_name)
587 else:
587 else:
588 self.shell.magic_autoreload("")
588 self.shell.magic_autoreload("")
589
589
590 self.shell.run_code("pass") # trigger reload
590 self.shell.run_code("pass") # trigger reload
591 self.assertEqual(mod.x, -99)
591 self.assertEqual(mod.x, -99)
592
592
593 def test_smoketest_aimport(self):
593 def test_smoketest_aimport(self):
594 self._check_smoketest(use_aimport=True)
594 self._check_smoketest(use_aimport=True)
595
595
596 def test_smoketest_autoreload(self):
596 def test_smoketest_autoreload(self):
597 self._check_smoketest(use_aimport=False)
597 self._check_smoketest(use_aimport=False)
@@ -1,6 +1,6 b''
1 # Security Policy
1 # Security Policy
2
2
3 ## Reporting a Vulnerability
3 ## Reporting a Vulnerability
4
4
5 All IPython and Jupyter security are handled via security@ipython.org.
5 All IPython and Jupyter security are handled via security@ipython.org.
6 You can find more informations on the Jupyter website. https://jupyter.org/security
6 You can find more information on the Jupyter website. https://jupyter.org/security
@@ -1,27 +1,27 b''
1 build: false
1 build: false
2 matrix:
2 matrix:
3 fast_finish: true # immediately finish build once one of the jobs fails.
3 fast_finish: true # immediately finish build once one of the jobs fails.
4
4
5 environment:
5 environment:
6 global:
6 global:
7 APPVEYOR_BUILD_WORKER_IMAGE: 'Visual Studio 2022'
7 APPVEYOR_BUILD_WORKER_IMAGE: 'Visual Studio 2022'
8 COLUMNS: 120 # Appveyor web viwer window width is 130 chars
8 COLUMNS: 120 # Appveyor web viewer window width is 130 chars
9
9
10 matrix:
10 matrix:
11 - PYTHON: "C:\\Python38"
11 - PYTHON: "C:\\Python38"
12 PYTHON_VERSION: "3.8.x"
12 PYTHON_VERSION: "3.8.x"
13 PYTHON_ARCH: "32"
13 PYTHON_ARCH: "32"
14
14
15 init:
15 init:
16 - "ECHO %PYTHON% %PYTHON_VERSION% %PYTHON_ARCH%"
16 - "ECHO %PYTHON% %PYTHON_VERSION% %PYTHON_ARCH%"
17
17
18 install:
18 install:
19 - "SET PATH=%PYTHON%;%PYTHON%\\Scripts;%PATH%"
19 - "SET PATH=%PYTHON%;%PYTHON%\\Scripts;%PATH%"
20 - python -m pip install --upgrade setuptools 'pip<22'
20 - python -m pip install --upgrade setuptools 'pip<22'
21 - pip install pytest-cov
21 - pip install pytest-cov
22 - pip install -e .[test_extra]
22 - pip install -e .[test_extra]
23 test_script:
23 test_script:
24 - pytest --color=yes -ra --cov --cov-report=xml
24 - pytest --color=yes -ra --cov --cov-report=xml
25 on_finish:
25 on_finish:
26 - curl -Os https://uploader.codecov.io/latest/windows/codecov.exe
26 - curl -Os https://uploader.codecov.io/latest/windows/codecov.exe
27 - codecov -e PYTHON_VERSION,PYTHON_ARCH
27 - codecov -e PYTHON_VERSION,PYTHON_ARCH
@@ -1,519 +1,519 b''
1
1
2 .. _ipython_directive:
2 .. _ipython_directive:
3
3
4 ========================
4 ========================
5 IPython Sphinx Directive
5 IPython Sphinx Directive
6 ========================
6 ========================
7
7
8 .. note::
8 .. note::
9
9
10 The IPython Sphinx Directive is in 'beta' and currently under
10 The IPython Sphinx Directive is in 'beta' and currently under
11 active development. Improvements to the code or documentation are welcome!
11 active development. Improvements to the code or documentation are welcome!
12
12
13 .. |rst| replace:: reStructured text
13 .. |rst| replace:: reStructured text
14
14
15 The :rst:dir:`ipython` directive is a stateful shell that can be used
15 The :rst:dir:`ipython` directive is a stateful shell that can be used
16 in |rst| files.
16 in |rst| files.
17
17
18 It knows about standard ipython prompts, and extracts the input and output
18 It knows about standard ipython prompts, and extracts the input and output
19 lines. These prompts will be renumbered starting at ``1``. The inputs will be
19 lines. These prompts will be renumbered starting at ``1``. The inputs will be
20 fed to an embedded ipython interpreter and the outputs from that interpreter
20 fed to an embedded ipython interpreter and the outputs from that interpreter
21 will be inserted as well. For example, code blocks like the following::
21 will be inserted as well. For example, code blocks like the following::
22
22
23 .. ipython::
23 .. ipython::
24
24
25 In [136]: x = 2
25 In [136]: x = 2
26
26
27 In [137]: x**3
27 In [137]: x**3
28 Out[137]: 8
28 Out[137]: 8
29
29
30 will be rendered as
30 will be rendered as
31
31
32 .. ipython::
32 .. ipython::
33
33
34 In [136]: x = 2
34 In [136]: x = 2
35
35
36 In [137]: x**3
36 In [137]: x**3
37 Out[137]: 8
37 Out[137]: 8
38
38
39 .. note::
39 .. note::
40
40
41 This tutorial should be read side-by-side with the Sphinx source
41 This tutorial should be read side-by-side with the Sphinx source
42 for this document because otherwise you will see only the rendered
42 for this document because otherwise you will see only the rendered
43 output and not the code that generated it. Excepting the example
43 output and not the code that generated it. Excepting the example
44 above, we will not in general be showing the literal ReST in this
44 above, we will not in general be showing the literal ReST in this
45 document that generates the rendered output.
45 document that generates the rendered output.
46
46
47
47
48 Directive and options
48 Directive and options
49 =====================
49 =====================
50
50
51 The IPython directive takes a number of options detailed here.
51 The IPython directive takes a number of options detailed here.
52
52
53 .. rst:directive:: ipython
53 .. rst:directive:: ipython
54
54
55 Create an IPython directive.
55 Create an IPython directive.
56
56
57 .. rst:directive:option:: doctest
57 .. rst:directive:option:: doctest
58
58
59 Run a doctest on IPython code blocks in rst.
59 Run a doctest on IPython code blocks in rst.
60
60
61 .. rst:directive:option:: python
61 .. rst:directive:option:: python
62
62
63 Used to indicate that the relevant code block does not have IPython prompts.
63 Used to indicate that the relevant code block does not have IPython prompts.
64
64
65 .. rst:directive:option:: okexcept
65 .. rst:directive:option:: okexcept
66
66
67 Allow the code block to raise an exception.
67 Allow the code block to raise an exception.
68
68
69 .. rst:directive:option:: okwarning
69 .. rst:directive:option:: okwarning
70
70
71 Allow the code block to emit an warning.
71 Allow the code block to emit an warning.
72
72
73 .. rst:directive:option:: suppress
73 .. rst:directive:option:: suppress
74
74
75 Silence any warnings or expected errors.
75 Silence any warnings or expected errors.
76
76
77 .. rst:directive:option:: verbatim
77 .. rst:directive:option:: verbatim
78
78
79 A noop that allows for any text to be syntax highlighted as valid IPython code.
79 A noop that allows for any text to be syntax highlighted as valid IPython code.
80
80
81 .. rst:directive:option:: savefig: OUTFILE [IMAGE_OPTIONS]
81 .. rst:directive:option:: savefig: OUTFILE [IMAGE_OPTIONS]
82
82
83 Save output from matplotlib to *outfile*.
83 Save output from matplotlib to *outfile*.
84
84
85 It's important to note that all of these options can be used for the entire
85 It's important to note that all of these options can be used for the entire
86 directive block or they can decorate individual lines of code as explained
86 directive block or they can decorate individual lines of code as explained
87 in :ref:`pseudo-decorators`.
87 in :ref:`pseudo-decorators`.
88
88
89
89
90 Persisting the Python session across IPython directive blocks
90 Persisting the Python session across IPython directive blocks
91 =============================================================
91 =============================================================
92
92
93 The state from previous sessions is stored, and standard error is
93 The state from previous sessions is stored, and standard error is
94 trapped. At doc build time, ipython's output and std err will be
94 trapped. At doc build time, ipython's output and std err will be
95 inserted, and prompts will be renumbered. So the prompt below should
95 inserted, and prompts will be renumbered. So the prompt below should
96 be renumbered in the rendered docs, and pick up where the block above
96 be renumbered in the rendered docs, and pick up where the block above
97 left off.
97 left off.
98
98
99 .. ipython::
99 .. ipython::
100 :verbatim:
100 :verbatim:
101
101
102 In [138]: z = x*3 # x is recalled from previous block
102 In [138]: z = x*3 # x is recalled from previous block
103
103
104 In [139]: z
104 In [139]: z
105 Out[139]: 6
105 Out[139]: 6
106
106
107 In [142]: print(z)
107 In [142]: print(z)
108 6
108 6
109
109
110 In [141]: q = z[) # this is a syntax error -- we trap ipy exceptions
110 In [141]: q = z[) # this is a syntax error -- we trap ipy exceptions
111 ------------------------------------------------------------
111 ------------------------------------------------------------
112 File "<ipython console>", line 1
112 File "<ipython console>", line 1
113 q = z[) # this is a syntax error -- we trap ipy exceptions
113 q = z[) # this is a syntax error -- we trap ipy exceptions
114 ^
114 ^
115 SyntaxError: invalid syntax
115 SyntaxError: invalid syntax
116
116
117
117
118 Adding documentation tests to your IPython directive
118 Adding documentation tests to your IPython directive
119 ====================================================
119 ====================================================
120
120
121 The embedded interpreter supports some limited markup. For example,
121 The embedded interpreter supports some limited markup. For example,
122 you can put comments in your ipython sessions, which are reported
122 you can put comments in your ipython sessions, which are reported
123 verbatim. There are some handy "pseudo-decorators" that let you
123 verbatim. There are some handy "pseudo-decorators" that let you
124 doctest the output. The inputs are fed to an embedded ipython
124 doctest the output. The inputs are fed to an embedded ipython
125 session and the outputs from the ipython session are inserted into
125 session and the outputs from the ipython session are inserted into
126 your doc. If the output in your doc and in the ipython session don't
126 your doc. If the output in your doc and in the ipython session don't
127 match on a doctest assertion, an error will occur.
127 match on a doctest assertion, an error will occur.
128
128
129
129
130 .. ipython::
130 .. ipython::
131
131
132 In [1]: x = 'hello world'
132 In [1]: x = 'hello world'
133
133
134 # this will raise an error if the ipython output is different
134 # this will raise an error if the ipython output is different
135 @doctest
135 @doctest
136 In [2]: x.upper()
136 In [2]: x.upper()
137 Out[2]: 'HELLO WORLD'
137 Out[2]: 'HELLO WORLD'
138
138
139 # some readline features cannot be supported, so we allow
139 # some readline features cannot be supported, so we allow
140 # "verbatim" blocks, which are dumped in verbatim except prompts
140 # "verbatim" blocks, which are dumped in verbatim except prompts
141 # are continuously numbered
141 # are continuously numbered
142 @verbatim
142 @verbatim
143 In [3]: x.st<TAB>
143 In [3]: x.st<TAB>
144 x.startswith x.strip
144 x.startswith x.strip
145
145
146 For more information on @doctest decorator, please refer to the end of this page in Pseudo-Decorators section.
146 For more information on @doctest decorator, please refer to the end of this page in Pseudo-Decorators section.
147
147
148 Multi-line input
148 Multi-line input
149 ================
149 ================
150
150
151 Multi-line input is supported.
151 Multi-line input is supported.
152
152
153 .. ipython::
153 .. ipython::
154 :verbatim:
154 :verbatim:
155
155
156 In [130]: url = 'http://ichart.finance.yahoo.com/table.csv?s=CROX\
156 In [130]: url = 'http://ichart.finance.yahoo.com/table.csv?s=CROX\
157 .....: &d=9&e=22&f=2009&g=d&a=1&br=8&c=2006&ignore=.csv'
157 .....: &d=9&e=22&f=2009&g=d&a=1&br=8&c=2006&ignore=.csv'
158
158
159 In [131]: print(url.split('&'))
159 In [131]: print(url.split('&'))
160 ['http://ichart.finance.yahoo.com/table.csv?s=CROX', 'd=9', 'e=22',
160 ['http://ichart.finance.yahoo.com/table.csv?s=CROX', 'd=9', 'e=22',
161
161
162 Testing directive outputs
162 Testing directive outputs
163 =========================
163 =========================
164
164
165 The IPython Sphinx Directive makes it possible to test the outputs that you provide with your code. To do this,
165 The IPython Sphinx Directive makes it possible to test the outputs that you provide with your code. To do this,
166 decorate the contents in your directive block with one of the options listed
166 decorate the contents in your directive block with one of the options listed
167 above.
167 above.
168
168
169 If an IPython doctest decorator is found, it will take these steps when your documentation is built:
169 If an IPython doctest decorator is found, it will take these steps when your documentation is built:
170
170
171 1. Run the *input* lines in your IPython directive block against the current Python kernel (remember that the session
171 1. Run the *input* lines in your IPython directive block against the current Python kernel (remember that the session
172 persists across IPython directive blocks);
172 persists across IPython directive blocks);
173
173
174 2. Compare the *output* of this with the output text that you've put in the IPython directive block (what comes
174 2. Compare the *output* of this with the output text that you've put in the IPython directive block (what comes
175 after `Out[NN]`);
175 after `Out[NN]`);
176
176
177 3. If there is a difference, the directive will raise an error and your documentation build will fail.
177 3. If there is a difference, the directive will raise an error and your documentation build will fail.
178
178
179 You can do doctesting on multi-line output as well. Just be careful
179 You can do doctesting on multi-line output as well. Just be careful
180 when using non-deterministic inputs like random numbers in the ipython
180 when using non-deterministic inputs like random numbers in the ipython
181 directive, because your inputs are run through a live interpreter, so
181 directive, because your inputs are run through a live interpreter, so
182 if you are doctesting random output you will get an error. Here we
182 if you are doctesting random output you will get an error. Here we
183 "seed" the random number generator for deterministic output, and we
183 "seed" the random number generator for deterministic output, and we
184 suppress the seed line so it doesn't show up in the rendered output
184 suppress the seed line so it doesn't show up in the rendered output
185
185
186 .. ipython::
186 .. ipython::
187
187
188 In [133]: import numpy.random
188 In [133]: import numpy.random
189
189
190 @suppress
190 @suppress
191 In [134]: numpy.random.seed(2358)
191 In [134]: numpy.random.seed(2358)
192
192
193 @doctest
193 @doctest
194 In [135]: numpy.random.rand(10,2)
194 In [135]: numpy.random.rand(10,2)
195 Out[135]:
195 Out[135]:
196 array([[0.64524308, 0.59943846],
196 array([[0.64524308, 0.59943846],
197 [0.47102322, 0.8715456 ],
197 [0.47102322, 0.8715456 ],
198 [0.29370834, 0.74776844],
198 [0.29370834, 0.74776844],
199 [0.99539577, 0.1313423 ],
199 [0.99539577, 0.1313423 ],
200 [0.16250302, 0.21103583],
200 [0.16250302, 0.21103583],
201 [0.81626524, 0.1312433 ],
201 [0.81626524, 0.1312433 ],
202 [0.67338089, 0.72302393],
202 [0.67338089, 0.72302393],
203 [0.7566368 , 0.07033696],
203 [0.7566368 , 0.07033696],
204 [0.22591016, 0.77731835],
204 [0.22591016, 0.77731835],
205 [0.0072729 , 0.34273127]])
205 [0.0072729 , 0.34273127]])
206
206
207 For more information on @supress and @doctest decorators, please refer to the end of this file in
207 For more information on @suppress and @doctest decorators, please refer to the end of this file in
208 Pseudo-Decorators section.
208 Pseudo-Decorators section.
209
209
210 Another demonstration of multi-line input and output
210 Another demonstration of multi-line input and output
211
211
212 .. ipython::
212 .. ipython::
213 :verbatim:
213 :verbatim:
214
214
215 In [106]: print(x)
215 In [106]: print(x)
216 jdh
216 jdh
217
217
218 In [109]: for i in range(10):
218 In [109]: for i in range(10):
219 .....: print(i)
219 .....: print(i)
220 .....:
220 .....:
221 .....:
221 .....:
222 0
222 0
223 1
223 1
224 2
224 2
225 3
225 3
226 4
226 4
227 5
227 5
228 6
228 6
229 7
229 7
230 8
230 8
231 9
231 9
232
232
233
233
234 Most of the "pseudo-decorators" can be used an options to ipython
234 Most of the "pseudo-decorators" can be used an options to ipython
235 mode. For example, to setup matplotlib pylab but suppress the output,
235 mode. For example, to setup matplotlib pylab but suppress the output,
236 you can do. When using the matplotlib ``use`` directive, it should
236 you can do. When using the matplotlib ``use`` directive, it should
237 occur before any import of pylab. This will not show up in the
237 occur before any import of pylab. This will not show up in the
238 rendered docs, but the commands will be executed in the embedded
238 rendered docs, but the commands will be executed in the embedded
239 interpreter and subsequent line numbers will be incremented to reflect
239 interpreter and subsequent line numbers will be incremented to reflect
240 the inputs::
240 the inputs::
241
241
242
242
243 .. ipython::
243 .. ipython::
244 :suppress:
244 :suppress:
245
245
246 In [144]: from matplotlib.pylab import *
246 In [144]: from matplotlib.pylab import *
247
247
248 In [145]: ion()
248 In [145]: ion()
249
249
250 .. ipython::
250 .. ipython::
251 :suppress:
251 :suppress:
252
252
253 In [144]: from matplotlib.pylab import *
253 In [144]: from matplotlib.pylab import *
254
254
255 In [145]: ion()
255 In [145]: ion()
256
256
257 Likewise, you can set ``:doctest:`` or ``:verbatim:`` to apply these
257 Likewise, you can set ``:doctest:`` or ``:verbatim:`` to apply these
258 settings to the entire block. For example,
258 settings to the entire block. For example,
259
259
260 .. ipython::
260 .. ipython::
261 :verbatim:
261 :verbatim:
262
262
263 In [9]: cd mpl/examples/
263 In [9]: cd mpl/examples/
264 /home/jdhunter/mpl/examples
264 /home/jdhunter/mpl/examples
265
265
266 In [10]: pwd
266 In [10]: pwd
267 Out[10]: '/home/jdhunter/mpl/examples'
267 Out[10]: '/home/jdhunter/mpl/examples'
268
268
269
269
270 In [14]: cd mpl/examples/<TAB>
270 In [14]: cd mpl/examples/<TAB>
271 mpl/examples/animation/ mpl/examples/misc/
271 mpl/examples/animation/ mpl/examples/misc/
272 mpl/examples/api/ mpl/examples/mplot3d/
272 mpl/examples/api/ mpl/examples/mplot3d/
273 mpl/examples/axes_grid/ mpl/examples/pylab_examples/
273 mpl/examples/axes_grid/ mpl/examples/pylab_examples/
274 mpl/examples/event_handling/ mpl/examples/widgets
274 mpl/examples/event_handling/ mpl/examples/widgets
275
275
276 In [14]: cd mpl/examples/widgets/
276 In [14]: cd mpl/examples/widgets/
277 /home/msierig/mpl/examples/widgets
277 /home/msierig/mpl/examples/widgets
278
278
279 In [15]: !wc *
279 In [15]: !wc *
280 2 12 77 README.txt
280 2 12 77 README.txt
281 40 97 884 buttons.py
281 40 97 884 buttons.py
282 26 90 712 check_buttons.py
282 26 90 712 check_buttons.py
283 19 52 416 cursor.py
283 19 52 416 cursor.py
284 180 404 4882 menu.py
284 180 404 4882 menu.py
285 16 45 337 multicursor.py
285 16 45 337 multicursor.py
286 36 106 916 radio_buttons.py
286 36 106 916 radio_buttons.py
287 48 226 2082 rectangle_selector.py
287 48 226 2082 rectangle_selector.py
288 43 118 1063 slider_demo.py
288 43 118 1063 slider_demo.py
289 40 124 1088 span_selector.py
289 40 124 1088 span_selector.py
290 450 1274 12457 total
290 450 1274 12457 total
291
291
292 You can create one or more pyplot plots and insert them with the
292 You can create one or more pyplot plots and insert them with the
293 ``@savefig`` decorator.
293 ``@savefig`` decorator.
294
294
295 For more information on @savefig decorator, please refer to the end of this page in Pseudo-Decorators section.
295 For more information on @savefig decorator, please refer to the end of this page in Pseudo-Decorators section.
296
296
297 .. ipython::
297 .. ipython::
298
298
299 @savefig plot_simple.png width=4in
299 @savefig plot_simple.png width=4in
300 In [151]: plot([1,2,3]);
300 In [151]: plot([1,2,3]);
301
301
302 # use a semicolon to suppress the output
302 # use a semicolon to suppress the output
303 @savefig hist_simple.png width=4in
303 @savefig hist_simple.png width=4in
304 In [151]: hist(np.random.randn(10000), 100);
304 In [151]: hist(np.random.randn(10000), 100);
305
305
306 In a subsequent session, we can update the current figure with some
306 In a subsequent session, we can update the current figure with some
307 text, and then resave
307 text, and then resave
308
308
309 .. ipython::
309 .. ipython::
310
310
311
311
312 In [151]: ylabel('number')
312 In [151]: ylabel('number')
313
313
314 In [152]: title('normal distribution')
314 In [152]: title('normal distribution')
315
315
316 @savefig hist_with_text.png width=4in
316 @savefig hist_with_text.png width=4in
317 In [153]: grid(True)
317 In [153]: grid(True)
318
318
319 You can also have function definitions included in the source.
319 You can also have function definitions included in the source.
320
320
321 .. ipython::
321 .. ipython::
322
322
323 In [3]: def square(x):
323 In [3]: def square(x):
324 ...: """
324 ...: """
325 ...: An overcomplicated square function as an example.
325 ...: An overcomplicated square function as an example.
326 ...: """
326 ...: """
327 ...: if x < 0:
327 ...: if x < 0:
328 ...: x = abs(x)
328 ...: x = abs(x)
329 ...: y = x * x
329 ...: y = x * x
330 ...: return y
330 ...: return y
331 ...:
331 ...:
332
332
333 Then call it from a subsequent section.
333 Then call it from a subsequent section.
334
334
335 .. ipython::
335 .. ipython::
336
336
337 In [4]: square(3)
337 In [4]: square(3)
338 Out [4]: 9
338 Out [4]: 9
339
339
340 In [5]: square(-2)
340 In [5]: square(-2)
341 Out [5]: 4
341 Out [5]: 4
342
342
343
343
344 Writing Pure Python Code
344 Writing Pure Python Code
345 ------------------------
345 ------------------------
346
346
347 Pure python code is supported by the optional argument `python`. In this pure
347 Pure python code is supported by the optional argument `python`. In this pure
348 python syntax you do not include the output from the python interpreter. The
348 python syntax you do not include the output from the python interpreter. The
349 following markup::
349 following markup::
350
350
351 .. ipython:: python
351 .. ipython:: python
352
352
353 foo = 'bar'
353 foo = 'bar'
354 print(foo)
354 print(foo)
355 foo = 2
355 foo = 2
356 foo**2
356 foo**2
357
357
358 Renders as
358 Renders as
359
359
360 .. ipython:: python
360 .. ipython:: python
361
361
362 foo = 'bar'
362 foo = 'bar'
363 print(foo)
363 print(foo)
364 foo = 2
364 foo = 2
365 foo**2
365 foo**2
366
366
367 We can even plot from python, using the savefig decorator, as well as, suppress
367 We can even plot from python, using the savefig decorator, as well as, suppress
368 output with a semicolon
368 output with a semicolon
369
369
370 .. ipython:: python
370 .. ipython:: python
371
371
372 @savefig plot_simple_python.png width=4in
372 @savefig plot_simple_python.png width=4in
373 plot([1,2,3]);
373 plot([1,2,3]);
374
374
375 For more information on @savefig decorator, please refer to the end of this page in Pseudo-Decorators section.
375 For more information on @savefig decorator, please refer to the end of this page in Pseudo-Decorators section.
376
376
377 Similarly, std err is inserted
377 Similarly, std err is inserted
378
378
379 .. ipython:: python
379 .. ipython:: python
380 :okexcept:
380 :okexcept:
381
381
382 foo = 'bar'
382 foo = 'bar'
383 foo[)
383 foo[)
384
384
385 Handling Comments
385 Handling Comments
386 ==================
386 ==================
387
387
388 Comments are handled and state is preserved
388 Comments are handled and state is preserved
389
389
390 .. ipython:: python
390 .. ipython:: python
391
391
392 # comments are handled
392 # comments are handled
393 print(foo)
393 print(foo)
394
394
395 If you don't see the next code block then the options work.
395 If you don't see the next code block then the options work.
396
396
397 .. ipython:: python
397 .. ipython:: python
398 :suppress:
398 :suppress:
399
399
400 ioff()
400 ioff()
401 ion()
401 ion()
402
402
403 Splitting Python statements across lines
403 Splitting Python statements across lines
404 ========================================
404 ========================================
405
405
406 Multi-line input is handled.
406 Multi-line input is handled.
407
407
408 .. ipython:: python
408 .. ipython:: python
409
409
410 line = 'Multi\
410 line = 'Multi\
411 line &\
411 line &\
412 support &\
412 support &\
413 works'
413 works'
414 print(line.split('&'))
414 print(line.split('&'))
415
415
416 Functions definitions are correctly parsed
416 Functions definitions are correctly parsed
417
417
418 .. ipython:: python
418 .. ipython:: python
419
419
420 def square(x):
420 def square(x):
421 """
421 """
422 An overcomplicated square function as an example.
422 An overcomplicated square function as an example.
423 """
423 """
424 if x < 0:
424 if x < 0:
425 x = abs(x)
425 x = abs(x)
426 y = x * x
426 y = x * x
427 return y
427 return y
428
428
429 And persist across sessions
429 And persist across sessions
430
430
431 .. ipython:: python
431 .. ipython:: python
432
432
433 print(square(3))
433 print(square(3))
434 print(square(-2))
434 print(square(-2))
435
435
436 Pretty much anything you can do with the ipython code, you can do with
436 Pretty much anything you can do with the ipython code, you can do with
437 a simple python script. Obviously, though it doesn't make sense
437 a simple python script. Obviously, though it doesn't make sense
438 to use the doctest option.
438 to use the doctest option.
439
439
440 .. _pseudo-decorators:
440 .. _pseudo-decorators:
441
441
442 Pseudo-Decorators
442 Pseudo-Decorators
443 =================
443 =================
444
444
445 Here are the supported decorators, and any optional arguments they
445 Here are the supported decorators, and any optional arguments they
446 take. Some of the decorators can be used as options to the entire
446 take. Some of the decorators can be used as options to the entire
447 block (eg ``verbatim`` and ``suppress``), and some only apply to the
447 block (eg ``verbatim`` and ``suppress``), and some only apply to the
448 line just below them (eg ``savefig``).
448 line just below them (eg ``savefig``).
449
449
450 @suppress
450 @suppress
451
451
452 execute the ipython input block, but suppress the input and output
452 execute the ipython input block, but suppress the input and output
453 block from the rendered output. Also, can be applied to the entire
453 block from the rendered output. Also, can be applied to the entire
454 ``.. ipython`` block as a directive option with ``:suppress:``.
454 ``.. ipython`` block as a directive option with ``:suppress:``.
455
455
456 @verbatim
456 @verbatim
457
457
458 insert the input and output block in verbatim, but auto-increment
458 insert the input and output block in verbatim, but auto-increment
459 the line numbers. Internally, the interpreter will be fed an empty
459 the line numbers. Internally, the interpreter will be fed an empty
460 string, so it is a no-op that keeps line numbering consistent.
460 string, so it is a no-op that keeps line numbering consistent.
461 Also, can be applied to the entire ``.. ipython`` block as a
461 Also, can be applied to the entire ``.. ipython`` block as a
462 directive option with ``:verbatim:``.
462 directive option with ``:verbatim:``.
463
463
464 @savefig OUTFILE [IMAGE_OPTIONS]
464 @savefig OUTFILE [IMAGE_OPTIONS]
465
465
466 save the figure to the static directory and insert it into the
466 save the figure to the static directory and insert it into the
467 document, possibly binding it into a minipage and/or putting
467 document, possibly binding it into a minipage and/or putting
468 code/figure label/references to associate the code and the
468 code/figure label/references to associate the code and the
469 figure. Takes args to pass to the image directive (*scale*,
469 figure. Takes args to pass to the image directive (*scale*,
470 *width*, etc can be kwargs); see `image options
470 *width*, etc can be kwargs); see `image options
471 <http://docutils.sourceforge.net/docs/ref/rst/directives.html#image>`_
471 <http://docutils.sourceforge.net/docs/ref/rst/directives.html#image>`_
472 for details.
472 for details.
473
473
474 @doctest
474 @doctest
475
475
476 Compare the pasted in output in the ipython block with the output
476 Compare the pasted in output in the ipython block with the output
477 generated at doc build time, and raise errors if they don't
477 generated at doc build time, and raise errors if they don't
478 match. Also, can be applied to the entire ``.. ipython`` block as a
478 match. Also, can be applied to the entire ``.. ipython`` block as a
479 directive option with ``:doctest:``.
479 directive option with ``:doctest:``.
480
480
481 Configuration Options
481 Configuration Options
482 =====================
482 =====================
483
483
484 ipython_savefig_dir
484 ipython_savefig_dir
485
485
486 The directory in which to save the figures. This is relative to the
486 The directory in which to save the figures. This is relative to the
487 Sphinx source directory. The default is `html_static_path`.
487 Sphinx source directory. The default is `html_static_path`.
488
488
489 ipython_rgxin
489 ipython_rgxin
490
490
491 The compiled regular expression to denote the start of IPython input
491 The compiled regular expression to denote the start of IPython input
492 lines. The default is `re.compile('In \[(\d+)\]:\s?(.*)\s*')`. You
492 lines. The default is `re.compile('In \[(\d+)\]:\s?(.*)\s*')`. You
493 shouldn't need to change this.
493 shouldn't need to change this.
494
494
495 ipython_rgxout
495 ipython_rgxout
496
496
497 The compiled regular expression to denote the start of IPython output
497 The compiled regular expression to denote the start of IPython output
498 lines. The default is `re.compile('Out\[(\d+)\]:\s?(.*)\s*')`. You
498 lines. The default is `re.compile('Out\[(\d+)\]:\s?(.*)\s*')`. You
499 shouldn't need to change this.
499 shouldn't need to change this.
500
500
501
501
502 ipython_promptin
502 ipython_promptin
503
503
504 The string to represent the IPython input prompt in the generated ReST.
504 The string to represent the IPython input prompt in the generated ReST.
505 The default is `'In [%d]:'`. This expects that the line numbers are used
505 The default is `'In [%d]:'`. This expects that the line numbers are used
506 in the prompt.
506 in the prompt.
507
507
508 ipython_promptout
508 ipython_promptout
509
509
510 The string to represent the IPython prompt in the generated ReST. The
510 The string to represent the IPython prompt in the generated ReST. The
511 default is `'Out [%d]:'`. This expects that the line numbers are used
511 default is `'Out [%d]:'`. This expects that the line numbers are used
512 in the prompt.
512 in the prompt.
513
513
514
514
515 Automatically generated documentation
515 Automatically generated documentation
516 =====================================
516 =====================================
517
517
518 .. automodule:: IPython.sphinxext.ipython_directive
518 .. automodule:: IPython.sphinxext.ipython_directive
519
519
@@ -1,251 +1,251 b''
1 # Simple tool to help for release
1 # Simple tool to help for release
2 # when releasing with bash, simple source it to get asked questions.
2 # when releasing with bash, simple source it to get asked questions.
3
3
4 # misc check before starting
4 # misc check before starting
5
5
6 python -c 'import keyring'
6 python -c 'import keyring'
7 python -c 'import twine'
7 python -c 'import twine'
8 python -c 'import sphinx'
8 python -c 'import sphinx'
9 python -c 'import sphinx_rtd_theme'
9 python -c 'import sphinx_rtd_theme'
10 python -c 'import pytest'
10 python -c 'import pytest'
11
11
12
12
13 BLACK=$(tput setaf 1)
13 BLACK=$(tput setaf 1)
14 RED=$(tput setaf 1)
14 RED=$(tput setaf 1)
15 GREEN=$(tput setaf 2)
15 GREEN=$(tput setaf 2)
16 YELLOW=$(tput setaf 3)
16 YELLOW=$(tput setaf 3)
17 BLUE=$(tput setaf 4)
17 BLUE=$(tput setaf 4)
18 MAGENTA=$(tput setaf 5)
18 MAGENTA=$(tput setaf 5)
19 CYAN=$(tput setaf 6)
19 CYAN=$(tput setaf 6)
20 WHITE=$(tput setaf 7)
20 WHITE=$(tput setaf 7)
21 NOR=$(tput sgr0)
21 NOR=$(tput sgr0)
22
22
23
23
24 echo "Will use $BLUE'$EDITOR'$NOR to edit files when necessary"
24 echo "Will use $BLUE'$EDITOR'$NOR to edit files when necessary"
25 echo -n "PREV_RELEASE (X.y.z) [$PREV_RELEASE]: "
25 echo -n "PREV_RELEASE (X.y.z) [$PREV_RELEASE]: "
26 read input
26 read input
27 PREV_RELEASE=${input:-$PREV_RELEASE}
27 PREV_RELEASE=${input:-$PREV_RELEASE}
28 echo -n "MILESTONE (X.y) [$MILESTONE]: "
28 echo -n "MILESTONE (X.y) [$MILESTONE]: "
29 read input
29 read input
30 MILESTONE=${input:-$MILESTONE}
30 MILESTONE=${input:-$MILESTONE}
31 echo -n "VERSION (X.y.z) [$VERSION]:"
31 echo -n "VERSION (X.y.z) [$VERSION]:"
32 read input
32 read input
33 VERSION=${input:-$VERSION}
33 VERSION=${input:-$VERSION}
34 echo -n "BRANCH (master|X.y) [$BRANCH]:"
34 echo -n "BRANCH (master|X.y) [$BRANCH]:"
35 read input
35 read input
36 BRANCH=${input:-$BRANCH}
36 BRANCH=${input:-$BRANCH}
37
37
38 ask_section(){
38 ask_section(){
39 echo
39 echo
40 echo $BLUE"$1"$NOR
40 echo $BLUE"$1"$NOR
41 echo -n $GREEN"Press Enter to continue, S to skip: "$NOR
41 echo -n $GREEN"Press Enter to continue, S to skip: "$NOR
42 if [ "$ZSH_NAME" = "zsh" ] ; then
42 if [ "$ZSH_NAME" = "zsh" ] ; then
43 read -k1 value
43 read -k1 value
44 value=${value%$'\n'}
44 value=${value%$'\n'}
45 else
45 else
46 read -n1 value
46 read -n1 value
47 fi
47 fi
48 if [ -z "$value" ] || [ $value = 'y' ]; then
48 if [ -z "$value" ] || [ $value = 'y' ]; then
49 return 0
49 return 0
50 fi
50 fi
51 return 1
51 return 1
52 }
52 }
53
53
54
54
55 maybe_edit(){
55 maybe_edit(){
56 echo
56 echo
57 echo $BLUE"$1"$NOR
57 echo $BLUE"$1"$NOR
58 echo -n $GREEN"Press ${BLUE}e$GREEN to Edit ${BLUE}$1$GREEN, any other keys to skip: "$NOR
58 echo -n $GREEN"Press ${BLUE}e$GREEN to Edit ${BLUE}$1$GREEN, any other keys to skip: "$NOR
59 if [ "$ZSH_NAME" = "zsh" ] ; then
59 if [ "$ZSH_NAME" = "zsh" ] ; then
60 read -k1 value
60 read -k1 value
61 value=${value%$'\n'}
61 value=${value%$'\n'}
62 else
62 else
63 read -n1 value
63 read -n1 value
64 fi
64 fi
65
65
66 echo
66 echo
67 if [ $value = 'e' ] ; then
67 if [ $value = 'e' ] ; then
68 $=EDITOR $1
68 $=EDITOR $1
69 fi
69 fi
70 }
70 }
71
71
72
72
73
73
74 echo
74 echo
75 if ask_section "Updating what's new with information from docs/source/whatsnew/pr"
75 if ask_section "Updating what's new with information from docs/source/whatsnew/pr"
76 then
76 then
77 python tools/update_whatsnew.py
77 python tools/update_whatsnew.py
78
78
79 echo
79 echo
80 echo $BLUE"please move the contents of "docs/source/whatsnew/development.rst" to version-X.rst"$NOR
80 echo $BLUE"please move the contents of "docs/source/whatsnew/development.rst" to version-X.rst"$NOR
81 echo $GREEN"Press enter to continue"$NOR
81 echo $GREEN"Press enter to continue"$NOR
82 read
82 read
83 fi
83 fi
84
84
85 if ask_section "Gen Stats, and authors"
85 if ask_section "Gen Stats, and authors"
86 then
86 then
87
87
88 echo
88 echo
89 echo $BLUE"here are all the authors that contributed to this release:"$NOR
89 echo $BLUE"here are all the authors that contributed to this release:"$NOR
90 git log --format="%aN <%aE>" $PREV_RELEASE... | sort -u -f
90 git log --format="%aN <%aE>" $PREV_RELEASE... | sort -u -f
91
91
92 echo
92 echo
93 echo $BLUE"If you see any duplicates cancel (Ctrl-C), then edit .mailmap."
93 echo $BLUE"If you see any duplicates cancel (Ctrl-C), then edit .mailmap."
94 echo $GREEN"Press enter to continue:"$NOR
94 echo $GREEN"Press enter to continue:"$NOR
95 read
95 read
96
96
97 echo $BLUE"generating stats"$NOR
97 echo $BLUE"generating stats"$NOR
98 python tools/github_stats.py --milestone $MILESTONE > stats.rst
98 python tools/github_stats.py --milestone $MILESTONE > stats.rst
99
99
100 echo $BLUE"stats.rst files generated."$NOR
100 echo $BLUE"stats.rst files generated."$NOR
101 echo $GREEN"Please merge it with the right file (github-stats-X.rst) and commit."$NOR
101 echo $GREEN"Please merge it with the right file (github-stats-X.rst) and commit."$NOR
102 echo $GREEN"press enter to continue."$NOR
102 echo $GREEN"press enter to continue."$NOR
103 read
103 read
104
104
105 fi
105 fi
106
106
107 if ask_section "Generate API difference (using frapuccino)"
107 if ask_section "Generate API difference (using frapuccino)"
108 then
108 then
109 echo $BLUE"Checking out $PREV_RELEASE"$NOR
109 echo $BLUE"Checking out $PREV_RELEASE"$NOR
110 git checkout $PREV_RELEASE
110 git checkout $PREV_RELEASE
111 sleep 1
111 sleep 1
112 echo $BLUE"Saving API to file $PREV_RELEASE"$NOR
112 echo $BLUE"Saving API to file $PREV_RELEASE"$NOR
113 frappuccino IPython IPython.kernel IPython.lib IPython.qt IPython.lib.kernel IPython.html IPython.frontend IPython.external --save IPython-$PREV_RELEASE.json
113 frappuccino IPython IPython.kernel IPython.lib IPython.qt IPython.lib.kernel IPython.html IPython.frontend IPython.external --save IPython-$PREV_RELEASE.json
114 echo $BLUE"comming back to $BRANCH"$NOR
114 echo $BLUE"coming back to $BRANCH"$NOR
115 git checkout $BRANCH
115 git checkout $BRANCH
116 sleep 1
116 sleep 1
117 echo $BLUE"comparing ..."$NOR
117 echo $BLUE"comparing ..."$NOR
118 frappuccino IPython IPython.kernel IPython.lib --compare IPython-$PREV_RELEASE.json
118 frappuccino IPython IPython.kernel IPython.lib --compare IPython-$PREV_RELEASE.json
119 echo $GREEN"Use the above guideline to write an API changelog ..."$NOR
119 echo $GREEN"Use the above guideline to write an API changelog ..."$NOR
120 echo $GREEN"Press any keys to continue"$NOR
120 echo $GREEN"Press any keys to continue"$NOR
121 read
121 read
122 fi
122 fi
123
123
124 echo "Cleaning repository"
124 echo "Cleaning repository"
125 git clean -xfdi
125 git clean -xfdi
126
126
127 echo $GREEN"please update version number in ${RED}IPython/core/release.py${NOR} , Do not commit yet – we'll do it later."$NOR
127 echo $GREEN"please update version number in ${RED}IPython/core/release.py${NOR} , Do not commit yet – we'll do it later."$NOR
128 echo $GREEN"I tried ${RED}sed -i bkp -e '/Uncomment/s/^# //g' IPython/core/release.py${NOR}"
128 echo $GREEN"I tried ${RED}sed -i bkp -e '/Uncomment/s/^# //g' IPython/core/release.py${NOR}"
129 sed -i bkp -e '/Uncomment/s/^# //g' IPython/core/release.py
129 sed -i bkp -e '/Uncomment/s/^# //g' IPython/core/release.py
130 rm IPython/core/release.pybkp
130 rm IPython/core/release.pybkp
131 git diff | cat
131 git diff | cat
132 maybe_edit IPython/core/release.py
132 maybe_edit IPython/core/release.py
133
133
134 echo $GREEN"Press enter to continue"$NOR
134 echo $GREEN"Press enter to continue"$NOR
135 read
135 read
136
136
137 if ask_section "Build the documentation ?"
137 if ask_section "Build the documentation ?"
138 then
138 then
139 make html -C docs
139 make html -C docs
140 echo
140 echo
141 echo $GREEN"Check the docs, press enter to continue"$NOR
141 echo $GREEN"Check the docs, press enter to continue"$NOR
142 read
142 read
143
143
144 fi
144 fi
145
145
146 if ask_section "Should we commit, tag, push... etc ? "
146 if ask_section "Should we commit, tag, push... etc ? "
147 then
147 then
148 echo
148 echo
149 echo $BLUE"Let's commit : git commit -am \"release $VERSION\" -S"
149 echo $BLUE"Let's commit : git commit -am \"release $VERSION\" -S"
150 echo $GREEN"Press enter to commit"$NOR
150 echo $GREEN"Press enter to commit"$NOR
151 read
151 read
152 git commit -am "release $VERSION" -S
152 git commit -am "release $VERSION" -S
153
153
154 echo
154 echo
155 echo $BLUE"git push origin \$BRANCH ($BRANCH)?"$NOR
155 echo $BLUE"git push origin \$BRANCH ($BRANCH)?"$NOR
156 echo $GREEN"Make sure you can push"$NOR
156 echo $GREEN"Make sure you can push"$NOR
157 echo $GREEN"Press enter to continue"$NOR
157 echo $GREEN"Press enter to continue"$NOR
158 read
158 read
159 git push origin $BRANCH
159 git push origin $BRANCH
160
160
161 echo
161 echo
162 echo "Let's tag : git tag -am \"release $VERSION\" \"$VERSION\" -s"
162 echo "Let's tag : git tag -am \"release $VERSION\" \"$VERSION\" -s"
163 echo $GREEN"Press enter to tag commit"$NOR
163 echo $GREEN"Press enter to tag commit"$NOR
164 read
164 read
165 git tag -am "release $VERSION" "$VERSION" -s
165 git tag -am "release $VERSION" "$VERSION" -s
166
166
167 echo
167 echo
168 echo $BLUE"And push the tag: git push origin \$VERSION ?"$NOR
168 echo $BLUE"And push the tag: git push origin \$VERSION ?"$NOR
169 echo $GREEN"Press enter to continue"$NOR
169 echo $GREEN"Press enter to continue"$NOR
170 read
170 read
171 git push origin $VERSION
171 git push origin $VERSION
172
172
173
173
174 echo $GREEN"please update version number and back to .dev in ${RED}IPython/core/release.py"
174 echo $GREEN"please update version number and back to .dev in ${RED}IPython/core/release.py"
175 echo $GREEN"I tried ${RED}sed -i bkp -e '/Uncomment/s/^/# /g' IPython/core/release.py${NOR}"
175 echo $GREEN"I tried ${RED}sed -i bkp -e '/Uncomment/s/^/# /g' IPython/core/release.py${NOR}"
176 sed -i bkp -e '/Uncomment/s/^/# /g' IPython/core/release.py
176 sed -i bkp -e '/Uncomment/s/^/# /g' IPython/core/release.py
177 rm IPython/core/release.pybkp
177 rm IPython/core/release.pybkp
178 git diff | cat
178 git diff | cat
179 echo $GREEN"Please bump ${RED}the minor version number${NOR}"
179 echo $GREEN"Please bump ${RED}the minor version number${NOR}"
180 maybe_edit IPython/core/release.py
180 maybe_edit IPython/core/release.py
181 echo ${BLUE}"Do not commit yet – we'll do it later."$NOR
181 echo ${BLUE}"Do not commit yet – we'll do it later."$NOR
182
182
183
183
184 echo $GREEN"Press enter to continue"$NOR
184 echo $GREEN"Press enter to continue"$NOR
185 read
185 read
186
186
187 echo
187 echo
188 echo "Let's commit : "$BLUE"git commit -am \"back to dev\""$NOR
188 echo "Let's commit : "$BLUE"git commit -am \"back to dev\""$NOR
189 echo $GREEN"Press enter to commit"$NOR
189 echo $GREEN"Press enter to commit"$NOR
190 read
190 read
191 git commit -am "back to dev"
191 git commit -am "back to dev"
192
192
193 echo
193 echo
194 echo $BLUE"git push origin \$BRANCH ($BRANCH)?"$NOR
194 echo $BLUE"git push origin \$BRANCH ($BRANCH)?"$NOR
195 echo $GREEN"Press enter to continue"$NOR
195 echo $GREEN"Press enter to continue"$NOR
196 read
196 read
197 git push origin $BRANCH
197 git push origin $BRANCH
198
198
199
199
200 echo
200 echo
201 echo $BLUE"let's : git checkout $VERSION"$NOR
201 echo $BLUE"let's : git checkout $VERSION"$NOR
202 echo $GREEN"Press enter to continue"$NOR
202 echo $GREEN"Press enter to continue"$NOR
203 read
203 read
204 git checkout $VERSION
204 git checkout $VERSION
205 fi
205 fi
206
206
207 if ask_section "Should we build and release ?"
207 if ask_section "Should we build and release ?"
208 then
208 then
209
209
210 echo $BLUE"going to set SOURCE_DATE_EPOCH"$NOR
210 echo $BLUE"going to set SOURCE_DATE_EPOCH"$NOR
211 echo $BLUE'export SOURCE_DATE_EPOCH=$(git show -s --format=%ct HEAD)'$NOR
211 echo $BLUE'export SOURCE_DATE_EPOCH=$(git show -s --format=%ct HEAD)'$NOR
212 echo $GREEN"Press enter to continue"$NOR
212 echo $GREEN"Press enter to continue"$NOR
213 read
213 read
214
214
215 export SOURCE_DATE_EPOCH=$(git show -s --format=%ct HEAD)
215 export SOURCE_DATE_EPOCH=$(git show -s --format=%ct HEAD)
216
216
217 echo $BLUE"SOURCE_DATE_EPOCH set to $SOURCE_DATE_EPOCH"$NOR
217 echo $BLUE"SOURCE_DATE_EPOCH set to $SOURCE_DATE_EPOCH"$NOR
218 echo $GREEN"Press enter to continue"$NOR
218 echo $GREEN"Press enter to continue"$NOR
219 read
219 read
220
220
221
221
222
222
223 echo
223 echo
224 echo $BLUE"Attempting to build package..."$NOR
224 echo $BLUE"Attempting to build package..."$NOR
225
225
226 tools/release
226 tools/release
227
227
228
228
229 echo $RED'$ shasum -a 256 dist/*'
229 echo $RED'$ shasum -a 256 dist/*'
230 shasum -a 256 dist/*
230 shasum -a 256 dist/*
231 echo $NOR
231 echo $NOR
232
232
233 echo $BLUE"We are going to rebuild, node the hash above, and compare them to the rebuild"$NOR
233 echo $BLUE"We are going to rebuild, node the hash above, and compare them to the rebuild"$NOR
234 echo $GREEN"Press enter to continue"$NOR
234 echo $GREEN"Press enter to continue"$NOR
235 read
235 read
236
236
237 echo
237 echo
238 echo $BLUE"Attempting to build package..."$NOR
238 echo $BLUE"Attempting to build package..."$NOR
239
239
240 tools/release
240 tools/release
241
241
242 echo $RED"Check the shasum for SOURCE_DATE_EPOCH=$SOURCE_DATE_EPOCH"
242 echo $RED"Check the shasum for SOURCE_DATE_EPOCH=$SOURCE_DATE_EPOCH"
243 echo $RED'$ shasum -a 256 dist/*'
243 echo $RED'$ shasum -a 256 dist/*'
244 shasum -a 256 dist/*
244 shasum -a 256 dist/*
245 echo $NOR
245 echo $NOR
246
246
247 if ask_section "upload packages ?"
247 if ask_section "upload packages ?"
248 then
248 then
249 tools/release upload
249 tools/release upload
250 fi
250 fi
251 fi
251 fi
General Comments 0
You need to be logged in to leave comments. Login now