-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathextension.js
1395 lines (1282 loc) · 49 KB
/
extension.js
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
const vscode = require('vscode');
const fs = require('fs');
const path = require('path');
const { exec } = require('child_process');
const { DOMParser } = require('@xmldom/xmldom');
const parser = new DOMParser({ errorHandler: { warning: null }, locator: {} }, { ignoreUndefinedEntities: true });
const execSync = require('child_process').execSync;
const workspaceFolderUri = vscode.workspace.workspaceFolders[0].uri;
const buildTargets = ['html', 'pdf'];
const dapsConfigGlobal = vscode.workspace.getConfiguration('daps');
const dbgChannel = vscode.window.createOutputChannel('DAPS');
let previewPanel = undefined;
/**
* Holds the DAPS terminal instance, or null if it hasn't been created yet.
*/
var terminal = null;
for (let i = 0; i < vscode.window.terminals.length; i++) {
if (vscode.window.terminals[i].name == 'DAPS') {
terminal = vscode.window.terminals[i];
break;
}
}
if (terminal == null) {
terminal = vscode.window.createTerminal('DAPS');
}
/**
* Provides the data for the DocBook structure tree view in the VS Code extension.
* This class is responsible for managing the tree view, including refreshing the
* view and providing the tree items.
*/
class docStructureTreeDataProvider {
constructor() {
this._onDidChangeTreeData = new vscode.EventEmitter();
this.onDidChangeTreeData = this._onDidChangeTreeData.event;
}
refresh() {
this._onDidChangeTreeData.fire();
}
getTreeItem(element) {
return element;
}
getChildren(element) {
// Check if there are any open XML editors
const hasOpenXmlEditor = vscode.window.visibleTextEditors.some(
editor => editor.document.languageId === 'xml'
);
if (!hasOpenXmlEditor) {
return this._createEmptyStructure('No DocBook XML editor opened');
}
const filePath = this._getActiveFile();
if (!filePath) {
return this._createEmptyStructure('No DocBook XML editor opened');
}
const xmlDoc = this._parseXmlDocument(filePath);
const structureElements = this._getStructureElements();
const sectionElements = getElementsWithAllowedTagNames(xmlDoc, structureElements);
if (sectionElements.length === 0) {
return this._createEmptyStructure('The current document has no structure');
}
return this._createTreeItems(element, sectionElements, structureElements);
}
_getActiveFile() {
return getActiveFile();
}
_parseXmlDocument(filePath) {
const docContent = fs.readFileSync(filePath, 'utf-8');
return parser.parseFromString(docContent, 'text/xml');
}
_getStructureElements() {
const dapsConfig = vscode.workspace.getConfiguration('daps');
return dapsConfig.get('structureElements');
}
_createEmptyStructure(message) {
return [{
label: message,
collapsibleState: vscode.TreeItemCollapsibleState.None,
}];
}
_createTreeItems(element, sectionElements, structureElements) {
return sectionElements
.filter(sectionElement => this._shouldIncludeElement(element, sectionElement, structureElements))
.map(sectionElement => this._createTreeItem(sectionElement, structureElements));
}
_shouldIncludeElement(element, sectionElement, structureElements) {
return (!element && !structureElements.includes(sectionElement.parentNode.nodeName)) ||
(element && `${sectionElement.parentNode.nodeName}_${sectionElement.parentNode.lineNumber}` === element.id);
}
_createTreeItem(sectionElement, structureElements) {
const collapsibleState = this._determineCollapsibleState(sectionElement, structureElements);
const label = this._createLabel(sectionElement);
return {
label,
collapsibleState,
id: `${sectionElement.nodeName}_${sectionElement.lineNumber}`,
parentId: `${sectionElement.parentNode.nodeName}_${sectionElement.parentNode.lineNumber}`,
command: {
title: 'Activate related line',
command: 'daps.focusLineInActiveEditor',
arguments: [sectionElement.lineNumber.toString()]
}
};
}
_determineCollapsibleState(sectionElement, structureElements) {
for (let i = 0; i < sectionElement.childNodes.length; i++) {
if (structureElements.includes(sectionElement.childNodes[i].nodeName)) {
return vscode.TreeItemCollapsibleState.Collapsed;
}
}
return vscode.TreeItemCollapsibleState.None;
}
_createLabel(sectionElement) {
const titleElement = sectionElement.getElementsByTagName('title')[0];
const title = titleElement ? titleElement.textContent : '*** MISSING TITLE ***';
return `(${sectionElement.nodeName.substring(0, 1)}) "${title}"`;
}
}
/**
* Provides CodeLens items for assembly modules in the current document.
* This class listens for save events on the active document and refreshes the CodeLenses when the document is saved.
* The CodeLenses provide actions to peek into the referenced resources and open them in a new tab.
*/
class assemblyModulesCodeLensesProvider {
constructor() {
this._cachedCodeLenses = new Map();
this._onDidChangeCodeLensesEmitter = new vscode.EventEmitter();
this.onDidChangeCodeLenses = this._onDidChangeCodeLensesEmitter.event;
// Listen for save events to refresh the CodeLenses
vscode.workspace.onDidSaveTextDocument((document) => {
const pattern = dapsConfigGlobal.get('dbAssemblyPattern');
if (vscode.languages.match({ pattern }, document)) {
this.refresh(document);
}
});
}
provideCodeLenses(document) {
// Return cached CodeLenses if available
const cached = this._cachedCodeLenses.get(document.uri.toString());
if (cached) {
return cached;
}
// If no cache is available, return an empty array
return [];
}
refresh(document) {
// Recompute CodeLenses and cache them
const codeLenses = this._computeCodeLenses(document);
this._cachedCodeLenses.set(document.uri.toString(), codeLenses);
// Notify VSCode to refresh CodeLenses
this._onDidChangeCodeLensesEmitter.fire();
}
_computeCodeLenses(document) {
const parser = new DOMParser(); // Assuming parser is declared elsewhere
const xmlDoc = parser.parseFromString(document.getText());
const resourceElements = xmlDoc.getElementsByTagName('resource');
// Build resource id->href mapping
const resources = {};
for (let i = 0; i < resourceElements.length; i++) {
const resource = resourceElements[i];
resources[resource.getAttribute('xml:id')] = resource.getAttribute('href');
}
// Process modules and create CodeLens items
const moduleElements = xmlDoc.getElementsByTagName('module');
const codeLenses = [];
for (let i = 0; i < moduleElements.length; i++) {
const module = moduleElements[i];
const lineNumber = module.lineNumber - 1;
const resourceRef = module.getAttribute('resourceref');
if (resourceRef) {
const activeRange = new vscode.Range(lineNumber, 0, lineNumber, 0);
const activeEditorPath = vscode.window.activeTextEditor.document.uri.fsPath;
const directoryPath = activeEditorPath.substring(0, activeEditorPath.lastIndexOf('/'));
const dapsConfig = vscode.workspace.getConfiguration('daps');
// Add peek action
if (dapsConfig.get('showAssemblyCodelens') == 'peek'
|| dapsConfig.get('showAssemblyCodelens') == 'both') {
const peekUri = vscode.Uri.file(`${directoryPath}/${resources[resourceRef]}`);
codeLenses.push(new vscode.CodeLens(activeRange, {
title: `Peek into ${path.basename(resources[resourceRef])} `,
command: "editor.action.peekLocations",
arguments: [document.uri, activeRange.start, [new vscode.Location(peekUri, new vscode.Range(0, 0, 15, 0))]]
}));
}
// Add open action
if (dapsConfig.get('showAssemblyCodelens') == 'link'
|| dapsConfig.get('showAssemblyCodelens') == 'both') {
codeLenses.push(new vscode.CodeLens(activeRange, {
title: "Open in a new tab",
command: 'daps.openFile',
arguments: [`${directoryPath}/${resources[resourceRef]}`]
}));
}
}
}
return codeLenses;
}
}
/**
* Provides a CodeLens provider that displays references to cross-references (xrefs) in the editor.
* The provider scans the current workspace for files containing xrefs and generates CodeLens items
* that allow the user to peek at or open the referenced content.
*/
class xrefCodeLensProvider {
constructor(context) {
this.context = context;
this.dapsConfig = vscode.workspace.getConfiguration('daps');
this.excludeDirs = this.dapsConfig.get('xrefCodelensExcludeDirs');
this._cachedCodeLenses = new Map();
// Event emitter to trigger code lens updates
this._onDidChangeCodeLensesEmitter = new vscode.EventEmitter();
this.onDidChangeCodeLenses = this._onDidChangeCodeLensesEmitter.event;
// Listen for save events to refresh the CodeLenses
vscode.workspace.onDidSaveTextDocument((document) => {
const pattern = "**/*.{xml,adoc}";
if (vscode.languages.match({ pattern }, document)) {
this.refresh(document);
}
});
}
provideCodeLenses(document) {
// Return cached CodeLenses if available
const cached = this._cachedCodeLenses.get(document.uri.toString());
if (cached) {
return cached;
}
// If no cache is available, return an empty array
return [];
}
refresh(document) {
// Recompute CodeLenses and cache them
const codeLenses = this._computeCodeLenses(document);
this._cachedCodeLenses.set(document.uri.toString(), codeLenses);
// Notify VSCode to refresh CodeLenses
this._onDidChangeCodeLensesEmitter.fire();
}
_computeCodeLenses(document) {
dbg(`codelens:xrefCodelensExcludeDirs: ${this.excludeDirs}`);
const fileType = document.languageId;
dbg(`codelens:xref:languageId: ${fileType}`);
const xrefElements = this._extractXrefElements(document, fileType);
dbg(`codelens:xref:xrefElements.length: ${xrefElements.length}`);
const workspaceFolderUri = vscode.workspace.workspaceFolders[0].uri; // Assuming single-root workspace
const codeLenses = [];
for (let i = 0; i < xrefElements.length; i++) {
const xrefLinkend = this._getXrefLinkend(xrefElements[i], fileType);
dbg(`codelens:xref:xrefLinkend: ${xrefLinkend}`);
const matchedReferers = searchInFiles(
workspaceFolderUri.fsPath,
this.excludeDirs,
this._getSearchPattern(xrefLinkend, fileType),
fileType === "asciidoc" ? /\.adoc$/ : /\.xml$/
);
dbg(`codelens:xref:matchedReferers: ${matchedReferers.length}`);
const lineNumber = xrefElements[i].lineNumber - (fileType === "xml" ? 1 : 0);
const columnNumber = xrefElements[i].columnNumber;
const activeRange = new vscode.Range(
new vscode.Position(lineNumber, columnNumber),
new vscode.Position(lineNumber, columnNumber)
);
matchedReferers.forEach((referer, index) => {
dbg(`codelens:xref:matchedReferer ${index}: ${referer.file}`);
if (this.dapsConfig.get('showXrefCodelens') === 'peek' || this.dapsConfig.get('showXrefCodelens') === 'both') {
const codeLensPeek = this._createPeekCodeLens(document, activeRange, referer);
codeLenses.push(codeLensPeek);
}
if (this.dapsConfig.get('showXrefCodelens') === 'link' || this.dapsConfig.get('showXrefCodelens') === 'both') {
const codeLensOpen = this._createOpenCodeLens(activeRange, referer);
codeLenses.push(codeLensOpen);
}
dbg(`codelens:xref:codeLenses.length: ${codeLenses.length}`);
});
}
return codeLenses;
}
_extractXrefElements(document, fileType) {
if (fileType === "asciidoc") {
return this._parseAsciidocXrefs(document);
} else if (fileType === "xml") {
const text = parser.parseFromString(document.getText());
return Array.from(text.getElementsByTagName('xref'));
}
return [];
}
_parseAsciidocXrefs(document) {
const text = document.getText();
const regex = /<<([^,>]+)(?:,([^>]*))?>>/g;
const xrefElements = [];
let match;
while ((match = regex.exec(text)) !== null) {
xrefElements.push({
lineNumber: document.positionAt(match.index).line,
columnNumber: document.positionAt(match.index).character,
match: match[1],
title: match[2] || null
});
}
return xrefElements;
}
_getXrefLinkend(xrefElement, fileType) {
if (fileType === "asciidoc") {
return xrefElement.match;
} else if (fileType === "xml") {
return xrefElement.getAttribute('linkend');
}
return null;
}
_getSearchPattern(xrefLinkend, fileType) {
if (fileType === "asciidoc") {
return `\\[#(${xrefLinkend})(?:,([^\\]]*))?\\]`;
} else if (fileType === "xml") {
return `xml:id=\"${xrefLinkend}\"`;
}
return null;
}
_createPeekCodeLens(document, activeRange, referer) {
const activeUri = document.uri;
const peekRange = new vscode.Range(
new vscode.Position(referer.line, 0),
new vscode.Position(referer.line + 15, 0)
);
const peekUri = vscode.Uri.file(referer.file);
const peekLocation = new vscode.Location(peekUri, peekRange);
return new vscode.CodeLens(activeRange, {
title: `Peek into ${path.basename(referer.file)}`,
command: "editor.action.peekLocations",
arguments: [activeUri, activeRange.start, [peekLocation]]
});
}
_createOpenCodeLens(activeRange, referer) {
return new vscode.CodeLens(activeRange, {
title: "Open in a new tab",
command: 'daps.openFile',
arguments: [referer.file, referer.line]
});
}
}
// This method is called when your extension is activated
// Your extension is activated the very first time the command is executed
/**
* @param {vscode.ExtensionContext} context
*/
function activate(context) {
dbg('Congratulations, your extension "daps" is now active!');
dbg('Debug channel opened');
var extensionPath = context.extensionPath;
dbg(`Extension path: ${extensionPath}`);
const dapsConfig = vscode.workspace.getConfiguration('daps');
/**
* E V E N T S L I S T E N I N G
*/
// TODO tbazant chack if event listeners need to check document.languageId === 'xml'
// when saving active editor:
context.subscriptions.push(
vscode.workspace.onDidSaveTextDocument((document) => {
const fileName = document.uri.path;
const scrollMap = createScrollMap(fileName);
dbg(`saved document: ${fileName}`);
// refresh HTML preview
if (fileName == getActiveFile() && previewPanel) {
vscode.commands.executeCommand('daps.docPreview');
previewPanel.webview.postMessage({ command: 'updateMap', map: scrollMap });
}
// refresh doc structure treeview
vscode.commands.executeCommand('docStructureTreeView.refresh');
}));
// when closing active editor:
context.subscriptions.push(
vscode.workspace.onDidCloseTextDocument(() => {
// clear the scroll map for HTML preview
let scrollMap = {};
}));
// when active editor is changed:
context.subscriptions.push(
vscode.window.onDidChangeActiveTextEditor((activeEditor) => {
if (activeEditor && activeEditor.document.languageId === 'xml') {
// refresh doc structure treeview
vscode.commands.executeCommand('docStructureTreeView.refresh');
// create scroll map for HTML preview
createScrollMap();
}
}));
// when the visible editors change
context.subscriptions.push(
vscode.window.onDidChangeVisibleTextEditors(() => {
// ensure the tree view is cleared when the last XML editor is closed and updated
vscode.commands.executeCommand('docStructureTreeView.refresh');
})
);
/**
* Focuses the active editor on the specified line number.
*
* This command is used to move the cursor and scroll the editor to the specified line number in the active text editor.
* If the 'onClickedStructureItemMoveCursor' configuration option is enabled, the cursor will be moved to the specified line.
* Otherwise, the editor will be scrolled to reveal the specified line.
*
* @param {number} lineNumber - The line number to focus in the active editor.
*/
vscode.commands.registerCommand('daps.focusLineInActiveEditor', async (lineNumber) => {
const activeTextEditor = vscode.window.activeTextEditor;
if (activeTextEditor) {
const dapsConfig = vscode.workspace.getConfiguration('daps');
if (dapsConfig.get('onClickedStructureItemMoveCursor')) {
// Ensure the lineNumber is within valid bounds
lineNumber = Math.max(0, Math.min(lineNumber, activeTextEditor.document.lineCount - 1));
// Create a Position object for the desired line
const position = new vscode.Position(lineNumber, 0);
// Move the cursor to the specified position
activeTextEditor.selection = new vscode.Selection(position, position);
// Reveal the position in the active editor
activeTextEditor.revealRange(new vscode.Range(position, position), vscode.TextEditorRevealType.InCenter);
// Create a Uri for the active document
const documentUri = activeTextEditor.document.uri;
// Show the document and move the cursor to the specified position
await vscode.window.showTextDocument(documentUri, {
selection: new vscode.Range(lineNumber, 0, lineNumber, 0),
viewColumn: activeTextEditor.viewColumn
});
} else {
// Create a Range object for the desired line
const lineRange = activeTextEditor.document.lineAt(lineNumber - 1).range;
// Reveal the line in the editor
activeTextEditor.revealRange(lineRange, vscode.TextEditorRevealType.InCenter);
}
}
});
/**
* Registers a command to open a file in the editor with a peek view.
*
* This command is used to open a file in the editor and display a peek view of the specified range of the file.
* The peek view allows the user to quickly view the contents of the file without switching to the full editor.
*
* @param {string} filePath - The path of the file to open.
* @param {vscode.Range} range - The range of the file to display in the peek view.
*/
context.subscriptions.push(vscode.commands.registerCommand('daps.peekFile', async (filePath, range) => {
const uri = vscode.Uri.file(filePath);
vscode.commands.executeCommand('editor.action.peekLocations', uri, range.start, [new vscode.Location(uri, range)], 'peek');
}));
/**
* create treeview for DocBook structure
*/
const treeDataProvider = new docStructureTreeDataProvider;
context.subscriptions.push(vscode.window.registerTreeDataProvider('docbookFileStructure', treeDataProvider))
vscode.commands.registerCommand('docStructureTreeView.refresh', () => {
treeDataProvider.refresh();
})
/**
* command for opening editor, optionally in a split window
*/
vscode.commands.registerCommand('daps.openFile', async (file, line) => {
const dapsConfig = vscode.workspace.getConfiguration('daps');
const viewMode = dapsConfig.get('openFileSplit') ? vscode.ViewColumn.Beside : { preview: false };
try {
const document = await vscode.workspace.openTextDocument(file);
const editor = vscode.window.showTextDocument(document, viewMode);
// Ensure the line number is valid
const lineNumber = Math.max(0, Math.min(line, document.lineCount - 1));
// Reveal the line in the editor
const position = new vscode.Position(lineNumber, 0);
const range = new vscode.Range(position, position);
(await editor).revealRange(range, vscode.TextEditorRevealType.AtTop);
editor.selection = new vscode.Selection(position, position);
} catch (err) {
vscode.window.showErrorMessage(`Error opening file: ${err.message}`);
}
});
/**
* Registers a code lens provider for assembly modules in the DAPS (DocBook Authoring and Publishing Suite) extension.
* The code lens provider is responsible for displaying code lens information for assembly modules in XML and Asciidoc files.
* The code lens information is displayed above the assembly module declarations and provides a way for users to navigate to the
* referenced assembly modules.
*/
context.subscriptions.push(vscode.languages.registerCodeLensProvider({
pattern: dapsConfigGlobal.get('dbAssemblyPattern')
}, new assemblyModulesCodeLensesProvider(context)));
/**
* Registers a code lens provider for XML and Asciidoc files in the DAPS (DocBook Authoring and Publishing Suite) extension.
* The code lens provider is responsible for displaying code lens information for cross-references (xrefs) in these file types.
* The code lens information is displayed above the xref declarations and provides a way for users to navigate to the
* referenced content.
*/
context.subscriptions.push(vscode.languages.registerCodeLensProvider({
pattern: "**/*.{xml,adoc}"
}, new xrefCodeLensProvider(context)));
/**
* enable autocomplete XML entities from external files
*/
if (dapsConfig.get('autocompleteXMLentities')) {
dbg(`autocompleteXMLentities: ${dapsConfig.get('autocompleteXMLentities')}`)
context.subscriptions.push(vscode.languages.registerCompletionItemProvider('xml', {
provideCompletionItems(document, position, token, context) {
dbg(`entity:doc: ${document.fileName}, pos: ${position.line}, token: ${token.isCancellationRequested}, context: ${context.triggerKind}`);
// Get array of entity files
let entityFiles = getXMLentityFiles(document.fileName);
dbg(`entity:Number of entity files: ${entityFiles.length}`);
// Extract entities from entity files
let entities = getXMLentites(entityFiles);
dbg(`entity:Number of entities: ${entities.length}`);
let result = [];
entities.forEach(entity => {
dbg(`entity:entity ${entity}`)
let completionItem = new vscode.CompletionItem(entity);
completionItem.label = `&${entity}`;
dbg(`entity:completionItem.label ${completionItem.label}`)
completionItem.kind = vscode.CompletionItemKind.Keyword;
dbg(`entity:completionItem.kind ${completionItem.kind}`)
completionItem.filterText = entity.substring(-1);
dbg(`entity:completionItem.filterText ${completionItem.filterText}`)
// Adjust `insertText` based on the trigger context
const lineText = document.lineAt(position).text;
dbg(`entity:lineText ${lineText}`);
const textBeforeCursor = lineText.slice(0, position.character);
dbg(`entity:textBeforeCursor ${textBeforeCursor}`);
const indexOfAmpersand = textBeforeCursor.lastIndexOf('&');
dbg(`entity:indexOfAmpersand ${indexOfAmpersand}`);
const textFromAmpersand = indexOfAmpersand !== -1 ? textBeforeCursor.slice(indexOfAmpersand) : '';
dbg(`entity:textFromAmpersand ${textFromAmpersand}`);
const charBeforeCursor = lineText[position.character - 1] || '';
dbg(`entity:charBeforeCursor ${charBeforeCursor}`);
// If the context was triggered by `&`, only insert the entity itself
if (charBeforeCursor === '&' || textFromAmpersand) {
completionItem.insertText = new vscode.SnippetString(entity);
} else {
completionItem.insertText = new vscode.SnippetString(`&${entity}`);
}
result.push(completionItem);
});
dbg(`Number of results: ${result.length}`);
return result;
}
}, '&'));
}
/**
* enables document HTML preview + handler to update it when src doc chanegs
*/
context.subscriptions.push(vscode.commands.registerCommand('daps.docPreview', function docPreview(contextFileURI) {
// get img src path from config
const dapsConfig = vscode.workspace.getConfiguration('daps');
// path to images
let docPreviewImgPath = dapsConfig.get('docPreviewImgPath');
dbg(`preview:docPreviewImgPath ${docPreviewImgPath}`);
const activeEditorDir = getActiveEditorDir();
dbg(`preview:activeEditorDir ${activeEditorDir}`);
// create a new webView if it does not exist yet
if (previewPanel === undefined) {
previewPanel = vscode.window.createWebviewPanel(
'htmlPreview', // Identifies the type of the webview
'HTML Preview', // Title displayed in the panel
vscode.ViewColumn.Two, // Editor column to show the webview panel
{
enableScripts: true,
localResourceRoots: [vscode.Uri.file(path.join(activeEditorDir, docPreviewImgPath))]
}
);
}
// what is the document i want to preview?
let srcXMLfile = getActiveFile(contextFileURI);
dbg(`Source XML file: ${srcXMLfile}`);
// compile transform command
let transformCmd = `xsltproc --stringparam img.src.path ${docPreviewImgPath} ${extensionPath}/xslt/doc-preview.xsl ${srcXMLfile}`;
dbg(`xsltproc cmd: ${transformCmd}`);
// get its stdout into a variable
let htmlContent = execSync(transformCmd).toString();
// Update <img/> tags for webview, create a regex to match <img src="...">
const imageRegex = /<img src="([^"]+)"/g;
// Replace all image src attributes
htmlContent = htmlContent.replace(imageRegex, (match, src) => {
var imgURI = undefined;
// For each image, create the path to the image
imgUri = vscode.Uri.file(path.join(activeEditorDir, docPreviewImgPath, src));
dbg(`preview:imgUri ${imgUri}`);
// check if imgURI extsts and if not, check SVG variant
if (!fs.existsSync(imgUri.path)) {
const svgPath = imgUri.path.replace(/\.[^/.]+$/, ".svg");
dbg(`preview:svgPath: ${svgPath}`);
if (fs.existsSync(svgPath)) {
imgUri = vscode.Uri.file(svgPath);
} else {
dbg(`preview:imgUri: Neither ${imgUri.path} nor ${svgPath} exist`)
}
}
dbg(`preview:final imgUri: ${imgUri}`);
// create img URI that the webview can swollow
const imgWebviewUri = previewPanel.webview.asWebviewUri(imgUri);
dbg(`preview:imgWebviewUri ${imgWebviewUri}`);
// Return the updated <img> tag with the new src
return `<img src="${imgWebviewUri}"`;
});
//compile the whole HTML for webview
let html = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML Preview</title>
</head>
<body>
<!-- Your preview content goes here -->
<div id="content">
${htmlContent}
</div>
<script>
const vscode = acquireVsCodeApi();
const srcXMLfile = "${srcXMLfile}";
let scrollMap = []; // Scroll map sent from the extension
let isProgrammaticScroll = false; // Flag to track programmatic scrolling
// Handle messages sent from the extension to the webview
window.addEventListener('message', event => {
const message = event.data; // The JSON data sent by the extension
switch (message.command) {
case 'updateMap':
scrollMap = message.map;
// Enhance the scrollMap with dynamically calculated offsets
scrollMap = scrollMap.map(entry => {
const element = document.getElementById(entry.id);
return {
...entry,
offset: element ? element.offsetTop : 0
};
});
console.log(scrollMap);
break;
case 'syncScroll':
// Scroll to a specific line programmatically
const lineToElement = scrollMap.find(item => item.line === message.line);
if (lineToElement) {
const element = document.getElementById(lineToElement.id);
if (element) {
isProgrammaticScroll = true; // Set the flag to ignore the scroll event
element.scrollIntoView({ behavior: 'smooth' });
}
}
break;
}
});
// Send scroll messages to the extension
document.addEventListener('scroll', () => {
if (isProgrammaticScroll) {
// Reset the flag and ignore this scroll event
isProgrammaticScroll = false;
return;
}
const scrollPosition = window.scrollY;
// Find the appropriate line based on scroll position
let lineToScroll = null;
for (let i = 0; i < scrollMap.length - 1; i++) {
if (
scrollPosition >= scrollMap[i].offset &&
scrollPosition < scrollMap[i + 1].offset
) {
lineToScroll = scrollMap[i].line;
break;
}
}
// Send message only if a matching line was found
if (lineToScroll !== null) {
console.log({
command: 'scroll',
position: scrollPosition,
line: lineToScroll,
srcXMLfile: srcXMLfile
});
vscode.postMessage({
command: 'scroll',
position: scrollPosition,
line: lineToScroll,
srcXMLfile: srcXMLfile
});
}
});
</script>
</body>
</html>`;
const scrollMap = createScrollMap(vscode.window.activeTextEditor.document.fileName);
dbg(`preview:scrollmap:length ${scrollMap.length}`);
previewPanel.webview.html = html;
previewPanel.webview.postMessage({ command: 'updateMap', map: scrollMap });
previewPanel.onDidDispose(() => {
previewPanel = undefined;
});
// listen to scroll messages from the active editor
vscode.window.onDidChangeTextEditorVisibleRanges(event => {
const editor = event.textEditor;
const topLine = editor.visibleRanges[0].start.line;
previewPanel.webview.postMessage({ command: 'syncScroll', line: topLine });
});
// Listen to scroll messages from the WebView
let previewLinkScrollBoth = dapsConfig.get('previewLinkScrollBoth');
if (previewLinkScrollBoth) {
previewPanel.webview.onDidReceiveMessage(async (message) => {
switch (message.command) {
case 'scroll': {
const scrollPosition = message.position;
dbg(`preview:scrollPosition ${scrollPosition}`);
const srcXMLfile = message.srcXMLfile;
dbg(`preview:srcXMLfile ${srcXMLfile}`);
const lineToScroll = message.line;
dbg(`preview:scroll:lineToScroll ${lineToScroll}`);
if (lineToScroll !== undefined) {
// Ensure the correct editor is opened
const fileUri = vscode.Uri.file(srcXMLfile);
// Check if the document is already open
let targetEditor = vscode.window.visibleTextEditors.find(editor =>
editor.document.uri.fsPath === fileUri.fsPath
);
if (!targetEditor) {
// Open the file if it is not already open
const document = await vscode.workspace.openTextDocument(fileUri);
targetEditor = await vscode.window.showTextDocument(document);
}
if (targetEditor) {
const position = new vscode.Position(lineToScroll - 1, 0); // Convert 1-based to 0-based
const range = new vscode.Range(position, position);
targetEditor.revealRange(range, vscode.TextEditorRevealType.InCenter);
}
}
break;
}
}
}, undefined, context.subscriptions);
}
}));
/**
* @description validates documentation identified by DC file
* @param {string} DCfile URI from context command (optional)
* @returns true or false depending on how validation happened
*/
context.subscriptions.push(vscode.commands.registerCommand('daps.validate', async function validate(contextDCfile) {
var DCfile = await getDCfile(contextDCfile);
if (DCfile) {
// assemble daps command
const dapsCmd = getDapsCmd({ DCfile: DCfile, cmd: 'validate' });
const dapsConfig = vscode.workspace.getConfiguration('daps');
// change working directory to current workspace
process.chdir(workspaceFolderUri.path);
dbg(`cwd is ${workspaceFolderUri.path}`);
// decide whether to run terminal
try {
if (dapsConfig.get('runTerminal')) {
dbg('Running command in terminal');
terminal.sendText(dapsCmd);
terminal.show(true);
} else {
vscode.window.showInformationMessage(`Running ${dapsCmd}`);
execSync(dapsCmd);
vscode.window.showInformationMessage('Validation succeeded.');
}
return true;
} catch (err) {
vscode.window.showErrorMessage(`Validation failed: ${err}`);
}
}
return false;
}));
/**
* @description builds HTML or PDF targets given DC file
* @param {object} DCfile URI from context command (optional)
* @returns true or false depending on how the build happened
*/
context.subscriptions.push(vscode.commands.registerCommand('daps.buildDCfile', async function buildDCfile(contextDCfile) {
var buildTarget;
var DCfile = await getDCfile(contextDCfile);
// try if buildTarget is included in settings or get it from user
const dapsConfig = vscode.workspace.getConfiguration('daps');
if (buildTarget = dapsConfig.get('buildTarget')) {
dbg(`buildTarget from config: ${buildTarget}`);
} else {
buildTarget = await vscode.window.showQuickPick(buildTargets);
dbg(`buildTarget form picker: ${buildTarget}`);
}
// assemble daps command
if (DCfile && buildTarget) {
var params = {
DCfile: DCfile,
buildTarget: buildTarget,
}
var dapsCmd = getDapsCmd(params);
const dapsConfig = vscode.workspace.getConfiguration('daps');
try {
// change working directory to current workspace
process.chdir(workspaceFolderUri.path);
dbg(`cwd is ${workspaceFolderUri.path}`);
if (dapsConfig.get('runTerminal')) {
dbg('Running command in terminal');
terminal.sendText(dapsCmd);
terminal.show(true);
} else {
vscode.window.showInformationMessage(`Running ${dapsCmd}`);
let cmdOutput = execSync(dapsCmd);
let targetBuild = cmdOutput.toString().trim();
if (buildTarget == 'html') {
targetBuild = targetBuild + 'index.html';
}
dbg('target build: ' + targetBuild);
vscode.window.showInformationMessage('Build succeeded.', 'Open document', 'Copy link').then(selected => {
dbg(selected);
if (selected === 'Open document') {
exec('xdg-open ' + targetBuild);
} else if (selected === 'Copy link') {
vscode.env.clipboard.writeText(targetBuild);
}
});
}
return true;
} catch (err) {
vscode.window.showErrorMessage(`Build failed: ${err}.message`);
}
}
return false;
}));
/**
* command to build single XML file
*/
context.subscriptions.push(vscode.commands.registerCommand('daps.buildXMLfile', async function buildXMLfile(contextFileURI) {
// decide on input XML file - take active editor if file not specified from context
var XMLfile = getActiveFile(contextFileURI);
var buildTarget = await getBuildTarget();
if (buildTarget) {
var params = {
XMLfile: XMLfile,
buildTarget: buildTarget,
options: ['--norefcheck']
}
// add --single option for HTML builds
if (buildTarget == 'html') {
params['options'].push('--single');
}
var dapsCmd = getDapsCmd(params);
const dapsConfig = vscode.workspace.getConfiguration('daps');
try {
await autoSave(XMLfile);
if (dapsConfig.get('runTerminal')) {
dbg('Running command in terminal');
terminal.sendText(dapsCmd);
terminal.show(true);
} else {
vscode.window.showInformationMessage(`Running ${dapsCmd}`);
let cmdOutput = execSync(dapsCmd);
let targetBuild = cmdOutput.toString().trim();
if (buildTarget == 'html') {
targetBuild = targetBuild + 'index.html';
}
dbg('target build: ' + targetBuild);
vscode.window.showInformationMessage('Build succeeded.', 'Open document', 'Copy link').then(selected => {
dbg(selected);
if (selected === 'Open document') {
exec('xdg-open ' + targetBuild);
} else if (selected === 'Copy link') {
vscode.env.clipboard.writeText(targetBuild);
}
});
}
return true;
} catch (err) {
vscode.window.showErrorMessage(`Build failed: ${err.message}`);
}
}
}));
context.subscriptions.push(vscode.commands.registerCommand('daps.buildRootId', async function buildRootId(contextFileURI) {
var buildTarget = await getBuildTarget();
var DCfile = await getDCfile();
var rootId = await getRootId(contextFileURI, DCfile);
// assemble daps command
if (DCfile && rootId && buildTarget) {
const params = {
DCfile: DCfile,
buildTarget: buildTarget,
rootId: rootId
}
const dapsCmd = getDapsCmd(params);
const dapsConfig = vscode.workspace.getConfiguration('daps');
try {
// change working directory to current workspace
process.chdir(workspaceFolderUri.path);
dbg(`cwd is ${workspaceFolderUri.path}`);
if (dapsConfig.get('runTerminal')) {
dbg('Running command in terminal');
terminal.sendText(dapsCmd);
terminal.show(true);
} else {
vscode.window.showInformationMessage(`Running ${dapsCmd}`);
let cmdOutput = execSync(dapsCmd);
let targetBuild = cmdOutput.toString().trim();
if (buildTarget == 'html') {
targetBuild = targetBuild + 'index.html';
}
dbg('target build: ' + targetBuild);
vscode.window.showInformationMessage('Build succeeded.', 'Open document', 'Copy link').then(selected => {
dbg(selected);
if (selected === 'Open document') {
exec('xdg-open ' + targetBuild);
} else if (selected === 'Copy link') {
vscode.env.clipboard.writeText(targetBuild);
}
});
}
return true;
} catch (err) {
vscode.window.showErrorMessage(`Build failed: ${err.message}`);
}
}
return false;
}));
context.subscriptions.push(vscode.commands.registerCommand('daps.XMLformat', async function XMLformat(contextFileURI) {
var XMLfile;
if (contextFileURI) { //check if XML file was passed as context
XMLfile = contextFileURI.path;
dbg(`XMLfile from context: ${XMLfile}`);
} else if (vscode.window.activeTextEditor) { // try the currently open file
XMLfile = vscode.window.activeTextEditor.document.fileName;
dbg(`XML file from active editor: ${XMLfile}`);