@lincyaw/language-server 0.0.0-stage → 1.0.0-rc.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +20 -2
- package/bin/presmium-language-server.mjs +14 -0
- package/package.json +48 -3
- package/src/domain/directives.ts +35 -0
- package/src/domain/index.ts +11 -0
- package/src/domain/messages.ts +38 -0
- package/src/domain/names.ts +27 -0
- package/src/domain/preview.ts +11 -0
- package/src/domain/protocol.ts +24 -0
- package/src/domain/sections.ts +26 -0
- package/src/domain/syntax.ts +84 -0
- package/src/node/anchors.ts +121 -0
- package/src/node/completion.ts +66 -0
- package/src/node/decks.ts +121 -0
- package/src/node/diagnostics.ts +39 -0
- package/src/node/preview.ts +111 -0
- package/src/node/server.ts +134 -0
- package/src/node/syntax.ts +30 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,21 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @lincyaw/language-server
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The language server of Presmium documents: diagnostics, anchor definitions and hovers, completion of directives, options and anchors, and the preview that follows the cursor.
|
|
4
|
+
|
|
5
|
+
Part of [Presmium](https://github.com/Lincyaw/presmium), which turns lectures written in MyST Markdown into web pages, slides, Jupyter notebooks and narrated lectures.
|
|
6
|
+
|
|
7
|
+
## Usage
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
pnpm exec presmium-language-server --stdio
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
It also takes `--node-ipc` and `--socket=<port>`. The VS Code extension starts it; other editors start it as a language server for Markdown files.
|
|
14
|
+
|
|
15
|
+
## Documentation
|
|
16
|
+
|
|
17
|
+
- [Author guide](https://github.com/Lincyaw/presmium/blob/main/site/guide/lecture.en.md)
|
|
18
|
+
|
|
19
|
+
## License
|
|
20
|
+
|
|
21
|
+
Apache-2.0
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createJiti } from 'jiti'
|
|
3
|
+
|
|
4
|
+
console.log = console.info = console.debug = console.error
|
|
5
|
+
|
|
6
|
+
const emitWarning = process.emitWarning
|
|
7
|
+
process.emitWarning = (warning, ...args) => {
|
|
8
|
+
const code = typeof args[0] === 'object' ? args[0]?.code : args[1]
|
|
9
|
+
if (code !== 'DEP0040') emitWarning.call(process, warning, ...args)
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
const jiti = createJiti(import.meta.url)
|
|
13
|
+
const { startServer } = await jiti.import('../src/node/server.ts')
|
|
14
|
+
startServer()
|
package/package.json
CHANGED
|
@@ -1,6 +1,51 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lincyaw/language-server",
|
|
3
|
-
"version": "0.0.0
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "1.0.0-rc.0",
|
|
4
|
+
"description": "Language server for Presmium documents: diagnostics, anchor definitions and hovers, completion and preview sync",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/Lincyaw/presmium.git",
|
|
9
|
+
"directory": "packages/language-server"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://github.com/Lincyaw/presmium/tree/main/packages/language-server#readme",
|
|
12
|
+
"bugs": "https://github.com/Lincyaw/presmium/issues",
|
|
13
|
+
"keywords": [
|
|
14
|
+
"presmium",
|
|
15
|
+
"lsp",
|
|
16
|
+
"language-server"
|
|
17
|
+
],
|
|
18
|
+
"type": "module",
|
|
19
|
+
"engines": {
|
|
20
|
+
"node": ">=22.19"
|
|
21
|
+
},
|
|
22
|
+
"publishConfig": {
|
|
23
|
+
"access": "public"
|
|
24
|
+
},
|
|
25
|
+
"bin": {
|
|
26
|
+
"presmium-language-server": "./bin/presmium-language-server.mjs"
|
|
27
|
+
},
|
|
28
|
+
"exports": {
|
|
29
|
+
"./domain": "./src/domain/index.ts",
|
|
30
|
+
"./protocol": "./src/domain/protocol.ts",
|
|
31
|
+
"./package.json": "./package.json"
|
|
32
|
+
},
|
|
33
|
+
"files": [
|
|
34
|
+
"bin",
|
|
35
|
+
"src"
|
|
36
|
+
],
|
|
37
|
+
"dependencies": {
|
|
38
|
+
"jiti": "^2.7.0",
|
|
39
|
+
"vscode-languageserver": "10.1.2",
|
|
40
|
+
"vscode-languageserver-textdocument": "1.0.15",
|
|
41
|
+
"@lincyaw/cli": "1.0.0-rc.0",
|
|
42
|
+
"@lincyaw/kernel": "1.0.0-rc.0",
|
|
43
|
+
"@lincyaw/compiler": "1.0.0-rc.0",
|
|
44
|
+
"@lincyaw/web": "1.0.0-rc.0",
|
|
45
|
+
"@lincyaw/host": "1.0.0-rc.0",
|
|
46
|
+
"@lincyaw/viewer": "1.0.0-rc.0"
|
|
47
|
+
},
|
|
48
|
+
"scripts": {
|
|
49
|
+
"typecheck": "tsc -p tsconfig.json"
|
|
50
|
+
}
|
|
6
51
|
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { DirectiveOptionType, DirectiveSpec } from '@lincyaw/kernel'
|
|
2
|
+
|
|
3
|
+
export interface OptionInfo {
|
|
4
|
+
type?: DirectiveOptionType
|
|
5
|
+
doc?: string
|
|
6
|
+
values?: string[]
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export interface DirectiveInfo {
|
|
10
|
+
name: string
|
|
11
|
+
source: string
|
|
12
|
+
doc?: string
|
|
13
|
+
options: Record<string, OptionInfo>
|
|
14
|
+
anchor?: boolean
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function directiveInfos(builtin: readonly DirectiveInfo[], plugins: { plugin: string, directives: readonly DirectiveSpec[] }[], run?: OptionInfo): Map<string, DirectiveInfo> {
|
|
18
|
+
const infos = new Map(builtin.map(info => [info.name, info]))
|
|
19
|
+
for (const { plugin, directives } of plugins) {
|
|
20
|
+
for (const spec of directives) {
|
|
21
|
+
if (infos.has(spec.name)) continue
|
|
22
|
+
const options = Object.fromEntries(Object.entries(spec.options ?? {}).map(([name, type]): [string, OptionInfo] => [name, name === 'run' && run ? { ...run, type } : { type }]))
|
|
23
|
+
infos.set(spec.name, { name: spec.name, source: plugin, options, ...spec.arg === 'anchor' ? { anchor: true } : {} })
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
return infos
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function optionsOf(info: DirectiveInfo, common: Record<string, OptionInfo>): Record<string, OptionInfo> {
|
|
30
|
+
return { ...common, ...info.options }
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function anchorDirectives(infos: Map<string, DirectiveInfo>): Set<string> {
|
|
34
|
+
return new Set([...infos.values()].filter(info => info.anchor).map(info => info.name))
|
|
35
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export { anchorDirectives, directiveInfos, optionsOf } from './directives.ts'
|
|
2
|
+
export type { DirectiveInfo, OptionInfo } from './directives.ts'
|
|
3
|
+
export { LS_MESSAGES } from './messages.ts'
|
|
4
|
+
export type { LsMessages } from './messages.ts'
|
|
5
|
+
export { declarationNames, regionNames } from './names.ts'
|
|
6
|
+
export { previewUrl } from './preview.ts'
|
|
7
|
+
export { PREVIEW_REQUEST, SECTION_REQUEST } from './protocol.ts'
|
|
8
|
+
export type { DocumentParams, PositionParams, Preview, SectionAt } from './protocol.ts'
|
|
9
|
+
export { blockAt, sectionAt } from './sections.ts'
|
|
10
|
+
export { anchorAt, directiveAt, fenceAt, typingAt, writtenOptions } from './syntax.ts'
|
|
11
|
+
export type { AnchorRef, Fence, Typing } from './syntax.ts'
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import type { Locale } from '@lincyaw/kernel'
|
|
2
|
+
|
|
3
|
+
export const LS_MESSAGES = {
|
|
4
|
+
'zh-CN': {
|
|
5
|
+
status: { exact: '已解析', moved: '已移动', fuzzy: '待确认', lost: '已失效' } as Record<string, string>,
|
|
6
|
+
pinnedAt: (commit: string) => `锁定在 ${commit}`,
|
|
7
|
+
drifted: '锁定之后已漂移',
|
|
8
|
+
recordedOutput: '录制的输出',
|
|
9
|
+
timedOut: '超时',
|
|
10
|
+
exitCode: (code: number | null) => `退出码 ${code}`,
|
|
11
|
+
noOutput: '(没有输出)',
|
|
12
|
+
runsLive: '*在浏览器中执行(`:run: live`),没有录制的输出。*',
|
|
13
|
+
notRecorded: '*还没有录制的输出。*',
|
|
14
|
+
moreLines: (count: number) => `…… 另有 ${count} 行`,
|
|
15
|
+
anchorScheme: '锚点类型',
|
|
16
|
+
options: '选项',
|
|
17
|
+
suggest: '提示',
|
|
18
|
+
builtIn: '内置',
|
|
19
|
+
},
|
|
20
|
+
'en': {
|
|
21
|
+
status: { exact: 'exact', moved: 'moved', fuzzy: 'to confirm', lost: 'lost' } as Record<string, string>,
|
|
22
|
+
pinnedAt: (commit: string) => `pinned at ${commit}`,
|
|
23
|
+
drifted: 'drifted since the pin',
|
|
24
|
+
recordedOutput: 'Recorded output',
|
|
25
|
+
timedOut: 'timed out',
|
|
26
|
+
exitCode: (code: number | null) => `exit code ${code}`,
|
|
27
|
+
noOutput: '(no output)',
|
|
28
|
+
runsLive: '*Runs in the browser (`:run: live`); no recorded output.*',
|
|
29
|
+
notRecorded: '*No recorded output yet.*',
|
|
30
|
+
moreLines: (count: number) => `… ${count} more lines`,
|
|
31
|
+
anchorScheme: 'anchor scheme',
|
|
32
|
+
options: 'Options',
|
|
33
|
+
suggest: 'Suggest',
|
|
34
|
+
builtIn: 'built-in',
|
|
35
|
+
},
|
|
36
|
+
} satisfies Record<Locale, unknown>
|
|
37
|
+
|
|
38
|
+
export type LsMessages = (typeof LS_MESSAGES)[Locale]
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
const REGION = /(?<![A-Za-z])#?region\b[ \t]*(.*?)[ \t]*(?:-->|\*\/|\*\))?[ \t]*$/i
|
|
2
|
+
|
|
3
|
+
export function regionNames(text: string): string[] {
|
|
4
|
+
const names = text.split(/\r?\n/).map(line => REGION.exec(line)?.[1] ?? '').filter(Boolean)
|
|
5
|
+
return [...new Set(names)]
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
const DECLARATION = /\b(class|def|function\*?|interface|type|enum|namespace|const|let|var)\s+([A-Za-z_$][\w$]*)/
|
|
9
|
+
const MEMBER = /^\s+(?:(?:export|public|private|protected|static|readonly|async|abstract|override|declare|get|set|def)\s+)*\*?([A-Za-z_$][\w$]*)\s*[(<:=?!]/
|
|
10
|
+
const ASSIGNMENT = /^([A-Za-z_]\w*)\s*(?::[^=]*)?=(?!=)/
|
|
11
|
+
const KEYWORDS = new Set(['if', 'for', 'while', 'switch', 'catch', 'return', 'else', 'elif', 'with', 'try', 'new', 'await', 'yield', 'throw', 'print', 'self', 'this', 'super'])
|
|
12
|
+
|
|
13
|
+
export function declarationNames(text: string): string[] {
|
|
14
|
+
const names = new Set<string>()
|
|
15
|
+
const classes: { name: string, indent: number }[] = []
|
|
16
|
+
for (const line of text.split(/\r?\n/)) {
|
|
17
|
+
if (!line.trim()) continue
|
|
18
|
+
const indent = /^[ \t]*/.exec(line)![0].length
|
|
19
|
+
while (classes.length > 0 && indent <= classes.at(-1)!.indent) classes.pop()
|
|
20
|
+
const declared = DECLARATION.exec(line)
|
|
21
|
+
const name = declared?.[2] ?? (classes.length > 0 ? MEMBER.exec(line)?.[1] : ASSIGNMENT.exec(line)?.[1])
|
|
22
|
+
if (!name || KEYWORDS.has(name)) continue
|
|
23
|
+
names.add([...classes.map(c => c.name), name].join('.'))
|
|
24
|
+
if (declared?.[1] === 'class') classes.push({ name, indent })
|
|
25
|
+
}
|
|
26
|
+
return [...names]
|
|
27
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { SectionAt } from './protocol.ts'
|
|
2
|
+
|
|
3
|
+
const page = (link: string) => link.split('#')[0]!
|
|
4
|
+
|
|
5
|
+
export function previewUrl(base: string, section: SectionAt | null | undefined, shown?: SectionAt): string {
|
|
6
|
+
const root = base.replace(/\/?$/, '/')
|
|
7
|
+
if (!section) return root
|
|
8
|
+
const id = encodeURIComponent(section.id)
|
|
9
|
+
const target = shown && page(shown.link) === page(section.link) ? `${page(section.link)}#${id}` : `${page(section.link)}?section=${id}`
|
|
10
|
+
return new URL(target.replace(/^\//, ''), root).href
|
|
11
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
export interface DocumentParams {
|
|
2
|
+
textDocument: { uri: string }
|
|
3
|
+
}
|
|
4
|
+
|
|
5
|
+
export interface PositionParams extends DocumentParams {
|
|
6
|
+
position: { line: number, character: number }
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export const PREVIEW_REQUEST = 'presmium/preview'
|
|
10
|
+
|
|
11
|
+
export interface Preview {
|
|
12
|
+
entry: string
|
|
13
|
+
url: string
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export const SECTION_REQUEST = 'presmium/section'
|
|
17
|
+
|
|
18
|
+
export interface SectionAt {
|
|
19
|
+
entry: string
|
|
20
|
+
id: string
|
|
21
|
+
index: number
|
|
22
|
+
title: string
|
|
23
|
+
link: string
|
|
24
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { irBlocks } from '@lincyaw/kernel'
|
|
2
|
+
import type { IRBlock, IRDocument, IRSection } from '@lincyaw/kernel'
|
|
3
|
+
|
|
4
|
+
export function sectionAt(doc: IRDocument, file: string, line: number): IRSection | undefined {
|
|
5
|
+
const headed = doc.sections.filter(s => s.source.file === file && s.source.line <= line).at(-1)
|
|
6
|
+
if (headed) return headed
|
|
7
|
+
let first: IRSection | undefined
|
|
8
|
+
let last: { section: IRSection, line: number } | undefined
|
|
9
|
+
for (const section of doc.sections) {
|
|
10
|
+
for (const block of irBlocks(section.blocks)) {
|
|
11
|
+
if (block.source.file !== file) continue
|
|
12
|
+
first ??= section
|
|
13
|
+
if (block.source.line <= line && block.source.line >= (last?.line ?? 0)) last = { section, line: block.source.line }
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
return last?.section ?? first ?? (file === doc.meta.entry ? doc.sections[0] : undefined)
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function blockAt(doc: IRDocument, file: string, line: number): IRBlock | undefined {
|
|
20
|
+
for (const section of doc.sections) {
|
|
21
|
+
for (const block of irBlocks(section.blocks)) {
|
|
22
|
+
if (block.source.file === file && block.source.line === line) return block
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
return undefined
|
|
26
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
export interface Fence {
|
|
2
|
+
line: number
|
|
3
|
+
name: string
|
|
4
|
+
nameStart: number
|
|
5
|
+
arg: string
|
|
6
|
+
argStart: number
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
const FENCE = /^([ \t]*(?:`{3,}|~{3,}|:{3,})\{)([^{}\s]*)\}(.*)$/
|
|
10
|
+
const OPTION = /^[ \t]*:[\w-]*(?::.*)?$/
|
|
11
|
+
|
|
12
|
+
export function fenceAt(lines: readonly string[], line: number): Fence | undefined {
|
|
13
|
+
const match = FENCE.exec(lines[line] ?? '')
|
|
14
|
+
if (!match) return undefined
|
|
15
|
+
const [, open, name, rest] = match as unknown as [string, string, string, string]
|
|
16
|
+
const after = open.length + name.length + 1
|
|
17
|
+
return { line, name, nameStart: open.length, arg: rest.trim(), argStart: after + rest.length - rest.trimStart().length }
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function directiveAt(lines: readonly string[], line: number): Fence | undefined {
|
|
21
|
+
for (let i = line; i >= 0; i--) {
|
|
22
|
+
const fence = fenceAt(lines, i)
|
|
23
|
+
if (fence) return fence
|
|
24
|
+
if (!OPTION.test(lines[i] ?? '')) return undefined
|
|
25
|
+
}
|
|
26
|
+
return undefined
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function writtenOptions(lines: readonly string[], fence: Fence): string[] {
|
|
30
|
+
const names: string[] = []
|
|
31
|
+
for (let i = fence.line + 1; i < lines.length && OPTION.test(lines[i]!); i++) {
|
|
32
|
+
const name = /^[ \t]*:([\w-]+):/.exec(lines[i]!)?.[1]
|
|
33
|
+
if (name) names.push(name)
|
|
34
|
+
}
|
|
35
|
+
return names
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface AnchorRef {
|
|
39
|
+
anchor: `${string}:${string}`
|
|
40
|
+
scheme: string
|
|
41
|
+
line: number
|
|
42
|
+
start: number
|
|
43
|
+
end: number
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function anchorAt(lines: readonly string[], line: number, schemes: readonly string[] = [], anchors: ReadonlySet<string> = new Set()): AnchorRef | undefined {
|
|
47
|
+
const fence = fenceAt(lines, line)
|
|
48
|
+
const word = (fence && anchors.has(fence.name) ? fence.arg : fence?.arg.split(/\s/)[0]) ?? ''
|
|
49
|
+
const colon = word.indexOf(':')
|
|
50
|
+
if (!fence || colon <= 0) return undefined
|
|
51
|
+
const scheme = word.slice(0, colon)
|
|
52
|
+
if (!anchors.has(fence.name) && !schemes.includes(scheme)) return undefined
|
|
53
|
+
return { anchor: word as AnchorRef['anchor'], scheme, line, start: fence.argStart, end: fence.argStart + word.length }
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export type Typing =
|
|
57
|
+
| { kind: 'directive', prefix: string, start: number, closed: boolean }
|
|
58
|
+
| { kind: 'argument', fence: Fence, prefix: string, start: number }
|
|
59
|
+
| { kind: 'option', fence: Fence, prefix: string, start: number, written: string[] }
|
|
60
|
+
| { kind: 'value', fence: Fence, option: string, prefix: string, start: number }
|
|
61
|
+
|
|
62
|
+
export function typingAt(lines: readonly string[], line: number, character: number): Typing | undefined {
|
|
63
|
+
const text = lines[line] ?? ''
|
|
64
|
+
const before = text.slice(0, character)
|
|
65
|
+
const opening = /^[ \t]*(?:`{3,}|~{3,}|:{3,})\{([\w-]*)$/.exec(before)
|
|
66
|
+
if (opening) return { kind: 'directive', prefix: opening[1]!, start: character - opening[1]!.length, closed: text[character] === '}' }
|
|
67
|
+
|
|
68
|
+
const fence = fenceAt(lines, line)
|
|
69
|
+
if (fence) {
|
|
70
|
+
const brace = fence.nameStart + fence.name.length
|
|
71
|
+
if (character <= brace) return undefined
|
|
72
|
+
const prefix = before.slice(brace + 1).trimStart()
|
|
73
|
+
return { kind: 'argument', fence, prefix, start: character - prefix.length }
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const directive = directiveAt(lines, line)
|
|
77
|
+
if (!directive) return undefined
|
|
78
|
+
const option = /^[ \t]*:([\w-]*)$/.exec(before)
|
|
79
|
+
if (option) return { kind: 'option', fence: directive, prefix: option[1]!, start: character - option[1]!.length, written: writtenOptions(lines, directive) }
|
|
80
|
+
const value = /^[ \t]*:([\w-]+):[ \t]*(.*)$/.exec(before)
|
|
81
|
+
if (!value) return undefined
|
|
82
|
+
const prefix = value[2]!.split(',').at(-1)!.trimStart()
|
|
83
|
+
return { kind: 'value', fence: directive, option: value[1]!, prefix, start: character - prefix.length }
|
|
84
|
+
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { readdir } from 'node:fs/promises'
|
|
2
|
+
import { isAbsolute, relative, resolve, sep } from 'node:path'
|
|
3
|
+
import { pathToFileURL } from 'node:url'
|
|
4
|
+
import type { Compilation } from '@lincyaw/compiler'
|
|
5
|
+
import { isRenderable } from '@lincyaw/kernel'
|
|
6
|
+
import type { AnchorString, CodeNode, Resolution, ResolvedLocation } from '@lincyaw/kernel'
|
|
7
|
+
import { CompletionItemKind, MarkupKind } from 'vscode-languageserver/node'
|
|
8
|
+
import type { CompletionItem, Hover, Location, Range } from 'vscode-languageserver/node'
|
|
9
|
+
import { blockAt, declarationNames, regionNames } from '../domain/index.ts'
|
|
10
|
+
import type { AnchorRef, LsMessages } from '../domain/index.ts'
|
|
11
|
+
|
|
12
|
+
const MAX_NAMES = 200
|
|
13
|
+
const MAX_LINES = 60
|
|
14
|
+
|
|
15
|
+
const suggest = (t: LsMessages) => ({ title: t.suggest, command: 'editor.action.triggerSuggest' })
|
|
16
|
+
|
|
17
|
+
function resolveAnchor(compilation: Compilation, anchor: AnchorString): Promise<Resolution> {
|
|
18
|
+
return compilation.resolvers.resolve(anchor, compilation.src, compilation.lock.get(anchor))
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function locationOf(compilation: Compilation, location: ResolvedLocation): Location {
|
|
22
|
+
const last = location.text.split(/\r?\n/).at(-1) ?? ''
|
|
23
|
+
return {
|
|
24
|
+
uri: pathToFileURL(resolve(compilation.workspaceRoot, location.file)).href,
|
|
25
|
+
range: { start: { line: location.startLine - 1, character: 0 }, end: { line: location.endLine - 1, character: last.length } },
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export async function anchorDefinition(compilation: Compilation, ref: AnchorRef): Promise<Location[]> {
|
|
30
|
+
const resolution = await resolveAnchor(compilation, ref.anchor)
|
|
31
|
+
const found = resolution.location ? [resolution.location] : resolution.candidates ?? []
|
|
32
|
+
return found.map(location => locationOf(compilation, location))
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function fenced(t: LsMessages, text: string, lang = ''): string {
|
|
36
|
+
const lines = text.replace(/\n+$/, '').split('\n')
|
|
37
|
+
const shown = lines.length > MAX_LINES ? [...lines.slice(0, MAX_LINES), t.moreLines(lines.length - MAX_LINES)] : lines
|
|
38
|
+
const fence = '`'.repeat(Math.max(3, ...[...text.matchAll(/`+/g)].map(m => m[0].length + 1)))
|
|
39
|
+
return `${fence}${lang}\n${shown.join('\n')}\n${fence}`
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function where(file: string, startLine: number, endLine: number): string {
|
|
43
|
+
return `\`${file}:${startLine}-${endLine}\``
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export async function anchorHover(compilation: Compilation, file: string, ref: AnchorRef, t: LsMessages): Promise<Hover> {
|
|
47
|
+
const range: Range = { start: { line: ref.line, character: ref.start }, end: { line: ref.line, character: ref.end } }
|
|
48
|
+
const block = blockAt(compilation.doc, file, ref.line + 1)
|
|
49
|
+
const node = block?.node.type === 'code' && block.node.origin?.anchor === ref.anchor ? block.node : undefined
|
|
50
|
+
const parts = node?.origin && node.origin.startLine > 0 ? codeNodeHover(node, t) : await resolvedHover(compilation, ref, t)
|
|
51
|
+
return { contents: { kind: MarkupKind.Markdown, value: parts.join('\n\n') }, range }
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function codeNodeHover(node: CodeNode, t: LsMessages): string[] {
|
|
55
|
+
const origin = node.origin!
|
|
56
|
+
const notes = [t.status[origin.status] ?? origin.status, origin.pin && t.pinnedAt(origin.pin.slice(0, 7)), origin.drift === 'drifted' && t.drifted].filter(Boolean)
|
|
57
|
+
const parts = [`**${origin.anchor}** ${where(origin.file, origin.startLine, origin.endLine)} (${notes.join(', ')})`, fenced(t, node.value, node.lang)]
|
|
58
|
+
const run = node.outputs?.[0]
|
|
59
|
+
if (run) {
|
|
60
|
+
const status = run.timedOut ? t.timedOut : run.ok ? `${run.durationMs} ms` : t.exitCode(run.exitCode)
|
|
61
|
+
parts.push(`**${t.recordedOutput}** (${run.executorId}, ${status})`, fenced(t, [run.stdout, run.stderr].filter(Boolean).join('\n') || t.noOutput))
|
|
62
|
+
} else if (node.run) {
|
|
63
|
+
parts.push(node.run.when === 'live' ? t.runsLive : t.notRecorded)
|
|
64
|
+
}
|
|
65
|
+
return parts
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async function resolvedHover(compilation: Compilation, ref: AnchorRef, t: LsMessages): Promise<string[]> {
|
|
69
|
+
const resolution = await resolveAnchor(compilation, ref.anchor)
|
|
70
|
+
const { location } = resolution
|
|
71
|
+
const parts = [[`**${ref.anchor}**`, location && where(location.file, location.startLine, location.endLine), `(${t.status[resolution.status] ?? resolution.status})`].filter(Boolean).join(' ')]
|
|
72
|
+
if (resolution.message) parts.push(resolution.message)
|
|
73
|
+
if (location && isRenderable(resolution)) parts.push(fenced(t, location.text, /\.([\w-]+)$/.exec(location.file)?.[1] ?? ''))
|
|
74
|
+
return parts
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export async function anchorCompletion(compilation: Compilation, prefix: string, line: number, start: number, end: number, t: LsMessages): Promise<CompletionItem[]> {
|
|
78
|
+
const edit = (from: number, newText: string) => ({ range: { start: { line, character: from }, end: { line, character: end } }, newText })
|
|
79
|
+
const colon = prefix.indexOf(':')
|
|
80
|
+
if (colon < 0) {
|
|
81
|
+
return compilation.resolvers.schemes().map(scheme => ({ label: `${scheme}:`, kind: CompletionItemKind.Keyword, detail: t.anchorScheme, textEdit: edit(start, `${scheme}:`), command: suggest(t) }))
|
|
82
|
+
}
|
|
83
|
+
const scheme = prefix.slice(0, colon)
|
|
84
|
+
const target = prefix.slice(colon + 1)
|
|
85
|
+
const hash = target.lastIndexOf('#')
|
|
86
|
+
|
|
87
|
+
if (hash < 0) {
|
|
88
|
+
const dir = target.slice(0, target.lastIndexOf('/') + 1)
|
|
89
|
+
const path = resolve(compilation.workspaceRoot, dir)
|
|
90
|
+
const inside = relative(compilation.workspaceRoot, path)
|
|
91
|
+
if (inside === '..' || inside.startsWith(`..${sep}`) || isAbsolute(inside)) return []
|
|
92
|
+
const entries = await readdir(path, { withFileTypes: true }).catch(() => [])
|
|
93
|
+
return entries.filter(entry => !entry.name.startsWith('.') && entry.name !== 'node_modules').map((entry) => {
|
|
94
|
+
const name = entry.isDirectory() ? `${entry.name}/` : `${entry.name}#`
|
|
95
|
+
return { label: name, kind: entry.isDirectory() ? CompletionItemKind.Folder : CompletionItemKind.File, textEdit: edit(start + colon + 1 + dir.length, name), command: suggest(t) }
|
|
96
|
+
})
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const file = target.slice(0, hash)
|
|
100
|
+
const text = await compilation.src.read(file)
|
|
101
|
+
if (text === undefined) return []
|
|
102
|
+
const typed = target.slice(hash + 1).toLowerCase()
|
|
103
|
+
const harvested = (scheme === 'region' ? regionNames(text) : scheme === 'symbol' ? declarationNames(text) : [...regionNames(text), ...declarationNames(text)])
|
|
104
|
+
.filter(name => name.toLowerCase().includes(typed))
|
|
105
|
+
const resolved = await Promise.all(harvested.slice(0, MAX_NAMES).map(async (name) => {
|
|
106
|
+
const resolution = await compilation.resolvers.resolve(`${scheme}:${file}#${name}`, compilation.src)
|
|
107
|
+
return isRenderable(resolution) ? { name, location: resolution.location! } : undefined
|
|
108
|
+
}))
|
|
109
|
+
return resolved.filter(found => found !== undefined).map(({ name, location }) => ({
|
|
110
|
+
label: name,
|
|
111
|
+
kind: scheme === 'region' ? CompletionItemKind.Reference : CompletionItemKind.Function,
|
|
112
|
+
detail: `${location.file}:${location.startLine}-${location.endLine}`,
|
|
113
|
+
documentation: { kind: MarkupKind.Markdown, value: fenced(t, location.text) },
|
|
114
|
+
textEdit: edit(start + colon + 1 + hash + 1, name),
|
|
115
|
+
}))
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export async function unitNames(compilation: Compilation, anchor: AnchorString): Promise<string[]> {
|
|
119
|
+
const resolution = await resolveAnchor(compilation, anchor)
|
|
120
|
+
return resolution.location ? regionNames(resolution.location.text) : []
|
|
121
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import type { Compilation } from '@lincyaw/compiler'
|
|
2
|
+
import { CompletionItemKind, MarkupKind } from 'vscode-languageserver/node'
|
|
3
|
+
import type { CompletionItem, Position } from 'vscode-languageserver/node'
|
|
4
|
+
import { anchorAt, optionsOf, typingAt } from '../domain/index.ts'
|
|
5
|
+
import type { DirectiveInfo, Fence } from '../domain/index.ts'
|
|
6
|
+
import { anchorCompletion, unitNames } from './anchors.ts'
|
|
7
|
+
import { deckSyntax } from './syntax.ts'
|
|
8
|
+
import type { DeckSyntax } from './syntax.ts'
|
|
9
|
+
|
|
10
|
+
function describe(info: DirectiveInfo, syntax: DeckSyntax): string {
|
|
11
|
+
const options = Object.keys(optionsOf(info, syntax.common)).map(name => `\`:${name}:\``).join(', ')
|
|
12
|
+
return [info.doc, `${syntax.t.options}: ${options}`].filter(Boolean).join('\n\n')
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function isAnchorArgument(fence: Fence, prefix: string, compilation: Compilation, syntax: DeckSyntax): boolean {
|
|
16
|
+
return syntax.anchors.has(fence.name) || compilation.resolvers.schemes().some(scheme => prefix.startsWith(`${scheme}:`))
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export async function complete(compilation: Compilation, lines: string[], position: Position): Promise<CompletionItem[]> {
|
|
20
|
+
const typing = typingAt(lines, position.line, position.character)
|
|
21
|
+
if (!typing) return []
|
|
22
|
+
const { line, character } = position
|
|
23
|
+
const edit = (newText: string) => ({ range: { start: { line, character: typing.start }, end: { line, character } }, newText })
|
|
24
|
+
const syntax = deckSyntax(compilation)
|
|
25
|
+
const infos = syntax.directives
|
|
26
|
+
|
|
27
|
+
switch (typing.kind) {
|
|
28
|
+
case 'directive':
|
|
29
|
+
return [...infos.values()].map(info => ({
|
|
30
|
+
label: info.name,
|
|
31
|
+
kind: CompletionItemKind.Keyword,
|
|
32
|
+
detail: info.source,
|
|
33
|
+
documentation: { kind: MarkupKind.Markdown, value: describe(info, syntax) },
|
|
34
|
+
textEdit: edit(typing.closed ? info.name : `${info.name}}`),
|
|
35
|
+
}))
|
|
36
|
+
|
|
37
|
+
case 'argument': {
|
|
38
|
+
if (typing.fence.name === 'component') {
|
|
39
|
+
return [...compilation.components].map(([name, plugin]) => ({ label: name, kind: CompletionItemKind.Class, detail: plugin, textEdit: edit(name) }))
|
|
40
|
+
}
|
|
41
|
+
if (!isAnchorArgument(typing.fence, typing.prefix, compilation, syntax)) return []
|
|
42
|
+
return anchorCompletion(compilation, typing.prefix, line, typing.start, character, syntax.t)
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
case 'option': {
|
|
46
|
+
const info = infos.get(typing.fence.name)
|
|
47
|
+
if (!info) return []
|
|
48
|
+
return Object.entries(optionsOf(info, syntax.common)).filter(([name]) => !typing.written.includes(name)).map(([name, option]) => ({
|
|
49
|
+
label: name,
|
|
50
|
+
kind: CompletionItemKind.Property,
|
|
51
|
+
detail: option.type,
|
|
52
|
+
documentation: option.doc,
|
|
53
|
+
textEdit: edit(`${name}: `),
|
|
54
|
+
}))
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
case 'value': {
|
|
58
|
+
const info = infos.get(typing.fence.name)
|
|
59
|
+
const values = [...(info && optionsOf(info, syntax.common)[typing.option]?.values) ?? []]
|
|
60
|
+
if (typing.option === 'executor') values.push(...compilation.plugins.flatMap(({ plugin }) => plugin?.executors?.map(e => e.id) ?? []))
|
|
61
|
+
const anchor = typing.option === 'steps' ? anchorAt(lines, typing.fence.line, compilation.resolvers.schemes(), syntax.anchors) : undefined
|
|
62
|
+
if (anchor) values.push(...await unitNames(compilation, anchor.anchor), 'all', 'none')
|
|
63
|
+
return [...new Set(values)].map(value => ({ label: value, kind: CompletionItemKind.Value, textEdit: edit(value) }))
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from 'node:fs'
|
|
2
|
+
import { basename, dirname, join } from 'node:path'
|
|
3
|
+
import { Compiler, DECK_ENTRY, readFrontmatter } from '@lincyaw/compiler'
|
|
4
|
+
import type { Compilation } from '@lincyaw/compiler'
|
|
5
|
+
import { ANCHOR_LOCK_PATH, errorMessage } from '@lincyaw/kernel'
|
|
6
|
+
import type { Finding } from '@lincyaw/kernel'
|
|
7
|
+
|
|
8
|
+
export class Deck {
|
|
9
|
+
readonly entry: string
|
|
10
|
+
readonly #compiler: Compiler
|
|
11
|
+
readonly #compiled: (deck: Deck) => void
|
|
12
|
+
compilation?: Compilation
|
|
13
|
+
findings: Finding[] = []
|
|
14
|
+
#running?: Promise<void>
|
|
15
|
+
#again = false
|
|
16
|
+
|
|
17
|
+
constructor(entry: string, compiled: (deck: Deck) => void) {
|
|
18
|
+
this.entry = entry
|
|
19
|
+
this.#compiler = new Compiler(entry)
|
|
20
|
+
this.#compiled = compiled
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
compile(): Promise<void> {
|
|
24
|
+
if (this.#running) {
|
|
25
|
+
this.#again = true
|
|
26
|
+
return this.#running
|
|
27
|
+
}
|
|
28
|
+
this.#running = (async () => {
|
|
29
|
+
do {
|
|
30
|
+
this.#again = false
|
|
31
|
+
await this.#compileOnce()
|
|
32
|
+
} while (this.#again)
|
|
33
|
+
this.#running = undefined
|
|
34
|
+
})()
|
|
35
|
+
return this.#running
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
ready(): Promise<void> {
|
|
39
|
+
return this.#running ?? Promise.resolve()
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
owns(file: string): boolean {
|
|
43
|
+
return this.compilation ? this.compilation.files.includes(file) : file === this.entry
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
reads(file: string): boolean {
|
|
47
|
+
const { compilation } = this
|
|
48
|
+
if (!compilation) return file === this.entry
|
|
49
|
+
return compilation.files.includes(file) || compilation.dependencies.files.includes(file) || file === join(compilation.deckDir, ANCHOR_LOCK_PATH)
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async #compileOnce(): Promise<void> {
|
|
53
|
+
try {
|
|
54
|
+
const compilation = await this.#compiler.compile()
|
|
55
|
+
this.findings = [...compilation.doc.diagnostics, ...await compilation.check()]
|
|
56
|
+
this.compilation = compilation
|
|
57
|
+
} catch (error) {
|
|
58
|
+
this.findings = [{ checkId: 'presmium.compile', severity: 'error', message: errorMessage(error), source: { file: this.entry, line: 1 } }]
|
|
59
|
+
}
|
|
60
|
+
this.#compiled(this)
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function declaresPlugins(file: string): boolean {
|
|
65
|
+
try {
|
|
66
|
+
return 'plugins' in readFrontmatter(readFileSync(file, 'utf8'))
|
|
67
|
+
} catch {
|
|
68
|
+
return false
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function candidateEntries(file: string): string[] {
|
|
73
|
+
const entries = basename(file) === DECK_ENTRY ? [file] : []
|
|
74
|
+
for (let dir = dirname(file); ; dir = dirname(dir)) {
|
|
75
|
+
const entry = join(dir, DECK_ENTRY)
|
|
76
|
+
if (entry !== file && existsSync(entry)) entries.push(entry)
|
|
77
|
+
if (dirname(dir) === dir) break
|
|
78
|
+
}
|
|
79
|
+
if (basename(file) !== DECK_ENTRY && declaresPlugins(file)) entries.push(file)
|
|
80
|
+
return entries
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export class Decks {
|
|
84
|
+
readonly #decks = new Map<string, Deck>()
|
|
85
|
+
readonly #compiled: (deck: Deck) => void
|
|
86
|
+
|
|
87
|
+
constructor(compiled: (deck: Deck) => void) {
|
|
88
|
+
this.#compiled = compiled
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
all(): Deck[] {
|
|
92
|
+
return [...this.#decks.values()]
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
open(entry: string): Deck {
|
|
96
|
+
let deck = this.#decks.get(entry)
|
|
97
|
+
if (!deck) {
|
|
98
|
+
deck = new Deck(entry, this.#compiled)
|
|
99
|
+
this.#decks.set(entry, deck)
|
|
100
|
+
void deck.compile()
|
|
101
|
+
}
|
|
102
|
+
return deck
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
async of(file: string): Promise<Deck | undefined> {
|
|
106
|
+
const known = this.all()
|
|
107
|
+
const owner = known.find(deck => deck.compilation?.files.includes(file))
|
|
108
|
+
if (owner) return owner
|
|
109
|
+
for (const deck of known) {
|
|
110
|
+
await deck.ready()
|
|
111
|
+
if (deck.owns(file)) return deck
|
|
112
|
+
}
|
|
113
|
+
for (const entry of candidateEntries(file)) {
|
|
114
|
+
if (known.some(deck => deck.entry === entry)) continue
|
|
115
|
+
const deck = this.open(entry)
|
|
116
|
+
await deck.ready()
|
|
117
|
+
if (deck.owns(file)) return deck
|
|
118
|
+
}
|
|
119
|
+
return undefined
|
|
120
|
+
}
|
|
121
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { Finding, Severity } from '@lincyaw/kernel'
|
|
2
|
+
import { DiagnosticSeverity } from 'vscode-languageserver/node'
|
|
3
|
+
import type { Diagnostic, Range } from 'vscode-languageserver/node'
|
|
4
|
+
import { fenceAt } from '../domain/index.ts'
|
|
5
|
+
|
|
6
|
+
const SEVERITY: Record<Severity, DiagnosticSeverity> = {
|
|
7
|
+
error: DiagnosticSeverity.Error,
|
|
8
|
+
warning: DiagnosticSeverity.Warning,
|
|
9
|
+
info: DiagnosticSeverity.Information,
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function rangeOf(text: string, line: number, message: string): Range {
|
|
13
|
+
const fence = fenceAt([text], 0)
|
|
14
|
+
const word = fence?.arg.split(/\s/)[0]
|
|
15
|
+
if (fence && word && message.includes(word)) {
|
|
16
|
+
return { start: { line, character: fence.argStart }, end: { line, character: fence.argStart + word.length } }
|
|
17
|
+
}
|
|
18
|
+
const start = text.length - text.trimStart().length
|
|
19
|
+
return { start: { line, character: start }, end: { line, character: text.trimEnd().length } }
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function toDiagnostics(findings: Finding[], entry: string, lines: (file: string) => string[]): Map<string, Diagnostic[]> {
|
|
23
|
+
const byFile = new Map<string, Diagnostic[]>()
|
|
24
|
+
const texts = new Map<string, string[]>()
|
|
25
|
+
for (const finding of findings) {
|
|
26
|
+
const file = finding.source?.file ?? entry
|
|
27
|
+
const line = Math.max(1, finding.source?.line ?? 1) - 1
|
|
28
|
+
if (!texts.has(file)) texts.set(file, lines(file))
|
|
29
|
+
const diagnostic: Diagnostic = {
|
|
30
|
+
range: rangeOf(texts.get(file)![line] ?? '', line, finding.message),
|
|
31
|
+
severity: SEVERITY[finding.severity],
|
|
32
|
+
source: 'presmium',
|
|
33
|
+
code: finding.checkId,
|
|
34
|
+
message: finding.hint ? `${finding.message}\n${finding.hint}` : finding.message,
|
|
35
|
+
}
|
|
36
|
+
byFile.set(file, [...byFile.get(file) ?? [], diagnostic])
|
|
37
|
+
}
|
|
38
|
+
return byFile
|
|
39
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process'
|
|
2
|
+
import type { ChildProcess } from 'node:child_process'
|
|
3
|
+
import { existsSync, readFileSync } from 'node:fs'
|
|
4
|
+
import { createRequire } from 'node:module'
|
|
5
|
+
import { dirname, join } from 'node:path'
|
|
6
|
+
import { createInterface } from 'node:readline'
|
|
7
|
+
|
|
8
|
+
const START_TIMEOUT = 120_000
|
|
9
|
+
const PREVIEW_DIR = '.presmium/preview'
|
|
10
|
+
|
|
11
|
+
const CLI = '@lincyaw/cli'
|
|
12
|
+
|
|
13
|
+
function cliBin(from: string): string | undefined {
|
|
14
|
+
let dir: string
|
|
15
|
+
try {
|
|
16
|
+
dir = dirname(createRequire(from).resolve(CLI))
|
|
17
|
+
} catch {
|
|
18
|
+
return undefined
|
|
19
|
+
}
|
|
20
|
+
for (; dirname(dir) !== dir; dir = dirname(dir)) {
|
|
21
|
+
const file = join(dir, 'package.json')
|
|
22
|
+
if (!existsSync(file)) continue
|
|
23
|
+
const pkg = JSON.parse(readFileSync(file, 'utf8')) as { name?: string, bin?: Record<string, string> }
|
|
24
|
+
if (pkg.name === CLI && pkg.bin?.presmium) return join(dir, pkg.bin.presmium)
|
|
25
|
+
}
|
|
26
|
+
return undefined
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function presmiumBin(deckDir: string): string {
|
|
30
|
+
const bin = cliBin(join(deckDir, 'package.json')) ?? cliBin(import.meta.url)
|
|
31
|
+
if (!bin) throw new Error(`${CLI} is not installed`)
|
|
32
|
+
return bin
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function stop(child: ChildProcess, signal: NodeJS.Signals = 'SIGTERM'): void {
|
|
36
|
+
if (!child.pid || child.exitCode !== null || child.signalCode !== null) return
|
|
37
|
+
if (process.platform === 'win32') {
|
|
38
|
+
const task = spawn('taskkill', ['/PID', String(child.pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' })
|
|
39
|
+
task.once('error', () => { child.kill(signal) })
|
|
40
|
+
} else child.kill(signal)
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export class Previews {
|
|
44
|
+
readonly #urls = new Map<string, Promise<string>>()
|
|
45
|
+
readonly #children = new Set<ChildProcess>()
|
|
46
|
+
readonly #log: (line: string) => void
|
|
47
|
+
|
|
48
|
+
constructor(log: (line: string) => void) {
|
|
49
|
+
this.#log = log
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
open(entry: string): Promise<string> {
|
|
53
|
+
const known = this.#urls.get(entry)
|
|
54
|
+
if (known) return known
|
|
55
|
+
const forget = () => {
|
|
56
|
+
if (this.#urls.get(entry) === url) this.#urls.delete(entry)
|
|
57
|
+
}
|
|
58
|
+
const url: Promise<string> = this.#start(entry, forget)
|
|
59
|
+
this.#urls.set(entry, url)
|
|
60
|
+
url.catch(forget)
|
|
61
|
+
return url
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
#start(entry: string, forget: () => void): Promise<string> {
|
|
65
|
+
const deckDir = dirname(entry)
|
|
66
|
+
const args = [presmiumBin(deckDir), 'dev', entry, '--to', 'web', '--out', join(deckDir, PREVIEW_DIR)]
|
|
67
|
+
const child = spawn(process.execPath, args, { cwd: deckDir, stdio: ['ignore', 'pipe', 'pipe'] })
|
|
68
|
+
this.#children.add(child)
|
|
69
|
+
return new Promise((resolve, reject) => {
|
|
70
|
+
let started = false
|
|
71
|
+
const fail = (error: Error) => {
|
|
72
|
+
clearTimeout(timer)
|
|
73
|
+
reject(error)
|
|
74
|
+
if (!started) stop(child)
|
|
75
|
+
}
|
|
76
|
+
const timer = setTimeout(() => fail(new Error('presmium dev did not start the web server in time')), START_TIMEOUT)
|
|
77
|
+
createInterface({ input: child.stderr! }).on('line', line => this.#log(line))
|
|
78
|
+
createInterface({ input: child.stdout! }).on('line', (line) => {
|
|
79
|
+
this.#log(line)
|
|
80
|
+
if (started) return
|
|
81
|
+
const url = /^web\s+(https?:\/\/\S+)/.exec(line)?.[1]
|
|
82
|
+
if (url) {
|
|
83
|
+
started = true
|
|
84
|
+
clearTimeout(timer)
|
|
85
|
+
resolve(url)
|
|
86
|
+
} else if (line.startsWith('watching;')) {
|
|
87
|
+
fail(new Error('presmium dev started no web server; is the web renderer installed?'))
|
|
88
|
+
}
|
|
89
|
+
})
|
|
90
|
+
child.once('error', fail)
|
|
91
|
+
child.once('exit', (code) => {
|
|
92
|
+
this.#children.delete(child)
|
|
93
|
+
forget()
|
|
94
|
+
fail(new Error(`presmium dev exited with code ${code}`))
|
|
95
|
+
})
|
|
96
|
+
})
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
async close(): Promise<void> {
|
|
100
|
+
const exits = [...this.#children].map(child => new Promise<void>((done) => {
|
|
101
|
+
const timer = setTimeout(() => {
|
|
102
|
+
stop(child, 'SIGKILL')
|
|
103
|
+
done()
|
|
104
|
+
}, 5000).unref()
|
|
105
|
+
child.once('exit', () => { clearTimeout(timer); done() })
|
|
106
|
+
stop(child)
|
|
107
|
+
}))
|
|
108
|
+
this.#urls.clear()
|
|
109
|
+
await Promise.all(exits)
|
|
110
|
+
}
|
|
111
|
+
}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs'
|
|
2
|
+
import { fileURLToPath, pathToFileURL } from 'node:url'
|
|
3
|
+
import { sectionLinks, toPages } from '@lincyaw/web/domain'
|
|
4
|
+
import { TextDocument } from 'vscode-languageserver-textdocument'
|
|
5
|
+
import { createConnection, DidChangeWatchedFilesNotification, ProposedFeatures, TextDocuments, TextDocumentSyncKind } from 'vscode-languageserver/node'
|
|
6
|
+
import { anchorAt, PREVIEW_REQUEST, SECTION_REQUEST, sectionAt } from '../domain/index.ts'
|
|
7
|
+
import type { DocumentParams, PositionParams, Preview, SectionAt } from '../domain/index.ts'
|
|
8
|
+
import { anchorDefinition, anchorHover } from './anchors.ts'
|
|
9
|
+
import { complete } from './completion.ts'
|
|
10
|
+
import { Decks } from './decks.ts'
|
|
11
|
+
import type { Deck } from './decks.ts'
|
|
12
|
+
import { toDiagnostics } from './diagnostics.ts'
|
|
13
|
+
import { Previews } from './preview.ts'
|
|
14
|
+
import { deckSyntax } from './syntax.ts'
|
|
15
|
+
|
|
16
|
+
const COMPILE_DELAY = 50
|
|
17
|
+
|
|
18
|
+
function fileOf(uri: string): string | undefined {
|
|
19
|
+
return uri.startsWith('file:') ? fileURLToPath(uri) : undefined
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function startServer(): void {
|
|
23
|
+
const connection = createConnection(ProposedFeatures.all)
|
|
24
|
+
const documents = new TextDocuments(TextDocument)
|
|
25
|
+
const previews = new Previews(line => connection.console.log(line))
|
|
26
|
+
const published = new Map<Deck, Set<string>>()
|
|
27
|
+
const timers = new Map<Deck, NodeJS.Timeout>()
|
|
28
|
+
|
|
29
|
+
const bufferLines = (uri: string) => documents.get(uri)?.getText().split(/\r?\n/) ?? []
|
|
30
|
+
const fileLines = (file: string): string[] => {
|
|
31
|
+
try {
|
|
32
|
+
return readFileSync(file, 'utf8').split(/\r?\n/)
|
|
33
|
+
} catch {
|
|
34
|
+
return []
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const publish = (deck: Deck) => {
|
|
39
|
+
const byFile = toDiagnostics(deck.findings, deck.entry, fileLines)
|
|
40
|
+
const files = new Set([...deck.compilation?.files ?? [deck.entry], ...byFile.keys()])
|
|
41
|
+
const uris = new Set([...files].map(file => pathToFileURL(file).href))
|
|
42
|
+
for (const file of files) void connection.sendDiagnostics({ uri: pathToFileURL(file).href, diagnostics: byFile.get(file) ?? [] })
|
|
43
|
+
for (const uri of published.get(deck) ?? []) {
|
|
44
|
+
if (!uris.has(uri)) void connection.sendDiagnostics({ uri, diagnostics: [] })
|
|
45
|
+
}
|
|
46
|
+
published.set(deck, uris)
|
|
47
|
+
}
|
|
48
|
+
const decks = new Decks(publish)
|
|
49
|
+
|
|
50
|
+
const changed = (files: string[]) => {
|
|
51
|
+
for (const deck of decks.all().filter(d => files.some(file => d.reads(file)))) {
|
|
52
|
+
clearTimeout(timers.get(deck))
|
|
53
|
+
timers.set(deck, setTimeout(() => void deck.compile(), COMPILE_DELAY))
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const deckOf = async (uri: string) => {
|
|
58
|
+
const file = fileOf(uri)
|
|
59
|
+
const deck = file ? await decks.of(file) : undefined
|
|
60
|
+
return file && deck?.compilation ? { file, deck, compilation: deck.compilation } : undefined
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
let watchFiles = false
|
|
64
|
+
connection.onInitialize(({ capabilities }) => {
|
|
65
|
+
watchFiles = capabilities.workspace?.didChangeWatchedFiles?.dynamicRegistration === true
|
|
66
|
+
return {
|
|
67
|
+
capabilities: {
|
|
68
|
+
textDocumentSync: { openClose: true, change: TextDocumentSyncKind.Incremental, save: { includeText: false } },
|
|
69
|
+
definitionProvider: true,
|
|
70
|
+
hoverProvider: true,
|
|
71
|
+
completionProvider: { triggerCharacters: ['{', ':', '#', '/', ','] },
|
|
72
|
+
},
|
|
73
|
+
serverInfo: { name: 'presmium-language-server' },
|
|
74
|
+
}
|
|
75
|
+
})
|
|
76
|
+
connection.onInitialized(() => {
|
|
77
|
+
if (watchFiles) void connection.client.register(DidChangeWatchedFilesNotification.type, { watchers: [{ globPattern: '**/*' }] })
|
|
78
|
+
})
|
|
79
|
+
|
|
80
|
+
documents.onDidOpen(({ document }) => {
|
|
81
|
+
const file = fileOf(document.uri)
|
|
82
|
+
if (file) void decks.of(file)
|
|
83
|
+
})
|
|
84
|
+
documents.onDidSave(({ document }) => {
|
|
85
|
+
const file = fileOf(document.uri)
|
|
86
|
+
if (file) changed([file])
|
|
87
|
+
})
|
|
88
|
+
connection.onDidChangeWatchedFiles(({ changes }) => changed(changes.flatMap(change => fileOf(change.uri) ?? [])))
|
|
89
|
+
|
|
90
|
+
const anchorOf = async (uri: string, line: number) => {
|
|
91
|
+
const found = await deckOf(uri)
|
|
92
|
+
if (!found) return undefined
|
|
93
|
+
const syntax = deckSyntax(found.compilation)
|
|
94
|
+
const ref = anchorAt(bufferLines(uri), line, found.compilation.resolvers.schemes(), syntax.anchors)
|
|
95
|
+
return ref && { ...found, ref, t: syntax.t }
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
connection.onDefinition(async ({ textDocument, position }) => {
|
|
99
|
+
const found = await anchorOf(textDocument.uri, position.line)
|
|
100
|
+
return found ? anchorDefinition(found.compilation, found.ref) : null
|
|
101
|
+
})
|
|
102
|
+
|
|
103
|
+
connection.onHover(async ({ textDocument, position }) => {
|
|
104
|
+
const found = await anchorOf(textDocument.uri, position.line)
|
|
105
|
+
return found ? anchorHover(found.compilation, found.file, found.ref, found.t) : null
|
|
106
|
+
})
|
|
107
|
+
|
|
108
|
+
connection.onCompletion(async ({ textDocument, position }) => {
|
|
109
|
+
const found = await deckOf(textDocument.uri)
|
|
110
|
+
return found ? complete(found.compilation, bufferLines(textDocument.uri), position) : []
|
|
111
|
+
})
|
|
112
|
+
|
|
113
|
+
connection.onRequest(SECTION_REQUEST, async ({ textDocument, position }: PositionParams): Promise<SectionAt | null> => {
|
|
114
|
+
const found = await deckOf(textDocument.uri)
|
|
115
|
+
const doc = found?.compilation.doc
|
|
116
|
+
const section = doc && sectionAt(doc, found.file, position.line + 1)
|
|
117
|
+
if (!section) return null
|
|
118
|
+
const link = sectionLinks(toPages(doc))[section.id] ?? '/'
|
|
119
|
+
return { entry: found.deck.entry, id: section.id, index: section.index, title: section.title, link }
|
|
120
|
+
})
|
|
121
|
+
|
|
122
|
+
connection.onRequest(PREVIEW_REQUEST, async ({ textDocument }: DocumentParams): Promise<Preview> => {
|
|
123
|
+
const file = fileOf(textDocument.uri)
|
|
124
|
+
const deck = file ? await decks.of(file) : undefined
|
|
125
|
+
if (!deck) throw new Error(`${textDocument.uri} is not a source file of a Presmium deck`)
|
|
126
|
+
return { entry: deck.entry, url: await previews.open(deck.entry) }
|
|
127
|
+
})
|
|
128
|
+
|
|
129
|
+
connection.onShutdown(() => previews.close())
|
|
130
|
+
process.once('exit', () => void previews.close())
|
|
131
|
+
|
|
132
|
+
documents.listen(connection)
|
|
133
|
+
connection.listen()
|
|
134
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { BUILTIN_DIRECTIVE_INFO, COMMON_DIRECTIVE_OPTIONS, RUN_OPTION } from '@lincyaw/compiler'
|
|
2
|
+
import type { Compilation, DirectiveOptionInfo } from '@lincyaw/compiler'
|
|
3
|
+
import { deckLocale } from '@lincyaw/kernel'
|
|
4
|
+
import type { Locale } from '@lincyaw/kernel'
|
|
5
|
+
import { anchorDirectives, directiveInfos, LS_MESSAGES } from '../domain/index.ts'
|
|
6
|
+
import type { DirectiveInfo, LsMessages, OptionInfo } from '../domain/index.ts'
|
|
7
|
+
|
|
8
|
+
export interface DeckSyntax {
|
|
9
|
+
directives: Map<string, DirectiveInfo>
|
|
10
|
+
common: Record<string, OptionInfo>
|
|
11
|
+
anchors: Set<string>
|
|
12
|
+
t: LsMessages
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function option(info: DirectiveOptionInfo, locale: Locale): OptionInfo {
|
|
16
|
+
return { ...info.type ? { type: info.type } : {}, ...info.doc ? { doc: info.doc[locale] } : {}, ...info.values ? { values: info.values } : {} }
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function options(infos: Record<string, DirectiveOptionInfo>, locale: Locale): Record<string, OptionInfo> {
|
|
20
|
+
return Object.fromEntries(Object.entries(infos).map(([name, info]) => [name, option(info, locale)]))
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function deckSyntax(compilation: Compilation): DeckSyntax {
|
|
24
|
+
const locale = deckLocale(compilation.doc.meta.lang)
|
|
25
|
+
const t = LS_MESSAGES[locale]
|
|
26
|
+
const builtin = BUILTIN_DIRECTIVE_INFO.map(info => ({ name: info.name, source: t.builtIn, doc: info.doc[locale], options: options(info.options, locale) }))
|
|
27
|
+
const plugins = compilation.plugins.flatMap(({ plugin }) => plugin ? [{ plugin: plugin.id, directives: plugin.directives ?? [] }] : [])
|
|
28
|
+
const directives = directiveInfos(builtin, plugins, option(RUN_OPTION, locale))
|
|
29
|
+
return { directives, common: options(COMMON_DIRECTIVE_OPTIONS, locale), anchors: anchorDirectives(directives), t }
|
|
30
|
+
}
|