-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuffer.ts
79 lines (64 loc) · 1.86 KB
/
buffer.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
import { Denops, diff, execute } from "./deps.ts";
export interface ContentsConstructor {
setKeybinds: (denops: Denops) => Promise<void>;
contents: () => string[];
}
export class VimBuffer {
#denops: Denops;
#currentContents: string[];
#keybindInitializer: (denops: Denops) => Promise<void>;
constructor(denops: Denops) {
this.#denops = denops;
this.#currentContents = [];
this.#keybindInitializer = async (_: Denops) => {};
}
setKeybindInitializer(f: (denops: Denops) => Promise<void>) {
this.#keybindInitializer = f;
}
async renderContents(contents: string[]) {
if (this.#currentContents.length == 0) {
await this.initBuffer(contents);
return;
}
await this.updateBuffer(contents);
}
private async initBuffer(contents: string[]) {
await this.#denops.cmd(`setlocal modifiable`);
await this.#denops.call("setline", 1, contents);
this.#currentContents = contents;
await this.#keybindInitializer(this.#denops);
await execute(
this.#denops,
[
`setlocal bufhidden=hide`,
`setlocal buftype=nofile`,
`setlocal nobuckup`,
`setlocal noswapfile`,
`setlocal nomodified`,
`setlocal nomodifiable`,
],
);
}
private async updateBuffer(contents: string[]) {
await this.#denops.cmd(`setlocal modifiable`);
let lnum = 1;
const ops = diff(this.#currentContents, contents);
ops.forEach((op) => {
switch (op.type) {
case "removed":
this.#denops.cmd(`call deletebufline('%', ${lnum})`);
break;
case "added":
this.#denops.cmd(
`call appendbufline('%', ${lnum - 1}, '${op.value}')`,
);
lnum++;
break;
default:
lnum++;
}
});
this.#currentContents = contents;
await this.#denops.cmd(`setlocal nomodifiable`);
}
}