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