-
Notifications
You must be signed in to change notification settings - Fork 0
/
plugin_trim_file.py
48 lines (40 loc) · 1.53 KB
/
plugin_trim_file.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
from sublime import Region
from sublime_plugin import TextCommand, EventListener
class TrimFileCommand(TextCommand):
"""
Remove leading and trailing whitespace from a file.
Run on save based on _trim_file_on_save setting.
"""
def run(self, edit, bof=True, eof=True):
view = self.view
if bof:
reg = view.find("\A\s*", 0)
view.replace(edit, reg, "")
if eof:
# reimplement ensure_newline_at_eof_on_save as it fires before on_pre_save
# also taking care of bug when cursor is at eof and \n ends up selected
reg = view.find("\s*\Z", 0)
settings = view.settings()
eof_newline = settings.get("_ensure_newline_at_eof_on_save")
if eof_newline:
view.replace(edit, reg, "\n")
s = view.size()
n = Region(s - 1, s)
selection = view.sel()
if selection.contains(n):
selection.subtract(n)
selection.add(Region(s))
else:
view.replace(edit, reg, "")
class TrimFileListener(EventListener):
def on_pre_save(self, view):
settings = view.settings()
eof_newline = settings.get("ensure_newline_at_eof_on_save")
if eof_newline is None:
eof_newline = settings.get("_ensure_newline_at_eof_on_save")
else:
settings.set("ensure_newline_at_eof_on_save", None)
settings.set("_ensure_newline_at_eof_on_save", eof_newline)
trim = settings.get("_trim_file_on_save")
if trim:
view.run_command("trim_file")