@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.
- package/LICENSE +21 -0
- package/README.md +58 -2
- package/dist/edit.js +1211 -0
- package/dist/edit.js.map +7 -0
- package/dist/index.js +1701 -0
- package/dist/index.js.map +7 -0
- package/dist/node.cjs +45925 -0
- package/dist/node.cjs.map +7 -0
- package/package.json +74 -4
- package/schema/README.md +45 -0
- package/schema/docbook/docbook.rng +18457 -0
- package/schema/jats/BITS-embedded-index2.ent.rng +340 -0
- package/schema/jats/BITS-question-answer2.ent.rng +795 -0
- package/schema/jats/JATS-XHTMLtablesetup1-3.ent.rng +614 -0
- package/schema/jats/JATS-ali-namespace1-3.ent.rng +284 -0
- package/schema/jats/JATS-archivearticle1-3-mathml3.rng +1277 -0
- package/schema/jats/JATS-archivecustom-classes1-3.ent.rng +427 -0
- package/schema/jats/JATS-archivecustom-mixes1-3.ent.rng +630 -0
- package/schema/jats/JATS-archivecustom-models1-3.ent.rng +2205 -0
- package/schema/jats/JATS-articlemeta1-3.ent.rng +3138 -0
- package/schema/jats/JATS-backmatter1-3.ent.rng +601 -0
- package/schema/jats/JATS-chars1-3.ent.rng +715 -0
- package/schema/jats/JATS-common-atts1-3.ent.rng +367 -0
- package/schema/jats/JATS-common1-3.ent.rng +6007 -0
- package/schema/jats/JATS-default-classes1-3.ent.rng +1953 -0
- package/schema/jats/JATS-default-mixes1-3.ent.rng +583 -0
- package/schema/jats/JATS-display1-3.ent.rng +1669 -0
- package/schema/jats/JATS-format1-3.ent.rng +1256 -0
- package/schema/jats/JATS-funding1-3.ent.rng +1389 -0
- package/schema/jats/JATS-journalmeta1-3.ent.rng +691 -0
- package/schema/jats/JATS-link1-3.ent.rng +664 -0
- package/schema/jats/JATS-list1-3.ent.rng +747 -0
- package/schema/jats/JATS-math1-3.ent.rng +620 -0
- package/schema/jats/JATS-mathml3-mathmlsetup1-3.ent.rng +459 -0
- package/schema/jats/JATS-nlmcitation1-3.ent.rng +522 -0
- package/schema/jats/JATS-para1-3.ent.rng +780 -0
- package/schema/jats/JATS-phrase1-3.ent.rng +725 -0
- package/schema/jats/JATS-references1-3.ent.rng +1713 -0
- package/schema/jats/JATS-related-object1-3.ent.rng +453 -0
- package/schema/jats/JATS-section1-3.ent.rng +482 -0
- package/schema/jats/mathml3-qname1.mod.rng +61 -0
- package/schema/jats/mathml3.rng +4094 -0
- package/schema/jats/xhtml-inlstyle-1.mod.rng +37 -0
- package/schema/jats/xhtml-table-1.mod.rng +426 -0
- package/schema/odd/teipublisher_odds.rng +12769 -0
- package/schema/opm/opm.schema.json +402 -0
- package/schema/tei/tei_all.rng +23212 -0
- package/src/core/association.ts +155 -0
- package/src/core/complete.ts +147 -0
- package/src/core/elements.ts +86 -0
- package/src/core/opmToml.ts +432 -0
- package/src/core/outline.ts +156 -0
- package/src/core/schema.ts +55 -0
- package/src/core/tags.ts +104 -0
- package/src/core/toml.ts +64 -0
- package/src/core/tomlScan.ts +155 -0
- package/src/core/validate.ts +128 -0
- package/src/core/wellformed.ts +16 -0
- package/src/edit.ts +12 -0
- package/src/index.ts +17 -0
- package/src/node.ts +39 -0
- package/src/server/server.ts +322 -0
|
@@ -0,0 +1,432 @@
|
|
|
1
|
+
// ── opm.toml: checking, completion and hover from opm's JSON Schema ───────
|
|
2
|
+
// schema/opm/opm.schema.json ships with opm (npm run schemas copies it), so
|
|
3
|
+
// what the editor knows about opm.toml follows opm. The checker understands
|
|
4
|
+
// the part of JSON Schema that file uses: type, properties,
|
|
5
|
+
// additionalProperties, required, items, enum, anyOf, minimum, $ref and
|
|
6
|
+
// deprecated.
|
|
7
|
+
import { parse, TomlError } from 'smol-toml';
|
|
8
|
+
import opmSchema from '../../schema/opm/opm.schema.json' with { type: 'json' };
|
|
9
|
+
import { scanToml, tableAt, readKey, type Seg, type TomlScan } from './tomlScan.ts';
|
|
10
|
+
|
|
11
|
+
export interface Schema {
|
|
12
|
+
type?: string | string[];
|
|
13
|
+
description?: string;
|
|
14
|
+
properties?: Record<string, Schema>;
|
|
15
|
+
additionalProperties?: boolean | Schema;
|
|
16
|
+
required?: string[];
|
|
17
|
+
items?: Schema;
|
|
18
|
+
enum?: unknown[];
|
|
19
|
+
anyOf?: Schema[];
|
|
20
|
+
minimum?: number;
|
|
21
|
+
default?: unknown;
|
|
22
|
+
examples?: unknown[];
|
|
23
|
+
deprecated?: boolean;
|
|
24
|
+
$ref?: string;
|
|
25
|
+
definitions?: Record<string, Schema>;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export const OPM_SCHEMA = opmSchema as Schema;
|
|
29
|
+
|
|
30
|
+
/** Whether a document is an opm project config, by its name. */
|
|
31
|
+
export const isOpmToml = (uri: string): boolean => /(^|[/\\])opm\.toml$/.test(uri);
|
|
32
|
+
|
|
33
|
+
export interface TomlProblem {
|
|
34
|
+
from: number;
|
|
35
|
+
to: number;
|
|
36
|
+
message: string;
|
|
37
|
+
severity: 'error' | 'warning';
|
|
38
|
+
/** syntax, unknown, type, enum, required, range or deprecated. */
|
|
39
|
+
code: string;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// ── schema navigation ────────────────────────────────────────────────────
|
|
43
|
+
|
|
44
|
+
function deref(s: Schema, root: Schema): Schema {
|
|
45
|
+
let seen = 0;
|
|
46
|
+
while (s.$ref && seen++ < 20) {
|
|
47
|
+
const target = s.$ref.replace(/^#\/definitions\//, '');
|
|
48
|
+
const { $ref: _, ...rest } = s;
|
|
49
|
+
s = { ...root.definitions?.[target], ...rest };
|
|
50
|
+
}
|
|
51
|
+
return s;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const typesOf = (s: Schema): string[] => (s.type === undefined ? [] : Array.isArray(s.type) ? s.type : [s.type]);
|
|
55
|
+
|
|
56
|
+
/** The anyOf branches of s (or s itself), dereferenced. */
|
|
57
|
+
const branches = (s: Schema, root: Schema): Schema[] => {
|
|
58
|
+
s = deref(s, root);
|
|
59
|
+
if (!s.anyOf) return [s];
|
|
60
|
+
const { anyOf, ...own } = s;
|
|
61
|
+
return anyOf.flatMap(b => branches(b, root)).map(b => ({ ...b, description: own.description ?? b.description, deprecated: own.deprecated ?? b.deprecated }));
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
/** The schema of the value at path, or undefined where the schema says nothing. */
|
|
65
|
+
export function schemaAt(path: Seg[], root: Schema = OPM_SCHEMA): Schema | undefined {
|
|
66
|
+
let s: Schema | undefined = deref(root, root);
|
|
67
|
+
for (const seg of path) {
|
|
68
|
+
if (!s) return undefined;
|
|
69
|
+
const options = branches(s, root);
|
|
70
|
+
if (typeof seg === 'number') {
|
|
71
|
+
const arr = options.find(b => typesOf(b).includes('array'));
|
|
72
|
+
s = arr?.items && deref(arr.items, root);
|
|
73
|
+
} else {
|
|
74
|
+
const obj = options.find(b => typesOf(b).includes('object') || b.properties);
|
|
75
|
+
const next: Schema | boolean | undefined = obj?.properties?.[seg] ?? obj?.additionalProperties;
|
|
76
|
+
s = next && typeof next === 'object' ? { ...deref(next, root), ...(obj?.properties?.[seg]?.description ? { description: obj.properties[seg].description } : {}) } : undefined;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return s;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// ── checking ─────────────────────────────────────────────────────────────
|
|
83
|
+
|
|
84
|
+
interface SchemaError { path: Seg[]; message: string; code: string; severity: 'error' | 'warning' }
|
|
85
|
+
|
|
86
|
+
const kindOf = (v: unknown): string =>
|
|
87
|
+
typeof v === 'string' ? 'string' : typeof v === 'boolean' ? 'boolean'
|
|
88
|
+
: typeof v === 'number' || typeof v === 'bigint' ? (Number.isInteger(Number(v)) ? 'integer' : 'number')
|
|
89
|
+
: Array.isArray(v) ? 'array' : v && typeof v === 'object' && !(v instanceof Date) && !('toISOString' in (v as object)) ? 'object' : 'datetime';
|
|
90
|
+
|
|
91
|
+
const accepts = (type: string, kind: string) => type === kind || (type === 'number' && kind === 'integer');
|
|
92
|
+
|
|
93
|
+
const NOUN: Record<string, string> = {
|
|
94
|
+
string: 'a string', integer: 'a whole number', number: 'a number', boolean: 'true or false',
|
|
95
|
+
array: 'a list', object: 'a table', datetime: 'a date',
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
/** "a string or a list of strings", from the branches a value could have matched. */
|
|
99
|
+
function expected(options: Schema[], root: Schema): string {
|
|
100
|
+
const words = options.flatMap(b => typesOf(b).map(t => {
|
|
101
|
+
if (t === 'array' && b.items) {
|
|
102
|
+
const item = typesOf(deref(b.items, root))[0];
|
|
103
|
+
return item ? `a list of ${NOUN[item].replace(/^an? /, '')}s` : NOUN.array;
|
|
104
|
+
}
|
|
105
|
+
return NOUN[t] ?? t;
|
|
106
|
+
}));
|
|
107
|
+
return [...new Set(words)].join(' or ');
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export function tableName(path: Seg[]): string {
|
|
111
|
+
const names = path.filter((s): s is string => typeof s === 'string');
|
|
112
|
+
const array = typeof path[path.length - 1] === 'number';
|
|
113
|
+
return names.length ? (array ? `[[${names.join('.')}]]` : `[${names.join('.')}]`) : 'the top level';
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const keyName = (path: Seg[]) => String(path.filter(s => typeof s === 'string').pop() ?? '');
|
|
117
|
+
|
|
118
|
+
function distance(a: string, b: string): number {
|
|
119
|
+
const d = Array.from({ length: b.length + 1 }, (_, j) => j);
|
|
120
|
+
for (let i = 1; i <= a.length; i++) {
|
|
121
|
+
let prev = d[0];
|
|
122
|
+
d[0] = i;
|
|
123
|
+
for (let j = 1; j <= b.length; j++) {
|
|
124
|
+
const tmp = d[j];
|
|
125
|
+
d[j] = Math.min(d[j] + 1, d[j - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1));
|
|
126
|
+
prev = tmp;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
return d[b.length];
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function check(value: unknown, s: Schema, path: Seg[], root: Schema, errors: SchemaError[]): void {
|
|
133
|
+
const options = branches(s, root);
|
|
134
|
+
const kind = kindOf(value);
|
|
135
|
+
const fits = options.filter(b => !typesOf(b).length || typesOf(b).some(t => accepts(t, kind)));
|
|
136
|
+
if (!fits.length) {
|
|
137
|
+
const name = path.length ? `"${keyName(path)}"` : 'opm.toml';
|
|
138
|
+
errors.push({ path, code: 'type', severity: 'error', message: `${name} should be ${expected(options, root)}, not ${NOUN[kind] ?? kind}.` });
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
let chosen = fits[0];
|
|
142
|
+
if (fits.length > 1) {
|
|
143
|
+
// the first branch the value passes, else the first that fits its kind
|
|
144
|
+
for (const b of fits) {
|
|
145
|
+
const trial: SchemaError[] = [];
|
|
146
|
+
checkOne(value, b, path, root, trial);
|
|
147
|
+
if (!trial.some(e => e.severity === 'error')) { chosen = b; break; }
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
checkOne(value, chosen, path, root, errors);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function checkOne(value: unknown, s: Schema, path: Seg[], root: Schema, errors: SchemaError[]): void {
|
|
154
|
+
if (s.deprecated && path.length) {
|
|
155
|
+
errors.push({ path, code: 'deprecated', severity: 'warning', message: s.description ?? `"${keyName(path)}" is deprecated.` });
|
|
156
|
+
}
|
|
157
|
+
if (s.enum && !s.enum.includes(value)) {
|
|
158
|
+
errors.push({ path, code: 'enum', severity: 'error', message: `"${keyName(path)}" should be one of ${s.enum.map(v => JSON.stringify(v)).join(', ')}.` });
|
|
159
|
+
}
|
|
160
|
+
if (s.minimum !== undefined && (typeof value === 'number' || typeof value === 'bigint') && Number(value) < s.minimum) {
|
|
161
|
+
errors.push({ path, code: 'range', severity: 'error', message: `"${keyName(path)}" should be at least ${s.minimum}.` });
|
|
162
|
+
}
|
|
163
|
+
if (Array.isArray(value) && s.items) {
|
|
164
|
+
value.forEach((item, n) => check(item, s.items!, [...path, n], root, errors));
|
|
165
|
+
} else if (kindOf(value) === 'object') {
|
|
166
|
+
const obj = value as Record<string, unknown>;
|
|
167
|
+
for (const req of s.required ?? []) {
|
|
168
|
+
if (!(req in obj)) errors.push({ path, code: 'required', severity: 'error', message: `${tableName(path)} needs "${req}".` });
|
|
169
|
+
}
|
|
170
|
+
for (const [k, v] of Object.entries(obj)) {
|
|
171
|
+
const prop = s.properties?.[k];
|
|
172
|
+
if (prop) { check(v, prop, [...path, k], root, errors); continue; }
|
|
173
|
+
if (s.additionalProperties === false) {
|
|
174
|
+
const known = Object.keys(s.properties ?? {});
|
|
175
|
+
const close = known.map(n => [n, distance(k, n)] as const).filter(([, d]) => d <= 2).sort((a, b) => a[1] - b[1])[0];
|
|
176
|
+
errors.push({
|
|
177
|
+
path: [...path, k], code: 'unknown', severity: 'warning',
|
|
178
|
+
message: `opm does not know "${k}" in ${tableName(path)}.${close ? ` Did you mean "${close[0]}"?` : ''}`,
|
|
179
|
+
});
|
|
180
|
+
} else if (s.additionalProperties && typeof s.additionalProperties === 'object') {
|
|
181
|
+
check(v, s.additionalProperties, [...path, k], root, errors);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
const startsWith = (path: Seg[], prefix: Seg[]) => prefix.length <= path.length && prefix.every((s, i) => path[i] === s);
|
|
188
|
+
const same = (a: Seg[], b: Seg[]) => a.length === b.length && startsWith(a, b);
|
|
189
|
+
|
|
190
|
+
/** Where an error at path is shown: the key or header that writes it, or the value it sits inside. */
|
|
191
|
+
function rangeOf(scan: TomlScan, e: SchemaError): { from: number; to: number } {
|
|
192
|
+
const key = scan.keys.find(k => same(k.path, e.path));
|
|
193
|
+
if (key) return e.code === 'unknown' || e.code === 'deprecated' ? { from: key.from, to: key.to } : { from: key.valueFrom, to: key.valueTo };
|
|
194
|
+
const table = scan.tables.find(t => same(t.path, e.path)) ?? scan.tables.find(t => startsWith(t.path, e.path));
|
|
195
|
+
if (table) return { from: table.from, to: table.to };
|
|
196
|
+
const below = scan.keys.find(k => startsWith(k.path, e.path));
|
|
197
|
+
if (below) return { from: below.from, to: below.to };
|
|
198
|
+
// inside an inline table or array: the value that holds it
|
|
199
|
+
let holder: { from: number; to: number } | undefined;
|
|
200
|
+
for (const k of scan.keys) if (startsWith(e.path, k.path)) holder = { from: k.valueFrom, to: k.valueTo };
|
|
201
|
+
return holder ?? { from: 0, to: 0 };
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** Problems in an opm.toml: TOML syntax first, then what opm's schema says. */
|
|
205
|
+
export function checkOpmToml(text: string, schema: Schema = OPM_SCHEMA): TomlProblem[] {
|
|
206
|
+
let data: unknown;
|
|
207
|
+
try {
|
|
208
|
+
data = parse(text);
|
|
209
|
+
} catch (err) {
|
|
210
|
+
if (!(err instanceof TomlError)) throw err;
|
|
211
|
+
const lines = text.split('\n');
|
|
212
|
+
const line = Math.max(0, Math.min(lines.length - 1, err.line - 1));
|
|
213
|
+
const start = lines.slice(0, line).reduce((n, l) => n + l.length + 1, 0);
|
|
214
|
+
const from = start + Math.max(0, Math.min(lines[line].length, err.column - 1));
|
|
215
|
+
const message = err.message.split('\n')[0].replace(/^Invalid TOML document: /, '');
|
|
216
|
+
return [{ from, to: Math.max(from, start + lines[line].length), message: `Not valid TOML: ${message}.`, severity: 'error', code: 'syntax' }];
|
|
217
|
+
}
|
|
218
|
+
const errors: SchemaError[] = [];
|
|
219
|
+
check(data, schema, [], schema, errors);
|
|
220
|
+
const scan = scanToml(text);
|
|
221
|
+
return errors.map(e => ({ ...rangeOf(scan, e), message: e.message, severity: e.severity, code: e.code }));
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// ── completion ───────────────────────────────────────────────────────────
|
|
225
|
+
|
|
226
|
+
export interface TomlOption {
|
|
227
|
+
label: string;
|
|
228
|
+
kind: 'table' | 'key' | 'value';
|
|
229
|
+
/** Short type summary, e.g. "string", "true or false". */
|
|
230
|
+
detail?: string;
|
|
231
|
+
/** The description from the schema. */
|
|
232
|
+
info?: string;
|
|
233
|
+
/** Text that replaces from…to. */
|
|
234
|
+
apply: string;
|
|
235
|
+
/** Where the cursor goes, as an offset into apply; the end when missing. */
|
|
236
|
+
cursor?: number;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
export interface TomlCompletions { from: number; to: number; options: TomlOption[] }
|
|
240
|
+
|
|
241
|
+
function summary(s: Schema, root: Schema): string {
|
|
242
|
+
const options = branches(s, root);
|
|
243
|
+
if (options.length === 1 && options[0].enum) return options[0].enum.map(v => JSON.stringify(v)).join(' | ');
|
|
244
|
+
return expected(options, root).replace(/^an? /, '').replace(/ or an? /g, ' or ');
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/** A starting value for a key, and where the cursor goes in it. */
|
|
248
|
+
function template(s: Schema, root: Schema): { text: string; cursor: number } {
|
|
249
|
+
const first = branches(s, root)[0] ?? {};
|
|
250
|
+
const t = typesOf(first)[0];
|
|
251
|
+
if (first.enum?.length) return { text: JSON.stringify(first.enum[0]), cursor: 1 };
|
|
252
|
+
if (t === 'string') return { text: '""', cursor: 1 };
|
|
253
|
+
if (t === 'array') {
|
|
254
|
+
const item = first.items && typesOf(deref(first.items, root))[0];
|
|
255
|
+
return item === 'string' ? { text: '[""]', cursor: 2 } : { text: '[]', cursor: 1 };
|
|
256
|
+
}
|
|
257
|
+
if (t === 'object') return { text: '{ }', cursor: 2 };
|
|
258
|
+
if (t === 'boolean') return { text: String(first.default ?? true), cursor: String(first.default ?? true).length };
|
|
259
|
+
return { text: '', cursor: 0 };
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
const isTable = (s: Schema, root: Schema) => branches(s, root).some(b => typesOf(b).includes('object') || b.properties);
|
|
263
|
+
const isTableArray = (s: Schema, root: Schema) => branches(s, root).some(b => {
|
|
264
|
+
if (!typesOf(b).includes('array') || !b.items) return false;
|
|
265
|
+
return isTable(b.items, root);
|
|
266
|
+
});
|
|
267
|
+
|
|
268
|
+
/** Whether a value is only ever written as a [header] or [[header]]: a table with known keys, or an array of tables. */
|
|
269
|
+
const isHeaderOnly = (s: Schema, root: Schema) => branches(s, root).every(b =>
|
|
270
|
+
(typesOf(b).includes('object') && !!b.properties) || (typesOf(b).includes('array') && !!b.items && isTable(b.items, root)));
|
|
271
|
+
|
|
272
|
+
/** Every table a header can name, as [path, array]: [transform.web], [[chunking]], [[chunking.fragments]], … */
|
|
273
|
+
function headers(root: Schema): { name: string; array: boolean; schema: Schema }[] {
|
|
274
|
+
const out: { name: string; array: boolean; schema: Schema }[] = [];
|
|
275
|
+
const walk = (s: Schema, names: string[], depth: number) => {
|
|
276
|
+
if (depth > 4) return;
|
|
277
|
+
for (const b of branches(s, root)) {
|
|
278
|
+
for (const [k, raw] of Object.entries(b.properties ?? {})) {
|
|
279
|
+
const p = deref(raw, root);
|
|
280
|
+
if (p.deprecated || raw.deprecated) continue;
|
|
281
|
+
const ns = [...names, k];
|
|
282
|
+
const desc = { ...p, description: raw.description ?? p.description };
|
|
283
|
+
if (isTable(p, root)) { out.push({ name: ns.join('.'), array: false, schema: desc }); walk(p, ns, depth + 1); }
|
|
284
|
+
if (isTableArray(p, root)) {
|
|
285
|
+
out.push({ name: ns.join('.'), array: true, schema: desc });
|
|
286
|
+
const items = branches(p, root).find(x => typesOf(x).includes('array'))?.items;
|
|
287
|
+
if (items) walk(items, ns, depth + 1);
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
};
|
|
292
|
+
walk(root, [], 0);
|
|
293
|
+
return out;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** Suggestions at offset: table names in a header, keys at the start of a line, values after "=". */
|
|
297
|
+
export function completeOpmToml(text: string, offset: number, schema: Schema = OPM_SCHEMA): TomlCompletions | null {
|
|
298
|
+
const lineStart = text.lastIndexOf('\n', offset - 1) + 1;
|
|
299
|
+
const before = text.slice(lineStart, offset);
|
|
300
|
+
if (/^\s*#/.test(before) || /#[^"']*$/.test(before)) return null;
|
|
301
|
+
const scan = scanToml(text);
|
|
302
|
+
|
|
303
|
+
// a header: [transform.w| or [[chunk|
|
|
304
|
+
const header = /^\s*(\[\[?)\s*([A-Za-z0-9_.-]*)$/.exec(before);
|
|
305
|
+
if (header) {
|
|
306
|
+
const from = offset - header[2].length;
|
|
307
|
+
const lineEnd = text.indexOf('\n', offset);
|
|
308
|
+
const rest = text.slice(offset, lineEnd < 0 ? text.length : lineEnd);
|
|
309
|
+
const closing = /^[A-Za-z0-9_.-]*\]{1,2}/.exec(rest);
|
|
310
|
+
const to = closing ? offset + closing[0].length : offset;
|
|
311
|
+
const double = header[1] === '[[';
|
|
312
|
+
return {
|
|
313
|
+
from, to,
|
|
314
|
+
options: headers(schema).filter(h => h.array === double).map(h => ({
|
|
315
|
+
label: h.name, kind: 'table', detail: h.array ? 'array of tables' : 'table', info: h.schema.description,
|
|
316
|
+
apply: h.name + (double ? ']]' : ']'),
|
|
317
|
+
})),
|
|
318
|
+
};
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
const table = tableAt(scan, offset);
|
|
322
|
+
const tablePath = table?.path ?? [];
|
|
323
|
+
|
|
324
|
+
// a value: key = …|
|
|
325
|
+
const eq = before.indexOf('=');
|
|
326
|
+
if (eq >= 0) {
|
|
327
|
+
const key = readKey(before, 0, ch => ch === '=');
|
|
328
|
+
if (!key) return null;
|
|
329
|
+
let s = schemaAt([...tablePath, ...key.parts], schema);
|
|
330
|
+
if (!s) return null;
|
|
331
|
+
let after = before.slice(eq + 1);
|
|
332
|
+
// inside a list: the item's schema
|
|
333
|
+
if ((after.match(/\[/g)?.length ?? 0) > (after.match(/\]/g)?.length ?? 0)) {
|
|
334
|
+
const arr = branches(s, schema).find(b => typesOf(b).includes('array'));
|
|
335
|
+
if (!arr?.items) return null;
|
|
336
|
+
s = deref(arr.items, schema);
|
|
337
|
+
after = after.slice(after.lastIndexOf(',') >= 0 && after.lastIndexOf(',') > after.lastIndexOf('[') ? after.lastIndexOf(',') + 1 : after.lastIndexOf('[') + 1);
|
|
338
|
+
}
|
|
339
|
+
const word = /("?)([^"\s,[\]{}=]*)$/.exec(after)!;
|
|
340
|
+
const quoted = word[1] === '"';
|
|
341
|
+
const from = offset - word[2].length - (quoted ? 1 : 0);
|
|
342
|
+
const values = new Map<string, string | undefined>();
|
|
343
|
+
for (const b of branches(s, schema)) {
|
|
344
|
+
for (const v of b.enum ?? []) values.set(JSON.stringify(v), b.description);
|
|
345
|
+
if (typesOf(b).includes('boolean')) { values.set('true', undefined); values.set('false', undefined); }
|
|
346
|
+
for (const v of b.examples ?? []) values.set(JSON.stringify(v), 'example');
|
|
347
|
+
if (b.default !== undefined && typeof b.default !== 'object') values.set(JSON.stringify(b.default), 'default');
|
|
348
|
+
}
|
|
349
|
+
if (!values.size) return null;
|
|
350
|
+
// a closing quote the editor already typed is replaced too
|
|
351
|
+
const to = quoted && text[offset] === '"' ? offset + 1 : offset;
|
|
352
|
+
return {
|
|
353
|
+
from, to,
|
|
354
|
+
options: [...values].map(([v, note]) => ({ label: v, kind: 'value', detail: note === 'example' || note === 'default' ? note : undefined, apply: v })),
|
|
355
|
+
};
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
// a key at the start of a line
|
|
359
|
+
const typed = /^\s*([A-Za-z0-9_.-]*)$/.exec(before);
|
|
360
|
+
if (!typed) return null;
|
|
361
|
+
const dots = typed[1].split('.');
|
|
362
|
+
const partial = dots.pop()!;
|
|
363
|
+
const parent = [...tablePath, ...dots.filter(Boolean)];
|
|
364
|
+
const s = schemaAt(parent, schema);
|
|
365
|
+
const from = offset - partial.length;
|
|
366
|
+
if (!table && !dots.filter(Boolean).length) {
|
|
367
|
+
// before any header: offer the tables themselves
|
|
368
|
+
return {
|
|
369
|
+
from, to: offset,
|
|
370
|
+
options: headers(schema).map(h => ({
|
|
371
|
+
label: h.array ? `[[${h.name}]]` : `[${h.name}]`, kind: 'table' as const, detail: h.array ? 'array of tables' : 'table', info: h.schema.description,
|
|
372
|
+
apply: h.array ? `[[${h.name}]]` : `[${h.name}]`,
|
|
373
|
+
})),
|
|
374
|
+
};
|
|
375
|
+
}
|
|
376
|
+
if (!s) return null;
|
|
377
|
+
const present = new Set(scan.keys.filter(k => startsWith(k.path, parent) && k.path.length > parent.length).map(k => k.path[parent.length]));
|
|
378
|
+
for (const t of scan.tables) if (startsWith(t.path, parent) && t.path.length > parent.length) present.add(t.path[parent.length]);
|
|
379
|
+
const options: TomlOption[] = [];
|
|
380
|
+
for (const b of branches(s, schema)) {
|
|
381
|
+
for (const [name, raw] of Object.entries(b.properties ?? {})) {
|
|
382
|
+
const p = deref(raw, schema);
|
|
383
|
+
if (present.has(name) || p.deprecated || raw.deprecated) continue;
|
|
384
|
+
// tables with keys of their own, and arrays of them, are written as headers
|
|
385
|
+
if (isHeaderOnly(p, schema)) continue;
|
|
386
|
+
const value = template(p, schema);
|
|
387
|
+
options.push({
|
|
388
|
+
label: name, kind: 'key', detail: summary(p, schema), info: raw.description ?? p.description,
|
|
389
|
+
apply: `${name} = ${value.text}`, cursor: name.length + 3 + value.cursor,
|
|
390
|
+
});
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
return { from, to: offset, options };
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
// ── hover ────────────────────────────────────────────────────────────────
|
|
397
|
+
|
|
398
|
+
export interface TomlHover { from: number; to: number; title: string; detail: string; info?: string }
|
|
399
|
+
|
|
400
|
+
/** What the schema says about the key or table header at offset. */
|
|
401
|
+
export function describeOpmToml(text: string, offset: number, schema: Schema = OPM_SCHEMA): TomlHover | null {
|
|
402
|
+
const scan = scanToml(text);
|
|
403
|
+
const table = scan.tables.find(t => t.from <= offset && offset <= t.to);
|
|
404
|
+
const key = table ? undefined : scan.keys.find(k => k.from <= offset && offset <= k.to);
|
|
405
|
+
const hit = table ?? key;
|
|
406
|
+
if (!hit) return null;
|
|
407
|
+
let path = hit.path;
|
|
408
|
+
// a dotted key: the part under the cursor
|
|
409
|
+
if (key) {
|
|
410
|
+
const parts = readKey(text, key.from, ch => ch === '=')?.parts ?? [];
|
|
411
|
+
const prefixLen = key.path.length - parts.length;
|
|
412
|
+
let at = key.from, n = 0;
|
|
413
|
+
for (; n < parts.length - 1; n++) {
|
|
414
|
+
at = text.indexOf(parts[n], at) + parts[n].length;
|
|
415
|
+
if (offset <= at) break;
|
|
416
|
+
}
|
|
417
|
+
path = key.path.slice(0, prefixLen + n + 1);
|
|
418
|
+
} else if (typeof path[path.length - 1] === 'number') {
|
|
419
|
+
path = path.slice(0, -1);
|
|
420
|
+
}
|
|
421
|
+
const s = schemaAt(path, schema);
|
|
422
|
+
if (!s) return null;
|
|
423
|
+
const extras: string[] = [summary(s, schema)];
|
|
424
|
+
const def = branches(s, schema).find(b => b.default !== undefined)?.default;
|
|
425
|
+
if (def !== undefined) extras.push(`default ${JSON.stringify(def)}`);
|
|
426
|
+
return {
|
|
427
|
+
from: hit.from, to: hit.to,
|
|
428
|
+
title: table ? tableName(table.path) : keyName(path),
|
|
429
|
+
detail: extras.join(', '),
|
|
430
|
+
info: s.description,
|
|
431
|
+
};
|
|
432
|
+
}
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
// ── document outline: ODD structure for ODDs, divisions for TEI ───────────
|
|
2
|
+
// The ODD outline is ODDity's (src/oddOutline.ts there), with editor-neutral results.
|
|
3
|
+
import { parse } from '@xml-tools/parser';
|
|
4
|
+
import { buildAst, type XMLElement, type XMLDocument } from '@xml-tools/ast';
|
|
5
|
+
|
|
6
|
+
/** LSP symbol kinds used here (the protocol's numbers). */
|
|
7
|
+
export const Kind = {
|
|
8
|
+
Module: 2, Namespace: 3, Package: 4, Class: 5, Method: 6, Property: 7,
|
|
9
|
+
Interface: 11, Constant: 14, Array: 18, Object: 19, Struct: 23, TypeParameter: 26,
|
|
10
|
+
} as const;
|
|
11
|
+
|
|
12
|
+
export interface OutlineSymbol {
|
|
13
|
+
name: string;
|
|
14
|
+
detail: string;
|
|
15
|
+
kind: number;
|
|
16
|
+
from: number;
|
|
17
|
+
to: number;
|
|
18
|
+
nameFrom: number;
|
|
19
|
+
nameTo: number;
|
|
20
|
+
children: OutlineSymbol[];
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const localName = (name: string | null) => (name ?? '').replace(/^[^:]*:/, '');
|
|
24
|
+
|
|
25
|
+
const unescape = (v: string) => v.replace(/&(?:#(\d+)|#x([0-9a-fA-F]+)|(quot|lt|gt|apos|amp));/g, (_, d, h, n) =>
|
|
26
|
+
d ? String.fromCharCode(Number(d)) : h ? String.fromCharCode(parseInt(h, 16)) : ({ quot: '"', lt: '<', gt: '>', apos: "'", amp: '&' } as Record<string, string>)[n]);
|
|
27
|
+
|
|
28
|
+
function attr(el: XMLElement, key: string): string | undefined {
|
|
29
|
+
const raw = el.attributes.find(a => a.key === key && a.value !== null)?.value;
|
|
30
|
+
return raw != null ? unescape(raw) : undefined;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function children(root: XMLDocument | XMLElement, name: string): XMLElement[] {
|
|
34
|
+
const out: XMLElement[] = [];
|
|
35
|
+
const walk = (el: XMLElement) => { if (localName(el.name) === name) out.push(el); el.subElements.forEach(walk); };
|
|
36
|
+
('rootElement' in root ? (root.rootElement ? [root.rootElement] : []) : [root]).forEach(walk);
|
|
37
|
+
return out;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function symbol(el: XMLElement, name: string, detail: string, kind: number, kids: OutlineSymbol[] = []): OutlineSymbol {
|
|
41
|
+
const p = el.position, open = el.syntax?.openName;
|
|
42
|
+
const from = p && p.startOffset >= 0 ? p.startOffset : 0, to = p && p.startOffset >= 0 ? p.endOffset + 1 : 0;
|
|
43
|
+
const named = open && open.startOffset >= 0;
|
|
44
|
+
return { name, detail, kind, from, to, nameFrom: named ? open.startOffset : from, nameTo: named ? open.endOffset + 1 : to, children: kids };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function ast(text: string): XMLDocument {
|
|
48
|
+
const { cst, tokenVector } = parse(text);
|
|
49
|
+
return buildAst(cst as Parameters<typeof buildAst>[0], tokenVector);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** The outline of an ODD: tagsDecl, then each schemaSpec with its specs and processing models. */
|
|
53
|
+
export function oddOutline(text: string): OutlineSymbol[] {
|
|
54
|
+
const doc = ast(text);
|
|
55
|
+
return [
|
|
56
|
+
...children(doc, 'tagsDecl').map(tagsDecl),
|
|
57
|
+
...children(doc, 'schemaSpec').map(schemaSpec),
|
|
58
|
+
];
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function tagsDecl(el: XMLElement): OutlineSymbol {
|
|
62
|
+
const kids = el.subElements.flatMap(c => {
|
|
63
|
+
switch (localName(c.name)) {
|
|
64
|
+
case 'behaviour': {
|
|
65
|
+
const ident = attr(c, 'ident') ?? '(no ident)', output = attr(c, 'output');
|
|
66
|
+
return [symbol(c, output ? `${ident} · ${output}` : ident, '', Kind.Method)];
|
|
67
|
+
}
|
|
68
|
+
case 'rendition': return [symbol(c, attr(c, 'xml:id') ?? attr(c, 'source') ?? '(rendition)', '', Kind.Property)];
|
|
69
|
+
case 'namespace': return [symbol(c, attr(c, 'name') ?? '(namespace)', '', Kind.Namespace)];
|
|
70
|
+
default: return [];
|
|
71
|
+
}
|
|
72
|
+
});
|
|
73
|
+
return symbol(el, 'tagsDecl', '', Kind.Namespace, kids);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function schemaSpec(el: XMLElement): OutlineSymbol {
|
|
77
|
+
const source = attr(el, 'source');
|
|
78
|
+
const kids = el.subElements.flatMap(c => {
|
|
79
|
+
const ident = attr(c, 'ident') ?? '(no ident)', mode = attr(c, 'mode') ?? '';
|
|
80
|
+
switch (localName(c.name)) {
|
|
81
|
+
case 'moduleRef': {
|
|
82
|
+
const include = attr(c, 'include'), except = attr(c, 'except');
|
|
83
|
+
const detail = [include && `include: ${include}`, except && `except: ${except}`].filter(Boolean).join(' · ');
|
|
84
|
+
return [symbol(c, attr(c, 'key') ?? '(no key)', detail, Kind.Module)];
|
|
85
|
+
}
|
|
86
|
+
case 'dataSpec': return [symbol(c, ident, mode, Kind.TypeParameter)];
|
|
87
|
+
case 'macroSpec': return [symbol(c, ident, mode, Kind.Constant)];
|
|
88
|
+
case 'classSpec': return [symbol(c, ident, [attr(c, 'type'), attr(c, 'mode')].filter(Boolean).join(' · '), Kind.Interface)];
|
|
89
|
+
case 'elementSpec': return [symbol(c, ident, mode, Kind.Class, rules(c))];
|
|
90
|
+
default: return [];
|
|
91
|
+
}
|
|
92
|
+
});
|
|
93
|
+
return symbol(el, attr(el, 'ident') ?? '(no ident)', source ? `source: ${source}` : '', Kind.Package, kids);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Direct model, modelGrp and modelSequence children, nested as in the ODD. */
|
|
97
|
+
function rules(parent: XMLElement): OutlineSymbol[] {
|
|
98
|
+
return parent.subElements.flatMap(c => {
|
|
99
|
+
const type = localName(c.name);
|
|
100
|
+
if (type !== 'model' && type !== 'modelGrp' && type !== 'modelSequence') return [];
|
|
101
|
+
const label = [attr(c, 'output'), attr(c, 'predicate'), type === 'model' ? (attr(c, 'behaviour') ?? '(no behaviour)') : type]
|
|
102
|
+
.filter(Boolean).join(' · ');
|
|
103
|
+
const kind = type === 'modelGrp' ? Kind.Namespace : type === 'modelSequence' ? Kind.Array : Kind.Method;
|
|
104
|
+
return [symbol(c, label, '', kind, type === 'model' ? [] : rules(c))];
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** TEI elements that make up a document's structure. */
|
|
109
|
+
const STRUCTURE = new Set(['teiCorpus', 'TEI', 'teiHeader', 'text', 'front', 'body', 'back', 'group', 'div',
|
|
110
|
+
'div1', 'div2', 'div3', 'div4', 'div5', 'div6', 'div7', 'floatingText']);
|
|
111
|
+
|
|
112
|
+
/** Text of an element, whitespace collapsed. */
|
|
113
|
+
function textOf(el: XMLElement): string {
|
|
114
|
+
const parts: { at: number; text: string }[] = [];
|
|
115
|
+
const walk = (e: XMLElement) => {
|
|
116
|
+
for (const t of e.textContents) parts.push({ at: t.position.startOffset, text: t.text ?? '' });
|
|
117
|
+
e.subElements.forEach(walk);
|
|
118
|
+
};
|
|
119
|
+
walk(el);
|
|
120
|
+
return parts.sort((a, b) => a.at - b.at).map(p => p.text).join('').replace(/\s+/g, ' ').trim();
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const MAX_LABEL = 60;
|
|
124
|
+
|
|
125
|
+
/** The outline of a TEI document: its texts and divisions, labelled by their heads. */
|
|
126
|
+
export function teiOutline(text: string): OutlineSymbol[] {
|
|
127
|
+
const root = ast(text).rootElement;
|
|
128
|
+
if (!root) return [];
|
|
129
|
+
const walk = (el: XMLElement): OutlineSymbol[] => {
|
|
130
|
+
const name = localName(el.name);
|
|
131
|
+
const kids = el.subElements.flatMap(walk);
|
|
132
|
+
if (!STRUCTURE.has(name)) return kids;
|
|
133
|
+
if (name === 'teiHeader') return [symbol(el, 'teiHeader', '', Kind.Object)];
|
|
134
|
+
const head = el.subElements.find(c => localName(c.name) === 'head');
|
|
135
|
+
let label = head ? textOf(head) : '';
|
|
136
|
+
if (label.length > MAX_LABEL) label = label.slice(0, MAX_LABEL).replace(/\s\S*$/, '') + '…';
|
|
137
|
+
const type = attr(el, 'type'), n = attr(el, 'n'), id = attr(el, 'xml:id');
|
|
138
|
+
const title = label || [type, n].filter(Boolean).join(' ') || name;
|
|
139
|
+
const detail = [label ? name : '', id ? `#${id}` : ''].filter(Boolean).join(' ');
|
|
140
|
+
return [symbol(el, title, detail, name.startsWith('div') ? Kind.Struct : Kind.Namespace, kids)];
|
|
141
|
+
};
|
|
142
|
+
return walk(root);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** A plain element tree, for XML that is neither ODD nor TEI. */
|
|
146
|
+
export function elementOutline(text: string, max = 2000): OutlineSymbol[] {
|
|
147
|
+
const root = ast(text).rootElement;
|
|
148
|
+
let count = 0;
|
|
149
|
+
const walk = (el: XMLElement): OutlineSymbol => {
|
|
150
|
+
count++;
|
|
151
|
+
const kids = count < max ? el.subElements.slice(0, max - count).map(walk) : [];
|
|
152
|
+
const id = attr(el, 'xml:id') ?? attr(el, 'id');
|
|
153
|
+
return symbol(el, el.name ?? '?', id ? `#${id}` : '', Kind.Object, kids);
|
|
154
|
+
};
|
|
155
|
+
return root ? [walk(root)] : [];
|
|
156
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// ── compiled RELAX NG grammars, kept once and shared by every document ─────
|
|
2
|
+
// Compiling a large RNG takes the better part of a second, so a grammar is
|
|
3
|
+
// compiled the first time it is asked for and kept until one of the files it
|
|
4
|
+
// was read from changes (invalidate).
|
|
5
|
+
import { convertRNGToPattern, type Grammar, type Resource } from 'salve-annos';
|
|
6
|
+
|
|
7
|
+
/** Reads the text of an RNG (or a file it includes) by URL. */
|
|
8
|
+
export type ReadText = (url: URL) => Promise<string>;
|
|
9
|
+
|
|
10
|
+
interface Entry { grammar: Promise<Grammar>; files: Set<string> }
|
|
11
|
+
|
|
12
|
+
export class Grammars {
|
|
13
|
+
private entries = new Map<string, Entry>();
|
|
14
|
+
private readText: ReadText;
|
|
15
|
+
|
|
16
|
+
constructor(readText: ReadText) {
|
|
17
|
+
this.readText = readText;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** The grammar of the RNG at url, compiled once. */
|
|
21
|
+
get(url: string): Promise<Grammar> {
|
|
22
|
+
const known = this.entries.get(url);
|
|
23
|
+
if (known) return known.grammar;
|
|
24
|
+
const files = new Set<string>();
|
|
25
|
+
const resourceLoader = {
|
|
26
|
+
load: async (u: URL): Promise<Resource> => {
|
|
27
|
+
files.add(u.href);
|
|
28
|
+
const text = await this.readText(u);
|
|
29
|
+
return { url: u, getText: async () => text };
|
|
30
|
+
},
|
|
31
|
+
};
|
|
32
|
+
// the options type wants every field; salve fills in the others
|
|
33
|
+
const grammar = convertRNGToPattern(new URL(url), { resourceLoader } as Parameters<typeof convertRNGToPattern>[1])
|
|
34
|
+
.then(r => r.pattern);
|
|
35
|
+
const entry = { grammar, files };
|
|
36
|
+
this.entries.set(url, entry);
|
|
37
|
+
// a schema that failed to compile is tried again next time
|
|
38
|
+
grammar.catch(() => { if (this.entries.get(url) === entry) this.entries.delete(url); });
|
|
39
|
+
return grammar;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Forget every grammar read from url, or all of them. Returns whether any was dropped. */
|
|
43
|
+
invalidate(url?: string): boolean {
|
|
44
|
+
if (url === undefined) {
|
|
45
|
+
const any = this.entries.size > 0;
|
|
46
|
+
this.entries.clear();
|
|
47
|
+
return any;
|
|
48
|
+
}
|
|
49
|
+
let dropped = false;
|
|
50
|
+
for (const [key, e] of this.entries) {
|
|
51
|
+
if (key === url || e.files.has(url)) { this.entries.delete(key); dropped = true; }
|
|
52
|
+
}
|
|
53
|
+
return dropped;
|
|
54
|
+
}
|
|
55
|
+
}
|