/
file-md.ts
88 lines (75 loc) · 2.54 KB
/
file-md.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
import { CodeGen } from '@volar/code-gen';
import { Mode, SourceMapBase } from '@volar/source-map';
import { VueLanguagePlugin } from '../sourceFile';
import { parse, SFCBlock } from '@vue/compiler-sfc';
const plugin: VueLanguagePlugin = () => {
return {
parseSFC(fileName, content) {
if (fileName.endsWith('.md')) {
content = content
// code block
.replace(/```[\s\S]*?```/g, match => '```' + ' '.repeat(match.length - 6) + '```')
// inline code block
.replace(/`[\s\S]*?`/g, match => `\`${' '.repeat(match.length - 2)}\``)
// # \<script setup>
.replace(/\\\<[\s\S]*?\>\n?/g, match => ' '.repeat(match.length));
const sfcBlockReg = /\<(script|style)[\s\S]*?\>([\s\S]*?)\<\/\1\>/g;
const codeGen = new CodeGen();
for (const match of content.matchAll(sfcBlockReg)) {
if (match.index !== undefined) {
const matchText = match[0];
codeGen.addCode2(matchText, match.index, undefined);
codeGen.addText('\n\n');
content = content.substring(0, match.index) + ' '.repeat(matchText.length) + content.substring(match.index + matchText.length);
}
}
content = content
// angle bracket: <http://foo.com>
.replace(/\<\S*\:\S*\>/g, match => ' '.repeat(match.length))
// [foo](http://foo.com)
.replace(/\[[\s\S]*?\]\([\s\S]*?\)/g, match => ' '.repeat(match.length));
codeGen.addText('<template>\n');
codeGen.addCode(
content,
{
start: 0,
end: content.length,
},
Mode.Offset,
undefined,
);
codeGen.addText('\n</template>');
const file2VueSourceMap = new SourceMapBase(codeGen.mappings);
const sfc = parse(codeGen.getText(), { sourceMap: false, ignoreEmpty: false });
if (sfc.descriptor.template) {
transformRange(sfc.descriptor.template);
}
if (sfc.descriptor.script) {
transformRange(sfc.descriptor.script);
}
if (sfc.descriptor.scriptSetup) {
transformRange(sfc.descriptor.scriptSetup);
}
for (const style of sfc.descriptor.styles) {
transformRange(style);
}
for (const customBlock of sfc.descriptor.customBlocks) {
transformRange(customBlock);
}
return sfc;
function transformRange(block: SFCBlock) {
const fileRange = file2VueSourceMap.getSourceRange(block.loc.start.offset, block.loc.end.offset)?.[0];
if (fileRange) {
block.loc.start.offset = fileRange.start;
block.loc.end.offset = fileRange.end;
}
else {
block.loc.start.offset = -1;
block.loc.end.offset = -1;
}
}
};
}
};
}
export = plugin;