@teipublisher/oddity-language-server 0.0.0-stage → 0.2.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.
Files changed (62) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +58 -2
  3. package/dist/edit.js +1211 -0
  4. package/dist/edit.js.map +7 -0
  5. package/dist/index.js +1701 -0
  6. package/dist/index.js.map +7 -0
  7. package/dist/node.cjs +45925 -0
  8. package/dist/node.cjs.map +7 -0
  9. package/package.json +74 -4
  10. package/schema/README.md +45 -0
  11. package/schema/docbook/docbook.rng +18457 -0
  12. package/schema/jats/BITS-embedded-index2.ent.rng +340 -0
  13. package/schema/jats/BITS-question-answer2.ent.rng +795 -0
  14. package/schema/jats/JATS-XHTMLtablesetup1-3.ent.rng +614 -0
  15. package/schema/jats/JATS-ali-namespace1-3.ent.rng +284 -0
  16. package/schema/jats/JATS-archivearticle1-3-mathml3.rng +1277 -0
  17. package/schema/jats/JATS-archivecustom-classes1-3.ent.rng +427 -0
  18. package/schema/jats/JATS-archivecustom-mixes1-3.ent.rng +630 -0
  19. package/schema/jats/JATS-archivecustom-models1-3.ent.rng +2205 -0
  20. package/schema/jats/JATS-articlemeta1-3.ent.rng +3138 -0
  21. package/schema/jats/JATS-backmatter1-3.ent.rng +601 -0
  22. package/schema/jats/JATS-chars1-3.ent.rng +715 -0
  23. package/schema/jats/JATS-common-atts1-3.ent.rng +367 -0
  24. package/schema/jats/JATS-common1-3.ent.rng +6007 -0
  25. package/schema/jats/JATS-default-classes1-3.ent.rng +1953 -0
  26. package/schema/jats/JATS-default-mixes1-3.ent.rng +583 -0
  27. package/schema/jats/JATS-display1-3.ent.rng +1669 -0
  28. package/schema/jats/JATS-format1-3.ent.rng +1256 -0
  29. package/schema/jats/JATS-funding1-3.ent.rng +1389 -0
  30. package/schema/jats/JATS-journalmeta1-3.ent.rng +691 -0
  31. package/schema/jats/JATS-link1-3.ent.rng +664 -0
  32. package/schema/jats/JATS-list1-3.ent.rng +747 -0
  33. package/schema/jats/JATS-math1-3.ent.rng +620 -0
  34. package/schema/jats/JATS-mathml3-mathmlsetup1-3.ent.rng +459 -0
  35. package/schema/jats/JATS-nlmcitation1-3.ent.rng +522 -0
  36. package/schema/jats/JATS-para1-3.ent.rng +780 -0
  37. package/schema/jats/JATS-phrase1-3.ent.rng +725 -0
  38. package/schema/jats/JATS-references1-3.ent.rng +1713 -0
  39. package/schema/jats/JATS-related-object1-3.ent.rng +453 -0
  40. package/schema/jats/JATS-section1-3.ent.rng +482 -0
  41. package/schema/jats/mathml3-qname1.mod.rng +61 -0
  42. package/schema/jats/mathml3.rng +4094 -0
  43. package/schema/jats/xhtml-inlstyle-1.mod.rng +37 -0
  44. package/schema/jats/xhtml-table-1.mod.rng +426 -0
  45. package/schema/odd/teipublisher_odds.rng +12769 -0
  46. package/schema/opm/opm.schema.json +402 -0
  47. package/schema/tei/tei_all.rng +23212 -0
  48. package/src/core/association.ts +155 -0
  49. package/src/core/complete.ts +147 -0
  50. package/src/core/elements.ts +86 -0
  51. package/src/core/opmToml.ts +432 -0
  52. package/src/core/outline.ts +156 -0
  53. package/src/core/schema.ts +55 -0
  54. package/src/core/tags.ts +104 -0
  55. package/src/core/toml.ts +64 -0
  56. package/src/core/tomlScan.ts +155 -0
  57. package/src/core/validate.ts +128 -0
  58. package/src/core/wellformed.ts +16 -0
  59. package/src/edit.ts +12 -0
  60. package/src/index.ts +17 -0
  61. package/src/node.ts +39 -0
  62. package/src/server/server.ts +322 -0
@@ -0,0 +1,322 @@
1
+ // ── the language server, independent of how it is connected ──────────────
2
+ // node.ts runs it over IPC/stdio for VS Code; a browser entry can run it in a web worker.
3
+ import {
4
+ type Connection, type CompletionItem, type Diagnostic, type DocumentSymbol, type InitializeResult, type SelectionRange,
5
+ TextDocuments, TextDocumentSyncKind, CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity,
6
+ InsertTextFormat, MarkupKind, SymbolKind,
7
+ } from 'vscode-languageserver';
8
+ import { TextDocument } from 'vscode-languageserver-textdocument';
9
+ import type { Grammar } from 'salve-annos';
10
+ import { Grammars, type ReadText } from '../core/schema.ts';
11
+ import { schemaFor, isOdd, vocabulary, type Defaults, type Files, type SchemaChoice } from '../core/association.ts';
12
+ import { validate, type Problem } from '../core/validate.ts';
13
+ import { wellFormed } from '../core/wellformed.ts';
14
+ import { possibleAt } from '../core/complete.ts';
15
+ import { matchingTags } from '../core/tags.ts';
16
+ import { elementsAround } from '../core/elements.ts';
17
+ import { oddOutline, teiOutline, elementOutline, type OutlineSymbol } from '../core/outline.ts';
18
+ import { checkOpmToml, completeOpmToml, describeOpmToml, isOpmToml, tableName } from '../core/opmToml.ts';
19
+ import { scanToml } from '../core/tomlScan.ts';
20
+
21
+ export const SOURCE = 'oddity-ls';
22
+
23
+ /** What the host gives the server: file access. */
24
+ export interface Host {
25
+ files: Files;
26
+ readText: ReadText;
27
+ /** Default schemas used when the client does not name its own. */
28
+ defaults?: Defaults;
29
+ }
30
+
31
+ export interface InitOptions {
32
+ /** Default schema URL by vocabulary, e.g. { odd: 'file:///…/teipublisher_odds.rng', tei: 'file:///…/tei_all.rng' }. */
33
+ defaultSchemas?: Defaults;
34
+ }
35
+
36
+ /** Custom request: the schema a document uses, or null. */
37
+ export const SCHEMA_FOR = 'oddity/schemaFor';
38
+ /** Custom notification to the client whenever a document's schema is known or changes. */
39
+ export const SCHEMA_CHANGED = 'oddity/schemaChanged';
40
+ /** Custom request: the elements the schema allows at an offset, [{ name, detail }], or null without a schema. */
41
+ export const ALLOWED_ELEMENTS = 'oddity/allowedElements';
42
+
43
+ const DELAY = 250;
44
+ const XML_TRIGGERS = ['<', ' ', '"', "'"];
45
+ /** Characters a snippet treats as syntax. */
46
+ const snippetEscape = (s: string) => s.replace(/[\\$}]/g, m => '\\' + m);
47
+
48
+ export function startServer(connection: Connection, host: Host): void {
49
+ const documents = new TextDocuments(TextDocument);
50
+ const grammars = new Grammars(host.readText);
51
+ let defaults: Defaults = { ...host.defaults };
52
+ let stops: string[] = [];
53
+ const timers = new Map<string, ReturnType<typeof setTimeout>>();
54
+ const announced = new Map<string, string>();
55
+
56
+ const choiceOf = (doc: TextDocument): SchemaChoice | null => schemaFor(doc.uri, doc.getText(), host.files, defaults, stops);
57
+
58
+ connection.onInitialize((params): InitializeResult => {
59
+ const options = (params.initializationOptions ?? {}) as InitOptions;
60
+ defaults = { ...defaults, ...options.defaultSchemas };
61
+ stops = (params.workspaceFolders ?? []).map(f => f.uri);
62
+ return {
63
+ capabilities: {
64
+ textDocumentSync: TextDocumentSyncKind.Incremental,
65
+ completionProvider: { triggerCharacters: [...XML_TRIGGERS, '[', '='] },
66
+ hoverProvider: true,
67
+ linkedEditingRangeProvider: true,
68
+ documentSymbolProvider: true,
69
+ selectionRangeProvider: true,
70
+ },
71
+ serverInfo: { name: 'oddity-language-server' },
72
+ };
73
+ });
74
+
75
+ async function grammarOf(choice: SchemaChoice | null): Promise<{ grammar?: Grammar; error?: string }> {
76
+ if (!choice) return {};
77
+ try {
78
+ return { grammar: await grammars.get(choice.url) };
79
+ } catch (err) {
80
+ return { error: err instanceof Error ? err.message : String(err) };
81
+ }
82
+ }
83
+
84
+ const toDiagnostic = (doc: TextDocument, p: Problem, code: string): Diagnostic => ({
85
+ range: { start: doc.positionAt(p.from), end: doc.positionAt(p.to) },
86
+ message: p.message,
87
+ severity: DiagnosticSeverity.Error,
88
+ source: SOURCE,
89
+ code,
90
+ });
91
+
92
+ async function check(uri: string): Promise<void> {
93
+ const doc = documents.get(uri);
94
+ if (!doc) return;
95
+ const version = doc.version, text = doc.getText();
96
+ if (isOpmToml(uri)) {
97
+ const diagnostics = checkOpmToml(text).map((p): Diagnostic => ({
98
+ range: { start: doc.positionAt(p.from), end: doc.positionAt(p.to) },
99
+ message: p.message,
100
+ severity: p.severity === 'error' ? DiagnosticSeverity.Error : DiagnosticSeverity.Warning,
101
+ source: SOURCE,
102
+ code: 'opm-toml-' + p.code,
103
+ tags: p.code === 'deprecated' ? [2 /* Deprecated */] : undefined,
104
+ }));
105
+ void connection.sendDiagnostics({ uri, version, diagnostics });
106
+ return;
107
+ }
108
+ const choice = choiceOf(doc);
109
+ const key = choice ? `${choice.via} ${choice.url}` : '';
110
+ if (announced.get(uri) !== key) {
111
+ announced.set(uri, key);
112
+ void connection.sendNotification(SCHEMA_CHANGED, { uri, schema: choice });
113
+ }
114
+ const syntax = wellFormed(text);
115
+ let diagnostics: Diagnostic[];
116
+ if (syntax.length) {
117
+ diagnostics = syntax.map(p => toDiagnostic(doc, p, 'well-formedness'));
118
+ } else {
119
+ const { grammar, error } = await grammarOf(choice);
120
+ if (documents.get(uri)?.version !== version) return;
121
+ if (error) {
122
+ diagnostics = [{
123
+ range: { start: { line: 0, character: 0 }, end: { line: 0, character: 0 } },
124
+ message: `The schema ${choice!.url} could not be loaded: ${error}`,
125
+ severity: DiagnosticSeverity.Warning, source: SOURCE, code: 'schema-load',
126
+ }];
127
+ } else {
128
+ diagnostics = grammar ? validate(grammar, text).map(p => toDiagnostic(doc, p, 'schema')) : [];
129
+ }
130
+ }
131
+ if (documents.get(uri)?.version !== version) return;
132
+ void connection.sendDiagnostics({ uri, version, diagnostics });
133
+ }
134
+
135
+ function schedule(uri: string, delay = DELAY): void {
136
+ clearTimeout(timers.get(uri));
137
+ timers.set(uri, setTimeout(() => {
138
+ timers.delete(uri);
139
+ check(uri).catch(err => connection.console.error(`Checking ${uri} failed: ${err instanceof Error ? err.stack : err}`));
140
+ }, delay));
141
+ }
142
+
143
+ const recheckAll = () => { for (const d of documents.all()) schedule(d.uri, 0); };
144
+
145
+ documents.onDidOpen(e => schedule(e.document.uri, 0));
146
+ documents.onDidChangeContent(e => schedule(e.document.uri));
147
+ documents.onDidClose(e => {
148
+ clearTimeout(timers.get(e.document.uri));
149
+ timers.delete(e.document.uri);
150
+ announced.delete(e.document.uri);
151
+ void connection.sendDiagnostics({ uri: e.document.uri, diagnostics: [] });
152
+ });
153
+
154
+ connection.onDidChangeWatchedFiles(({ changes }) => {
155
+ for (const c of changes) if (/\.rng$/i.test(c.uri)) grammars.invalidate(c.uri);
156
+ recheckAll();
157
+ });
158
+
159
+ connection.onCompletion(async ({ textDocument, position, context }) => {
160
+ const doc = documents.get(textDocument.uri);
161
+ if (!doc) return [];
162
+ if (isOpmToml(doc.uri)) return tomlCompletion(doc, position);
163
+ if (context?.triggerCharacter && !XML_TRIGGERS.includes(context.triggerCharacter)) return [];
164
+ const { grammar } = await grammarOf(choiceOf(doc));
165
+ if (!grammar) return [];
166
+ const at = doc.offsetAt(position);
167
+ const possible = possibleAt(grammar, doc.getText(), at);
168
+ if (!possible) return [];
169
+ const manual = context?.triggerKind !== CompletionTriggerKind.TriggerCharacter;
170
+ // between tags elements are offered only on request, not on every space or quote
171
+ if (!possible.inTag && !manual) return [];
172
+ const range = { start: doc.positionAt(possible.from), end: position };
173
+ return possible.suggestions.map((s, i): CompletionItem => {
174
+ const item: CompletionItem = {
175
+ label: s.label,
176
+ // shown beside every entry of the list, as opm studio does; detail only in the expanded pane
177
+ labelDetails: s.detail ? { description: s.detail } : undefined,
178
+ detail: s.detail,
179
+ documentation: s.info ? { kind: MarkupKind.PlainText, value: s.info } : undefined,
180
+ sortText: String(i).padStart(5, '0'),
181
+ };
182
+ if (s.kind === 'element') {
183
+ item.kind = CompletionItemKind.Class;
184
+ item.textEdit = possible.inTag
185
+ ? { range, newText: s.label }
186
+ : { range, newText: `<${s.label}>$0</${s.label}>` };
187
+ if (!possible.inTag) { item.insertTextFormat = InsertTextFormat.Snippet; item.filterText = s.label; }
188
+ } else if (s.kind === 'attribute') {
189
+ item.kind = CompletionItemKind.Property;
190
+ item.textEdit = { range, newText: `${s.label}="$1"` };
191
+ item.insertTextFormat = InsertTextFormat.Snippet;
192
+ item.command = { title: 'Suggest values', command: 'editor.action.triggerSuggest' };
193
+ } else {
194
+ item.kind = CompletionItemKind.Value;
195
+ item.textEdit = { range, newText: s.label };
196
+ }
197
+ return item;
198
+ });
199
+ });
200
+
201
+ function tomlCompletion(doc: TextDocument, position: { line: number; character: number }): CompletionItem[] {
202
+ const r = completeOpmToml(doc.getText(), doc.offsetAt(position));
203
+ if (!r) return [];
204
+ const range = { start: doc.positionAt(r.from), end: doc.positionAt(r.to) };
205
+ const KIND = { table: CompletionItemKind.Module, key: CompletionItemKind.Property, value: CompletionItemKind.Value } as const;
206
+ return r.options.map((o, i): CompletionItem => {
207
+ const snippet = o.cursor !== undefined && o.cursor < o.apply.length;
208
+ return {
209
+ label: o.label,
210
+ kind: KIND[o.kind],
211
+ labelDetails: o.detail ? { description: o.detail } : undefined,
212
+ detail: o.detail,
213
+ documentation: o.info ? { kind: MarkupKind.PlainText, value: o.info } : undefined,
214
+ sortText: String(i).padStart(5, '0'),
215
+ filterText: doc.getText(range).startsWith('"') ? o.label : o.label.replace(/^\[+/, ''),
216
+ insertTextFormat: snippet ? InsertTextFormat.Snippet : InsertTextFormat.PlainText,
217
+ textEdit: { range, newText: snippet ? snippetEscape(o.apply.slice(0, o.cursor)) + '$0' + snippetEscape(o.apply.slice(o.cursor)) : o.apply },
218
+ };
219
+ });
220
+ }
221
+
222
+ connection.onHover(({ textDocument, position }) => {
223
+ const doc = documents.get(textDocument.uri);
224
+ if (!doc || !isOpmToml(doc.uri)) return null;
225
+ const h = describeOpmToml(doc.getText(), doc.offsetAt(position));
226
+ if (!h) return null;
227
+ return {
228
+ range: { start: doc.positionAt(h.from), end: doc.positionAt(h.to) },
229
+ contents: { kind: MarkupKind.Markdown, value: `**${h.title}**: ${h.detail}${h.info ? '\n\n' + h.info : ''}` },
230
+ };
231
+ });
232
+
233
+ connection.languages.onLinkedEditingRange(({ textDocument, position }) => {
234
+ const doc = documents.get(textDocument.uri);
235
+ if (!doc || isOpmToml(doc.uri)) return null;
236
+ const ranges = matchingTags(doc.getText(), doc.offsetAt(position));
237
+ if (!ranges) return null;
238
+ return {
239
+ ranges: ranges.map(r => ({ start: doc.positionAt(r.from), end: doc.positionAt(r.to) })),
240
+ wordPattern: '[^\\s<>/="\']+',
241
+ };
242
+ });
243
+
244
+ connection.onDocumentSymbol(({ textDocument }) => {
245
+ const doc = documents.get(textDocument.uri);
246
+ if (!doc) return [];
247
+ const text = doc.getText();
248
+ if (isOpmToml(doc.uri)) return tomlOutline(doc);
249
+ let symbols: OutlineSymbol[];
250
+ try {
251
+ symbols = isOdd(doc.uri) ? oddOutline(text) : vocabulary(text) === 'tei' ? teiOutline(text) : elementOutline(text);
252
+ } catch {
253
+ return [];
254
+ }
255
+ const convert = (s: OutlineSymbol): DocumentSymbol => ({
256
+ name: s.name || ' ',
257
+ detail: s.detail,
258
+ kind: s.kind as DocumentSymbol['kind'],
259
+ range: { start: doc.positionAt(s.from), end: doc.positionAt(s.to) },
260
+ selectionRange: { start: doc.positionAt(s.nameFrom), end: doc.positionAt(s.nameTo) },
261
+ children: s.children.map(convert),
262
+ });
263
+ return symbols.map(convert);
264
+ });
265
+
266
+ // the tables of opm.toml, each with its keys
267
+ function tomlOutline(doc: TextDocument): DocumentSymbol[] {
268
+ const text = doc.getText(), scan = scanToml(text);
269
+ const range = (from: number, to: number) => ({ start: doc.positionAt(from), end: doc.positionAt(to) });
270
+ const tables = scan.tables.map((t, n): DocumentSymbol => {
271
+ const end = n + 1 < scan.tables.length ? scan.tables[n + 1].from : text.length;
272
+ const keys = scan.keys.filter(k => k.from > t.from && k.from < end);
273
+ const last = keys.length ? keys[keys.length - 1].valueTo : t.to;
274
+ return {
275
+ name: tableName(t.path), kind: t.array ? SymbolKind.Array : SymbolKind.Module,
276
+ range: range(t.from, last), selectionRange: range(t.from, t.to),
277
+ children: keys.map(k => ({
278
+ name: text.slice(k.from, k.to), kind: SymbolKind.Property,
279
+ range: range(k.from, k.valueTo), selectionRange: range(k.from, k.to),
280
+ })),
281
+ };
282
+ });
283
+ return tables;
284
+ }
285
+
286
+ // Expand Selection steps through the enclosing elements
287
+ connection.onSelectionRanges(({ textDocument, positions }) => {
288
+ const doc = documents.get(textDocument.uri);
289
+ if (!doc) return [];
290
+ if (isOpmToml(doc.uri)) return positions.map(position => ({ range: { start: position, end: position } }));
291
+ const text = doc.getText();
292
+ return positions.map(position => {
293
+ const at = doc.offsetAt(position);
294
+ // built from the outermost element in, so each range's parent is the next larger one
295
+ let range: SelectionRange | undefined;
296
+ for (const e of elementsAround(text, at).reverse()) {
297
+ range = { range: { start: doc.positionAt(e.from), end: doc.positionAt(e.to) }, parent: range };
298
+ }
299
+ return range ?? { range: { start: position, end: position } };
300
+ });
301
+ });
302
+
303
+ connection.onRequest(ALLOWED_ELEMENTS, async ({ uri, offset }: { uri: string; offset: number }) => {
304
+ const doc = documents.get(uri);
305
+ if (!doc) return null;
306
+ const { grammar } = await grammarOf(choiceOf(doc));
307
+ if (!grammar) return null;
308
+ // what may start here: the text before, as if an element were begun at offset
309
+ const before = doc.getText().slice(0, offset);
310
+ const possible = possibleAt(grammar, before, offset);
311
+ if (!possible) return null;
312
+ return possible.suggestions.filter(s => s.kind === 'element').map(s => ({ name: s.label, detail: s.detail }));
313
+ });
314
+
315
+ connection.onRequest(SCHEMA_FOR, ({ uri }: { uri: string }) => {
316
+ const doc = documents.get(uri);
317
+ return doc ? choiceOf(doc) : null;
318
+ });
319
+
320
+ documents.listen(connection);
321
+ connection.listen();
322
+ }