-
Notifications
You must be signed in to change notification settings - Fork 4
/
MarkdownDocumentController.ts
237 lines (210 loc) · 5.63 KB
/
MarkdownDocumentController.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
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
import { Disposable } from "@hediet/std/disposable";
import { action, observable } from "mobx";
import { Code, Item, Root } from "remark";
import {
languages,
workspace,
Uri,
Position,
TextDocument,
CancellationToken,
CompletionContext,
CompletionList,
SignatureHelpContext,
SignatureHelp,
Diagnostic,
LocationLink,
ConfigurationTarget,
} from "vscode";
import { parseMarkdown } from "../utils/parseMarkdown";
import { ProjectionTarget } from "./ProjectionTarget";
import { CodeBlock } from "./CodeBlock";
import { exec, spawnSync } from "child_process";
import { promisify } from "util";
import { existsSync, readFileSync, writeFileSync } from "fs";
import { homedir } from "os";
import { join } from "path";
export class MarkdownDocumentController {
public readonly dispose = Disposable.fn();
private readonly diagnostics = this.dispose.track(
languages.createDiagnosticCollection()
);
@observable.ref public blocks: ReadonlyArray<CodeBlock> = [];
private targets = new Map<string, ProjectionTarget>();
constructor(private readonly doc: TextDocument) {
this.setVsCodeExcludeConfig();
this.setGitignoreExcludeConfig();
this.dispose.track(
workspace.onDidChangeTextDocument(
({ contentChanges, document }) => {
if (document !== this.doc) {
return;
}
this.processContent();
}
)
);
this.processContent();
this.dispose.track(
languages.onDidChangeDiagnostics(({ uris }) => {
if (
uris.length === 1 &&
uris[0].toString() === this.doc.uri.toString()
) {
return;
}
this.updateDiagnostics();
})
);
this.updateDiagnostics();
}
private async setGitignoreExcludeConfig() {
const { stdout } = await promisify(exec)(
"git config --get core.excludesfile"
);
let file: string;
if (existsSync(stdout)) {
file = stdout;
} else {
file = join(homedir(), ".git-global-excludes-file");
writeFileSync(file, "", { encoding: "utf-8" });
spawnSync("git", ["config", "--global", "core.excludesFile", file]);
}
const lines = readFileSync(file, { encoding: "utf-8" }).split("\n");
if (!lines.some((l) => l.trim() === ".tmp-projections/")) {
lines.push(".tmp-projections/");
writeFileSync(file, lines.join("\n"), {
encoding: "utf-8",
});
}
}
private setVsCodeExcludeConfig() {
const existing: Record<string, boolean> =
workspace.getConfiguration().get("files.exclude") || {};
existing[".tmp-projections/"] = true;
workspace
.getConfiguration()
.update("files.exclude", existing, ConfigurationTarget.Global);
}
private updateDiagnostics() {
const d = new Array<Diagnostic>();
for (const t of this.targets.values()) {
d.push(...t.getDiagnostics());
}
this.diagnostics.set(this.doc.uri, d);
}
@action
private processContent(): void {
const blocks = this.getCodeBlocks();
this.blocks = blocks;
const newTargets = new Map<string, ProjectionTarget>();
for (const block of blocks) {
let target: ProjectionTarget;
const options = {
id: block.id,
language: block.language,
extension: block.extension,
};
const key = JSON.stringify(options);
if (this.targets.has(key)) {
target = this.targets.get(key)!;
} else {
target = new ProjectionTarget(this.doc.uri, options);
}
newTargets.set(key, target);
target.update(block);
}
for (const [key, val] of this.targets) {
if (!newTargets.has(key)) {
val.dispose();
}
}
this.targets = newTargets;
this.updateDiagnostics();
}
private getCodeBlocks(): CodeBlock[] {
const content = this.doc.getText();
const root = parseMarkdown(content);
const codeblocks = new Array<Code>();
collectAllCodeBlocks(root, codeblocks);
return codeblocks.map((b, idx) => CodeBlock.from(idx, b, this.doc));
}
private getTarget(position: Position): ProjectionTarget | undefined {
const target = [...this.targets.values()].find((t) =>
t.block.contentRange.contains(position)
);
return target;
}
public async provideCompletionItems(
position: Position,
token: CancellationToken,
context: CompletionContext
): Promise<CompletionList> {
const target = this.getTarget(position);
if (!target) {
return new CompletionList([], true);
}
return target.provideCompletionItems(position, token, context);
}
public async provideDefinition(
position: Position,
token: CancellationToken
): Promise<LocationLink[]> {
const target = this.getTarget(position);
if (!target) {
return [];
}
return await target.provideDefinition(position, token);
}
public async provideSignatureHelp(
position: Position,
token: CancellationToken,
context: SignatureHelpContext
): Promise<SignatureHelp | undefined> {
const target = this.getTarget(position);
if (!target) {
return undefined;
}
return await target.provideSignatureHelp(position, token, context);
}
}
function modifySegments(
uri: Uri,
effect: (segments: string[]) => string[] | void
) {
const segments = uri.path.split("/");
let result = effect(segments);
if (!result) {
result = segments;
}
return uri.with({ path: result.join("/") });
}
export function addSegmentToUri(uri: Uri, segment: string): Uri {
return modifySegments(uri, (s) => {
s.push(segment);
});
}
export function getParentUri(uri: Uri): Uri {
return modifySegments(uri, (s) => {
s.pop();
});
}
function collectAllCodeBlocks(item: Item | Root, codeblocks: Code[]): void {
switch (item.type) {
case "code":
codeblocks.push(item);
return;
case "root":
for (const c of item.children) {
collectAllCodeBlocks(c, codeblocks);
}
return;
case "list":
for (const c of item.children) {
for (const x of c.children) {
collectAllCodeBlocks(x, codeblocks);
}
}
return;
}
}