Show More
@@ -1,755 +1,756 | |||
|
1 | 1 | # encoding: utf-8 |
|
2 | 2 | """Magic functions for InteractiveShell. |
|
3 | 3 | """ |
|
4 | 4 | |
|
5 | 5 | #----------------------------------------------------------------------------- |
|
6 | 6 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
7 | 7 | # Copyright (C) 2001 Fernando Perez <fperez@colorado.edu> |
|
8 | 8 | # Copyright (C) 2008 The IPython Development Team |
|
9 | 9 | |
|
10 | 10 | # Distributed under the terms of the BSD License. The full license is in |
|
11 | 11 | # the file COPYING, distributed as part of this software. |
|
12 | 12 | #----------------------------------------------------------------------------- |
|
13 | 13 | |
|
14 | 14 | import os |
|
15 | 15 | import re |
|
16 | 16 | import sys |
|
17 | 17 | from getopt import getopt, GetoptError |
|
18 | 18 | |
|
19 | 19 | from traitlets.config.configurable import Configurable |
|
20 | 20 | from . import oinspect |
|
21 | 21 | from .error import UsageError |
|
22 | 22 | from .inputtransformer2 import ESC_MAGIC, ESC_MAGIC2 |
|
23 | 23 | from ..utils.ipstruct import Struct |
|
24 | 24 | from ..utils.process import arg_split |
|
25 | 25 | from ..utils.text import dedent |
|
26 | 26 | from traitlets import Bool, Dict, Instance, observe |
|
27 | 27 | from logging import error |
|
28 | 28 | |
|
29 | 29 | #----------------------------------------------------------------------------- |
|
30 | 30 | # Globals |
|
31 | 31 | #----------------------------------------------------------------------------- |
|
32 | 32 | |
|
33 | 33 | # A dict we'll use for each class that has magics, used as temporary storage to |
|
34 | 34 | # pass information between the @line/cell_magic method decorators and the |
|
35 | 35 | # @magics_class class decorator, because the method decorators have no |
|
36 | 36 | # access to the class when they run. See for more details: |
|
37 | 37 | # http://stackoverflow.com/questions/2366713/can-a-python-decorator-of-an-instance-method-access-the-class |
|
38 | 38 | |
|
39 | 39 | magics = dict(line={}, cell={}) |
|
40 | 40 | |
|
41 | 41 | magic_kinds = ('line', 'cell') |
|
42 | 42 | magic_spec = ('line', 'cell', 'line_cell') |
|
43 | 43 | magic_escapes = dict(line=ESC_MAGIC, cell=ESC_MAGIC2) |
|
44 | 44 | |
|
45 | 45 | #----------------------------------------------------------------------------- |
|
46 | 46 | # Utility classes and functions |
|
47 | 47 | #----------------------------------------------------------------------------- |
|
48 | 48 | |
|
49 | 49 | class Bunch: pass |
|
50 | 50 | |
|
51 | 51 | |
|
52 | 52 | def on_off(tag): |
|
53 | 53 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" |
|
54 | 54 | return ['OFF','ON'][tag] |
|
55 | 55 | |
|
56 | 56 | |
|
57 | 57 | def compress_dhist(dh): |
|
58 | 58 | """Compress a directory history into a new one with at most 20 entries. |
|
59 | 59 | |
|
60 | 60 | Return a new list made from the first and last 10 elements of dhist after |
|
61 | 61 | removal of duplicates. |
|
62 | 62 | """ |
|
63 | 63 | head, tail = dh[:-10], dh[-10:] |
|
64 | 64 | |
|
65 | 65 | newhead = [] |
|
66 | 66 | done = set() |
|
67 | 67 | for h in head: |
|
68 | 68 | if h in done: |
|
69 | 69 | continue |
|
70 | 70 | newhead.append(h) |
|
71 | 71 | done.add(h) |
|
72 | 72 | |
|
73 | 73 | return newhead + tail |
|
74 | 74 | |
|
75 | 75 | |
|
76 | 76 | def needs_local_scope(func): |
|
77 | 77 | """Decorator to mark magic functions which need to local scope to run.""" |
|
78 | 78 | func.needs_local_scope = True |
|
79 | 79 | return func |
|
80 | 80 | |
|
81 | 81 | #----------------------------------------------------------------------------- |
|
82 | 82 | # Class and method decorators for registering magics |
|
83 | 83 | #----------------------------------------------------------------------------- |
|
84 | 84 | |
|
85 | 85 | def magics_class(cls): |
|
86 | 86 | """Class decorator for all subclasses of the main Magics class. |
|
87 | 87 | |
|
88 | 88 | Any class that subclasses Magics *must* also apply this decorator, to |
|
89 | 89 | ensure that all the methods that have been decorated as line/cell magics |
|
90 | 90 | get correctly registered in the class instance. This is necessary because |
|
91 | 91 | when method decorators run, the class does not exist yet, so they |
|
92 | 92 | temporarily store their information into a module global. Application of |
|
93 | 93 | this class decorator copies that global data to the class instance and |
|
94 | 94 | clears the global. |
|
95 | 95 | |
|
96 | 96 | Obviously, this mechanism is not thread-safe, which means that the |
|
97 | 97 | *creation* of subclasses of Magic should only be done in a single-thread |
|
98 | 98 | context. Instantiation of the classes has no restrictions. Given that |
|
99 | 99 | these classes are typically created at IPython startup time and before user |
|
100 | 100 | application code becomes active, in practice this should not pose any |
|
101 | 101 | problems. |
|
102 | 102 | """ |
|
103 | 103 | cls.registered = True |
|
104 | 104 | cls.magics = dict(line = magics['line'], |
|
105 | 105 | cell = magics['cell']) |
|
106 | 106 | magics['line'] = {} |
|
107 | 107 | magics['cell'] = {} |
|
108 | 108 | return cls |
|
109 | 109 | |
|
110 | 110 | |
|
111 | 111 | def record_magic(dct, magic_kind, magic_name, func): |
|
112 | 112 | """Utility function to store a function as a magic of a specific kind. |
|
113 | 113 | |
|
114 | 114 | Parameters |
|
115 | 115 | ---------- |
|
116 | 116 | dct : dict |
|
117 | 117 | A dictionary with 'line' and 'cell' subdicts. |
|
118 | 118 | magic_kind : str |
|
119 | 119 | Kind of magic to be stored. |
|
120 | 120 | magic_name : str |
|
121 | 121 | Key to store the magic as. |
|
122 | 122 | func : function |
|
123 | 123 | Callable object to store. |
|
124 | 124 | """ |
|
125 | 125 | if magic_kind == 'line_cell': |
|
126 | 126 | dct['line'][magic_name] = dct['cell'][magic_name] = func |
|
127 | 127 | else: |
|
128 | 128 | dct[magic_kind][magic_name] = func |
|
129 | 129 | |
|
130 | 130 | |
|
131 | 131 | def validate_type(magic_kind): |
|
132 | 132 | """Ensure that the given magic_kind is valid. |
|
133 | 133 | |
|
134 | 134 | Check that the given magic_kind is one of the accepted spec types (stored |
|
135 | 135 | in the global `magic_spec`), raise ValueError otherwise. |
|
136 | 136 | """ |
|
137 | 137 | if magic_kind not in magic_spec: |
|
138 | 138 | raise ValueError('magic_kind must be one of %s, %s given' % |
|
139 | 139 | magic_kinds, magic_kind) |
|
140 | 140 | |
|
141 | 141 | |
|
142 | 142 | # The docstrings for the decorator below will be fairly similar for the two |
|
143 | 143 | # types (method and function), so we generate them here once and reuse the |
|
144 | 144 | # templates below. |
|
145 | 145 | _docstring_template = \ |
|
146 | 146 | """Decorate the given {0} as {1} magic. |
|
147 | 147 | |
|
148 | 148 | The decorator can be used with or without arguments, as follows. |
|
149 | 149 | |
|
150 | 150 | i) without arguments: it will create a {1} magic named as the {0} being |
|
151 | 151 | decorated:: |
|
152 | 152 | |
|
153 | 153 | @deco |
|
154 | 154 | def foo(...) |
|
155 | 155 | |
|
156 | 156 | will create a {1} magic named `foo`. |
|
157 | 157 | |
|
158 | 158 | ii) with one string argument: which will be used as the actual name of the |
|
159 | 159 | resulting magic:: |
|
160 | 160 | |
|
161 | 161 | @deco('bar') |
|
162 | 162 | def foo(...) |
|
163 | 163 | |
|
164 | 164 | will create a {1} magic named `bar`. |
|
165 | 165 | |
|
166 | 166 | To register a class magic use ``Interactiveshell.register_magic(class or instance)``. |
|
167 | 167 | """ |
|
168 | 168 | |
|
169 | 169 | # These two are decorator factories. While they are conceptually very similar, |
|
170 | 170 | # there are enough differences in the details that it's simpler to have them |
|
171 | 171 | # written as completely standalone functions rather than trying to share code |
|
172 | 172 | # and make a single one with convoluted logic. |
|
173 | 173 | |
|
174 | 174 | def _method_magic_marker(magic_kind): |
|
175 | 175 | """Decorator factory for methods in Magics subclasses. |
|
176 | 176 | """ |
|
177 | 177 | |
|
178 | 178 | validate_type(magic_kind) |
|
179 | 179 | |
|
180 | 180 | # This is a closure to capture the magic_kind. We could also use a class, |
|
181 | 181 | # but it's overkill for just that one bit of state. |
|
182 | 182 | def magic_deco(arg): |
|
183 | 183 | if callable(arg): |
|
184 | 184 | # "Naked" decorator call (just @foo, no args) |
|
185 | 185 | func = arg |
|
186 | 186 | name = func.__name__ |
|
187 | 187 | retval = arg |
|
188 | 188 | record_magic(magics, magic_kind, name, name) |
|
189 | 189 | elif isinstance(arg, str): |
|
190 | 190 | # Decorator called with arguments (@foo('bar')) |
|
191 | 191 | name = arg |
|
192 | 192 | def mark(func, *a, **kw): |
|
193 | 193 | record_magic(magics, magic_kind, name, func.__name__) |
|
194 | 194 | return func |
|
195 | 195 | retval = mark |
|
196 | 196 | else: |
|
197 | 197 | raise TypeError("Decorator can only be called with " |
|
198 | 198 | "string or function") |
|
199 | 199 | return retval |
|
200 | 200 | |
|
201 | 201 | # Ensure the resulting decorator has a usable docstring |
|
202 | 202 | magic_deco.__doc__ = _docstring_template.format('method', magic_kind) |
|
203 | 203 | return magic_deco |
|
204 | 204 | |
|
205 | 205 | |
|
206 | 206 | def _function_magic_marker(magic_kind): |
|
207 | 207 | """Decorator factory for standalone functions. |
|
208 | 208 | """ |
|
209 | 209 | validate_type(magic_kind) |
|
210 | 210 | |
|
211 | 211 | # This is a closure to capture the magic_kind. We could also use a class, |
|
212 | 212 | # but it's overkill for just that one bit of state. |
|
213 | 213 | def magic_deco(arg): |
|
214 | 214 | # Find get_ipython() in the caller's namespace |
|
215 | 215 | caller = sys._getframe(1) |
|
216 | 216 | for ns in ['f_locals', 'f_globals', 'f_builtins']: |
|
217 | 217 | get_ipython = getattr(caller, ns).get('get_ipython') |
|
218 | 218 | if get_ipython is not None: |
|
219 | 219 | break |
|
220 | 220 | else: |
|
221 | 221 | raise NameError('Decorator can only run in context where ' |
|
222 | 222 | '`get_ipython` exists') |
|
223 | 223 | |
|
224 | 224 | ip = get_ipython() |
|
225 | 225 | |
|
226 | 226 | if callable(arg): |
|
227 | 227 | # "Naked" decorator call (just @foo, no args) |
|
228 | 228 | func = arg |
|
229 | 229 | name = func.__name__ |
|
230 | 230 | ip.register_magic_function(func, magic_kind, name) |
|
231 | 231 | retval = arg |
|
232 | 232 | elif isinstance(arg, str): |
|
233 | 233 | # Decorator called with arguments (@foo('bar')) |
|
234 | 234 | name = arg |
|
235 | 235 | def mark(func, *a, **kw): |
|
236 | 236 | ip.register_magic_function(func, magic_kind, name) |
|
237 | 237 | return func |
|
238 | 238 | retval = mark |
|
239 | 239 | else: |
|
240 | 240 | raise TypeError("Decorator can only be called with " |
|
241 | 241 | "string or function") |
|
242 | 242 | return retval |
|
243 | 243 | |
|
244 | 244 | # Ensure the resulting decorator has a usable docstring |
|
245 | 245 | ds = _docstring_template.format('function', magic_kind) |
|
246 | 246 | |
|
247 | 247 | ds += dedent(""" |
|
248 | 248 | Note: this decorator can only be used in a context where IPython is already |
|
249 | 249 | active, so that the `get_ipython()` call succeeds. You can therefore use |
|
250 | 250 | it in your startup files loaded after IPython initializes, but *not* in the |
|
251 | 251 | IPython configuration file itself, which is executed before IPython is |
|
252 | 252 | fully up and running. Any file located in the `startup` subdirectory of |
|
253 | 253 | your configuration profile will be OK in this sense. |
|
254 | 254 | """) |
|
255 | 255 | |
|
256 | 256 | magic_deco.__doc__ = ds |
|
257 | 257 | return magic_deco |
|
258 | 258 | |
|
259 | 259 | |
|
260 | 260 | MAGIC_NO_VAR_EXPAND_ATTR = '_ipython_magic_no_var_expand' |
|
261 | 261 | MAGIC_OUTPUT_CAN_BE_DISABLED = '_ipython_magic_output_can_be_disabled' |
|
262 | 262 | |
|
263 | 263 | def no_var_expand(magic_func): |
|
264 | 264 | """Mark a magic function as not needing variable expansion |
|
265 | 265 | |
|
266 | 266 | By default, IPython interprets `{a}` or `$a` in the line passed to magics |
|
267 | 267 | as variables that should be interpolated from the interactive namespace |
|
268 | 268 | before passing the line to the magic function. |
|
269 | 269 | This is not always desirable, e.g. when the magic executes Python code |
|
270 | 270 | (%timeit, %time, etc.). |
|
271 | 271 | Decorate magics with `@no_var_expand` to opt-out of variable expansion. |
|
272 | 272 | |
|
273 | 273 | .. versionadded:: 7.3 |
|
274 | 274 | """ |
|
275 | 275 | setattr(magic_func, MAGIC_NO_VAR_EXPAND_ATTR, True) |
|
276 | 276 | return magic_func |
|
277 | 277 | |
|
278 | ||
|
278 | 279 | def output_can_be_disabled(magic_func): |
|
279 | 280 | """Mark a magic function so its output may be disabled. |
|
280 | 281 | |
|
281 | 282 | The output is disabled if the Python expression used as a parameter of |
|
282 | 283 | the magic ends in a semicolon, not counting a Python comment that can |
|
283 | 284 | follows it. |
|
284 | 285 | """ |
|
285 | 286 | setattr(magic_func, MAGIC_OUTPUT_CAN_BE_DISABLED, True) |
|
286 | 287 | return magic_func |
|
287 | 288 | |
|
288 | 289 | # Create the actual decorators for public use |
|
289 | 290 | |
|
290 | 291 | # These three are used to decorate methods in class definitions |
|
291 | 292 | line_magic = _method_magic_marker('line') |
|
292 | 293 | cell_magic = _method_magic_marker('cell') |
|
293 | 294 | line_cell_magic = _method_magic_marker('line_cell') |
|
294 | 295 | |
|
295 | 296 | # These three decorate standalone functions and perform the decoration |
|
296 | 297 | # immediately. They can only run where get_ipython() works |
|
297 | 298 | register_line_magic = _function_magic_marker('line') |
|
298 | 299 | register_cell_magic = _function_magic_marker('cell') |
|
299 | 300 | register_line_cell_magic = _function_magic_marker('line_cell') |
|
300 | 301 | |
|
301 | 302 | #----------------------------------------------------------------------------- |
|
302 | 303 | # Core Magic classes |
|
303 | 304 | #----------------------------------------------------------------------------- |
|
304 | 305 | |
|
305 | 306 | class MagicsManager(Configurable): |
|
306 | 307 | """Object that handles all magic-related functionality for IPython. |
|
307 | 308 | """ |
|
308 | 309 | # Non-configurable class attributes |
|
309 | 310 | |
|
310 | 311 | # A two-level dict, first keyed by magic type, then by magic function, and |
|
311 | 312 | # holding the actual callable object as value. This is the dict used for |
|
312 | 313 | # magic function dispatch |
|
313 | 314 | magics = Dict() |
|
314 | 315 | lazy_magics = Dict( |
|
315 | 316 | help=""" |
|
316 | 317 | Mapping from magic names to modules to load. |
|
317 | 318 | |
|
318 | 319 | This can be used in IPython/IPykernel configuration to declare lazy magics |
|
319 | 320 | that will only be imported/registered on first use. |
|
320 | 321 | |
|
321 | 322 | For example:: |
|
322 | 323 | |
|
323 | 324 | c.MagicsManager.lazy_magics = { |
|
324 | 325 | "my_magic": "slow.to.import", |
|
325 | 326 | "my_other_magic": "also.slow", |
|
326 | 327 | } |
|
327 | 328 | |
|
328 | 329 | On first invocation of `%my_magic`, `%%my_magic`, `%%my_other_magic` or |
|
329 | 330 | `%%my_other_magic`, the corresponding module will be loaded as an ipython |
|
330 | 331 | extensions as if you had previously done `%load_ext ipython`. |
|
331 | 332 | |
|
332 | 333 | Magics names should be without percent(s) as magics can be both cell |
|
333 | 334 | and line magics. |
|
334 | 335 | |
|
335 | 336 | Lazy loading happen relatively late in execution process, and |
|
336 | 337 | complex extensions that manipulate Python/IPython internal state or global state |
|
337 | 338 | might not support lazy loading. |
|
338 | 339 | """ |
|
339 | 340 | ).tag( |
|
340 | 341 | config=True, |
|
341 | 342 | ) |
|
342 | 343 | |
|
343 | 344 | # A registry of the original objects that we've been given holding magics. |
|
344 | 345 | registry = Dict() |
|
345 | 346 | |
|
346 | 347 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True) |
|
347 | 348 | |
|
348 | 349 | auto_magic = Bool(True, help= |
|
349 | 350 | "Automatically call line magics without requiring explicit % prefix" |
|
350 | 351 | ).tag(config=True) |
|
351 | 352 | @observe('auto_magic') |
|
352 | 353 | def _auto_magic_changed(self, change): |
|
353 | 354 | self.shell.automagic = change['new'] |
|
354 | 355 | |
|
355 | 356 | _auto_status = [ |
|
356 | 357 | 'Automagic is OFF, % prefix IS needed for line magics.', |
|
357 | 358 | 'Automagic is ON, % prefix IS NOT needed for line magics.'] |
|
358 | 359 | |
|
359 | 360 | user_magics = Instance('IPython.core.magics.UserMagics', allow_none=True) |
|
360 | 361 | |
|
361 | 362 | def __init__(self, shell=None, config=None, user_magics=None, **traits): |
|
362 | 363 | |
|
363 | 364 | super(MagicsManager, self).__init__(shell=shell, config=config, |
|
364 | 365 | user_magics=user_magics, **traits) |
|
365 | 366 | self.magics = dict(line={}, cell={}) |
|
366 | 367 | # Let's add the user_magics to the registry for uniformity, so *all* |
|
367 | 368 | # registered magic containers can be found there. |
|
368 | 369 | self.registry[user_magics.__class__.__name__] = user_magics |
|
369 | 370 | |
|
370 | 371 | def auto_status(self): |
|
371 | 372 | """Return descriptive string with automagic status.""" |
|
372 | 373 | return self._auto_status[self.auto_magic] |
|
373 | 374 | |
|
374 | 375 | def lsmagic(self): |
|
375 | 376 | """Return a dict of currently available magic functions. |
|
376 | 377 | |
|
377 | 378 | The return dict has the keys 'line' and 'cell', corresponding to the |
|
378 | 379 | two types of magics we support. Each value is a list of names. |
|
379 | 380 | """ |
|
380 | 381 | return self.magics |
|
381 | 382 | |
|
382 | 383 | def lsmagic_docs(self, brief=False, missing=''): |
|
383 | 384 | """Return dict of documentation of magic functions. |
|
384 | 385 | |
|
385 | 386 | The return dict has the keys 'line' and 'cell', corresponding to the |
|
386 | 387 | two types of magics we support. Each value is a dict keyed by magic |
|
387 | 388 | name whose value is the function docstring. If a docstring is |
|
388 | 389 | unavailable, the value of `missing` is used instead. |
|
389 | 390 | |
|
390 | 391 | If brief is True, only the first line of each docstring will be returned. |
|
391 | 392 | """ |
|
392 | 393 | docs = {} |
|
393 | 394 | for m_type in self.magics: |
|
394 | 395 | m_docs = {} |
|
395 | 396 | for m_name, m_func in self.magics[m_type].items(): |
|
396 | 397 | if m_func.__doc__: |
|
397 | 398 | if brief: |
|
398 | 399 | m_docs[m_name] = m_func.__doc__.split('\n', 1)[0] |
|
399 | 400 | else: |
|
400 | 401 | m_docs[m_name] = m_func.__doc__.rstrip() |
|
401 | 402 | else: |
|
402 | 403 | m_docs[m_name] = missing |
|
403 | 404 | docs[m_type] = m_docs |
|
404 | 405 | return docs |
|
405 | 406 | |
|
406 | 407 | def register_lazy(self, name: str, fully_qualified_name: str): |
|
407 | 408 | """ |
|
408 | 409 | Lazily register a magic via an extension. |
|
409 | 410 | |
|
410 | 411 | |
|
411 | 412 | Parameters |
|
412 | 413 | ---------- |
|
413 | 414 | name : str |
|
414 | 415 | Name of the magic you wish to register. |
|
415 | 416 | fully_qualified_name : |
|
416 | 417 | Fully qualified name of the module/submodule that should be loaded |
|
417 | 418 | as an extensions when the magic is first called. |
|
418 | 419 | It is assumed that loading this extensions will register the given |
|
419 | 420 | magic. |
|
420 | 421 | """ |
|
421 | 422 | |
|
422 | 423 | self.lazy_magics[name] = fully_qualified_name |
|
423 | 424 | |
|
424 | 425 | def register(self, *magic_objects): |
|
425 | 426 | """Register one or more instances of Magics. |
|
426 | 427 | |
|
427 | 428 | Take one or more classes or instances of classes that subclass the main |
|
428 | 429 | `core.Magic` class, and register them with IPython to use the magic |
|
429 | 430 | functions they provide. The registration process will then ensure that |
|
430 | 431 | any methods that have decorated to provide line and/or cell magics will |
|
431 | 432 | be recognized with the `%x`/`%%x` syntax as a line/cell magic |
|
432 | 433 | respectively. |
|
433 | 434 | |
|
434 | 435 | If classes are given, they will be instantiated with the default |
|
435 | 436 | constructor. If your classes need a custom constructor, you should |
|
436 | 437 | instanitate them first and pass the instance. |
|
437 | 438 | |
|
438 | 439 | The provided arguments can be an arbitrary mix of classes and instances. |
|
439 | 440 | |
|
440 | 441 | Parameters |
|
441 | 442 | ---------- |
|
442 | 443 | *magic_objects : one or more classes or instances |
|
443 | 444 | """ |
|
444 | 445 | # Start by validating them to ensure they have all had their magic |
|
445 | 446 | # methods registered at the instance level |
|
446 | 447 | for m in magic_objects: |
|
447 | 448 | if not m.registered: |
|
448 | 449 | raise ValueError("Class of magics %r was constructed without " |
|
449 | 450 | "the @register_magics class decorator") |
|
450 | 451 | if isinstance(m, type): |
|
451 | 452 | # If we're given an uninstantiated class |
|
452 | 453 | m = m(shell=self.shell) |
|
453 | 454 | |
|
454 | 455 | # Now that we have an instance, we can register it and update the |
|
455 | 456 | # table of callables |
|
456 | 457 | self.registry[m.__class__.__name__] = m |
|
457 | 458 | for mtype in magic_kinds: |
|
458 | 459 | self.magics[mtype].update(m.magics[mtype]) |
|
459 | 460 | |
|
460 | 461 | def register_function(self, func, magic_kind='line', magic_name=None): |
|
461 | 462 | """Expose a standalone function as magic function for IPython. |
|
462 | 463 | |
|
463 | 464 | This will create an IPython magic (line, cell or both) from a |
|
464 | 465 | standalone function. The functions should have the following |
|
465 | 466 | signatures: |
|
466 | 467 | |
|
467 | 468 | * For line magics: `def f(line)` |
|
468 | 469 | * For cell magics: `def f(line, cell)` |
|
469 | 470 | * For a function that does both: `def f(line, cell=None)` |
|
470 | 471 | |
|
471 | 472 | In the latter case, the function will be called with `cell==None` when |
|
472 | 473 | invoked as `%f`, and with cell as a string when invoked as `%%f`. |
|
473 | 474 | |
|
474 | 475 | Parameters |
|
475 | 476 | ---------- |
|
476 | 477 | func : callable |
|
477 | 478 | Function to be registered as a magic. |
|
478 | 479 | magic_kind : str |
|
479 | 480 | Kind of magic, one of 'line', 'cell' or 'line_cell' |
|
480 | 481 | magic_name : optional str |
|
481 | 482 | If given, the name the magic will have in the IPython namespace. By |
|
482 | 483 | default, the name of the function itself is used. |
|
483 | 484 | """ |
|
484 | 485 | |
|
485 | 486 | # Create the new method in the user_magics and register it in the |
|
486 | 487 | # global table |
|
487 | 488 | validate_type(magic_kind) |
|
488 | 489 | magic_name = func.__name__ if magic_name is None else magic_name |
|
489 | 490 | setattr(self.user_magics, magic_name, func) |
|
490 | 491 | record_magic(self.magics, magic_kind, magic_name, func) |
|
491 | 492 | |
|
492 | 493 | def register_alias(self, alias_name, magic_name, magic_kind='line', magic_params=None): |
|
493 | 494 | """Register an alias to a magic function. |
|
494 | 495 | |
|
495 | 496 | The alias is an instance of :class:`MagicAlias`, which holds the |
|
496 | 497 | name and kind of the magic it should call. Binding is done at |
|
497 | 498 | call time, so if the underlying magic function is changed the alias |
|
498 | 499 | will call the new function. |
|
499 | 500 | |
|
500 | 501 | Parameters |
|
501 | 502 | ---------- |
|
502 | 503 | alias_name : str |
|
503 | 504 | The name of the magic to be registered. |
|
504 | 505 | magic_name : str |
|
505 | 506 | The name of an existing magic. |
|
506 | 507 | magic_kind : str |
|
507 | 508 | Kind of magic, one of 'line' or 'cell' |
|
508 | 509 | """ |
|
509 | 510 | |
|
510 | 511 | # `validate_type` is too permissive, as it allows 'line_cell' |
|
511 | 512 | # which we do not handle. |
|
512 | 513 | if magic_kind not in magic_kinds: |
|
513 | 514 | raise ValueError('magic_kind must be one of %s, %s given' % |
|
514 | 515 | magic_kinds, magic_kind) |
|
515 | 516 | |
|
516 | 517 | alias = MagicAlias(self.shell, magic_name, magic_kind, magic_params) |
|
517 | 518 | setattr(self.user_magics, alias_name, alias) |
|
518 | 519 | record_magic(self.magics, magic_kind, alias_name, alias) |
|
519 | 520 | |
|
520 | 521 | # Key base class that provides the central functionality for magics. |
|
521 | 522 | |
|
522 | 523 | |
|
523 | 524 | class Magics(Configurable): |
|
524 | 525 | """Base class for implementing magic functions. |
|
525 | 526 | |
|
526 | 527 | Shell functions which can be reached as %function_name. All magic |
|
527 | 528 | functions should accept a string, which they can parse for their own |
|
528 | 529 | needs. This can make some functions easier to type, eg `%cd ../` |
|
529 | 530 | vs. `%cd("../")` |
|
530 | 531 | |
|
531 | 532 | Classes providing magic functions need to subclass this class, and they |
|
532 | 533 | MUST: |
|
533 | 534 | |
|
534 | 535 | - Use the method decorators `@line_magic` and `@cell_magic` to decorate |
|
535 | 536 | individual methods as magic functions, AND |
|
536 | 537 | |
|
537 | 538 | - Use the class decorator `@magics_class` to ensure that the magic |
|
538 | 539 | methods are properly registered at the instance level upon instance |
|
539 | 540 | initialization. |
|
540 | 541 | |
|
541 | 542 | See :mod:`magic_functions` for examples of actual implementation classes. |
|
542 | 543 | """ |
|
543 | 544 | # Dict holding all command-line options for each magic. |
|
544 | 545 | options_table = None |
|
545 | 546 | # Dict for the mapping of magic names to methods, set by class decorator |
|
546 | 547 | magics = None |
|
547 | 548 | # Flag to check that the class decorator was properly applied |
|
548 | 549 | registered = False |
|
549 | 550 | # Instance of IPython shell |
|
550 | 551 | shell = None |
|
551 | 552 | |
|
552 | 553 | def __init__(self, shell=None, **kwargs): |
|
553 | 554 | if not(self.__class__.registered): |
|
554 | 555 | raise ValueError('Magics subclass without registration - ' |
|
555 | 556 | 'did you forget to apply @magics_class?') |
|
556 | 557 | if shell is not None: |
|
557 | 558 | if hasattr(shell, 'configurables'): |
|
558 | 559 | shell.configurables.append(self) |
|
559 | 560 | if hasattr(shell, 'config'): |
|
560 | 561 | kwargs.setdefault('parent', shell) |
|
561 | 562 | |
|
562 | 563 | self.shell = shell |
|
563 | 564 | self.options_table = {} |
|
564 | 565 | # The method decorators are run when the instance doesn't exist yet, so |
|
565 | 566 | # they can only record the names of the methods they are supposed to |
|
566 | 567 | # grab. Only now, that the instance exists, can we create the proper |
|
567 | 568 | # mapping to bound methods. So we read the info off the original names |
|
568 | 569 | # table and replace each method name by the actual bound method. |
|
569 | 570 | # But we mustn't clobber the *class* mapping, in case of multiple instances. |
|
570 | 571 | class_magics = self.magics |
|
571 | 572 | self.magics = {} |
|
572 | 573 | for mtype in magic_kinds: |
|
573 | 574 | tab = self.magics[mtype] = {} |
|
574 | 575 | cls_tab = class_magics[mtype] |
|
575 | 576 | for magic_name, meth_name in cls_tab.items(): |
|
576 | 577 | if isinstance(meth_name, str): |
|
577 | 578 | # it's a method name, grab it |
|
578 | 579 | tab[magic_name] = getattr(self, meth_name) |
|
579 | 580 | else: |
|
580 | 581 | # it's the real thing |
|
581 | 582 | tab[magic_name] = meth_name |
|
582 | 583 | # Configurable **needs** to be initiated at the end or the config |
|
583 | 584 | # magics get screwed up. |
|
584 | 585 | super(Magics, self).__init__(**kwargs) |
|
585 | 586 | |
|
586 | 587 | def arg_err(self,func): |
|
587 | 588 | """Print docstring if incorrect arguments were passed""" |
|
588 | 589 | print('Error in arguments:') |
|
589 | 590 | print(oinspect.getdoc(func)) |
|
590 | 591 | |
|
591 | 592 | def format_latex(self, strng): |
|
592 | 593 | """Format a string for latex inclusion.""" |
|
593 | 594 | |
|
594 | 595 | # Characters that need to be escaped for latex: |
|
595 | 596 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) |
|
596 | 597 | # Magic command names as headers: |
|
597 | 598 | cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC, |
|
598 | 599 | re.MULTILINE) |
|
599 | 600 | # Magic commands |
|
600 | 601 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC, |
|
601 | 602 | re.MULTILINE) |
|
602 | 603 | # Paragraph continue |
|
603 | 604 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
604 | 605 | |
|
605 | 606 | # The "\n" symbol |
|
606 | 607 | newline_re = re.compile(r'\\n') |
|
607 | 608 | |
|
608 | 609 | # Now build the string for output: |
|
609 | 610 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) |
|
610 | 611 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', |
|
611 | 612 | strng) |
|
612 | 613 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) |
|
613 | 614 | strng = par_re.sub(r'\\\\',strng) |
|
614 | 615 | strng = escape_re.sub(r'\\\1',strng) |
|
615 | 616 | strng = newline_re.sub(r'\\textbackslash{}n',strng) |
|
616 | 617 | return strng |
|
617 | 618 | |
|
618 | 619 | def parse_options(self, arg_str, opt_str, *long_opts, **kw): |
|
619 | 620 | """Parse options passed to an argument string. |
|
620 | 621 | |
|
621 | 622 | The interface is similar to that of :func:`getopt.getopt`, but it |
|
622 | 623 | returns a :class:`~IPython.utils.struct.Struct` with the options as keys |
|
623 | 624 | and the stripped argument string still as a string. |
|
624 | 625 | |
|
625 | 626 | arg_str is quoted as a true sys.argv vector by using shlex.split. |
|
626 | 627 | This allows us to easily expand variables, glob files, quote |
|
627 | 628 | arguments, etc. |
|
628 | 629 | |
|
629 | 630 | Parameters |
|
630 | 631 | ---------- |
|
631 | 632 | arg_str : str |
|
632 | 633 | The arguments to parse. |
|
633 | 634 | opt_str : str |
|
634 | 635 | The options specification. |
|
635 | 636 | mode : str, default 'string' |
|
636 | 637 | If given as 'list', the argument string is returned as a list (split |
|
637 | 638 | on whitespace) instead of a string. |
|
638 | 639 | list_all : bool, default False |
|
639 | 640 | Put all option values in lists. Normally only options |
|
640 | 641 | appearing more than once are put in a list. |
|
641 | 642 | posix : bool, default True |
|
642 | 643 | Whether to split the input line in POSIX mode or not, as per the |
|
643 | 644 | conventions outlined in the :mod:`shlex` module from the standard |
|
644 | 645 | library. |
|
645 | 646 | """ |
|
646 | 647 | |
|
647 | 648 | # inject default options at the beginning of the input line |
|
648 | 649 | caller = sys._getframe(1).f_code.co_name |
|
649 | 650 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) |
|
650 | 651 | |
|
651 | 652 | mode = kw.get('mode','string') |
|
652 | 653 | if mode not in ['string','list']: |
|
653 | 654 | raise ValueError('incorrect mode given: %s' % mode) |
|
654 | 655 | # Get options |
|
655 | 656 | list_all = kw.get('list_all',0) |
|
656 | 657 | posix = kw.get('posix', os.name == 'posix') |
|
657 | 658 | strict = kw.get('strict', True) |
|
658 | 659 | |
|
659 | 660 | preserve_non_opts = kw.get("preserve_non_opts", False) |
|
660 | 661 | remainder_arg_str = arg_str |
|
661 | 662 | |
|
662 | 663 | # Check if we have more than one argument to warrant extra processing: |
|
663 | 664 | odict = {} # Dictionary with options |
|
664 | 665 | args = arg_str.split() |
|
665 | 666 | if len(args) >= 1: |
|
666 | 667 | # If the list of inputs only has 0 or 1 thing in it, there's no |
|
667 | 668 | # need to look for options |
|
668 | 669 | argv = arg_split(arg_str, posix, strict) |
|
669 | 670 | # Do regular option processing |
|
670 | 671 | try: |
|
671 | 672 | opts,args = getopt(argv, opt_str, long_opts) |
|
672 | 673 | except GetoptError as e: |
|
673 | 674 | raise UsageError( |
|
674 | 675 | '%s ( allowed: "%s" %s)' % (e.msg, opt_str, " ".join(long_opts)) |
|
675 | 676 | ) from e |
|
676 | 677 | for o, a in opts: |
|
677 | 678 | if mode == "string" and preserve_non_opts: |
|
678 | 679 | # remove option-parts from the original args-string and preserve remaining-part. |
|
679 | 680 | # This relies on the arg_split(...) and getopt(...)'s impl spec, that the parsed options are |
|
680 | 681 | # returned in the original order. |
|
681 | 682 | remainder_arg_str = remainder_arg_str.replace(o, "", 1).replace( |
|
682 | 683 | a, "", 1 |
|
683 | 684 | ) |
|
684 | 685 | if o.startswith("--"): |
|
685 | 686 | o = o[2:] |
|
686 | 687 | else: |
|
687 | 688 | o = o[1:] |
|
688 | 689 | try: |
|
689 | 690 | odict[o].append(a) |
|
690 | 691 | except AttributeError: |
|
691 | 692 | odict[o] = [odict[o],a] |
|
692 | 693 | except KeyError: |
|
693 | 694 | if list_all: |
|
694 | 695 | odict[o] = [a] |
|
695 | 696 | else: |
|
696 | 697 | odict[o] = a |
|
697 | 698 | |
|
698 | 699 | # Prepare opts,args for return |
|
699 | 700 | opts = Struct(odict) |
|
700 | 701 | if mode == 'string': |
|
701 | 702 | if preserve_non_opts: |
|
702 | 703 | args = remainder_arg_str.lstrip() |
|
703 | 704 | else: |
|
704 | 705 | args = " ".join(args) |
|
705 | 706 | |
|
706 | 707 | return opts,args |
|
707 | 708 | |
|
708 | 709 | def default_option(self, fn, optstr): |
|
709 | 710 | """Make an entry in the options_table for fn, with value optstr""" |
|
710 | 711 | |
|
711 | 712 | if fn not in self.lsmagic(): |
|
712 | 713 | error("%s is not a magic function" % fn) |
|
713 | 714 | self.options_table[fn] = optstr |
|
714 | 715 | |
|
715 | 716 | |
|
716 | 717 | class MagicAlias(object): |
|
717 | 718 | """An alias to another magic function. |
|
718 | 719 | |
|
719 | 720 | An alias is determined by its magic name and magic kind. Lookup |
|
720 | 721 | is done at call time, so if the underlying magic changes the alias |
|
721 | 722 | will call the new function. |
|
722 | 723 | |
|
723 | 724 | Use the :meth:`MagicsManager.register_alias` method or the |
|
724 | 725 | `%alias_magic` magic function to create and register a new alias. |
|
725 | 726 | """ |
|
726 | 727 | def __init__(self, shell, magic_name, magic_kind, magic_params=None): |
|
727 | 728 | self.shell = shell |
|
728 | 729 | self.magic_name = magic_name |
|
729 | 730 | self.magic_params = magic_params |
|
730 | 731 | self.magic_kind = magic_kind |
|
731 | 732 | |
|
732 | 733 | self.pretty_target = '%s%s' % (magic_escapes[self.magic_kind], self.magic_name) |
|
733 | 734 | self.__doc__ = "Alias for `%s`." % self.pretty_target |
|
734 | 735 | |
|
735 | 736 | self._in_call = False |
|
736 | 737 | |
|
737 | 738 | def __call__(self, *args, **kwargs): |
|
738 | 739 | """Call the magic alias.""" |
|
739 | 740 | fn = self.shell.find_magic(self.magic_name, self.magic_kind) |
|
740 | 741 | if fn is None: |
|
741 | 742 | raise UsageError("Magic `%s` not found." % self.pretty_target) |
|
742 | 743 | |
|
743 | 744 | # Protect against infinite recursion. |
|
744 | 745 | if self._in_call: |
|
745 | 746 | raise UsageError("Infinite recursion detected; " |
|
746 | 747 | "magic aliases cannot call themselves.") |
|
747 | 748 | self._in_call = True |
|
748 | 749 | try: |
|
749 | 750 | if self.magic_params: |
|
750 | 751 | args_list = list(args) |
|
751 | 752 | args_list[0] = self.magic_params + " " + args[0] |
|
752 | 753 | args = tuple(args_list) |
|
753 | 754 | return fn(*args, **kwargs) |
|
754 | 755 | finally: |
|
755 | 756 | self._in_call = False |
General Comments 0
You need to be logged in to leave comments.
Login now