-
Notifications
You must be signed in to change notification settings - Fork 182
Expand file tree
/
Copy pathlsp.ts
More file actions
1006 lines (884 loc) · 31.7 KB
/
Copy pathlsp.ts
File metadata and controls
1006 lines (884 loc) · 31.7 KB
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
import { spawnSync } from "child_process";
import { resolve } from "path";
import * as vscode from "vscode";
import * as lc from "vscode-languageclient";
import * as Is from "vscode-languageclient/lib/common/utils/is";
import type { SymbolInformation, LanguageClientOptions } from "vscode-languageclient/node";
import type { BaseLanguageClient as LanguageClient } from "vscode-languageclient";
import { HoverDummyStorage } from "./features/hover-storage";
import type { HoverTmpStorage } from "./features/hover-storage.tmp";
import { extensionState } from "./state";
import {
bytesBase64Encode,
DisposeList,
getSensibleTextEditorColumn,
typstDocumentSelector,
} from "./util";
import type { ExportActionOpts, ExportOpts } from "./cmd.export";
import { substVscodeVarsInConfig, TinymistConfig } from "./config";
import { TinymistStatus, wordCountItemProcess } from "./ui-extends";
import { previewProcessOutline } from "./features/preview";
import { l10nMsg } from "./l10n";
import { wordPattern } from "./language";
import type { createSystemLanguageClient } from "./lsp.system";
interface ResourceRoutes {
"/fonts": any;
"/symbols": any;
"/preview/index.html": string;
"/dir/package": string;
"/dir/package/local": string;
"/package/by-namespace": PackageInfo[];
"/package/symbol": SymbolInfo;
"/package/docs": string;
}
/// kill the probe task after 60s
const PROBE_TIMEOUT = 60_000;
/**
* The result of starting a preview task.
*/
export interface PreviewResult {
/**
* The frontend address
*/
staticServerAddr?: string;
/**
* The frontend port
*/
staticServerPort?: number;
/**
* The data plane address
*/
dataPlanePort?: number;
/**
* Whether the preview content is provided by the primary compiler instance. This must be indicate by the CLI argument `--not-primary`
* when starts a preview task by *LSP Command*.
*
* Context: If there is a only preview task, the (primary) compiler instance which is used by LSP is used.
* If there are multiple preview tasks, tinymist will spawn a new compiler instance for each additional task.
*/
isPrimary?: boolean;
}
// That's very unfortunate that sourceScrollBySpan doesn't work well.
export interface SourceScrollBySpanRequest {
event: "sourceScrollBySpan";
span: string;
}
export interface PanelScrollByPositionRequest {
event: "panelScrollByPosition";
position: any;
}
export interface PanelScrollOrCursorMoveRequest {
event: "panelScrollTo" | "changeCursorPosition";
filepath: string;
line: any;
character: any;
}
export type ScrollPreviewRequest =
| SourceScrollBySpanRequest
| PanelScrollByPositionRequest
| PanelScrollOrCursorMoveRequest;
interface JumpInfo {
filepath: string;
start: [number, number] | null;
end: [number, number] | null;
}
class BufferedOutputChannel implements vscode.OutputChannel {
private readonly channel: vscode.OutputChannel;
private buffer = "";
constructor(
name: string,
languageId?: string,
private readonly maxChars: number = 200_000,
) {
this.channel = languageId
? vscode.window.createOutputChannel(name, languageId)
: vscode.window.createOutputChannel(name);
}
get name(): string {
return this.channel.name;
}
append(value: string): void {
this.push(value);
this.channel.append(value);
}
appendLine(value: string): void {
this.push(`${value}\n`);
this.channel.appendLine(value);
}
clear(): void {
this.buffer = "";
this.channel.clear();
}
show(preserveFocus?: boolean): void;
show(column?: vscode.ViewColumn, preserveFocus?: boolean): void;
show(
columnOrPreserveFocus?: vscode.ViewColumn | boolean,
preserveFocus?: boolean,
): void {
if (typeof columnOrPreserveFocus === "boolean" || columnOrPreserveFocus === undefined) {
this.channel.show(columnOrPreserveFocus);
return;
}
this.channel.show(columnOrPreserveFocus, preserveFocus);
}
hide(): void {
this.channel.hide();
}
replace(value: string): void {
this.buffer = "";
this.push(value);
if ("replace" in this.channel && typeof this.channel.replace === "function") {
this.channel.replace(value);
return;
}
this.channel.clear();
this.channel.append(value);
}
dispose(): void {
this.channel.dispose();
}
getText(maxChars?: number): string {
if (maxChars === 0) {
return "";
}
if (maxChars === undefined || maxChars < 0 || this.buffer.length <= maxChars) {
return this.buffer;
}
return this.buffer.slice(-maxChars);
}
private push(value: string): void {
if (!value || this.maxChars <= 0) {
return;
}
this.buffer += value;
if (this.buffer.length > this.maxChars) {
this.buffer = this.buffer.slice(-this.maxChars);
}
}
}
export class LanguageState {
static Client: typeof createSystemLanguageClient = undefined!;
static HoverTmpStorage?: typeof HoverTmpStorage = undefined;
outputChannel = new BufferedOutputChannel("Tinymist Typst", "log");
context: vscode.ExtensionContext = undefined!;
client: LanguageClient | undefined = undefined;
_watcher: vscode.FileSystemWatcher | undefined = undefined;
clientPromiseResolve = (_client: LanguageClient) => { };
clientPromise: Promise<LanguageClient> = new Promise((resolve) => {
this.clientPromiseResolve = resolve;
});
async stop() {
this.clientPromiseResolve = (_client: LanguageClient) => { };
this.clientPromise = new Promise((resolve) => {
this.clientPromiseResolve = resolve;
});
if (this._watcher) {
this._watcher.dispose();
this._watcher = undefined;
}
if (this.client) {
await this.client.stop();
this.client = undefined;
}
// Reset server readiness flag so other code doesn't assume a running server
if (extensionState?.mut) {
extensionState.mut.serverReady = false;
}
}
getClient() {
return this.clientPromise;
}
/**
* Checks if the LSP server is available and shows a warning if not.
* @returns true if server is available, false otherwise
*/
checkServerHealth(): boolean {
if (this.client) return true;
// Server health check: warn user if server is unavailable
if (!extensionState.mut.serverHealthWarningShown) {
extensionState.mut.serverHealthWarningShown = true;
void vscode.window
.showWarningMessage(
l10nMsg(
"Tinymist server is not available. Some features like auto-formatting on Enter may not work. Try restarting the server.",
),
l10nMsg("Restart Server"),
)
.then((selection) => {
if (selection === l10nMsg("Restart Server")) {
void vscode.commands.executeCommand("tinymist.restartServer");
}
});
}
return false;
}
probeEnvPath(configName: string, configPath?: string): string {
const isWindows = process.platform === "win32";
const binarySuffix = isWindows ? ".exe" : "";
const binaryName = "tinymist" + binarySuffix;
const serverPaths: [string, string][] = configPath
? [[`\`${configName}\` (${configPath})`, configPath]]
: [
["Bundled", resolve(__dirname, binaryName)],
["In PATH", binaryName],
];
return tinymist.probePaths(serverPaths);
}
probePaths(paths: [string, string][]): string {
const messages = [];
for (const [loc, path] of paths) {
let messageSuffix;
try {
const result = spawnSync(path, ["probe"], { timeout: PROBE_TIMEOUT });
if (result.status === 0) {
return path;
}
const statusMessage = result.status !== null ? [`return status: ${result.status}`] : [];
const errorMessage =
result.error?.message !== undefined ? [`error: ${result.error.message}`] : [];
const messages = [statusMessage, errorMessage];
messageSuffix = messages.length !== 0 ? `:\n\t${messages.flat().join("\n\t")}` : "";
} catch (e) {
if (e instanceof Error) {
messageSuffix = `: ${e.message}`;
} else {
messageSuffix = `: ${JSON.stringify(e)}`;
}
}
messages.push([loc, path, `failed to probe${messageSuffix}`]);
}
const infos = messages
.map(([loc, path, message]) => `${loc} ('${path}'): ${message}`)
.join("\n");
throw new Error(`Could not find a valid tinymist binary.\n${infos}`);
}
async initClient(config: TinymistConfig) {
const context = this.context;
const trustedCommands = {
enabledCommands: ["tinymist.openInternal", "tinymist.openExternal", "tinymist.replaceText"],
};
const hoverStorage =
extensionState.features.renderDocs && LanguageState.HoverTmpStorage
? new LanguageState.HoverTmpStorage(context)
: new HoverDummyStorage();
const clientOptions: LanguageClientOptions = {
documentSelector: typstDocumentSelector,
initializationOptions: config,
outputChannel: this.outputChannel,
middleware: {
workspace: {
async configuration(params, token, next) {
const items = params.items.map((item) => item.section);
const result = await next(params, token);
if (!Array.isArray(result)) {
return result;
}
return substVscodeVarsInConfig(items, result);
},
},
provideHover: async (document, position, token, next) => {
const hover = await next(document, position, token);
if (!hover) {
return hover;
}
const hoverHandler = await hoverStorage.startHover();
for (const content of hover.contents) {
if (content instanceof vscode.MarkdownString) {
content.isTrusted = trustedCommands;
content.supportHtml = true;
// https://github.com/James-Yu/LaTeX-Workshop/blob/a0267e507867ae8be94b48a70d0541865fcf905f/src/preview/hover/ongraphics.ts
// outline all data "data:image/svg+xml;base64," to render huge image correctly
// Workaround for https://github.com/microsoft/vscode/issues/137632
// https://github.com/microsoft/vscode/issues/97759
if (vscode.env.remoteName) {
} else {
if (context.storageUri) {
content.baseUri = vscode.Uri.joinPath(context.storageUri, "tmp/");
}
content.value = content.value.replace(
/"data:image\/svg\+xml;base64,([^"]*)"/g,
(_, content: string) => `"${hoverHandler.storeImage(content)}"`,
);
}
}
}
await hoverHandler.finish();
return hover;
},
// Using custom handling of CodeActions to support action groups and snippet edits.
// Note that this means we have to re-implement lazy edit resolving ourselves as well.
async provideCodeActions(
document: vscode.TextDocument,
range: vscode.Range,
context: vscode.CodeActionContext,
token: vscode.CancellationToken,
_next: lc.ProvideCodeActionsSignature,
) {
const params: lc.CodeActionParams = {
textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document),
range: client.code2ProtocolConverter.asRange(range),
context: await client.code2ProtocolConverter.asCodeActionContext(context, token),
};
const callback = async (
values: (lc.Command | lc.CodeAction)[] | null,
): Promise<(vscode.Command | vscode.CodeAction)[] | undefined> => {
if (values === null) return undefined;
const result: (vscode.CodeAction | vscode.Command)[] = [];
for (const item of values) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const kind = client.protocol2CodeConverter.asCodeActionKind((item as any).kind);
const action = new vscode.CodeAction(item.title, kind);
action.command = {
command: "tinymist.resolveCodeAction",
title: item.title,
arguments: [item],
};
// console.log("replace", action, "=>", action);
// Set a dummy edit, so that VS Code doesn't try to resolve this.
action.edit = new vscode.WorkspaceEdit();
result.push(action);
}
return result;
};
return client
.sendRequest(lc.CodeActionRequest.type, params, token)
.then(callback, (_error) => undefined);
},
},
};
const client = (this.client = await LanguageState.Client(context, config, clientOptions));
this.clientPromiseResolve(client);
return client;
}
async startClient(): Promise<void> {
const client = this.client;
console.log("this.client", !!this.client);
if (!client) {
throw new Error("Language client is not set");
}
this.registerClientSideWatch(client);
client.onNotification("tinymist/compileStatus", (params: TinymistStatus) => {
wordCountItemProcess(params);
});
if (extensionState.features.preview) {
this.registerPreviewNotifications(client);
}
// Track server readiness state
client.onDidChangeState((event) => {
extensionState.mut.serverReady = event.newState === lc.State.Running;
});
await client.start();
// Reset server health warning flag when client successfully starts
extensionState.mut.serverHealthWarningShown = false;
return;
}
async executeCommand<R>(command: string, args: any[]) {
return await (
await this.getClient()
).sendRequest<R>("workspace/executeCommand", {
command,
arguments: args,
});
}
exportPdf = exportCommand("tinymist.exportPdf");
exportSvg = exportCommand("tinymist.exportSvg");
exportPng = exportCommand("tinymist.exportPng");
exportHtml = exportCommand("tinymist.exportHtml");
exportMarkdown = exportCommand("tinymist.exportMarkdown");
exportTeX = exportCommand("tinymist.exportTeX");
exportText = exportCommand("tinymist.exportText");
exportQuery = exportCommand("tinymist.exportQuery");
exportAnsiHighlight = exportStringCommand("tinymist.exportAnsiHighlight");
exportAst = exportStringCommand("tinymist.exportAst");
getResource<T extends keyof ResourceRoutes>(path: T, ...args: any[]) {
return tinymist.executeCommand<ResourceRoutes[T]>("tinymist.getResources", [path, ...args]);
}
getWorkspaceLabels() {
return tinymist.executeCommand<SymbolInformation[]>("tinymist.getWorkspaceLabels", []);
}
interactCodeContext<Qs extends InteractCodeContextQuery[]>(
documentUri: string | vscode.Uri,
query: Qs,
): Promise<InteractCodeContextResponses<Qs> | undefined> {
return tinymist.executeCommand("tinymist.interactCodeContext", [
{
textDocument: {
uri: typeof documentUri !== "string" ? documentUri.toString() : documentUri,
},
query,
},
]);
}
showLog() {
if (this.client) {
this.client.outputChannel.show();
}
}
getLogText(maxChars?: number) {
return this.outputChannel.getText(maxChars);
}
/**
* The commands group for the *Document Preview* feature. This feature is used to preview multiple
* documents at the same time.
*
* A preview task is started by calling {@link startPreview} or {@link startBrowsingPreview} with
* the *CLI arguments* to pass to the preview task like you would do in the terminal. Although
* language server will stop a preview task when no connection is active for a while, it can be
* killed by calling {@link killPreview} with a task id of the preview task.
*
* The task id of a preview task is determined by the client. If no task id is provided, you
* cannot force kill a preview task from client. You also cannot have multiple preview tasks at
* the same time without specifying it.
*
* When a preview task is active, the client can request to scroll preview panel by the calling
* {@link scrollPreview}. The server will translate client requests and control the preview panel
* internally.
*
* Besides calling commands from the client to the server, a client must also handle notifications
* from the server. Please check body of {@link registerPreviewNotifications} for a list of them.
*/
static _GroupDocumentPreviewFeatureCommands = null;
/**
* Starts a preview task. See {@link _GroupDocumentPreviewFeatureCommands} for more information.
*
* @param previewArgs - The *CLI arguments* to pass to the preview task. See help of the preview
* CLI command for more information.
* @returns The result of the preview task.
*/
async startPreview(previewArgs: string[]): Promise<PreviewResult> {
const res = await tinymist.executeCommand<PreviewResult>(`tinymist.doStartPreview`, [
previewArgs,
]);
return res || {};
}
/**
* Starts a browsing preview task. See {@link _GroupDocumentPreviewFeatureCommands} for more information.
* The difference between this and {@link startPreview} is that the main file will change according to the requests
* sent to the language server.
*
* @param previewArgs - The *CLI arguments* to pass to the preview task. See help of the preview
* CLI command for more information.
* @returns The result of the preview task.
*/
async startBrowsingPreview(previewArgs: string[]): Promise<PreviewResult> {
const res = await tinymist.executeCommand<PreviewResult>(`tinymist.doStartBrowsingPreview`, [
previewArgs,
]);
return res || {};
}
/**
* Kills a preview task. See {@link _GroupDocumentPreviewFeatureCommands} for more information.
*
* @param taskId - The task ID of the preview task to kill.
*/
async killPreview(taskId: string): Promise<void> {
return await tinymist.executeCommand(`tinymist.doKillPreview`, [taskId]);
}
/**
* Kills all preview tasks. See {@link _GroupDocumentPreviewFeatureCommands} for more information.
*/
async killAllPreview(): Promise<void> {
return await tinymist.executeCommand(`tinymist.doKillPreview`, []);
}
/**
* Scrolls the preview to a specific position. See {@link _GroupDocumentPreviewFeatureCommands}
* for more information.
*
* @param taskId - The task ID of the preview task to scroll.
* @param req - The request to scroll to.
*/
async scrollPreview(taskId: string, req: ScrollPreviewRequest): Promise<void> {
return await tinymist.executeCommand(`tinymist.scrollPreview`, [taskId, req]);
}
/**
* Scrolls all the preview to some position. See {@link _GroupDocumentPreviewFeatureCommands}
* for more information.
*/
async scrollAllPreview(): Promise<void> {
return await tinymist.executeCommand(`tinymist.scrollPreview`, []);
}
registerClientSideWatch(client: LanguageClient) {
const watches = new Set<string>();
const hasRead = new Map<string, [number, FileResult | undefined]>();
let watchClock = 0;
const tryRead = async (uri: vscode.Uri) =>
vscode.workspace.fs.readFile(uri).then(
(data): FileResult => {
return { type: "ok", content: bytesBase64Encode(data) } as const;
},
(err: any): FileResult => {
console.error("Failed to read file", uri, err);
return { type: "err", error: err.message as string } as const;
},
);
const registerHasRead = (uri: string, currentClock: number, content?: FileResult) => {
const previous = hasRead.get(uri);
if (previous && previous[0] >= currentClock) {
return false;
}
hasRead.set(uri, [currentClock, content]);
return true;
};
let watcher = () => {
if (this._watcher) {
return this._watcher;
}
console.log("registering watcher");
this._watcher = vscode.workspace.createFileSystemWatcher("**/*");
const watchRead = async (currentClock: number, uri: vscode.Uri) => {
console.log("watchRead", uri, currentClock, watches);
const uriStr = uri.toString();
if (!watches.has(uriStr)) {
return;
}
const content = await tryRead(uri);
if (!registerHasRead(uriStr, currentClock, content)) {
return;
}
const inserts: FileChange[] = [{ uri: uriStr, content }];
const removes: string[] = [];
client.sendRequest(fsChange, { inserts, removes, isSync: false });
};
this._watcher.onDidChange((uri) => {
const currentClock = watchClock++;
console.log("fs change", uri, currentClock);
watchRead(currentClock, uri);
});
this._watcher.onDidCreate((uri) => {
const currentClock = watchClock++;
console.log("fs create", uri, currentClock);
watchRead(currentClock, uri);
});
this._watcher.onDidDelete((uri) => {
const currentClock = watchClock++;
console.log("fs delete", uri, currentClock);
watchRead(currentClock, uri);
});
return this._watcher;
};
// todo: move registering to initClient to avoid unhandled errors.
client.onRequest("tinymist/fs/watch", (params: FsWatchRequest) => {
const currentClock = watchClock++;
console.log(
"fs watch request",
params,
vscode.workspace.workspaceFolders?.map((folder) => folder.uri.toString()),
);
const filesToRead = new Set<string>();
const filesDeleted = new Set<string>();
for (const path of params.inserts) {
if (!watches.has(path)) {
filesToRead.add(path);
watches.add(path);
}
}
for (const path of params.removes) {
if (watches.has(path)) {
filesDeleted.add(path);
watches.delete(path);
}
}
const removes: string[] = params.removes.filter((path) => {
return filesDeleted.has(path) && registerHasRead(path, currentClock, undefined);
});
(async () => {
const paths = Array.from(filesToRead);
const readFiles = await Promise.all(paths.map((path) => tryRead(vscode.Uri.parse(path))));
watcher();
const inserts: FileChange[] = paths
.map((path, idx) => ({
uri: path,
content: readFiles[idx],
}))
.filter((change) => registerHasRead(change.uri, currentClock, change.content));
console.log("fs watch read", currentClock, inserts, removes);
client.sendRequest(fsChange, { inserts, removes, isSync: true });
})();
});
}
/**
* Registers the preview notifications receiving from the language server. See
* {@link _GroupDocumentPreviewFeatureCommands} for more information.
*/
registerPreviewNotifications(client: LanguageClient) {
// (Required) The server requests to dispose (clean up) a preview task when it is no longer
// needed.
client.onNotification("tinymist/preview/dispose", ({ taskId }) => {
const dispose = previewDisposes[taskId];
if (dispose) {
dispose();
delete previewDisposes[taskId];
} else {
console.warn("No dispose function found for task", taskId);
}
});
// (Optional) The server requests to scroll the source code to a specific position
client.onNotification("tinymist/preview/scrollSource", async (jump: JumpInfo) => {
console.log(
"recv editorScrollTo request",
jump,
"active",
vscode.window.activeTextEditor !== undefined,
"documents",
vscode.workspace.textDocuments.map((doc) => doc.uri.fsPath),
);
if (jump.start === null || jump.end === null) {
return;
}
function inputHasUri(
input: unknown,
): input is vscode.TabInputText | vscode.TabInputCustom | vscode.TabInputNotebook {
return (
input instanceof vscode.TabInputText ||
input instanceof vscode.TabInputCustom ||
input instanceof vscode.TabInputNotebook
);
}
// Resolve the affiliated column if it is already opened
let affiliatedColumn: vscode.ViewColumn | undefined = undefined;
for (const group of vscode.window.tabGroups.all) {
for (const tab of group.tabs) {
if (!tab || !inputHasUri(tab.input)) {
continue;
}
if (tab.input.uri.fsPath === jump.filepath) {
affiliatedColumn = group.viewColumn;
break;
}
}
if (affiliatedColumn !== undefined) {
break;
}
}
// open this file and show in editor
const doc =
vscode.workspace.textDocuments.find((doc) => doc.uri.fsPath === jump.filepath) ||
(await vscode.workspace.openTextDocument(jump.filepath));
const col = affiliatedColumn || getSensibleTextEditorColumn();
const editor = await vscode.window.showTextDocument(doc, col);
const startPosition = new vscode.Position(jump.start[0], jump.start[1]);
const endPosition = new vscode.Position(jump.end[0], jump.end[1]);
const range = new vscode.Range(startPosition, endPosition);
editor.selection = new vscode.Selection(range.start, range.end);
editor.revealRange(range, vscode.TextEditorRevealType.InCenter);
});
// (Optional) The server requests to update the document outline
client.onNotification("tinymist/documentOutline", async (data: any) => {
previewProcessOutline(data);
});
}
/**
* End of {@link _GroupDocumentPreviewFeatureCommands}
*/
/**
* The code is borrowed from https://github.com/rust-lang/rust-analyzer/commit/00726cf697271617945b02baa932d2915ebce8b7/editors/code/src/config.ts#L98
* Last checked time: 2025-03-20
*
* Sets up additional language configuration that's impossible to do via a
* separate language-configuration.json file. See [1] for more information.
*
* [1]: https://github.com/Microsoft/vscode/issues/11514#issuecomment-244707076
*/
configureLang = undefined as vscode.Disposable | undefined;
configureLanguage(typingContinueCommentsOnNewline: boolean) {
// Only need to dispose of the config if there's a change
if (this.configureLang) {
this.configureLang.dispose();
this.configureLang = undefined;
}
let onEnterRules: vscode.OnEnterRule[] = [
{
// Carry indentation from the previous line
// if it's only whitespace
beforeText: /^\s+$/,
action: { indentAction: vscode.IndentAction.None },
},
{
// After the end of a function/field chain,
// with the semicolon on the same line
beforeText: /^\s+\..*;/,
action: { indentAction: vscode.IndentAction.Outdent },
},
{
// After the end of a function/field chain,
// with semicolon detached from the rest
beforeText: /^\s+;/,
previousLineText: /^\s+\..*/,
action: { indentAction: vscode.IndentAction.Outdent },
},
];
if (typingContinueCommentsOnNewline) {
const indentAction = vscode.IndentAction.None;
onEnterRules = [
...onEnterRules,
{
// Doc single-line comment
// e.g. ///|
beforeText: /^\s*\/{3}.*$/,
action: { indentAction, appendText: "/// " },
},
{
// Parent doc single-line comment
// e.g. //!|
beforeText: /^\s*\/{2}!.*$/,
action: { indentAction, appendText: "//! " },
},
{
// Begins an auto-closed multi-line comment (standard or parent doc)
// e.g. /** | */ or /*! | */
beforeText: /^\s*\/\*(\*|!)(?!\/)([^*]|\*(?!\/))*$/,
afterText: /^\s*\*\/$/,
action: {
indentAction: vscode.IndentAction.IndentOutdent,
appendText: " * ",
},
},
{
// Begins a multi-line comment (standard or parent doc)
// e.g. /** ...| or /*! ...|
beforeText: /^\s*\/\*(\*|!)(?!\/)([^*]|\*(?!\/))*$/,
action: { indentAction, appendText: " * " },
},
{
// Continues a multi-line comment
// e.g. * ...|
beforeText: /^( {2})* \*( ([^*]|\*(?!\/))*)?$/,
action: { indentAction, appendText: "* " },
},
{
// Dedents after closing a multi-line comment
// e.g. */|
beforeText: /^( {2})* \*\/\s*$/,
action: { indentAction, removeText: 1 },
},
];
}
console.log("Setting up language configuration", typingContinueCommentsOnNewline);
this.configureLang = vscode.languages.setLanguageConfiguration("typst", {
onEnterRules,
wordPattern,
});
}
}
export const tinymist = new LanguageState();
// Type definitions for export responses (matches Rust OnExportResponse)
export type ExportResponse =
| { path: string | null; data: string | null } // Single
| { totalPages: number; items: ExportedPage[] }; // Multiple
type ExportedPage = { page: number; path: string | null; data: string | null };
function exportCommand(command: string) {
return (
uri: string,
extraOpts?: ExportOpts,
actions?: ExportActionOpts,
): Promise<ExportResponse | null> => {
return tinymist.executeCommand<ExportResponse | null>(command, [
uri,
extraOpts ?? {},
actions ?? {},
]);
};
}
function exportStringCommand(command: string) {
return (uri: string, extraOpts?: ExportOpts): Promise<string> => {
return tinymist.executeCommand<string>(command, [uri, extraOpts ?? {}]);
};
}
type InteractCodeContextQuery = PathAtQuery | ModeAtQuery | StyleAtQuery;
type LspPosition = {
line: number;
character: number;
};
interface PathAtQuery {
kind: "pathAt";
code: string;
inputs?: Record<string, string>;
}
interface ModeAtQuery {
kind: "modeAt";
position: LspPosition;
}
interface StyleAtQuery {
kind: "styleAt";
position: LspPosition;
style: string[];
}
type InteractCodeContextResponses<Qs extends [...InteractCodeContextQuery[]]> = {
[Index in keyof Qs]: InteractCodeContextResponse<Qs[Index]>;
} & { length: Qs["length"] };
type InteractCodeContextResponse<Q extends InteractCodeContextQuery> = Q extends PathAtQuery
? CodeContextQueryResult
: Q extends ModeAtQuery
? ModeAtQueryResult
: Q extends StyleAtQuery
? StyleAtQueryResult
: never;
export type CodeContextQueryResult<T = any> =
| {
value: T;
}
| {
error: string;
};
export type InterpretMode = "math" | "markup" | "code" | "comment" | "string" | "raw";
export type StyleAtQueryResult = {
style: any[];
};
export type ModeAtQueryResult = {
mode: InterpretMode;
};
const previewDisposes: Record<string, () => void> = {};
export function registerPreviewTaskDispose(taskId: string, dl: DisposeList): void {
if (previewDisposes[taskId]) {
throw new Error(`Task ${taskId} already exists`);
}
dl.add(() => {
delete previewDisposes[taskId];
});
previewDisposes[taskId] = () => dl.dispose();
}
export interface PackageInfo {
path: string;
namespace: string;
name: string;
version: string;
}
export interface SymbolInfo {
name: string;
kind: string;
children: SymbolInfo[];
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function isCodeActionWithoutEditsAndCommands(value: any): boolean {
const candidate: lc.CodeAction = value;
return (
candidate &&
Is.string(candidate.title) &&
(candidate.diagnostics === void 0 || Is.typedArray(candidate.diagnostics, lc.Diagnostic.is)) &&
(candidate.kind === void 0 || Is.string(candidate.kind)) &&
candidate.edit === void 0 &&
candidate.command === void 0
);
}
interface FsWatchRequest {
inserts: string[];
removes: string[];
}
interface FileResult {
type: "ok" | "err";
content?: string;
error?: string;
}
interface FileChange {
uri: string;
content: FileResult;
}
/**
* A parameter literal used in requests to pass a list of file changes.
*/
export interface FsChangeParams {