返回 slidev
languagePlugin.ts
根目录 / packages / vscode / language-server / languagePlugin.ts
1 import type { SlidevMarkdown } from '@slidev/types'
2 import type { LanguagePlugin, VirtualCode } from '@volar/language-core'
3 import type { URI } from 'vscode-uri'
4 import { parseSync } from '@slidev/parser'
5
6 export const slidevLanguagePlugin: LanguagePlugin<URI> = {
7 getLanguageId() {
8 return undefined
9 },
10 createVirtualCode(uri, languageId, snapshot) {
11 if (languageId === 'markdown') {
12 const source = snapshot.getText(0, snapshot.getLength())
13 const parsed = parseSync(source, uri.fsPath, {
14 noParseYAML: true,
15 preserveCR: true,
16 })
17
18 return {
19 id: 'root',
20 languageId: 'markdown',
21 mappings: [],
22 embeddedCodes: [
23 ...getEmbeddedCodes(parsed),
24 ],
25 snapshot,
26 }
27 }
28 },
29 }
30
31 function* getEmbeddedCodes(parsed: SlidevMarkdown): Generator<VirtualCode> {
32 const lines = parsed.raw.split('\n')
33 function lineToPos(line: number) {
34 let pos = 0
35 for (let i = 0; i <= line && i < lines.length; i++) {
36 pos += lines[i].length + 1
37 }
38 return pos
39 }
40 for (const { frontmatterRaw, start, contentStart, content, index } of parsed.slides) {
41 if (frontmatterRaw != null) {
42 yield {
43 id: `frontmatter_${index}`,
44 languageId: 'yaml',
45 snapshot: {
46 getText: (start, end) => frontmatterRaw.substring(start, end),
47 getLength: () => frontmatterRaw.length,
48 getChangeRange: () => undefined,
49 },
50 mappings: [
51 {
52 sourceOffsets: [
53 lineToPos(start),
54 ],
55 generatedOffsets: [0],
56 lengths: [frontmatterRaw.length],
57 data: {
58 verification: true,
59 completion: true,
60 semantic: true,
61 navigation: true,
62 structure: true,
63 format: true,
64 },
65 },
66 ],
67 embeddedCodes: [],
68 }
69 }
70 if (content) {
71 yield {
72 id: `content_${index}`,
73 languageId: 'markdown',
74 snapshot: {
75 getText: (start, end) => content.substring(start, end),
76 getLength: () => content.length,
77 getChangeRange: () => undefined,
78 },
79 mappings: [
80 {
81 sourceOffsets: [
82 lineToPos(contentStart),
83 ],
84 generatedOffsets: [0],
85 lengths: [content.length],
86 data: {
87 verification: true,
88 completion: true,
89 semantic: true,
90 navigation: true,
91 structure: true,
92 format: false,
93 },
94 },
95 ],
96 embeddedCodes: [],
97 }
98 }
99 }
100 }
101
101 lines TYPESCRIPT