-
Notifications
You must be signed in to change notification settings - Fork 78
/
extension.ts
196 lines (168 loc) · 6.18 KB
/
extension.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
import {
type ExtensionContext,
workspace,
window,
commands,
ViewColumn,
Uri,
WorkspaceConfiguration,
} from "vscode";
import * as path from "path";
import * as child_process from "child_process";
import {
LanguageClient,
type LanguageClientOptions,
type ServerOptions,
} from "vscode-languageclient/node";
let client: LanguageClient | undefined = undefined;
export function activate(context: ExtensionContext): Promise<void> {
return startClient(context).catch((e) => {
void window.showErrorMessage(`Failed to activate typst-lsp: ${e}`);
throw e;
});
}
async function startClient(context: ExtensionContext): Promise<void> {
const config = workspace.getConfiguration("typst-lsp");
const serverCommand = getServer(config);
const run = {
command: serverCommand,
options: { env: Object.assign({}, process.env, { RUST_BACKTRACE: "1" }) },
};
const serverOptions: ServerOptions = {
run,
debug: run,
};
const clientOptions: LanguageClientOptions = {
documentSelector: [{ scheme: "file", language: "typst" }],
initializationOptions: config,
};
client = new LanguageClient("typst-lsp", "Typst Language Server", serverOptions, clientOptions);
context.subscriptions.push(
commands.registerCommand("typst-lsp.exportCurrentPdf", commandExportCurrentPdf)
);
context.subscriptions.push(
commands.registerCommand("typst-lsp.pinMainToCurrent", () => commandPinMain(true))
);
context.subscriptions.push(
commands.registerCommand("typst-lsp.unpinMain", () => commandPinMain(false))
);
context.subscriptions.push(commands.registerCommand("typst-lsp.showPdf", commandShowPdf));
context.subscriptions.push(commands.registerCommand("typst-lsp.clearCache", commandClearCache));
return client.start();
}
export function deactivate(): Promise<void> | undefined {
return client?.stop();
}
function getServer(conf: WorkspaceConfiguration): string {
const pathInConfig = conf.get<string | null>("serverPath");
if (pathInConfig !== undefined && pathInConfig !== null && pathInConfig !== "") {
const validation = validateServer(pathInConfig);
if (!validation.valid) {
throw new Error(
`\`typst-lsp.serverPath\` (${pathInConfig}) does not point to a valid typst-lsp binary:\n${validation.message}`
);
}
return pathInConfig;
}
const windows = process.platform === "win32";
const suffix = windows ? ".exe" : "";
const binaryName = "typst-lsp" + suffix;
const bundledPath = path.resolve(__dirname, binaryName);
const bundledValidation = validateServer(bundledPath);
if (bundledValidation.valid) {
return bundledPath;
}
const binaryValidation = validateServer(binaryName);
if (binaryValidation.valid) {
return binaryName;
}
throw new Error(
`Could not find a valid typst-lsp binary.\nBundled: ${bundledValidation.message}\nIn PATH: ${binaryValidation.message}`
);
}
function validateServer(path: string): { valid: true } | { valid: false; message: string } {
try {
const result = child_process.spawnSync(path);
if (result.status === 0) {
return { valid: true };
} else {
const statusMessage = result.status !== null ? [`return status: ${result.status}`] : [];
const errorMessage =
result.error?.message !== undefined ? [`error: ${result.error.message}`] : [];
const messages = [statusMessage, errorMessage];
const messageSuffix =
messages.length !== 0 ? `:\n\t${messages.flat().join("\n\t")}` : "";
const message = `Failed to launch '${path}'${messageSuffix}`;
return { valid: false, message };
}
} catch (e) {
if (e instanceof Error) {
return { valid: false, message: `Failed to launch '${path}': ${e.message}` };
} else {
return { valid: false, message: `Failed to launch '${path}': ${JSON.stringify(e)}` };
}
}
}
async function commandExportCurrentPdf(): Promise<void> {
const activeEditor = window.activeTextEditor;
if (activeEditor === undefined) {
return;
}
const uri = activeEditor.document.uri.toString();
await client?.sendRequest("workspace/executeCommand", {
command: "typst-lsp.doPdfExport",
arguments: [uri],
});
}
async function commandPinMain(isPin: boolean): Promise<void> {
if (!isPin) {
await client?.sendRequest("workspace/executeCommand", {
command: "typst-lsp.doPinMain",
arguments: ["detached"],
});
}
const activeEditor = window.activeTextEditor;
if (activeEditor === undefined) {
return;
}
const uri = activeEditor.document.uri.toString();
await client?.sendRequest("workspace/executeCommand", {
command: "typst-lsp.doPinMain",
arguments: [uri],
});
}
/**
* Implements the functionality for the 'Show PDF' button shown in the editor title
* if a `.typ` file is opened.
*/
async function commandShowPdf(): Promise<void> {
const activeEditor = window.activeTextEditor;
if (activeEditor === undefined) {
return;
}
const uri = activeEditor.document.uri;
// change the file extension to `.pdf` as we want to open the pdf file
// and not the currently opened `.typ` file.
const n = uri.toString().lastIndexOf(".");
const pdf_uri = Uri.parse(uri.toString().slice(0, n) + ".pdf");
try {
await workspace.fs.stat(pdf_uri);
} catch {
// only create pdf if it does not exist yet
await commandExportCurrentPdf();
} finally {
// here we can be sure that the pdf exists
await commands.executeCommand("vscode.open", pdf_uri, ViewColumn.Beside);
}
}
async function commandClearCache(): Promise<void> {
const activeEditor = window.activeTextEditor;
if (activeEditor === undefined) {
return;
}
const uri = activeEditor.document.uri.toString();
await client?.sendRequest("workspace/executeCommand", {
command: "typst-lsp.doClearCache",
arguments: [uri],
});
}