forked from SublimeText/LaTeXTools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jumpto_tex_file.py
263 lines (227 loc) · 8.85 KB
/
jumpto_tex_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
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
import re
import os
import codecs
import subprocess
import shlex
import traceback
import sublime
import sublime_plugin
try:
_ST3 = True
from .getTeXRoot import get_tex_root
from .latextools_utils import get_setting
except:
_ST3 = False
from getTeXRoot import get_tex_root
from latextools_utils import get_setting
# TODO this might be moved to a generic util
def run_after_loading(view, func):
"""Run a function after the view has finished loading"""
def run():
if view.is_loading():
sublime.set_timeout(run, 10)
else:
# add an additional delay, because it might not be ready
# even if the loading function returns false
sublime.set_timeout(func, 10)
run()
_INPUT_REG = re.compile(
r"\\(?:input|include|subfile)"
r"\{(?P<file>[^}]+)\}",
re.UNICODE
)
_BIB_REG = re.compile(
r"\\(?:bibliography|nobibliography|addbibresource|add(?:global|section)bib)"
r"(?:\[[^\]]*\])?"
r"\{(?P<file>[^}]+)\}",
re.UNICODE
)
_IMAGE_REG = re.compile(
r"\\includegraphics"
r"(?:\[[^\]]*\])?"
r"\{(?P<file>[^\}]+)\}",
re.UNICODE
)
def _jumpto_tex_file(view, window, tex_root, file_name,
auto_create_missing_folders, auto_insert_root):
base_path, base_name = os.path.split(tex_root)
_, ext = os.path.splitext(file_name)
if not ext:
file_name += '.tex'
# clean-up any directory manipulating components
file_name = os.path.normpath(file_name)
containing_folder, file_name = os.path.split(file_name)
# allow absolute paths on \include or \input
isabs = os.path.isabs(containing_folder)
if not isabs:
containing_folder = os.path.normpath(
os.path.join(base_path, containing_folder))
# create the missing folder
if auto_create_missing_folders and\
not os.path.exists(containing_folder):
try:
os.makedirs(containing_folder)
except OSError:
# most likely a permissions error
print('Error occurred while creating path "{0}"'
.format(containing_folder))
traceback.print_last()
else:
print('Created folder: "{0}"'.format(containing_folder))
if not os.path.exists(containing_folder):
sublime.status_message(
"Cannot open tex file as folders are missing")
return
is_root_inserted = False
full_new_path = os.path.join(containing_folder, file_name)
if auto_insert_root and not os.path.exists(full_new_path):
if isabs:
root_path = tex_root
else:
root_path = os.path.join(
os.path.relpath(base_path, containing_folder),
base_name)
# Use slashes consistent with TeX's usage
if sublime.platform() == 'windows' and not isabs:
root_path = root_path.replace('\\', '/')
root_string = '%!TEX root = {0}\n'.format(root_path)
try:
with codecs.open(full_new_path, "w", "utf8")\
as new_file:
new_file.write(root_string)
is_root_inserted = True
except OSError:
print('An error occurred while creating file "{0}"'
.format(file_name))
traceback.print_last()
# open the file
print("Open the file '{0}'".format(full_new_path))
new_view = window.open_file(full_new_path)
# await opening and move cursor to end of the new view
# (does not work on st2)
if _ST3 and auto_insert_root and is_root_inserted:
def set_caret_position():
cursor_pos = len(root_string)
new_view.sel().clear()
new_view.sel().add(sublime.Region(cursor_pos,
cursor_pos))
run_after_loading(new_view, set_caret_position)
def _jumpto_bib_file(view, window, tex_root, file_name,
auto_create_missing_folders):
# just abuse the insights of _jumpto_tex_file and call it
# disable all tex features and open the file
_, ext = os.path.splitext(file_name)
if not ext:
file_name += '.bib'
_jumpto_tex_file(view, window, tex_root, file_name,
auto_create_missing_folders, False)
def _jumpto_image_file(view, window, tex_root, file_name):
base_path = os.path.dirname(tex_root)
image_types = get_setting(
"image_types", [
"png", "pdf", "jpg", "jpeg", "eps"
])
file_path = os.path.normpath(
os.path.join(base_path, file_name))
_, extension = os.path.splitext(file_path)
extension = extension[1:] # strip the leading point
if not extension:
for ext in image_types:
test_path = file_path + "." + ext
print("Test file: '{0}'".format(test_path))
if os.path.exists(test_path):
extension = ext
file_path = test_path
print("Found file: '{0}'".format(test_path))
break
if not os.path.exists(file_path):
sublime.status_message(
"file does not exists: '{0}'".format(file_path))
return
def run_command(command):
if not _ST3:
command = str(command)
command = shlex.split(command)
# if $file is used, substitute it by the file path
if "$file" in command:
command = [file_path if c == "$file" else c
for c in command]
# if $file is not used, append the file path
else:
command.append(file_path)
print("RUN: {0}".format(command))
subprocess.Popen(command)
psystem = sublime.platform()
commands = get_setting("open_image_command", {}).get(psystem, None)
print("Commands: '{0}'".format(commands))
print("Open File: '{0}'".format(file_path))
if commands is None:
window.open_file(file_path)
elif type(commands) is str:
run_command(commands)
else:
for d in commands:
print(d)
# validate the entry
if "command" not in d:
message = "Invalid entry {0}, missing: 'command'"\
.format(str(d))
sublime.status_message(message)
print(message)
continue
# check whether the extension matches
if "extension" in d:
if extension == d["extension"] or\
extension in d["extension"]:
run_command(d["command"])
break
# if no extension matches always run the command
else:
run_command(d["command"])
break
else:
sublime.status_message(
"No opening command for {0} defined"
.format(extension))
window.open_file(file_path)
class JumptoTexFileCommand(sublime_plugin.TextCommand):
def run(self, edit, auto_create_missing_folders=True,
auto_insert_root=True):
view = self.view
window = view.window()
tex_root = get_tex_root(view)
if tex_root is None:
sublime.status_message("Save your current file first")
return
for sel in view.sel():
line_r = view.line(sel)
line = view.substr(line_r)
def is_inside(g):
"""check whether the selection is inside the command"""
if g is None:
return False
b = line_r.begin()
# the region, which should contain the selection
reg = g.regs[0]
return reg[0] <= sel.begin() - b and sel.end() - b <= reg[1]
for g in filter(is_inside, _INPUT_REG.finditer(line)):
file_name = g.group("file")
print("Jumpto tex file '{0}'".format(file_name))
_jumpto_tex_file(view, window, tex_root, file_name,
auto_create_missing_folders, auto_insert_root)
for g in filter(is_inside, _BIB_REG.finditer(line)):
file_group = g.group("file")
if "," in file_group:
file_names = file_group.split(",")
file_names = [f.strip() for f in file_names]
print("Bib files: {0}".format(file_names))
else:
file_names = [file_group]
for file_name in file_names:
print("Jumpto bib file '{0}'".format(file_name))
_jumpto_bib_file(view, window, tex_root, file_name,
auto_create_missing_folders)
for g in filter(is_inside, _IMAGE_REG.finditer(line)):
file_name = g.group("file")
print("Jumpto image file '{0}'".format(file_name))
_jumpto_image_file(view, window, tex_root, file_name)