This repository has been archived by the owner on Apr 12, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
/
beautify_latex.py
129 lines (107 loc) · 4.72 KB
/
beautify_latex.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
import os.path
import sublime
import sublime_plugin
import sys
import re
import subprocess
import tempfile
class BeautifyLatexOnSave(sublime_plugin.EventListener):
def on_pre_save(self, view):
self.settings = sublime.load_settings('BeautifyLatex.sublime-settings')
if self.settings.get('run_on_save'):
view.run_command("beautify_latex", {"save": False, "error": False})
class BeautifyLatexCommand(sublime_plugin.TextCommand):
def run(self, edit, error=True, save=True):
self.load_settings()
self.view.settings().set('translate_tabs_to_spaces',
self.settings.get('translate_tabs_to_spaces'))
self.view.settings().set('tab_size', self.settings.get('tab_size'))
try:
if self.is_latex_file():
self.beautify_buffer(edit)
if save and self.settings.get('save_on_beautify'):
self.view.run_command('save')
else:
if error:
raise Exception("This is not a Latex file.")
except:
msg = "Error: {0}".format(sys.exc_info()[1])
sublime.error_message(msg)
def beautify_buffer(self, edit):
buffer_region = sublime.Region(0, self.view.size())
buffer_text = self.view.substr(buffer_region)
if buffer_text == "":
return
self.save_viewport_state()
ext = os.path.splitext(self.view.file_name())[1]
with tempfile.NamedTemporaryFile(delete=False, suffix=ext) as temp:
try:
temp.write(buffer_text.encode("utf-8"))
temp.flush()
temp.close()
beautified_buffer = self.pipe(self.cmd(temp.name))
fix_lines = beautified_buffer.replace(os.linesep, '\n')
self.check_valid_output(fix_lines)
self.view.replace(edit, buffer_region, fix_lines)
finally:
os.unlink(temp.name)
self.reset_viewport_state()
def check_valid_output(self, text):
if text == "":
msg = "invalid output. Check your latexindent settings"
raise Exception(msg)
def cmd(self, path="-"):
executable = self.settings.get('cmd')
if executable is None:
executable = self.which(
'latexindent.exe') or self.which('latexindent') or self.which('latexindent.pl')
if executable is None or (not os.path.exists(executable)):
msg = "latexindent executable not found."
raise Exception(msg)
return '"' + executable + '" "' + str(path) + '"'
def finalize_output(self, text):
lines = text.splitlines()
finalized_output = "\n".join(lines)
if self.view.settings().get("ensure_newline_at_eof_on_save") and not text.endswith("\n"):
text += "\n"
return finalized_output
def load_settings(self):
self.settings = sublime.load_settings('BeautifyLatex.sublime-settings')
def save_viewport_state(self):
self.previous_selection = [(region.a, region.b)
for region in self.view.sel()]
self.previous_position = self.view.viewport_position()
def reset_viewport_state(self):
self.view.set_viewport_position((0, 0,), False)
self.view.set_viewport_position(self.previous_position, False)
self.view.sel().clear()
for a, b in self.previous_selection:
self.view.sel().add(sublime.Region(a, b))
def is_latex_file(self):
file_patterns = self.settings.get('file_patterns') or ['\.tex']
return self.match_pattern(file_patterns)
def match_pattern(self, file_patterns):
patterns = re.compile(r'\b(?:%s)\b' % '|'.join(file_patterns))
return patterns.search(os.path.basename(self.view.file_name()))
def pipe(self, cmd):
cwd = os.path.dirname(self.view.file_name())
beautifier = subprocess.Popen(
cmd, shell=True, cwd=cwd, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
out = beautifier.communicate(''.encode("utf-8"))[0]
return out.decode('utf8')
# http://stackoverflow.com/questions/377017/test-if-executable-exists-in-python/377028#377028
def which(self, program):
import os
def is_exe(fpath):
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
fpath, fname = os.path.split(program)
if fpath:
if is_exe(program):
return program
else:
for path in os.environ["PATH"].split(os.pathsep):
path = path.strip('"')
exe_file = os.path.join(path, program)
if is_exe(exe_file):
return exe_file
return None