-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcustom.ts
More file actions
294 lines (275 loc) · 8.54 KB
/
custom.ts
File metadata and controls
294 lines (275 loc) · 8.54 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
import type { Denops } from "@denops/std";
import * as buffer from "@denops/std/buffer";
import * as vars from "@denops/std/variable";
import * as autocmd from "@denops/std/autocmd";
import { TextLineStream } from "@std/streams/text-line-stream";
import { mergeReadableStreams } from "@std/streams/merge-readable-streams";
import { toFileUrl } from "@std/path/to-file-url";
import { fromFileUrl } from "@std/path/from-file-url";
import { dirname } from "@std/path/dirname";
import { copy } from "@std/fs/copy";
import { buildRefineSetting, type Setting } from "@vim-fall/custom/setting";
import {
type ActionPickerParams,
buildRefineActionPicker,
} from "@vim-fall/custom/action-picker";
import {
buildDefinePickerFromCurator,
buildDefinePickerFromSource,
type PickerParams,
} from "@vim-fall/custom/picker";
import { modern } from "@vim-fall/std/builtin/coordinator/modern";
import { MODERN_THEME } from "@vim-fall/std/builtin/theme/modern";
import { fzf } from "@vim-fall/std/builtin/matcher/fzf";
import { ExpectedError } from "./error.ts";
const defaultCustomUrl = new URL(
"./_assets/default.custom.ts",
import.meta.url,
);
let initialized: undefined | Promise<void>;
const defaultSetting: Setting = {
coordinator: modern(),
theme: MODERN_THEME,
};
let setting = { ...defaultSetting };
const defaultActionPickerParams: ActionPickerParams = {
matchers: [fzf()],
coordinator: modern({
widthRatio: 0.4,
heightRatio: 0.4,
hidePreview: true,
}),
};
let actionPickerParams = { ...defaultActionPickerParams };
const pickerParamsMap = new Map<string, PickerParams>();
/**
* Edit user custom
*/
export async function editUserCustom(
denops: Denops,
options: buffer.OpenOptions,
): Promise<void> {
const path = fromFileUrl(await getUserCustomUrl(denops));
// Try to copy the default custom file if the user custom file does not exist.
try {
const parent = dirname(path);
await Deno.mkdir(parent, { recursive: true });
await copy(defaultCustomUrl, path, { overwrite: false });
} catch (err) {
if (err instanceof Deno.errors.AlreadyExists) {
// Expected. Do nothing.
} else {
throw err;
}
}
// Open the user custom file.
const info = await buffer.open(denops, path, options);
// Register autocmd to reload the user custom when the buffer is written.
await autocmd.group(denops, "fall_config", (helper) => {
helper.remove("*");
helper.define(
"BufWritePost",
`<buffer=${info.bufnr}>`,
`call denops#notify("${denops.name}", "custom:reload", [#{ verbose: v:true }])`,
);
});
}
/**
* Load user custom from the g:fall_config_path.
*/
export function loadUserCustom(
denops: Denops,
{ reload = false, verbose = false } = {},
): Promise<void> {
if (initialized && !reload) {
return initialized;
}
// Avoid reloading when the user custom is not yet loaded.
reload = initialized ? reload : false;
initialized = (async () => {
const configUrl = await getUserCustomUrl(denops);
const suffix = reload ? `#${performance.now()}` : "";
try {
const { main } = await import(`${configUrl.href}${suffix}`);
reset();
await main(buildContext(denops));
await autocmd.emit(denops, "User", "FallCustomLoaded");
if (verbose) {
await denops.cmd(
`echomsg "[fall] User custom is loaded: ${configUrl}"`,
);
}
} catch (err) {
// Avoid loading default configration if reload is set to keep the previous configuration.
if (reload) {
if (err instanceof Deno.errors.NotFound) {
console.debug(`User custom not found: '${configUrl}'. Skip.`);
} else {
console.warn(`Failed to load user custom. Skip: ${err}`);
}
return;
}
// Fallback to the default configuration.
if (err instanceof Deno.errors.NotFound) {
console.debug(
`User custom not found: '${configUrl}'. Fallback to the default custom.`,
);
} else {
console.warn(
`Failed to load user custom. Fallback to the default custom: ${err}`,
);
}
const { main } = await import(defaultCustomUrl.href);
reset();
await main(buildContext(denops));
if (verbose) {
await denops.cmd(
`echomsg "[fall] Default custom is loaded: ${defaultCustomUrl}"`,
);
}
}
})();
return initialized;
}
/**
* Recache user custom by running `deno cache --reload` command.
*/
export async function recacheUserCustom(
denops: Denops,
{ verbose, signal }: { verbose?: boolean; signal?: AbortSignal },
): Promise<void> {
const configUrl = await getUserCustomUrl(denops);
const cmd = new Deno.Command(Deno.execPath(), {
args: ["cache", "--no-lock", "--reload", "--allow-import", configUrl.href],
stdin: "null",
stdout: "piped",
stderr: "piped",
});
await using proc = cmd.spawn();
signal?.addEventListener("abort", () => {
try {
proc.kill();
} catch {
// Do nothing
}
}, { once: true });
mergeReadableStreams(proc.stdout, proc.stderr)
.pipeThrough(new TextDecoderStream(), { signal })
.pipeThrough(new TextLineStream(), { signal })
.pipeTo(
new WritableStream({
async start() {
if (verbose) {
await denops.cmd(
`redraw | echomsg "[fall] Recaching Deno modules referred in user custom: ${configUrl}"`,
);
}
},
async write(line) {
if (verbose) {
await denops.cmd(
`redraw | echohl Comment | echomsg "[fall] ${line}" | echohl NONE`,
);
}
},
async close() {
await autocmd.emit(denops, "User", "FallCustomRecached");
if (verbose) {
await denops.cmd(
`redraw | echomsg "[fall] The Deno modules referenced in user custom are re-cached. Restart Vim to apply the changes: ${configUrl}"`,
);
}
},
}),
{ signal },
);
await proc.status;
}
/**
* Get global custom.
*/
export function getSetting(): Readonly<Setting> {
return setting;
}
/**
* Get action picker params.
*/
export function getActionPickerParams(): Readonly<
ActionPickerParams
> {
return actionPickerParams;
}
/**
* Get item picker params.
*/
export function getPickerParams(
name: string,
): Readonly<PickerParams> | undefined {
const params = pickerParamsMap.get(name);
if (params) {
return params;
}
return undefined;
}
/**
* List item picker names.
*/
export function listPickerNames(): readonly string[] {
return Array.from(pickerParamsMap.keys());
}
function reset(): void {
setting = { ...defaultSetting };
actionPickerParams = { ...defaultActionPickerParams };
pickerParamsMap.clear();
}
function buildContext(denops: Denops): {
denops: Denops;
refineSetting: ReturnType<typeof buildRefineSetting>;
refineActionPicker: ReturnType<typeof buildRefineActionPicker>;
definePickerFromSource: ReturnType<typeof buildDefinePickerFromSource>;
definePickerFromCurator: ReturnType<typeof buildDefinePickerFromCurator>;
} {
const definePickerFromSource = buildDefinePickerFromSource(pickerParamsMap);
const definePickerFromCurator = buildDefinePickerFromCurator(pickerParamsMap);
return {
denops,
refineSetting: buildRefineSetting(setting),
refineActionPicker: buildRefineActionPicker(actionPickerParams),
definePickerFromSource: (name, source, params) => {
validatePickerName(name);
validateActions(params.actions);
return definePickerFromSource(name, source, params);
},
definePickerFromCurator: (name, curator, params) => {
validatePickerName(name);
validateActions(params.actions);
return definePickerFromCurator(name, curator, params);
},
};
}
async function getUserCustomUrl(denops: Denops): Promise<URL> {
try {
const path = await vars.g.get(denops, "fall_custom_path") as string;
return toFileUrl(path);
} catch (err) {
throw new Error(
`Failed to get user custom path from 'g:fall_custom_path': ${err}`,
);
}
}
function validatePickerName(name: string): void {
if (pickerParamsMap.has(name)) {
throw new ExpectedError(`Picker '${name}' is already defined.`);
}
if (name.startsWith("@")) {
throw new ExpectedError(`Picker name must not start with '@': ${name}`);
}
}
function validateActions(actions: Record<PropertyKey, unknown>): void {
Object.keys(actions).forEach((name) => {
if (name.startsWith("@")) {
throw new ExpectedError(`Action name must not start with '@': ${name}`);
}
});
}
export type { ActionPickerParams, PickerParams, Setting };