| 1 |
"""Example extension, also used for testing. |
| 2 |
|
| 3 |
See extend.txt for more details on creating an extension. |
| 4 |
See config-extension.def for configuring an extension. |
| 5 |
""" |
| 6 |
|
| 7 |
from idlelib.config import idleConf |
| 8 |
from functools import wraps |
| 9 |
|
| 10 |
|
| 11 |
def 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 |
| 24 |
|
| 25 |
|
| 26 |
class ZzDummy: |
| 27 |
"""Prepend or remove initial text from selected lines.""" |
| 28 |
|
| 29 |
# Extend the format menu. |
| 30 |
menudefs = [ |
| 31 |
('format', [ |
| 32 |
('Z in', '<<z-in>>'), |
| 33 |
('Z out', '<<z-out>>'), |
| 34 |
] ) |
| 35 |
] |
| 36 |
|
| 37 |
def __init__(self, editwin): |
| 38 |
"Initialize the settings for this extension." |
| 39 |
self.editwin = editwin |
| 40 |
self.text = editwin.text |
| 41 |
self.formatter = editwin.fregion |
| 42 |
|
| 43 |
@classmethod |
| 44 |
def reload(cls): |
| 45 |
"Load class variables from config." |
| 46 |
cls.ztext = idleConf.GetOption('extensions', 'ZzDummy', 'z-text') |
| 47 |
|
| 48 |
@format_selection |
| 49 |
def z_in_event(self, line): |
| 50 |
"""Insert text at the beginning of each selected line. |
| 51 |
|
| 52 |
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 |
|
| 67 |
|
| 68 |
ZzDummy.reload() |
| 69 |
|
| 70 |
|
| 71 |
if __name__ == "__main__": |
| 72 |
import unittest |
| 73 |
unittest.main('idlelib.idle_test.test_zzdummy', verbosity=2, exit=False) |