-
Notifications
You must be signed in to change notification settings - Fork 182
Expand file tree
/
Copy pathextension.shared.ts
More file actions
266 lines (242 loc) · 8.81 KB
/
Copy pathextension.shared.ts
File metadata and controls
266 lines (242 loc) · 8.81 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
import { type ExtensionContext, commands } from "vscode";
import * as vscode from "vscode";
import { loadTinymistConfig, TinymistConfig } from "./config";
import { tinymist } from "./lsp";
import { extensionState } from "./state";
import { previewPreload } from "./features/preview";
import { onEnterHandler } from "./lsp.on-enter";
import { ExecContext, ExecResult, ICommand, IContext } from "./context";
import { spawn } from "cross-spawn";
/**
* The condition
*/
type FeatureCondition = boolean;
/**
* The initialization vector
*/
type ActivationVector = (context: IContext) => void;
/**
* The initialization vector
*/
type DeactivationVector = (context: ExtensionContext) => void;
/**
* The feature entry. A conditional feature activation vector is required
* and an optional deactivation vector is also supported.
*/
export type FeatureEntry =
| [FeatureCondition, ActivationVector]
| [FeatureCondition, ActivationVector, DeactivationVector];
function configureEditorAndLanguage(context: ExtensionContext, trait: TinymistTrait) {
const isDevMode = vscode.ExtensionMode.Development == context.extensionMode;
const isWeb = extensionState.features.web;
const { config } = trait;
// Inform server that we support named completion callback at the client side
config.triggerSuggest = true;
config.triggerSuggestAndParameterHints = true;
config.triggerParameterHints = true;
config.supportHtmlInMarkdown = true;
config.supportClientCodelens = true;
config.supportExtendedCodeAction = true;
config.customizedShowDocument = true;
config.delegateFsRequests = false; // todo: detect live sharing.
// Sets shared features
extensionState.features.preview = !isWeb && config.previewFeature === "enable";
extensionState.features.wordSeparator = config.configureDefaultWordSeparator !== "disable";
extensionState.features.devKit = isDevMode || config.devKit === "enable";
extensionState.features.dragAndDrop = !isWeb && config.dragAndDrop === "enable";
extensionState.features.copyAndPaste = !isWeb && config.copyAndPaste === "enable";
extensionState.features.onEnter = !isWeb && !!config.onEnterEvent;
extensionState.features.renderDocs = !isWeb && config.renderDocs === "enable";
// Configures advanced editor settings to affect the host process
const configWordSeparators = async () => {
const wordSeparators = "`~!@#$%^&*()=+[{]}\\|;:'\",.<>/?";
const config1 = vscode.workspace.getConfiguration("", { languageId: "typst" });
await config1.update("editor.wordSeparators", wordSeparators, true, true);
const config2 = vscode.workspace.getConfiguration("", { languageId: "typst-code" });
await config2.update("editor.wordSeparators", wordSeparators, true, true);
};
// Runs configuration asynchronously to avoid blocking the activation
if (extensionState.features.wordSeparator) {
configWordSeparators().catch((e) =>
console.error("cannot change editor.wordSeparators for typst", e),
);
} else {
// console.log("skip configuring word separator on startup");
}
// Configures advanced language configuration
tinymist.configureLanguage(config["typingContinueCommentsOnNewline"] || false);
context.subscriptions.push(
vscode.workspace.onDidChangeConfiguration((e) => {
if (e.affectsConfiguration("tinymist.typingContinueCommentsOnNewline")) {
const config = loadTinymistConfig();
// Update language configuration
tinymist.configureLanguage(config["typingContinueCommentsOnNewline"] || false);
}
}),
);
}
interface TinymistTrait {
activateTable(): FeatureEntry[];
config: TinymistConfig;
}
export async function tinymistActivate(
context: ExtensionContext,
trait: TinymistTrait,
): Promise<void> {
const { activateTable, config } = trait;
tinymist.context = context;
const contextExt = new IContext(context);
// Sets a global context key to indicate that the extension is activated
vscode.commands.executeCommand("setContext", "ext.tinymistActivated", true);
context.subscriptions.push({
dispose: () => {
vscode.commands.executeCommand("setContext", "ext.tinymistActivated", false);
},
});
// Sets a global context key to indicate that the navigate Md to Pdf icon is enabled
const enableNavigateMdToPdfIcon =
config.convertExtension instanceof Array &&
config.convertExtension.some(
(item: any) =>
item === "markdown" ||
(typeof item === "object" &&
item.language === "markdown" &&
item.showNavigationIcon !== false),
);
console.log("enableNavigateMdToPdfIcon:", config.convertExtension, enableNavigateMdToPdfIcon);
vscode.commands.executeCommand(
"setContext",
"ext.navigateMdToPdfIcon",
enableNavigateMdToPdfIcon,
);
context.subscriptions.push({
dispose: () => {
if (enableNavigateMdToPdfIcon) {
vscode.commands.executeCommand("setContext", "ext.navigateMdToPdfIcon", false);
}
},
});
configureEditorAndLanguage(context, trait);
// Initializes language client
/// If `system`, we need to probe the binary path, otherwise, we directly set `probed` to be true.
let isProbed = !extensionState.features.lspSystem;
if (extensionState.features.lsp && extensionState.features.lspSystem) {
try {
const executable = tinymist.probeEnvPath("tinymist.serverPath", config.serverPath);
// todo: guide installation?
config.probedServerPath = executable;
contextExt.tinymistExecutable = executable;
isProbed = true;
contextExt.tinymistExec = makeExecCommand(contextExt, executable);
} catch (e) {
vscode.window.showErrorMessage(`Cannot find a valid tinymist binary. Some features like auto-formatting on Enter may not work. Please check your tinymist.serverPath configuration. Exception: ${e}`);
}
}
/// Language server is valid if it is enabled and the binary is probed.
const isLsEnabledAndProbed = extensionState.features.lsp && isProbed;
if (isLsEnabledAndProbed) {
await tinymist.initClient(config);
}
// Register Shared commands
context.subscriptions.push(
commands.registerCommand("tinymist.onEnter", onEnterHandler),
commands.registerCommand("tinymist.restartServer", async () => {
await tinymistDeactivate(trait);
await tinymistActivate(context, trait);
}),
commands.registerCommand("tinymist.getLogText", (options?: { maxChars?: number }) => {
return tinymist.getLogText(options?.maxChars);
}),
commands.registerCommand("tinymist.showLog", () => tinymist.showLog()),
);
// Activates platform-dependent features
for (const [condition, activate] of activateTable()) {
if (condition) {
activate(contextExt);
}
}
// Starts language client
if (isLsEnabledAndProbed) {
await tinymist.startClient();
}
// Loads the preview HTML from the binary
if (isLsEnabledAndProbed && extensionState.features.preview) {
previewPreload(context);
}
return;
}
export async function tinymistDeactivate(
trait: Pick<TinymistTrait, "activateTable">,
): Promise<void> {
for (const [condition, , deactivate] of trait.activateTable()) {
if (deactivate && condition) {
deactivate(tinymist.context);
}
}
if (tinymist.context) {
for (const disposable of tinymist.context.subscriptions.splice(0)) {
disposable.dispose();
}
}
await tinymist.stop();
tinymist.context = undefined!;
}
function makeExecCommand(
context: IContext,
executable?: string,
): ICommand<ExecContext, Promise<ExecResult | undefined>> {
return {
command: "tinymist.executeCli",
execute: async (ctx, cliArgs: string[]) => {
if (!executable) {
return;
}
const cwd = context.getCwd(ctx);
const proc = spawn(executable, cliArgs, {
env: {
...process.env,
RUST_BACKTRACE: "1",
},
cwd,
});
if (ctx.killer) {
ctx.killer.event(() => {
proc.kill();
});
}
const capturedStdout: Buffer[] = [];
const capturedStderr: Buffer[] = [];
proc.stdout.on("data", (data: Buffer) => {
if (ctx.stdout) {
ctx.stdout(data);
} else {
capturedStdout.push(data);
}
});
proc.stderr.on("data", (data: Buffer) => {
if (ctx.stderr) {
ctx.stderr(data);
} else {
capturedStderr.push(data);
}
});
return new Promise<ExecResult>((resolve, reject) => {
proc.on("error", reject);
proc.on("exit", (code: any, signal) => {
resolve({
stdout: Buffer.concat(capturedStdout),
stderr: Buffer.concat(capturedStderr),
code: code || 0,
signal,
});
});
});
},
};
}
export function statusBarFormatString() {
const formatter = (
(vscode.workspace.getConfiguration("tinymist").get("statusBarFormat") as string) || ""
).trim();
return formatter;
}