blob: 1247e8f1cc052860b173e9959deaf134d4b6906a [file] [log] [blame]
Cheryl Sabellae40e2a22021-01-05 02:26:43 -05001"""Example extension, also used for testing.
2
3See extend.txt for more details on creating an extension.
4See config-extension.def for configuring an extension.
5"""
wohlganger58fc71c2017-09-10 16:19:47 -05006
7from idlelib.config import idleConf
Cheryl Sabellae40e2a22021-01-05 02:26:43 -05008from functools import wraps
wohlganger58fc71c2017-09-10 16:19:47 -05009
Cheryl Sabellae40e2a22021-01-05 02:26:43 -050010
11def format_selection(format_line):
12 "Apply a formatting function to all of the selected lines."
13
14 @wraps(format_line)
15 def apply(self, event=None):
16 head, tail, chars, lines = self.formatter.get_region()
17 for pos in range(len(lines) - 1):
18 line = lines[pos]
19 lines[pos] = format_line(self, line)
20 self.formatter.set_region(head, tail, chars, lines)
21 return 'break'
22
23 return apply
wohlganger58fc71c2017-09-10 16:19:47 -050024
25
26class ZzDummy:
Cheryl Sabellae40e2a22021-01-05 02:26:43 -050027 """Prepend or remove initial text from selected lines."""
wohlganger58fc71c2017-09-10 16:19:47 -050028
Cheryl Sabellae40e2a22021-01-05 02:26:43 -050029 # Extend the format menu.
30 menudefs = [
31 ('format', [
32 ('Z in', '<<z-in>>'),
33 ('Z out', '<<z-out>>'),
34 ] )
35 ]
wohlganger58fc71c2017-09-10 16:19:47 -050036
37 def __init__(self, editwin):
Cheryl Sabellae40e2a22021-01-05 02:26:43 -050038 "Initialize the settings for this extension."
39 self.editwin = editwin
wohlganger58fc71c2017-09-10 16:19:47 -050040 self.text = editwin.text
Cheryl Sabellae40e2a22021-01-05 02:26:43 -050041 self.formatter = editwin.fregion
wohlganger58fc71c2017-09-10 16:19:47 -050042
43 @classmethod
44 def reload(cls):
Cheryl Sabellae40e2a22021-01-05 02:26:43 -050045 "Load class variables from config."
wohlganger58fc71c2017-09-10 16:19:47 -050046 cls.ztext = idleConf.GetOption('extensions', 'ZzDummy', 'z-text')
47
Cheryl Sabellae40e2a22021-01-05 02:26:43 -050048 @format_selection
49 def z_in_event(self, line):
50 """Insert text at the beginning of each selected line.
wohlganger58fc71c2017-09-10 16:19:47 -050051
Cheryl Sabellae40e2a22021-01-05 02:26:43 -050052 This is bound to the <<z-in>> virtual event when the extensions
53 are loaded.
54 """
55 return f'{self.ztext}{line}'
56
57 @format_selection
58 def z_out_event(self, line):
59 """Remove specific text from the beginning of each selected line.
60
61 This is bound to the <<z-out>> virtual event when the extensions
62 are loaded.
63 """
64 zlength = 0 if not line.startswith(self.ztext) else len(self.ztext)
65 return line[zlength:]
66
wohlganger58fc71c2017-09-10 16:19:47 -050067
68ZzDummy.reload()
69
Cheryl Sabellae40e2a22021-01-05 02:26:43 -050070
71if __name__ == "__main__":
72 import unittest
73 unittest.main('idlelib.idle_test.test_zzdummy', verbosity=2, exit=False)