##// END OF EJS Templates
Allow adding macros.
Thomas Kluyver -
Show More
@@ -1,53 +1,60 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 import sys
12 12
13 13 import IPython.utils.io
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 22
23 23 Args to macro are available in _margv list if you need them.
24 24 """
25 25
26 26 def __init__(self,code):
27 27 """store the macro value, as a single string which can be executed"""
28 28 lines = []
29 29 enc = None
30 30 for line in code.splitlines():
31 31 coding_match = coding_declaration.match(line)
32 32 if coding_match:
33 33 enc = coding_match.group(1)
34 34 else:
35 35 lines.append(line)
36 36 code = "\n".join(lines)
37 37 if isinstance(code, bytes):
38 38 code = code.decode(enc or sys.getdefaultencoding())
39 39 self.value = code + '\n'
40 40
41 41 def __str__(self):
42 42 enc = sys.stdin.encoding or sys.getdefaultencoding()
43 43 return self.value.encode(enc, "replace")
44 44
45 45 def __unicode__(self):
46 46 return self.value
47 47
48 48 def __repr__(self):
49 49 return 'IPython.macro.Macro(%s)' % repr(self.value)
50 50
51 51 def __getstate__(self):
52 52 """ needed for safe pickling via %store """
53 53 return {'value': self.value}
54
55 def __add__(self, other):
56 if isinstance(other, Macro):
57 return Macro(self.value + other.value)
58 elif isinstance(other, basestring):
59 return Macro(self.value + other)
60 raise TypeError
General Comments 0
You need to be logged in to leave comments. Login now