zzdummy.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. """Example extension, also used for testing.
  2. See extend.txt for more details on creating an extension.
  3. See config-extension.def for configuring an extension.
  4. """
  5. from idlelib.config import idleConf
  6. from functools import wraps
  7. def format_selection(format_line):
  8. "Apply a formatting function to all of the selected lines."
  9. @wraps(format_line)
  10. def apply(self, event=None):
  11. head, tail, chars, lines = self.formatter.get_region()
  12. for pos in range(len(lines) - 1):
  13. line = lines[pos]
  14. lines[pos] = format_line(self, line)
  15. self.formatter.set_region(head, tail, chars, lines)
  16. return 'break'
  17. return apply
  18. class ZzDummy:
  19. """Prepend or remove initial text from selected lines."""
  20. # Extend the format menu.
  21. menudefs = [
  22. ('format', [
  23. ('Z in', '<<z-in>>'),
  24. ('Z out', '<<z-out>>'),
  25. ] )
  26. ]
  27. def __init__(self, editwin):
  28. "Initialize the settings for this extension."
  29. self.editwin = editwin
  30. self.text = editwin.text
  31. self.formatter = editwin.fregion
  32. @classmethod
  33. def reload(cls):
  34. "Load class variables from config."
  35. cls.ztext = idleConf.GetOption('extensions', 'ZzDummy', 'z-text')
  36. @format_selection
  37. def z_in_event(self, line):
  38. """Insert text at the beginning of each selected line.
  39. This is bound to the <<z-in>> virtual event when the extensions
  40. are loaded.
  41. """
  42. return f'{self.ztext}{line}'
  43. @format_selection
  44. def z_out_event(self, line):
  45. """Remove specific text from the beginning of each selected line.
  46. This is bound to the <<z-out>> virtual event when the extensions
  47. are loaded.
  48. """
  49. zlength = 0 if not line.startswith(self.ztext) else len(self.ztext)
  50. return line[zlength:]
  51. ZzDummy.reload()
  52. if __name__ == "__main__":
  53. import unittest
  54. unittest.main('idlelib.idle_test.test_zzdummy', verbosity=2, exit=False)