-
Notifications
You must be signed in to change notification settings - Fork 4
/
preview_panel.ts
1470 lines (1380 loc) · 47.9 KB
/
preview_panel.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
995
996
997
998
999
1000
// Copyright (c) 2022, Geoffrey M. Poore
// All rights reserved.
//
// Licensed under the BSD 3-Clause License:
// http://opensource.org/licenses/BSD-3-Clause
//
import * as vscode from 'vscode';
import * as child_process from 'child_process';
import * as fs from 'fs';
import * as path from 'path';
import type { ExtensionState } from './types';
import PandocPreviewDefaults from './pandoc_preview_defaults';
import {countNewlines} from './util';
import {checkCodebraidVersion, minCodebraidVersion} from './check_codebraid';
type UpdatingStatus = null | 'waiting' | 'running' | 'finished';
const yamlMetadataRegex = /^---[ \t]*\r?\n.+?\n(?:---|\.\.\.)[ \t]*\r?\n/us;
export default class PreviewPanel implements vscode.Disposable {
// `PreviewPanel` interacts extensively with `vscode.TextEditor` and
// `vscode.TextDocument`. It is important to realize that editor and
// document states do not necessarily correspond to typical user
// descriptions. For example, `document.isClosed` describes an internal
// state that can be triggered by switching tabs so that a document is not
// visible. It does not describe whether a tab that displays a document
// exists anywhere in the current VS Code window. Relevant links:
// * https://code.visualstudio.com/api/references/vscode-api
// * https://github.com/microsoft/vscode/issues/15178
// * https://github.com/microsoft/vscode/issues/15723
// * https://github.com/microsoft/vscode/issues/21617
// * https://github.com/microsoft/vscode/issues/33728
//
// Class
// -----
disposables: vscode.Disposable[];
// Extension
// ---------
extension: ExtensionState;
_onDisposeExtensionCallback?: () => void;
// Files
// -----
cwd: string;
// All file paths associated with the document that contain document text,
// typically paths for Markdown files. That is, all paths excluding
// config, data, media, and so forth. For a single-file document, this is
// just obtained from `editor.document.fileName` at preview launch. For
// multi-file documents, file names are obtained using
// `codebraid.preview.pandoc.previewDefaultsFile` in extension config,
// which defaults to `_codebraid_preview.yaml`. If this file exists in
// the directory of the document that launches preview, it is read and
// checked for the key `input-files`. If this key exists and the list of
// `input-files` includes the document that launched the preview, then the
// list is used to define the file paths for the document. Note that file
// names are stored in an `Array` rather than a `Set` to allow for a
// single file to be included multiple times.
fileNames: Array<string>;
uriCache: Map<string, vscode.Uri>;
// Track visible editor that is relevant.
visibleEditor: vscode.TextEditor | undefined;
// Track recent visible files to determine which visible editor to sync
// with. It may be worth tracking `viewColumn` as well eventually.
currentFileName: string;
previousFileName: string | undefined;
// Pandoc
// ------
fromFormat: string;
fileScope: boolean;
toFormat: string;
pandocPreviewDefaults: PandocPreviewDefaults;
defaultsFileName: string | undefined;
// Display
// -------
panel: vscode.WebviewPanel | undefined;
resourceWebviewUris: Record<string, vscode.Uri>;
resourcePaths: Record<string, string>;
baseTag: string;
contentSecurityOptions: Map<string, Array<string>>;
contentSecurityTag: string;
codebraidPreviewJsTag: string;
sourceSupportsScrollSync: boolean;
isScrollingEditorWithPreview: boolean;
isScrollingEditorWithPreviewTimer: NodeJS.Timer | undefined;
scrollSyncOffset: number;
scrollSyncMap: Map<string, [number, number]> | undefined;
scrollSyncMapMaxLine: number;
isShowingUpdatingMessage: boolean;
// Subprocess
// ----------
pandocPreviewArgs: Array<string>;
pandocShowRawArgs: Array<string>;
pandocWithCodebraidOutputArgs: Array<string>;
pandocExportArgs: Array<string>;
waitedForPythonExtensionActivation: boolean | undefined;
codebraidCommand: Array<string> | null | undefined;
codebraidArgs: Array<string>;
pythonPathToCodebraidCommandCache: Map<string, Array<string>>;
buildProcessOptions: child_process.ExecFileOptions;
codebraidProcessOptions: child_process.SpawnOptions;
lastBuildTime: number;
needsBuild: boolean;
buildIsScheduled: boolean;
buildIsInProgress: boolean;
usingCodebraid: boolean;
codebraidIsInProgress: boolean;
codebraidHasMessageErrors: boolean;
didCheckInitialCodebraidCache: boolean;
oldCodebraidOutput: Map<string, Array<string>>;
currentCodebraidOutput: Map<string, Array<string>>;
codebraidProcessingStatus: Map<string, boolean>;
codebraidPlaceholderLangs: Map<string, string>;
constructor(editor: vscode.TextEditor, extension: ExtensionState) {
this.disposables = [];
this.extension = extension;
this.cwd = path.dirname(editor.document.uri.fsPath);
this.fileNames = [editor.document.fileName];
this.uriCache = new Map();
this.visibleEditor = editor;
this.currentFileName = editor.document.fileName;
this.fromFormat = extension.config.pandoc.fromFormat;
this.fileScope = false;
this.toFormat = 'html';
this.pandocPreviewDefaults = new PandocPreviewDefaults(this);
vscode.window.onDidChangeActiveTextEditor(
this.onDidChangeActiveTextEditor,
this,
this.disposables
);
vscode.window.onDidChangeVisibleTextEditors(
this.onDidChangeVisibleTextEditors,
this,
this.disposables
);
this.panel = vscode.window.createWebviewPanel(
'codebraidPreview', // Type
'Codebraid Preview', // Panel title
vscode.ViewColumn.Beside, // Editor column
{ // Options
enableScripts: true,
retainContextWhenHidden: true,
localResourceRoots: [
vscode.Uri.file(this.cwd),
vscode.Uri.file(this.extension.context.asAbsolutePath('media')),
vscode.Uri.file(this.extension.context.asAbsolutePath('scripts')),
vscode.Uri.file(this.extension.context.asAbsolutePath('node_modules/katex/dist')),
vscode.Uri.file(this.extension.context.asAbsolutePath('node_modules/@vscode/codicons/dist')),
],
}
);
this.disposables.push(this.panel);
// Cleanup may be triggered by the webview panel being closed. Since
// `retainContextWhenHidden` is true, the panel won't be disposed when
// it isn't visible.
this.panel.onDidDispose(
() => {
this.panel = undefined;
this.dispose();
},
this,
this.disposables
);
this.resourceWebviewUris = {
katex: this.panel.webview.asWebviewUri(
vscode.Uri.file(this.extension.context.asAbsolutePath('node_modules/katex/dist'))
),
vscodeCodicon: this.panel.webview.asWebviewUri(
vscode.Uri.file(this.extension.context.asAbsolutePath('node_modules/@vscode/codicons/dist/codicon.css'))
),
vscodeCss: this.panel.webview.asWebviewUri(
vscode.Uri.file(this.extension.context.asAbsolutePath('media/vscode-markdown.css'))
),
codebraidCss: this.panel.webview.asWebviewUri(
vscode.Uri.file(this.extension.context.asAbsolutePath('media/codebraid-preview.css'))
),
codebraidPreviewJs: this.panel.webview.asWebviewUri(
vscode.Uri.file(this.extension.context.asAbsolutePath('scripts/codebraid-preview.js'))
),
};
this.resourcePaths = {
pandocSourcePosPreprocFilter: this.extension.context.asAbsolutePath('scripts/pandoc-sourcepos-preproc.lua'),
pandocSourcePosSyncFilter: this.extension.context.asAbsolutePath('scripts/pandoc-sourcepos-sync.lua'),
pandocShowRawFilter: this.extension.context.asAbsolutePath('scripts/pandoc-raw.lua'),
pandocCodebraidOutputFilter: this.extension.context.asAbsolutePath('scripts/pandoc-codebraid-output.lua'),
};
this.baseTag = `<base href="${this.panel.webview.asWebviewUri(vscode.Uri.file(this.cwd))}/">`;
this.contentSecurityOptions = new Map([
['style-src', [`${this.panel.webview.cspSource}`, `'unsafe-inline'`]],
['font-src', [`${this.panel.webview.cspSource}`]],
['img-src', [`${this.panel.webview.cspSource}`]],
['script-src', [`${this.panel.webview.cspSource}`, `'unsafe-inline'`]],
]);
let contentSecurityContent: Array<string> = [];
for (const [src, opt] of this.contentSecurityOptions) {
contentSecurityContent.push(`${src} ${opt.join(' ')};`);
}
this.contentSecurityTag = [
`<meta http-equiv="Content-Security-Policy"`,
`content="default-src 'none';`,
contentSecurityContent.join(' '),
`">`
].join(' ');
this.codebraidPreviewJsTag = `<script type="module" src="${this.resourceWebviewUris.codebraidPreviewJs}"></script>`;
this.sourceSupportsScrollSync = false;
this.isScrollingEditorWithPreview = false;
this.scrollSyncOffset = 0;
this.scrollSyncMapMaxLine = 0;
this.isShowingUpdatingMessage = true;
this.showUpdatingMessage(null, null);
this.pandocPreviewArgs = [
`--standalone`,
`--lua-filter="${this.resourcePaths.pandocSourcePosSyncFilter}"`,
`--css=${this.resourceWebviewUris.vscodeCss}`,
`--css=${this.resourceWebviewUris.vscodeCodicon}`,
`--css=${this.resourceWebviewUris.codebraidCss}`,
`--katex=${this.resourceWebviewUris.katex}/`,
];
this.pandocShowRawArgs = [
`--lua-filter="${this.resourcePaths.pandocShowRawFilter}"`,
];
this.pandocWithCodebraidOutputArgs = [
`--lua-filter="${this.resourcePaths.pandocCodebraidOutputFilter}"`,
];
this.pandocExportArgs = [
'--standalone',
];
this.codebraidArgs = [
'pandoc',
'--only-code-output', 'codebraid_preview',
'--stdin-json-header',
];
this.pythonPathToCodebraidCommandCache = new Map();
this.buildProcessOptions = {
maxBuffer: 1024*1024*16, // = <default>*16 = 16_777_216 bytes
cwd: this.cwd,
shell: true // not ideal, but consistently 2-5x faster
};
this.codebraidProcessOptions = {
cwd: this.cwd,
shell: true,
};
this.didCheckInitialCodebraidCache = false;
this.oldCodebraidOutput = new Map();
this.currentCodebraidOutput = new Map();
this.codebraidProcessingStatus = new Map();
this.codebraidPlaceholderLangs = new Map();
this.lastBuildTime = 0;
this.needsBuild = true;
this.buildIsScheduled = false;
this.buildIsInProgress = false;
this.codebraidIsInProgress = false;
this.codebraidHasMessageErrors = false;
this.usingCodebraid = false;
vscode.workspace.onDidChangeTextDocument(
this.onDidChangeTextDocument,
this,
this.disposables
);
vscode.workspace.onDidSaveTextDocument(
this.onDidSaveTextDocument,
this,
this.disposables
);
vscode.window.onDidChangeTextEditorVisibleRanges(
this.onDidChangeTextEditorVisibleRanges,
this,
this.disposables
);
this.panel.webview.onDidReceiveMessage(
this.onDidReceiveMessage,
this,
this.disposables
);
// Need to wait until any preview defaults file is read and processed
// before creating initial preview.
this.pandocPreviewDefaults.update().then(() => {
this.update().then(() => {
this.onDidChangePreviewEditor(editor);
});
});
}
registerOnDisposeCallback(callback: () => void) {
this._onDisposeExtensionCallback = callback;
}
dispose() {
this.panel = undefined;
for (const disposable of this.disposables) {
disposable.dispose();
}
this.disposables.length = 0;
if (this._onDisposeExtensionCallback) {
this._onDisposeExtensionCallback();
this._onDisposeExtensionCallback = undefined;
}
}
onPandocPreviewDefaultsInvalidNotRelevant() {
this.fileNames = [this.currentFileName];
this.previousFileName = undefined;
this.fromFormat = this.extension.config.pandoc.fromFormat;
this.fileScope = false;
this.toFormat = 'html';
this.defaultsFileName = undefined;
}
formatMessage(title: string, message: string) {
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
${this.baseTag}
${this.contentSecurityTag}
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="${this.resourceWebviewUris.vscodeCss}">
<link rel="stylesheet" href="${this.resourceWebviewUris.vscodeCodicon}">
<link rel="stylesheet" href="${this.resourceWebviewUris.codebraidCss}">
<style>
body {
min-height: 100vh;
display: flex;
align-items: center;
justify-content: space-around;
}
</style>
<title>${title}</title>
</head>
<body>
<div>
${message}
</div>
</body>
</html>`;
}
updatingMessageClassMap = new Map([
['waiting', 'codebraid-updating codebraid-updating-waiting'],
['running', 'codebraid-updating codebraid-updating-running'],
['finished', 'codebraid-updating codebraid-updating-finished'],
]);
showUpdatingMessage(codebraidStatus: UpdatingStatus, pandocStatus: UpdatingStatus) {
if (!this.panel) {
return;
}
let messageList: Array<string> = [];
if (codebraidStatus === null && pandocStatus === null) {
messageList.push('<h1>Updating Codebraid Preview<span class="codebraid-updating-anim">...</span></h1>');
} else {
messageList.push('<h1>Updating Codebraid Preview...</h1>');
}
if (codebraidStatus !== null) {
messageList.push(`<p class="${this.updatingMessageClassMap.get(codebraidStatus)}">Codebraid: load cache</p>`);
}
if (pandocStatus !== null) {
messageList.push(`<p class="${this.updatingMessageClassMap.get(pandocStatus)}">Pandoc: convert</p>`);
}
this.panel.webview.html = this.formatMessage(
'Updating Codebraid Preview...',
messageList.join('\n')
);
}
convertStringToLiteralHtml(s: string) {
return s.replaceAll('&', '&')
.replaceAll('<', '<')
.replaceAll('>', '>')
.replaceAll('"', '"')
.replaceAll("'", ''');
}
onDidChangeActiveTextEditor(editor: vscode.TextEditor | undefined) {
if (!this.panel) {
return;
}
if (!editor) {
this.onDidChangeVisibleTextEditors(vscode.window.visibleTextEditors);
return;
}
if (editor.document.uri.scheme !== 'file' || this.fileNames.indexOf(editor.document.fileName) === -1) {
this.onDidChangeVisibleTextEditors(vscode.window.visibleTextEditors);
return;
}
this.visibleEditor = editor;
if (editor.document.fileName !== this.currentFileName) {
this.previousFileName = this.currentFileName;
this.currentFileName = editor.document.fileName;
}
this.onDidChangePreviewEditor(editor);
}
onDidChangeVisibleTextEditors(editors: readonly vscode.TextEditor[]) {
if (!this.panel) {
return;
}
this.visibleEditor = undefined;
for (const editor of editors) {
if (editor.document.uri.scheme === 'file' && editor.document.fileName === this.currentFileName) {
this.visibleEditor = editor;
this.onDidChangePreviewEditor(editor);
return;
}
}
if (this.fileNames.length === 1) {
return;
}
if (this.previousFileName) {
for (const editor of editors) {
if (editor.document.uri.scheme === 'file' && editor.document.fileName === this.previousFileName) {
this.visibleEditor = editor;
this.currentFileName = this.previousFileName;
this.previousFileName = undefined;
this.onDidChangePreviewEditor(editor);
return;
}
}
}
for (const editor of editors) {
if (editor.document.uri.scheme === 'file' && this.fileNames.indexOf(editor.document.fileName) !== -1) {
this.visibleEditor = editor;
this.previousFileName = this.currentFileName;
this.currentFileName = editor.document.fileName;
this.onDidChangePreviewEditor(editor);
return;
}
}
}
onDidChangeTextDocument(event: vscode.TextDocumentChangeEvent) {
if (!this.panel) {
return;
}
if (event.contentChanges.length !== 0 && event.document.uri.scheme === 'file') {
if (this.fileNames.indexOf(event.document.fileName) !== -1) {
this.update();
}
}
}
onDidSaveTextDocument(document: vscode.TextDocument) {
if (!this.panel) {
return;
}
if (document.fileName === this.pandocPreviewDefaults.fileName) {
this.pandocPreviewDefaults.update().then(() => {
this.update();
});
}
}
onDidChangeTextEditorVisibleRanges(event: vscode.TextEditorVisibleRangesChangeEvent) {
if (!this.panel) {
return;
}
if (event.visibleRanges.length === 0 || this.isScrollingEditorWithPreview) {
return;
}
let document = event.textEditor.document;
if (document.uri.scheme === 'file' && document.fileName === this.currentFileName) {
if (!this.sourceSupportsScrollSync) {
return;
}
if (this.extension.statusBarConfig.scrollPreviewWithEditor !== undefined) {
if (!this.extension.statusBarConfig.scrollPreviewWithEditor) {
return;
}
} else if (!this.extension.config.scrollPreviewWithEditor) {
return;
}
let startLine = event.visibleRanges[0].start.line + 1; // Webview is one-indexed
if (this.scrollSyncMap) {
let fileStartEndLine = this.scrollSyncMap.get(document.fileName);
if (fileStartEndLine) {
startLine += fileStartEndLine[0] - 1;
} else {
return;
}
}
startLine += this.scrollSyncOffset;
this.panel.webview.postMessage(
{
command: 'codebraidPreview.scrollPreview',
start: startLine,
}
);
}
}
onDidChangePreviewEditor(editor: vscode.TextEditor) {
if (!this.panel) {
return;
}
// Scroll preview when switching to a new editor for the first time.
if (this.isScrollingEditorWithPreview) {
return;
}
if (!this.sourceSupportsScrollSync) {
return;
}
if (this.extension.statusBarConfig.scrollPreviewWithEditor !== undefined) {
if (!this.extension.statusBarConfig.scrollPreviewWithEditor) {
return;
}
} else if (!this.extension.config.scrollPreviewWithEditor) {
return;
}
let startLine = editor.visibleRanges[0].start.line + 1; // Webview is one-indexed
if (this.scrollSyncMap) {
let fileStartEndLine = this.scrollSyncMap.get(editor.document.fileName);
if (fileStartEndLine) {
startLine += fileStartEndLine[0] - 1;
} else {
return;
}
}
startLine += this.scrollSyncOffset;
this.panel.webview.postMessage(
{
command: 'codebraidPreview.scrollPreview',
start: startLine,
}
);
}
async onDidReceiveMessage(message: any) {
if (!this.panel) {
return;
}
switch (message.command) {
case 'codebraidPreview.scrollEditor': {
if (!this.visibleEditor || !this.sourceSupportsScrollSync) {
return;
}
if (this.extension.statusBarConfig.scrollEditorWithPreview !== undefined) {
if (!this.extension.statusBarConfig.scrollEditorWithPreview) {
return;
}
} else if (!this.extension.config.scrollEditorWithPreview) {
return;
}
this.isScrollingEditorWithPreview = true;
let scrollStartLine: number = message.start - this.scrollSyncOffset;
if (this.scrollSyncMap) {
let scrollFileName = undefined;
for (const [fileName, [fileStartLine, fileEndLine]] of this.scrollSyncMap) {
if (fileStartLine <= scrollStartLine && scrollStartLine <= fileEndLine) {
scrollFileName = fileName;
scrollStartLine -= fileStartLine - 1;
break;
}
}
if (scrollFileName) {
let column = this.visibleEditor.viewColumn;
let document = await vscode.workspace.openTextDocument(scrollFileName);
let editor = await vscode.window.showTextDocument(document, column);
this.visibleEditor = editor;
}
}
if (!this.panel) {
return;
}
scrollStartLine -= 1; // Webview is one-indexed
if (scrollStartLine < 0) {
return;
}
let range = new vscode.Range(scrollStartLine, 0, scrollStartLine, 0);
this.visibleEditor.revealRange(range, vscode.TextEditorRevealType.AtTop);
if (this.isScrollingEditorWithPreviewTimer !== undefined) {
clearTimeout(this.isScrollingEditorWithPreviewTimer);
}
this.isScrollingEditorWithPreviewTimer = setTimeout(
() => {
this.isScrollingEditorWithPreview = false;
this.isScrollingEditorWithPreviewTimer = undefined;
},
50
);
return;
}
case 'codebraidPreview.moveCursor': {
if (!this.visibleEditor) {
return;
}
this.isScrollingEditorWithPreview = true;
const cursorLine: number = message.start - 1;
const position = new vscode.Position(cursorLine, 0);
const selection = new vscode.Selection(position, position);
this.visibleEditor.selection = selection;
const range = new vscode.Range(cursorLine, 0, cursorLine, 0);
this.visibleEditor.revealRange(range, vscode.TextEditorRevealType.InCenterIfOutsideViewport);
vscode.window.showTextDocument(this.visibleEditor.document, this.visibleEditor.viewColumn, false);
if (this.isScrollingEditorWithPreviewTimer !== undefined) {
clearTimeout(this.isScrollingEditorWithPreviewTimer);
}
this.isScrollingEditorWithPreviewTimer = setTimeout(
() => {
this.isScrollingEditorWithPreview = false;
this.isScrollingEditorWithPreviewTimer = undefined;
},
50
);
return;
}
}
}
switchEditor(editor: vscode.TextEditor) {
// This is called by `startPreview()`, which checks the editor for
// validity first.
if (!this.panel) {
return;
}
this.visibleEditor = editor;
if (!this.panel.visible) {
this.panel.reveal(vscode.ViewColumn.Beside);
}
if (editor.document.fileName !== this.currentFileName) {
this.previousFileName = this.currentFileName;
this.currentFileName = editor.document.fileName;
}
this.onDidChangePreviewEditor(editor);
}
setWebviewHTML(html: string) {
if (!this.panel) {
return;
}
this.isShowingUpdatingMessage = false;
this.panel.webview.html = html.replace(
`<head>`,
`<head>\n ${this.baseTag}\n ${this.contentSecurityTag}\n ${this.codebraidPreviewJsTag}`
);
}
async getFileTexts(fileNames: Array<string>, fromFormatIsCommonmark: boolean | undefined) : Promise<Array<string> | undefined> {
let fileTexts: Array<string> = [];
for (let fileName of fileNames) {
let fileText: string;
try {
let fileDocument = await vscode.workspace.openTextDocument(fileName);
fileText = fileDocument.getText();
} catch {
if (!this.panel) {
return;
}
vscode.window.showErrorMessage(`Missing input file "${fileName}"`);
return undefined;
}
fileTexts.push(fileText);
if (!this.usingCodebraid && fromFormatIsCommonmark !== undefined) {
if (fromFormatIsCommonmark) {
if (fileText.indexOf('.cb-') !== -1) {
this.usingCodebraid = true;
}
} else if (fileText.indexOf('.cb-') !== -1 || fileText.indexOf('.cb.') !== -1) {
this.usingCodebraid = true;
}
}
}
return fileTexts;
}
async getPythonExecCommand(): Promise<Array<string> | undefined> {
// Get Python command currently set in Python extension
const pythonExtension = vscode.extensions.getExtension('ms-python.python');
if (!pythonExtension) {
return undefined;
}
if (!pythonExtension.isActive) {
await pythonExtension.activate();
if (!this.panel) {
return undefined;
}
}
let currentUri: vscode.Uri | undefined = this.uriCache.get(this.currentFileName);
if (!currentUri) {
currentUri = vscode.Uri.file(this.currentFileName);
this.uriCache.set(this.currentFileName, currentUri);
}
// To get execCommand from microsoft/vscode-python extension:
// interface IExtensionApi
// https://github.com/microsoft/vscode-python/issues/12596
// https://github.com/microsoft/vscode-python/blob/3698950c97982f31bb9dbfc19c4cd8308acda284/src/client/api.ts
// Work around https://github.com/microsoft/vscode-python/issues/15467
// following the approach used in the mypy extension:
// https://github.com/matangover/mypy-vscode/blob/48162f345c7f14b96f29976660100ae1dd49cc0a/src/extension.ts#L694
let pythonExecCommand: Array<string> | undefined = pythonExtension.exports.settings.getExecutionDetails(currentUri).execCommand;
if (!pythonExecCommand) {
// Setting scoped to the first workspace folder, or global fallback
pythonExecCommand = pythonExtension.exports.settings.getExecutionDetails(undefined).execCommand;
}
if (!this.waitedForPythonExtensionActivation) {
if (pythonExecCommand && pythonExecCommand.length === 1 && pythonExecCommand[0] === 'python') {
let seconds = 0;
while (seconds < 5 && this.panel) {
await new Promise((resolve) => setTimeout(resolve, 1000));
seconds += 1;
pythonExecCommand = pythonExtension.exports.settings.getExecutionDetails(currentUri).execCommand;
if (!pythonExecCommand) {
pythonExecCommand = pythonExtension.exports.settings.getExecutionDetails(undefined).execCommand;
}
if (!pythonExecCommand || pythonExecCommand.length !== 1 || pythonExecCommand[0] !== 'python') {
break;
}
}
}
this.waitedForPythonExtensionActivation = true;
this.extension.log(
`Retrieving initial Python exec command from Python extension:\n ${pythonExecCommand?.join(' ')}`
);
}
return pythonExecCommand;
}
async setCodebraidCommand() {
let codebraidCommand: Array<string> = [];
let isCodebraidCompatible: boolean | null | undefined;
let pythonPath: string | undefined;
const pythonExecCommand = await this.getPythonExecCommand();
if (pythonExecCommand) {
if (pythonExecCommand.length === 1) {
pythonPath = pythonExecCommand[0];
} else {
for (const elem of pythonExecCommand) {
if (elem.includes('python')) {
pythonPath = elem;
break;
}
}
}
}
if (!pythonPath) {
pythonPath = vscode.workspace.getConfiguration('python').defaultInterpreterPath;
}
if (pythonPath && this.pythonPathToCodebraidCommandCache.has(pythonPath)) {
this.codebraidCommand = this.pythonPathToCodebraidCommandCache.get(pythonPath);
return;
}
if (pythonPath) {
const pythonPathElems: Array<string> = pythonPath.replaceAll('\\', '/').split('/');
if (pythonPathElems.length > 1 && pythonPathElems.at(-1)?.includes('python')) {
pythonPathElems.pop(); // Remove python executable
let binaryDir: string | undefined;
if (pythonPathElems.at(-1) === 'bin' || pythonPathElems.at(-1) === 'Scripts') {
binaryDir = pythonPathElems.at(-1);
pythonPathElems.pop();
}
const pythonRootPath: string = pythonPathElems.join('/');
const pythonRootPathQuoted: string = `"${pythonPathElems.join('/')}"`;
try {
await fs.promises.access(`${pythonRootPath}/conda-meta`, fs.constants.X_OK).then(() => {
// Using full paths to avoid https://github.com/conda/conda/issues/11174
codebraidCommand.push(...['conda', 'run', '--prefix', pythonRootPathQuoted, '--no-capture-output']);
});
} catch {
}
codebraidCommand.push(`${pythonRootPathQuoted}/${binaryDir ? binaryDir : 'Scripts'}/codebraid`);
isCodebraidCompatible = await checkCodebraidVersion(codebraidCommand);
}
}
if (isCodebraidCompatible === undefined) {
codebraidCommand = ['codebraid'];
isCodebraidCompatible = await checkCodebraidVersion(codebraidCommand);
if (isCodebraidCompatible && pythonPath) {
if (this.codebraidCommand === undefined || (Array.isArray(this.codebraidCommand) &&
(this.codebraidCommand.length !== 1 || this.codebraidCommand[0] !== 'codebraid'))) {
vscode.window.showWarningMessage([
`The Python interpreter selected in VS Code does not have codebraid installed or it could not be found.`,
`Falling back to codebraid on PATH.`
].join(' '));
this.extension.log([
`Could not find codebraid installation as part of Python interpreter selected in VS code:`,
` ${pythonPath}`,
`Falling back to codebraid on PATH.`
].join('\n'));
}
}
}
if (isCodebraidCompatible === undefined) {
this.codebraidCommand = undefined;
vscode.window.showErrorMessage([
`Could not find codebraid executable.`,
`Code execution is disabled.`,
`Install from https://pypi.org/project/codebraid/, v${minCodebraidVersion}+.`,
].join(' '));
} else if (isCodebraidCompatible === null) {
this.codebraidCommand = null;
vscode.window.showErrorMessage([
`Codebraid executable failed to return version information.`,
`Code execution is disabled.`,
`Consider reinstalling from https://pypi.org/project/codebraid/, v${minCodebraidVersion}+.`,
].join(' '));
} else if (isCodebraidCompatible === false) {
this.codebraidCommand = null;
vscode.window.showErrorMessage([
`Codebraid executable is outdated and unsupported.`,
`Code execution is disabled.`,
`Upgrade from https://pypi.org/project/codebraid/, v${minCodebraidVersion}+.`,
].join(' '));
} else {
if (this.codebraidCommand === undefined) {
this.extension.log(`Setting initial Codebraid command:\n ${codebraidCommand.join(' ')}`);
}
this.codebraidCommand = codebraidCommand;
if (pythonPath && (codebraidCommand.length !== 1 || codebraidCommand[0] !== 'codebraid')) {
this.pythonPathToCodebraidCommandCache.set(pythonPath, codebraidCommand);
}
}
}
isFromFormatCommonMark(format: string) : boolean {
return /^(?:commonmark_x|commonmark|gfm)(?:$|[+-])/.test(format);
}
async update() {
if (!this.panel) {
this.needsBuild = false;
return;
} else {
this.needsBuild = true;
}
if (this.buildIsScheduled || this.buildIsInProgress) {
return;
}
if (!this.panel.visible) {
this.buildIsScheduled = true;
// There currently isn't an event for the webview becoming visible
setTimeout(
() => {
this.buildIsScheduled = false;
this.update();
},
this.extension.config.minBuildInterval
);
return;
}
let timeNow = Date.now();
if (this.lastBuildTime + this.extension.config.minBuildInterval > timeNow) {
this.buildIsScheduled = true;
setTimeout(
() => {
this.buildIsScheduled = false;
this.update();
},
this.lastBuildTime + this.extension.config.minBuildInterval - timeNow
);
return;
}
if (!this.pandocPreviewDefaults.isValid) {
this.pandocPreviewDefaults.showErrorMessage();
return;
}
this.buildIsInProgress = true;
this.needsBuild = false;
this.lastBuildTime = timeNow;
// Collect all data that depends on config and preview defaults so
// that everything from here onward isn't affected by config or
// preview changes during await's.
const fileNames = this.fileNames;
let fromFormat = this.fromFormat;
const fileScope = this.fileScope;
const toFormat = this.toFormat;
const defaultsFileName = this.defaultsFileName;
const normalizedConfigPandocOptions = this.extension.normalizedConfigPandocOptions;
let fromFormatIsCommonmark: boolean = this.isFromFormatCommonMark(fromFormat);
this.sourceSupportsScrollSync = fromFormatIsCommonmark;
if (fromFormatIsCommonmark) {
fromFormat += '+sourcepos';
}
let maybeFileTexts: Array<string> | undefined = await this.getFileTexts(fileNames, fromFormatIsCommonmark);
if (!maybeFileTexts) {
this.buildIsInProgress = false;
this.sourceSupportsScrollSync = false;
return;
}
const fileTexts: Array<string> = maybeFileTexts;
if (this.usingCodebraid && !this.didCheckInitialCodebraidCache && !this.codebraidIsInProgress) {
this.didCheckInitialCodebraidCache = true;
if (this.isShowingUpdatingMessage) {
this.showUpdatingMessage('running', 'waiting');
}
await this.runCodebraidNoExecute();
if (this.isShowingUpdatingMessage) {
this.showUpdatingMessage('finished', 'running');
}
} else if (this.isShowingUpdatingMessage) {
this.showUpdatingMessage(null, 'running');
}
const executable: string = 'pandoc';
const args: Array<string> = [];
if (fromFormatIsCommonmark && (defaultsFileName || normalizedConfigPandocOptions.length > 0)) {
args.push(...['--lua-filter', `"${this.resourcePaths.pandocSourcePosPreprocFilter}"`]);
}
if (defaultsFileName) {
args.push(...['--defaults', `"${defaultsFileName}"`]);
}
args.push(...normalizedConfigPandocOptions);
args.push(...this.pandocPreviewArgs);
if (this.extension.config.pandoc.showRaw) {
args.push(...this.pandocShowRawArgs);
}
if (this.usingCodebraid) {
args.push(...this.pandocWithCodebraidOutputArgs);
}
if (fileScope) {
args.push('--file-scope');
}
args.push(`--from=${fromFormat}`);
args.push(`--to=${toFormat}`);
let buildProcess = child_process.execFile(
executable,
args,
this.buildProcessOptions,
(error, stdout, stderr) => {
if (!this.panel) {
return;
}
let output: string;
if (error) {
output = this.formatMessage(
'Codebraid Preview',
[
'<h1 style="color:red;">Codebraid Preview Error</h1>',
`<h2><code>${executable}</code> failed:</h2>`,
'<pre style="white-space: pre-wrap;">',
this.convertStringToLiteralHtml(String(error)),
'</pre>',
''
].join('\n')
);
this.scrollSyncOffset = 0;
this.sourceSupportsScrollSync = false;
} else {
output = stdout;
}
this.setWebviewHTML(output);
this.buildIsInProgress = false;
if (this.needsBuild) {
setTimeout(() => {this.update();}, 0);
}
}
);
this.scrollSyncOffset = 0;
let includingCodebraidOutput: boolean;
if (this.usingCodebraid && (this.currentCodebraidOutput.size > 0 || this.oldCodebraidOutput.size > 0)) {
includingCodebraidOutput = true;
} else {
includingCodebraidOutput = false;
}
if (includingCodebraidOutput) {
let metadataStartList: Array<string> = [
`---`,
`codebraid_meta:`,
` commonmark: ${fromFormatIsCommonmark}`,
` running: ${this.codebraidIsInProgress}`,
];
if (this.codebraidIsInProgress && this.codebraidProcessingStatus.size > 0) {
metadataStartList.push(` collection_processing:`);
for (const [k, v] of this.codebraidProcessingStatus) {
metadataStartList.push(` "${k}": ${v}`);