-
Notifications
You must be signed in to change notification settings - Fork 535
/
manager.ts
994 lines (916 loc) · 39.8 KB
/
manager.ts
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
import * as vscode from 'vscode'
import * as os from 'os'
import * as path from 'path'
import * as fs from 'fs-extra'
import * as cs from 'cross-spawn'
import * as chokidar from 'chokidar'
import * as micromatch from 'micromatch'
import {latexParser} from 'latex-utensils'
import * as utils from '../utils/utils'
import {Extension} from '../main'
import {Suggestion as CiteEntry} from '../providers/completer/citation'
import {Suggestion as CmdEntry} from '../providers/completer/command'
import {Suggestion as EnvEntry} from '../providers/completer/environment'
/**
* The content cache for each LaTeX file `filepath`.
*/
interface Content {
[filepath: string]: { // The path of a LaTeX file.
/**
* The dirty (under editing) content of the LaTeX file.
*/
content: string,
/**
* Completion item and other items for the LaTeX file.
*/
element: {
reference?: vscode.CompletionItem[],
environment?: EnvEntry[],
bibitem?: CiteEntry[],
command?: CmdEntry[],
package?: string[]
},
/**
* The sub-files of the LaTeX file. They should be tex or plain files.
*/
children: {
/**
* The index of character sub-content is inserted
*/
index: number,
/**
* The path of the sub-file
*/
file: string
}[],
/**
* The array of the paths of `.bib` files referenced from the LaTeX file.
*/
bibs: string[]
}
}
export const enum BuildEvents {
never = 'never',
onSave = 'onSave',
onFileChange = 'onFileChange'
}
export class Manager {
/**
* The content cache for each LaTeX file.
*/
readonly cachedContent: Content = {}
private readonly extension: Extension
private fileWatcher?: chokidar.FSWatcher
private pdfWatcher?: chokidar.FSWatcher
private bibWatcher?: chokidar.FSWatcher
private filesWatched: string[] = []
private pdfsWatched: string[] = []
private bibsWatched: string[] = []
private watcherOptions: chokidar.WatchOptions
private rsweaveExt: string[] = ['.rnw', '.Rnw', '.rtex', '.Rtex', '.snw', '.Snw']
private jlweaveExt: string[] = ['.jnw', '.jtexw']
private weaveExt: string[] = []
private pdfWatcherOptions: chokidar.WatchOptions
constructor(extension: Extension) {
this.extension = extension
const configuration = vscode.workspace.getConfiguration('latex-workshop')
const usePolling = configuration.get('latex.watch.usePolling') as boolean
const interval = configuration.get('latex.watch.interval') as number
const delay = configuration.get('latex.watch.delay') as number
const pdfDelay = configuration.get('latex.watch.pdfDelay') as number
this.weaveExt = this.jlweaveExt.concat(this.rsweaveExt)
this.watcherOptions = {
useFsEvents: false,
usePolling,
interval,
binaryInterval: Math.max(interval, 1000),
awaitWriteFinish: {stabilityThreshold: delay}
}
this.pdfWatcherOptions = {
useFsEvents: false,
usePolling,
interval,
binaryInterval: Math.max(interval, 1000),
awaitWriteFinish: {stabilityThreshold: pdfDelay}
}
this.initiatePdfWatcher()
}
/**
* Returns the output directory developed according to the input tex path
* and 'latex.outDir' config. If `texPath` is `undefined`, the default root
* file is used. If there is not root file, returns './'.
* The returned path always uses `/` even on Windows.
*
* @param texPath The path of a LaTeX file.
*/
getOutDir(texPath?: string) {
if (this.extension.liveshare.isGuest) {
return this.extension.liveshare.getOutDir(texPath)
}
if (texPath === undefined) {
texPath = this.rootFile
}
// rootFile is also undefined
if (texPath === undefined) {
return './'
}
const configuration = vscode.workspace.getConfiguration('latex-workshop')
const outDir = configuration.get('latex.outDir') as string
const out = utils.replaceArgumentPlaceholders(texPath, this.extension.builder.tmpDir)(outDir)
return path.normalize(out).split(path.sep).join('/')
}
/**
* The path of the directory of the root file.
*/
get rootDir() {
return this.rootFile ? path.dirname(this.rootFile) : undefined
}
// Here we have something complex. We use a private rootFiles to hold the
// roots of each workspace, and use rootFile to return the cached content.
private rootFiles: { [key: string]: string | undefined } = {}
/**
* The path of the root LaTeX file of the current workspace.
* It is `undefined` before `findRoot` called.
*/
get rootFile() {
return this.rootFiles[this.workspaceRootDir]
}
set rootFile(root: string | undefined) {
this.rootFiles[this.workspaceRootDir] = root
}
private localRootFiles: { [key: string]: string | undefined } = {}
get localRootFile() {
return this.localRootFiles[this.workspaceRootDir]
}
set localRootFile(localRoot: string | undefined) {
this.localRootFiles[this.workspaceRootDir] = localRoot
}
private rootFilesLanguageIds: { [key: string]: string | undefined } = {}
get rootFileLanguageId() {
return this.rootFilesLanguageIds[this.workspaceRootDir]
}
set rootFileLanguageId(id: string | undefined) {
this.rootFilesLanguageIds[this.workspaceRootDir] = id
}
private inferLanguageId(filename: string): string | undefined {
const ext = path.extname(filename)
if (ext === '.tex') {
return 'latex'
} else if (this.jlweaveExt.includes(ext)) {
return 'jlweave'
} else if (this.rsweaveExt.includes(ext)) {
return 'rsweave'
} else {
return undefined
}
}
/**
* Returns the path of a PDF file with respect to `texPath`.
*
* @param texPath The path of a LaTeX file.
* @param respectOutDir If `true`, the 'latex.outDir' config is respected.
*/
tex2pdf(texPath: string, respectOutDir: boolean = true) {
if (this.extension.liveshare.isGuest) {
const livesharePdfPath = path.join(this.getOutDir(texPath), path.basename(`${texPath.substr(0, texPath.lastIndexOf('.'))}.pdf`))
this.extension.liveshare.requestPdf(texPath, !fs.existsSync(livesharePdfPath))
this.watchPdfFile(livesharePdfPath)
return livesharePdfPath
}
let outDir = './'
if (respectOutDir) {
outDir = this.getOutDir(texPath)
}
return path.resolve(path.dirname(texPath), outDir, path.basename(`${texPath.substr(0, texPath.lastIndexOf('.'))}.pdf`))
}
/**
* Returns `true` if the language of `id` is one of supported languages.
*
* @param id The identifier of language.
*/
hasTexId(id: string) {
return ['tex', 'latex', 'latex-expl3', 'doctex', 'jlweave', 'rsweave'].includes(id)
}
private workspaceRootDir: string = ''
private findWorkspace() {
const workspaceFolders = vscode.workspace.workspaceFolders
const firstDir = workspaceFolders && workspaceFolders[0]
// If no workspace is opened.
if (workspaceFolders === undefined || !firstDir) {
this.workspaceRootDir = ''
return
}
// If we don't have an active text editor, we can only make a guess.
// Let's guess the first one.
if (!vscode.window.activeTextEditor) {
this.workspaceRootDir = firstDir.uri.fsPath
return
}
// Guess that the correct workspace folder path should be contained in
// the path of active editor. If there are multiple matches, take the
// first one.
const activeFile = vscode.window.activeTextEditor.document.uri.fsPath
for (const workspaceFolder of workspaceFolders) {
if (activeFile.includes(workspaceFolder.uri.fsPath)) {
this.workspaceRootDir = workspaceFolder.uri.fsPath
return
}
}
// Guess that the first workspace is the chosen one.
this.workspaceRootDir = firstDir.uri.fsPath
}
/**
* Finds the root file with respect to the current workspace and returns it.
* The found root is also set to `rootFile`.
*/
async findRoot(): Promise<string | undefined> {
this.findWorkspace()
this.localRootFile = undefined
const findMethods = [
() => this.findRootFromMagic(),
() => this.findRootFromActive(),
() => this.findRootFromCurrentRoot(),
() => this.findRootInWorkspace()
]
for (const method of findMethods) {
const rootFile = await method()
if (rootFile === undefined) {
continue
}
if (this.rootFile !== rootFile) {
this.extension.logger.addLogMessage(`Root file changed: from ${this.rootFile} to ${rootFile}`)
this.extension.logger.addLogMessage('Start to find all dependencies.')
this.rootFile = rootFile
this.rootFileLanguageId = this.inferLanguageId(rootFile)
this.initiateFileWatcher()
this.initiateBibWatcher()
this.parseFileAndSubs(this.rootFile) // finish the parsing is required for subsequent refreshes.
this.extension.structureProvider.refresh()
this.extension.structureProvider.update()
} else {
this.extension.logger.addLogMessage(`Keep using the same root file: ${this.rootFile}.`)
}
return rootFile
}
return undefined
}
private findRootFromCurrentRoot(): string | undefined {
if (!vscode.window.activeTextEditor || this.rootFile === undefined) {
return undefined
}
if (this.getIncludedTeX().includes(vscode.window.activeTextEditor.document.fileName)) {
return this.rootFile
}
return undefined
}
private findRootFromMagic(): string | undefined {
if (!vscode.window.activeTextEditor) {
return undefined
}
const regex = /^(?:%\s*!\s*T[Ee]X\sroot\s*=\s*(.*\.tex)$)/m
let content = vscode.window.activeTextEditor.document.getText()
let result = content.match(regex)
const fileStack: string[] = []
if (result) {
let file = path.resolve(path.dirname(vscode.window.activeTextEditor.document.fileName), result[1])
if (!fs.existsSync(file)) {
const msg = `Not found root file specified in the magic comment: ${file}`
this.extension.logger.addLogMessage(msg)
throw new Error(msg)
}
fileStack.push(file)
this.extension.logger.addLogMessage(`Found root file by magic comment: ${file}`)
content = fs.readFileSync(file).toString()
result = content.match(regex)
while (result) {
file = path.resolve(path.dirname(file), result[1])
if (fileStack.includes(file)) {
this.extension.logger.addLogMessage(`Looped root file by magic comment found: ${file}, stop here.`)
return file
} else {
fileStack.push(file)
this.extension.logger.addLogMessage(`Recursively found root file by magic comment: ${file}`)
}
if (!fs.existsSync(file)) {
const msg = `Not found root file specified in the magic comment: ${file}`
this.extension.logger.addLogMessage(msg)
throw new Error(msg)
}
content = fs.readFileSync(file).toString()
result = content.match(regex)
}
return file
}
return undefined
}
private findRootFromActive(): string | undefined {
if (!vscode.window.activeTextEditor) {
return undefined
}
const regex = /\\begin{document}/m
const content = utils.stripComments(vscode.window.activeTextEditor.document.getText(), '%')
const result = content.match(regex)
if (result) {
const rootSubFile = this.findSubFiles(content)
const file = vscode.window.activeTextEditor.document.fileName
if (rootSubFile) {
this.localRootFile = file
return rootSubFile
} else {
this.extension.logger.addLogMessage(`Found root file from active editor: ${file}`)
return file
}
}
return undefined
}
private findSubFiles(content: string): string | undefined {
if (!vscode.window.activeTextEditor) {
return undefined
}
const regex = /(?:\\documentclass\[(.*)\]{subfiles})/
const result = content.match(regex)
if (result) {
const file = utils.resolveFile([path.dirname(vscode.window.activeTextEditor.document.fileName)], result[1])
if (file) {
this.extension.logger.addLogMessage(`Found root file of this subfile from active editor: ${file}`)
} else {
this.extension.logger.addLogMessage(`Cannot find root file of this subfile from active editor: ${result[1]}`)
}
return file
}
return undefined
}
private async findRootInWorkspace(): Promise<string | undefined> {
const regex = /\\begin{document}/m
if (!this.workspaceRootDir) {
return undefined
}
const configuration = vscode.workspace.getConfiguration('latex-workshop')
const rootFilesIncludePatterns = configuration.get('latex.search.rootFiles.include') as string[]
const rootFilesIncludeGlob = '{' + rootFilesIncludePatterns.join(',') + '}'
const rootFilesExcludePatterns = configuration.get('latex.search.rootFiles.exclude') as string[]
const rootFilesExcludeGlob = rootFilesExcludePatterns.length > 0 ? '{' + rootFilesExcludePatterns.join(',') + '}' : undefined
try {
const files = await vscode.workspace.findFiles(rootFilesIncludeGlob, rootFilesExcludeGlob)
const candidates: string[] = []
for (const file of files) {
const content = utils.stripComments(fs.readFileSync(file.fsPath).toString(), '%')
const result = content.match(regex)
if (result) {
// Can be a root
const children = this.getTeXChildren(file.fsPath, file.fsPath, [], content)
if (vscode.window.activeTextEditor && children.includes(vscode.window.activeTextEditor.document.fileName)) {
this.extension.logger.addLogMessage(`Found root file from parent: ${file.fsPath}`)
return file.fsPath
}
// Not including the active file, yet can still be a root candidate
candidates.push(file.fsPath)
}
}
if (candidates.length > 0) {
this.extension.logger.addLogMessage(`Found files that might be root, choose the first one: ${candidates}`)
return candidates[0]
}
} catch (e) {}
return undefined
}
/**
* Returns a string array which holds all imported tex files
* from the given `file`. If `file` is `undefined`, traces from the
* root file, or return empty array if the root file is `undefined`
*
* @param file The path of a LaTeX file
*/
getIncludedTeX(file?: string, includedTeX: string[] = []) {
if (file === undefined) {
file = this.rootFile
}
if (file === undefined) {
return []
}
if (!(file in this.extension.manager.cachedContent)) {
return []
}
includedTeX.push(file)
for (const child of this.extension.manager.cachedContent[file].children) {
if (includedTeX.includes(child.file)) {
// Already included
continue
}
this.getIncludedTeX(child.file, includedTeX)
}
return includedTeX
}
private getDirtyContent(file: string, reload: boolean = false): string {
for (const cachedFile of Object.keys(this.cachedContent)) {
if (reload) {
break
}
if (path.relative(cachedFile, file) !== '') {
continue
}
return this.cachedContent[cachedFile].content
}
const fileContent = utils.stripComments(fs.readFileSync(file).toString(), '%')
this.cachedContent[file] = {content: fileContent, element: {}, children: [], bibs: []}
return fileContent
}
private isExcluded(file: string): boolean {
const globsToIgnore = vscode.workspace.getConfiguration('latex-workshop').get('latex.watch.files.ignore') as string[]
const format = (str: string): string => {
if (os.platform() === 'win32') {
return str.replace(/\\/g, '/')
}
return str
}
return micromatch.some(file, globsToIgnore, { format })
}
/**
* Searches the subfiles, `\input` siblings, `.bib` files, and related `.fls` file
* to construct a file dependency data structure related to `file` in `this.cachedContent`.
*
* This function is called when the root file is found or a watched file is changed.
*
* @param file The path of a LaTeX file. It is added to the watcher if not being watched.
* @param onChange If `true`, the content of `file` is read from the file system. If `false`, the cache of `file` is used.
*/
private parseFileAndSubs(file: string, onChange: boolean = false) {
if (this.isExcluded(file)) {
this.extension.logger.addLogMessage(`Ignoring: ${file}`)
return
}
this.extension.logger.addLogMessage(`Parsing a file and its subfiles: ${file}`)
if (this.fileWatcher && !this.filesWatched.includes(file)) {
// The file is first time considered by the extension.
this.fileWatcher.add(file)
this.filesWatched.push(file)
}
const content = this.getDirtyContent(file, onChange)
this.cachedContent[file].children = []
this.cachedContent[file].bibs = []
this.cachedFullContent = undefined
this.parseInputFiles(content, file)
this.parseBibFiles(content, file)
// We need to parse the fls to discover file dependencies when defined by TeX macro
// It happens a lot with subfiles, https://tex.stackexchange.com/questions/289450/path-of-figures-in-different-directories-with-subfile-latex
this.parseFlsFile(file)
}
private cachedFullContent: string | undefined
/**
* Returns the flattened content from the given `file`,
* typically the root file.
*
* @param file The path of a LaTeX file.
*/
getContent(file?: string, fileTrace: string[] = []): string {
// Here we make a copy, so that the tree structure of tex dependency
// Can be maintained. For instance, main -> s1 and s2, both of which
// has s3 as a subfile. This subtrace will allow s3 to be expanded in
// both s1 and s2.
if (file === undefined) {
file = this.rootFile
}
if (file === undefined) {
return ''
}
if (this.cachedFullContent && file === this.rootFile) {
return this.cachedFullContent
}
const subFileTrace = Array.from(fileTrace)
subFileTrace.push(file)
if (this.cachedContent[file].children.length === 0) {
if (file === this.rootFile) {
this.cachedFullContent = this.cachedContent[file].content
}
return this.cachedContent[file].content
}
let content = this.cachedContent[file].content
// Do it reverse, so that we can directly insert the new content without
// messing up the previous line numbers.
for (let index = this.cachedContent[file].children.length - 1; index >=0; index--) {
const child = this.cachedContent[file].children[index]
if (subFileTrace.includes(child.file)) {
continue
}
// As index can be 1E307 (included by fls file), here we need a min.
const pos = Math.min(content.length, child.index)
content = [content.slice(0, pos), this.getContent(child.file, subFileTrace), content.slice(pos)].join('')
}
if (file === this.rootFile) {
this.cachedFullContent = content
}
return content
}
private getTeXChildren(file: string, baseFile: string, children: string[], content?: string): string[] {
if (content === undefined) {
content = utils.stripComments(fs.readFileSync(file).toString(), '%')
}
// Update children of current file
if (this.cachedContent[file] === undefined) {
this.cachedContent[file] = {content, element: {}, bibs: [], children: []}
const inputReg = /(?:\\(?:input|InputIfFileExists|include|SweaveInput|subfile|(?:(?:sub)?(?:import|inputfrom|includefrom)\*?{([^}]*)}))(?:\[[^[\]{}]*\])?){([^}]*)}/g
while (true) {
const result = inputReg.exec(content)
if (!result) {
break
}
const inputFile = this.parseInputFilePath(result, baseFile)
if (!inputFile ||
!fs.existsSync(inputFile) ||
path.relative(inputFile, baseFile) === '') {
continue
}
this.cachedContent[file].children.push({
index: result.index,
file: inputFile
})
}
}
this.cachedContent[file].children.forEach(child => {
if (children.includes(child.file)) {
// Already included
return
}
children.push(child.file)
this.getTeXChildren(child.file, baseFile, children)
})
return children
}
private parseInputFiles(content: string, baseFile: string) {
const inputReg = /(?:\\(?:input|InputIfFileExists|include|SweaveInput|subfile|(?:(?:sub)?(?:import|inputfrom|includefrom)\*?{([^}]*)}))(?:\[[^[\]{}]*\])?){([^}]*)}/g
while (true) {
const result = inputReg.exec(content)
if (!result) {
break
}
const inputFile = this.parseInputFilePath(result, baseFile)
if (!inputFile ||
!fs.existsSync(inputFile) ||
path.relative(inputFile, baseFile) === '') {
continue
}
this.cachedContent[baseFile].children.push({
index: result.index,
file: inputFile
})
if (this.filesWatched.includes(inputFile)) {
continue
}
this.parseFileAndSubs(inputFile)
}
}
private parseInputFilePath(regResult: RegExpExecArray, baseFile: string): string | undefined {
const texDirs = vscode.workspace.getConfiguration('latex-workshop').get('latex.texDirs') as string[]
if (regResult[0].startsWith('\\subimport') || regResult[0].startsWith('\\subinputfrom') || regResult[0].startsWith('\\subincludefrom')) {
return utils.resolveFile([path.dirname(baseFile)], path.join(regResult[1], regResult[2]))
} else if (regResult[0].startsWith('\\import') || regResult[0].startsWith('\\inputfrom') || regResult[0].startsWith('\\includefrom')) {
return utils.resolveFile([regResult[1]], regResult[2])
} else {
if (this.rootFile) {
return utils.resolveFile([path.dirname(baseFile), path.dirname(this.rootFile), ...texDirs], regResult[2])
} else {
return utils.resolveFile([path.dirname(baseFile), ...texDirs], regResult[2])
}
}
}
private parseBibFiles(content: string, baseFile: string) {
const bibReg = /(?:\\(?:bibliography|addbibresource)(?:\[[^[\]{}]*\])?){(.+?)}|(?:\\putbib)\[(.+?)\]/g
while (true) {
const result = bibReg.exec(content)
if (!result) {
break
}
const bibs = (result[1] ? result[1] : result[2]).split(',').map((bib) => {
return bib.trim()
})
for (const bib of bibs) {
const bibPath = this.resolveBibPath(bib, path.dirname(baseFile))
if (bibPath === undefined) {
continue
}
this.cachedContent[baseFile].bibs.push(bibPath)
this.watchBibFile(bibPath)
}
}
}
/**
* Parses the content of a `.fls` file attached to the given `srcFile`.
* All `INPUT` files are considered as subfiles/non-tex files included in `srcFile`,
* and all `OUTPUT` files will be checked if they are `.aux` files.
* If so, the `.aux` files are parsed for any possible `.bib` files.
*
* @param srcFile The path of a LaTeX file.
*/
parseFlsFile(srcFile: string) {
this.extension.logger.addLogMessage('Parse fls file.')
const rootDir = path.dirname(srcFile)
const outDir = this.getOutDir(srcFile)
const baseName = path.parse(srcFile).name
const flsFile = path.resolve(rootDir, path.join(outDir, baseName + '.fls'))
if (!fs.existsSync(flsFile)) {
this.extension.logger.addLogMessage(`Cannot find fls file: ${flsFile}`)
return
}
this.extension.logger.addLogMessage(`Fls file found: ${flsFile}`)
const ioFiles = this.parseFlsContent(fs.readFileSync(flsFile).toString(), rootDir)
ioFiles.input.forEach((inputFile: string) => {
// Drop files that are also listed as OUTPUT or should be ignored
if (ioFiles.output.includes(inputFile) ||
this.isExcluded(inputFile) ||
!fs.existsSync(inputFile)) {
return
}
// Drop the current rootFile often listed as INPUT and drop any file that is already in the texFileTree
if (srcFile === inputFile || inputFile in this.cachedContent) {
return
}
if (path.extname(inputFile) === '.tex') {
// Parse tex files as imported subfiles.
this.cachedContent[srcFile].children.push({
index: Number.MAX_VALUE,
file: inputFile
})
this.parseFileAndSubs(inputFile)
} else if (this.fileWatcher && !this.filesWatched.includes(inputFile)) {
// Watch non-tex files.
this.fileWatcher.add(inputFile)
this.filesWatched.push(inputFile)
}
})
ioFiles.output.forEach((outputFile: string) => {
if (path.extname(outputFile) === '.aux' && fs.existsSync(outputFile)) {
this.extension.logger.addLogMessage(`Parse aux file: ${outputFile}`)
this.parseAuxFile(fs.readFileSync(outputFile).toString(),
path.dirname(outputFile).replace(outDir, rootDir))
}
})
}
private parseAuxFile(content: string, srcDir: string) {
const regex = /^\\bibdata{(.*)}$/gm
while (true) {
const result = regex.exec(content)
if (!result) {
return
}
const bibs = (result[1] ? result[1] : result[2]).split(',').map((bib) => {
return bib.trim()
})
for (const bib of bibs) {
const bibPath = this.resolveBibPath(bib, srcDir)
if (bibPath === undefined) {
continue
}
if (this.rootFile && !this.cachedContent[this.rootFile].bibs.includes(bibPath)) {
this.cachedContent[this.rootFile].bibs.push(bibPath)
}
this.watchBibFile(bibPath)
}
}
}
private parseFlsContent(content: string, rootDir: string): {input: string[], output: string[]} {
const inputFiles: Set<string> = new Set()
const outputFiles: Set<string> = new Set()
const regex = /^(?:(INPUT)\s*(.*))|(?:(OUTPUT)\s*(.*))$/gm
// regex groups
// #1: an INPUT entry --> #2 input file path
// #3: an OUTPUT entry --> #4: output file path
while (true) {
const result = regex.exec(content)
if (!result) {
break
}
if (result[1]) {
const inputFilePath = path.resolve(rootDir, result[2])
if (inputFilePath) {
inputFiles.add(inputFilePath)
}
} else if (result[3]) {
const outputFilePath = path.resolve(rootDir, result[4])
if (outputFilePath) {
outputFiles.add(outputFilePath)
}
}
}
return {input: Array.from(inputFiles), output: Array.from(outputFiles)}
}
private initiateFileWatcher() {
if (this.fileWatcher !== undefined &&
this.rootFile !== undefined &&
!this.filesWatched.includes(this.rootFile)) {
// We have an instantiated fileWatcher, but the rootFile is not being watched.
// => the user has changed the root. Clean up the old watcher so we reform it.
this.resetFileWatcher()
this.createFileWatcher()
}
if (this.fileWatcher === undefined) {
this.createFileWatcher()
}
}
private createFileWatcher() {
this.extension.logger.addLogMessage(`Instantiating a new file watcher for ${this.rootFile}`)
if (this.rootFile) {
this.fileWatcher = chokidar.watch(this.rootFile, this.watcherOptions)
this.filesWatched.push(this.rootFile)
}
if (this.fileWatcher) {
this.fileWatcher.on('add', (file: string) => this.onWatchingNewFile(file))
this.fileWatcher.on('change', (file: string) => this.onWatchedFileChanged(file))
this.fileWatcher.on('unlink', (file: string) => this.onWatchedFileDeleted(file))
}
// this.findAdditionalDependentFilesFromFls(this.rootFile)
}
private resetFileWatcher() {
this.extension.logger.addLogMessage('Root file changed -> cleaning up old file watcher.')
if (this.fileWatcher) {
this.fileWatcher.close()
}
this.filesWatched = []
// We also clean the completions from the old project
this.extension.completer.input.reset()
}
private onWatchingNewFile(file: string) {
this.extension.logger.addLogMessage(`Added to file watcher: ${file}`)
if (['.tex', '.bib'].concat(this.weaveExt).includes(path.extname(file)) &&
!file.includes('expl3-code.tex')) {
this.updateCompleterOnChange(file)
}
}
private onWatchedFileChanged(file: string) {
this.extension.logger.addLogMessage(`File watcher - file changed: ${file}`)
// It is possible for either tex or non-tex files in the watcher.
if (['.tex', '.bib'].concat(this.weaveExt).includes(path.extname(file)) &&
!file.includes('expl3-code.tex')) {
this.parseFileAndSubs(file, true)
this.updateCompleterOnChange(file)
}
this.buildOnFileChanged(file)
}
private initiateBibWatcher() {
if (this.bibWatcher !== undefined) {
return
}
this.extension.logger.addLogMessage('Creating Bib file watcher.')
this.bibWatcher = chokidar.watch([], this.watcherOptions)
this.bibWatcher.on('change', (file: string) => this.onWatchedBibChanged(file))
this.bibWatcher.on('unlink', (file: string) => this.onWatchedBibDeleted(file))
}
private onWatchedBibChanged(file: string) {
this.extension.logger.addLogMessage(`Bib file watcher - file changed: ${file}`)
this.extension.completer.citation.parseBibFile(file)
this.buildOnFileChanged(file, true)
}
private onWatchedBibDeleted(file: string) {
this.extension.logger.addLogMessage(`Bib file watcher - file deleted: ${file}`)
if (this.bibWatcher) {
this.bibWatcher.unwatch(file)
}
this.bibsWatched.splice(this.bibsWatched.indexOf(file), 1)
this.extension.completer.citation.removeEntriesInFile(file)
}
private onWatchedFileDeleted(file: string) {
this.extension.logger.addLogMessage(`File watcher - file deleted: ${file}`)
if (this.fileWatcher) {
this.fileWatcher.unwatch(file)
}
this.filesWatched.splice(this.filesWatched.indexOf(file), 1)
delete this.cachedContent[file]
if (file === this.rootFile) {
this.extension.logger.addLogMessage(`Root file deleted: ${file}`)
this.extension.logger.addLogMessage('Start searching a new root file.')
this.findRoot()
}
}
private initiatePdfWatcher() {
if (this.pdfWatcher !== undefined) {
return
}
this.extension.logger.addLogMessage('Creating PDF file watcher.')
this.pdfWatcher = chokidar.watch([], this.pdfWatcherOptions)
this.pdfWatcher.on('change', (file: string) => this.onWatchedPdfChanged(file))
this.pdfWatcher.on('unlink', (file: string) => this.onWatchedPdfDeleted(file))
}
private onWatchedPdfChanged(file: string) {
if (this.extension.liveshare.isHost) {
this.extension.liveshare.sendPdfUpdateToGuests(file)
}
this.extension.logger.addLogMessage(`PDF file watcher - file changed: ${file}`)
this.extension.viewer.refreshExistingViewer()
}
private onWatchedPdfDeleted(file: string) {
this.extension.logger.addLogMessage(`PDF file watcher - file deleted: ${file}`)
if (this.pdfWatcher) {
this.pdfWatcher.unwatch(file)
}
this.pdfsWatched.splice(this.pdfsWatched.indexOf(file), 1)
}
watchPdfFile(pdfPath: string) {
if (this.pdfWatcher && !this.pdfsWatched.includes(pdfPath)) {
this.extension.logger.addLogMessage(`Added to PDF file watcher: ${pdfPath}`)
this.pdfWatcher.add(pdfPath)
this.pdfsWatched.push(pdfPath)
}
}
private buildOnFileChanged(file: string, bibChanged: boolean = false) {
const configuration = vscode.workspace.getConfiguration('latex-workshop')
if (configuration.get('latex.autoBuild.run') as string !== BuildEvents.onFileChange) {
return
}
if (this.extension.builder.disableBuildAfterSave) {
this.extension.logger.addLogMessage('Auto Build Run is temporarily disabled during a second.')
return
}
this.extension.logger.addLogMessage(`Auto build started detecting the change of a file: ${file}`)
if (!bibChanged && this.localRootFile && configuration.get('latex.rootFile.useSubFile')) {
this.extension.commander.build(true, this.localRootFile, this.rootFileLanguageId)
} else {
this.extension.commander.build(true, this.rootFile, this.rootFileLanguageId)
}
}
// This function updates all completers upon tex-file changes.
private updateCompleterOnChange(file: string) {
fs.readFile(file).then(buffer => buffer.toString()).then(content => this.updateCompleter(file, content))
this.extension.completer.input.getGraphicsPath(file)
}
/**
* Updates all completers upon tex-file changes, or active file content is changed.
*/
async updateCompleter(file: string, content: string) {
this.extension.completer.citation.update(file, content)
const languageId: string | undefined = vscode.window.activeTextEditor?.document.languageId
let latexAst: latexParser.AstRoot | latexParser.AstPreamble | undefined = undefined
if (!languageId || languageId !== 'latex-expl3') {
latexAst = await this.extension.pegParser.parseLatex(content)
}
if (latexAst) {
const nodes = latexAst.content
const lines = content.split('\n')
this.extension.completer.reference.update(file, nodes, lines)
this.extension.completer.environment.update(file, nodes, lines)
this.extension.completer.command.update(file, nodes)
this.extension.completer.command.updatePkg(file, nodes)
} else {
this.extension.logger.addLogMessage(`Cannot parse a TeX file: ${file}`)
this.extension.logger.addLogMessage('Fall back to regex-based completion.')
// Do the update with old style.
const contentNoComment = utils.stripComments(content, '%')
this.extension.completer.reference.update(file, undefined, undefined, contentNoComment)
this.extension.completer.environment.update(file, undefined, undefined, contentNoComment)
this.extension.completer.command.update(file, undefined, contentNoComment)
this.extension.completer.command.updatePkg(file, undefined, contentNoComment)
}
}
private kpsewhichBibPath(bib: string): string | undefined {
const kpsewhich = vscode.workspace.getConfiguration('latex-workshop').get('kpsewhich.path') as string
this.extension.logger.addLogMessage(`Calling ${kpsewhich} to resolve file: ${bib}`)
try {
const kpsewhichReturn = cs.sync(kpsewhich, ['-format=.bib', bib])
if (kpsewhichReturn.status === 0) {
const bibPath = kpsewhichReturn.stdout.toString().replace(/\r?\n/, '')
if (bibPath === '') {
return undefined
} else {
this.extension.logger.addLogMessage(`Found .bib file using kpsewhich: ${bibPath}`)
return bibPath
}
}
} catch(e) {
this.extension.logger.addLogMessage(`Cannot run kpsewhich to resolve .bib file: ${bib}`)
}
return undefined
}
private resolveBibPath(bib: string, baseDir: string) {
const configuration = vscode.workspace.getConfiguration('latex-workshop')
const bibDirs = configuration.get('latex.bibDirs') as string[]
let searchDirs: string[]
if (this.rootDir) {
// chapterbib requires to load the .bib file in every chapter using
// the path relative to the rootDir
searchDirs = [this.rootDir, baseDir, ...bibDirs]
} else {
searchDirs = [baseDir, ...bibDirs]
}
const bibPath = utils.resolveFile(searchDirs, bib, '.bib')
if (!bibPath) {
this.extension.logger.addLogMessage(`Cannot find .bib file: ${bib}`)
if (configuration.get('kpsewhich.enabled')) {
return this.kpsewhichBibPath(bib)
} else {
return undefined
}
}
this.extension.logger.addLogMessage(`Found .bib file: ${bibPath}`)
return bibPath
}
private watchBibFile(bibPath: string) {
if (this.bibWatcher && !this.bibsWatched.includes(bibPath)) {
this.extension.logger.addLogMessage(`Added to bib file watcher: ${bibPath}`)
this.bibWatcher.add(bibPath)
this.bibsWatched.push(bibPath)
this.extension.completer.citation.parseBibFile(bibPath)
}
}
setEnvVar() {
const configuration = vscode.workspace.getConfiguration('latex-workshop')
process.env['LATEXWORKSHOP_DOCKER_LATEX'] = configuration.get('docker.image.latex') as string
}
}