macro.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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 import py3compat
  10. from IPython.utils.encoding import DEFAULT_ENCODING
  11. coding_declaration = re.compile(r"#\s*coding[:=]\s*([-\w.]+)")
  12. class Macro(object):
  13. """Simple class to store the value of macros as strings.
  14. Macro is just a callable that executes a string of IPython
  15. input when called.
  16. """
  17. def __init__(self,code):
  18. """store the macro value, as a single string which can be executed"""
  19. lines = []
  20. enc = None
  21. for line in code.splitlines():
  22. coding_match = coding_declaration.match(line)
  23. if coding_match:
  24. enc = coding_match.group(1)
  25. else:
  26. lines.append(line)
  27. code = "\n".join(lines)
  28. if isinstance(code, bytes):
  29. code = code.decode(enc or DEFAULT_ENCODING)
  30. self.value = code + '\n'
  31. def __str__(self):
  32. return py3compat.unicode_to_str(self.value)
  33. def __unicode__(self):
  34. return self.value
  35. def __repr__(self):
  36. return 'IPython.macro.Macro(%s)' % repr(self.value)
  37. def __getstate__(self):
  38. """ needed for safe pickling via %store """
  39. return {'value': self.value}
  40. def __add__(self, other):
  41. if isinstance(other, Macro):
  42. return Macro(self.value + other.value)
  43. elif isinstance(other, py3compat.string_types):
  44. return Macro(self.value + other)
  45. raise TypeError