Show More
@@ -1,59 +1,57 b'' | |||
|
1 | 1 | """Support for interactive macros in IPython""" |
|
2 | 2 | |
|
3 | 3 | #***************************************************************************** |
|
4 | 4 | # Copyright (C) 2001-2005 Fernando Perez <fperez@colorado.edu> |
|
5 | 5 | # |
|
6 | 6 | # Distributed under the terms of the BSD License. The full license is in |
|
7 | 7 | # the file COPYING, distributed as part of this software. |
|
8 | 8 | #***************************************************************************** |
|
9 | 9 | |
|
10 | 10 | import re |
|
11 | 11 | |
|
12 | 12 | from IPython.utils import py3compat |
|
13 | 13 | from IPython.utils.encoding import DEFAULT_ENCODING |
|
14 | 14 | |
|
15 | 15 | coding_declaration = re.compile(r"#\s*coding[:=]\s*([-\w.]+)") |
|
16 | 16 | |
|
17 | 17 | class Macro(object): |
|
18 | 18 | """Simple class to store the value of macros as strings. |
|
19 | 19 | |
|
20 | 20 | Macro is just a callable that executes a string of IPython |
|
21 | 21 | input when called. |
|
22 | ||
|
23 | Args to macro are available in _margv list if you need them. | |
|
24 | 22 | """ |
|
25 | 23 | |
|
26 | 24 | def __init__(self,code): |
|
27 | 25 | """store the macro value, as a single string which can be executed""" |
|
28 | 26 | lines = [] |
|
29 | 27 | enc = None |
|
30 | 28 | for line in code.splitlines(): |
|
31 | 29 | coding_match = coding_declaration.match(line) |
|
32 | 30 | if coding_match: |
|
33 | 31 | enc = coding_match.group(1) |
|
34 | 32 | else: |
|
35 | 33 | lines.append(line) |
|
36 | 34 | code = "\n".join(lines) |
|
37 | 35 | if isinstance(code, bytes): |
|
38 | 36 | code = code.decode(enc or DEFAULT_ENCODING) |
|
39 | 37 | self.value = code + '\n' |
|
40 | 38 | |
|
41 | 39 | def __str__(self): |
|
42 | 40 | return py3compat.unicode_to_str(self.value) |
|
43 | 41 | |
|
44 | 42 | def __unicode__(self): |
|
45 | 43 | return self.value |
|
46 | 44 | |
|
47 | 45 | def __repr__(self): |
|
48 | 46 | return 'IPython.macro.Macro(%s)' % repr(self.value) |
|
49 | 47 | |
|
50 | 48 | def __getstate__(self): |
|
51 | 49 | """ needed for safe pickling via %store """ |
|
52 | 50 | return {'value': self.value} |
|
53 | 51 | |
|
54 | 52 | def __add__(self, other): |
|
55 | 53 | if isinstance(other, Macro): |
|
56 | 54 | return Macro(self.value + other.value) |
|
57 | 55 | elif isinstance(other, basestring): |
|
58 | 56 | return Macro(self.value + other) |
|
59 | 57 | raise TypeError |
General Comments 0
You need to be logged in to leave comments.
Login now