-
Notifications
You must be signed in to change notification settings - Fork 7
/
LuaFormat.py
executable file
·68 lines (51 loc) · 1.95 KB
/
LuaFormat.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import sublime
import sublime_plugin
import sys
def reload(name):
rubbish_pool = []
for key in sys.modules:
if name in key:
rubbish_pool.append(key)
for key in rubbish_pool:
del sys.modules[key]
reload('LuaFormat.core')
try:
from .core import *
except:
from core import *
def get_settings():
return sublime.load_settings('LuaFormat.sublime-settings')
class LuaFormatCommand(sublime_plugin.TextCommand):
def run(self, edit):
# check whether the lua files
suffix_setting = self.view.settings().get('syntax')
file_suffix = suffix_setting.split('.')[0]
if file_suffix[-3:].lower() != 'lua': return
# get lines of replacement
r = sublime.Region(0, self.view.size())
self.view.unfold(r)
# get characters of view
lines = []
for region in self.view.lines(r):
cache = self.view.substr(region)
if len(cache) == 0: cache = ' '
lines.append(cache)
# get cursor position before the replacement
selection = self.view.sel()[0].b
row, col = self.view.rowcol(selection)
# replace the content after format
print("Run Lua Format")
self.view.replace(edit, r, lua_format(lines, get_settings()))
# set tab_size from lua-format-setting
self.view.run_command("set_setting", {"setting": "tab_size", "value": get_settings().get('tab_size', 4)})
# deal cursor position
selection = self.view.full_line(self.view.text_point(row - 1, 0)).b
cursor_pos = sublime.Region(selection, selection)
regions = self.view.sel()
regions.clear()
regions.add(cursor_pos)
sublime.set_timeout_async(lambda: self.view.show(cursor_pos), 0)
class LuaFormatOnPreSave(sublime_plugin.EventListener):
def on_pre_save(self, view):
if get_settings().get('auto_format_on_save', False):
view.run_command("lua_format")