-
Notifications
You must be signed in to change notification settings - Fork 367
/
jumpto_tex_file.py
290 lines (241 loc) · 9.72 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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
import re
import os
import codecs
import shlex
import traceback
import sublime
import sublime_plugin
from .deprecated_command import deprecate
from .getTeXRoot import get_tex_root
from .latextools_utils import analysis, get_setting, utils
from .latextools_utils.external_command import external_command
INPUT_REG = re.compile(
r"\\(?:input|include|subfile|loadglsentries)"
r"\{(?P<file>[^}]+)\}",
re.UNICODE
)
IMPORT_REG = re.compile(
r"\\(?:(?:sub)?import|(?:sub)?inputfrom|(?:sub)?includefrom)"
r"\*?"
r"\{(?P<path>[^}]+)\}"
r"(?:\{(?P<file>[^}]+)\})?", # optional for compat with jumpto-anywhere
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):
root_base_path, root_base_name = os.path.split(tex_root)
ana = analysis.get_analysis(tex_root)
base_path = ana.tex_base_path(view.file_name())
_, 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(root_base_path, containing_folder),
root_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))
# await opening and move cursor to end of the new view
if auto_insert_root and is_root_inserted:
cursor_pos = len(root_string)
new_region = sublime.Region(cursor_pos, cursor_pos)
utils.open_and_select_region(view, full_new_path, new_region)
else:
window.open_file(full_new_path)
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 _validate_image(file_path, image_types):
_, extension = os.path.splitext(file_path)
extension = extension[1:] # strip the leading point
if extension:
if os.path.exists(file_path):
return file_path
else:
for ext in image_types:
test_path = file_path + "." + ext
print("Test file: '{0}'".format(test_path))
if os.path.exists(test_path):
print("Found file: '{0}'".format(test_path))
return test_path
def find_image(tex_root, file_name, tex_file_name=None):
ana = analysis.get_analysis(tex_root)
base_path = ana.tex_base_path(tex_file_name)
image_types = get_setting(
"image_types", [
"png", "pdf", "jpg", "jpeg", "eps"
])
for graphics_path in [base_path] + ana.graphics_paths():
file_path = _validate_image(
os.path.normpath(os.path.join(graphics_path, file_name)),
image_types
)
if file_path:
return file_path
def open_image(window, file_path):
def run_command(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)
external_command(command, shell=True)
_, extension = os.path.splitext(file_path)
extension = extension[1:] # strip the leading point
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)
def _jumpto_image_file(view, window, tex_root, file_name):
file_path = find_image(tex_root, file_name, tex_file_name=view.file_name())
if not file_path:
sublime.status_message("file does not exists: '{0}'".format(file_path))
return
open_image(window, file_path)
def _split_bib_args(bib_args):
if "," in bib_args:
file_names = bib_args.split(",")
file_names = [f.strip() for f in file_names]
print("Bib files: {0}".format(file_names))
else:
file_names = [bib_args]
return file_names
class LatextoolsJumptoFileCommand(sublime_plugin.TextCommand):
def run(self, edit, auto_create_missing_folders=True,
auto_insert_root=True, position=None):
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
if position is None:
selections = list(view.sel())
else:
selections = [sublime.Region(position, position)]
for sel in selections:
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, IMPORT_REG.finditer(line)):
if not g.group("file"):
continue
file_name = os.path.join(g.group("path"), 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")
file_names = _split_bib_args(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)
deprecate(globals(), 'JumptoTexFileCommand', LatextoolsJumptoFileCommand)