macro.py 1.7 KB

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