|
| 1 | +''' |
| 2 | +Provides both a trailing spaces highlighter and a deletion command. |
| 3 | +
|
| 4 | +Config summary (see README.md for details): |
| 5 | +
|
| 6 | + # key binding |
| 7 | + { "keys": ["ctrl+shift+t"], "command": "delete_trailing_spaces" } |
| 8 | +
|
| 9 | + # file settings |
| 10 | + { |
| 11 | + "trailing_spaces_highlight_color": "invalid", |
| 12 | + "trailing_spaces_file_max_size": 1000 |
| 13 | + } |
| 14 | +
|
| 15 | +@author: Jean-Denis Vauguet <[email protected]>, Oktay Acikalin <[email protected]> |
| 16 | +@license: MIT (http://www.opensource.org/licenses/mit-license.php) |
| 17 | +@since: 2011-02-25 |
| 18 | +''' |
| 19 | + |
| 20 | +import sublime, sublime_plugin |
| 21 | + |
| 22 | +DEFAULT_MAX_FILE_SIZE = 1048576 |
| 23 | +DEFAULT_COLOR_SCOPE_NAME = "invalid" |
| 24 | + |
| 25 | +# Return an array of regions matching trailing spaces. |
| 26 | +def find_trailing_spaces(view): |
| 27 | + trails = view.find_all('[ \t]+$') |
| 28 | + regions = [] |
| 29 | + for trail in trails: |
| 30 | + regions.append(trail) |
| 31 | + return regions |
| 32 | + |
| 33 | +# Highlight matching regions. |
| 34 | +class TrailingSpacesHighlightListener(sublime_plugin.EventListener): |
| 35 | + def on_modified(self, view): |
| 36 | + max_size = view.settings().get('trailing_spaces_file_max_size', |
| 37 | + DEFAULT_MAX_FILE_SIZE) |
| 38 | + color_scope_name = view.settings().get('trailing_spaces_highlight_color', |
| 39 | + DEFAULT_COLOR_SCOPE_NAME) |
| 40 | + if view.size() <= max_size: |
| 41 | + regions = find_trailing_spaces(view) |
| 42 | + view.add_regions('TrailingSpacesHighlightListener', |
| 43 | + regions, color_scope_name, |
| 44 | + sublime.DRAW_EMPTY) |
| 45 | + |
| 46 | +# Allows to erase matching regions. |
| 47 | +class DeleteTrailingSpacesCommand(sublime_plugin.TextCommand): |
| 48 | + def run(self, edit): |
| 49 | + regions = find_trailing_spaces(self.view) |
| 50 | + |
| 51 | + if regions: |
| 52 | + # deleting a region changes the other regions positions, so we |
| 53 | + # handle this maintaining an offset |
| 54 | + offset = 0 |
| 55 | + for region in regions: |
| 56 | + r = sublime.Region(region.a + offset, region.b + offset) |
| 57 | + self.view.erase(edit, sublime.Region(r.a, r.b)) |
| 58 | + offset -= r.size() |
| 59 | + |
| 60 | + msg_parts = {"nbRegions": len(regions), |
| 61 | + "plural": 's' if len(regions) > 1 else ''} |
| 62 | + msg = "Deleted %(nbRegions)s trailing spaces region%(plural)s" % msg_parts |
| 63 | + else: |
| 64 | + msg = "No trailing spaces to delete!" |
| 65 | + |
| 66 | + sublime.status_message(msg) |
0 commit comments