Raymond Hettinger | eb81695 | 2009-05-29 01:22:18 +0000 | [diff] [blame] | 1 | 'Provides "Strip trailing whitespace" under the "Format" menu.' |
| 2 | |
Raymond Hettinger | eb81695 | 2009-05-29 01:22:18 +0000 | [diff] [blame] | 3 | class RstripExtension: |
| 4 | |
| 5 | menudefs = [ |
Terry Jan Reedy | 4f133e2 | 2013-07-13 02:34:43 -0400 | [diff] [blame^] | 6 | ('format', [None, ('Strip trailing whitespace', '<<do-rstrip>>'), ] ), ] |
Raymond Hettinger | eb81695 | 2009-05-29 01:22:18 +0000 | [diff] [blame] | 7 | |
| 8 | def __init__(self, editwin): |
| 9 | self.editwin = editwin |
| 10 | self.editwin.text.bind("<<do-rstrip>>", self.do_rstrip) |
| 11 | |
| 12 | def do_rstrip(self, event=None): |
| 13 | |
| 14 | text = self.editwin.text |
| 15 | undo = self.editwin.undo |
| 16 | |
| 17 | undo.undo_block_start() |
| 18 | |
Terry Jan Reedy | 4f133e2 | 2013-07-13 02:34:43 -0400 | [diff] [blame^] | 19 | end_line = int(float(text.index('end'))) |
Raymond Hettinger | eb81695 | 2009-05-29 01:22:18 +0000 | [diff] [blame] | 20 | for cur in range(1, end_line): |
Terry Jan Reedy | 4f133e2 | 2013-07-13 02:34:43 -0400 | [diff] [blame^] | 21 | txt = text.get('%i.0' % cur, '%i.end' % cur) |
| 22 | raw = len(txt) |
Raymond Hettinger | eb81695 | 2009-05-29 01:22:18 +0000 | [diff] [blame] | 23 | cut = len(txt.rstrip()) |
Terry Jan Reedy | 4f133e2 | 2013-07-13 02:34:43 -0400 | [diff] [blame^] | 24 | # Since text.delete() marks file as changed, even if not, |
| 25 | # only call it when needed to actually delete something. |
| 26 | if cut < raw: |
| 27 | text.delete('%i.%i' % (cur, cut), '%i.end' % cur) |
Raymond Hettinger | eb81695 | 2009-05-29 01:22:18 +0000 | [diff] [blame] | 28 | |
| 29 | undo.undo_block_stop() |
Terry Jan Reedy | 4f133e2 | 2013-07-13 02:34:43 -0400 | [diff] [blame^] | 30 | |
| 31 | if __name__ == "__main__": |
| 32 | import unittest |
| 33 | unittest.main('idlelib.idle_test.test_rstrip', verbosity=2, exit=False) |