@teipublisher/oddity-language-server 0.0.0-stage → 0.1.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 +48 -2
- package/dist/edit.js +313 -0
- package/dist/edit.js.map +7 -0
- package/dist/index.js +803 -0
- package/dist/index.js.map +7 -0
- package/dist/node.cjs +44962 -0
- package/dist/node.cjs.map +7 -0
- package/package.json +74 -4
- package/schema/README.md +41 -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/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/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/validate.ts +128 -0
- package/src/core/wellformed.ts +16 -0
- package/src/edit.ts +11 -0
- package/src/index.ts +16 -0
- package/src/node.ts +39 -0
- package/src/server/server.ts +248 -0
package/src/core/tags.ts
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
// ── start and end tags: matching pairs and closing tags ──────────────────
|
|
2
|
+
// A light scanner rather than a parser: it has to work on half-typed documents.
|
|
3
|
+
|
|
4
|
+
export interface Tag {
|
|
5
|
+
kind: 'open' | 'close' | 'empty';
|
|
6
|
+
name: string;
|
|
7
|
+
/** Offset of the '<'. */
|
|
8
|
+
from: number;
|
|
9
|
+
nameFrom: number;
|
|
10
|
+
nameTo: number;
|
|
11
|
+
/** Offset just after the '>', or the end of the text for an unfinished tag. */
|
|
12
|
+
to: number;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const SKIP: [string, string][] = [['<!--', '-->'], ['<![CDATA[', ']]>'], ['<?', '?>'], ['<!', '>']];
|
|
16
|
+
|
|
17
|
+
/** Every tag in text, skipping comments, CDATA, processing instructions and declarations. */
|
|
18
|
+
export function scanTags(text: string): Tag[] {
|
|
19
|
+
const tags: Tag[] = [];
|
|
20
|
+
let i = 0;
|
|
21
|
+
while ((i = text.indexOf('<', i)) >= 0) {
|
|
22
|
+
const skip = SKIP.find(([open]) => text.startsWith(open, i));
|
|
23
|
+
if (skip) {
|
|
24
|
+
const end = text.indexOf(skip[1], i + skip[0].length);
|
|
25
|
+
if (end < 0) break;
|
|
26
|
+
i = end + skip[1].length;
|
|
27
|
+
continue;
|
|
28
|
+
}
|
|
29
|
+
const closing = text[i + 1] === '/';
|
|
30
|
+
const nameFrom = i + (closing ? 2 : 1);
|
|
31
|
+
const name = text.slice(nameFrom).match(/^[^\s<>/="']*/)![0];
|
|
32
|
+
// the end of the tag: the first '>' outside a quoted value
|
|
33
|
+
let j = nameFrom + name.length, quote = '';
|
|
34
|
+
for (; j < text.length; j++) {
|
|
35
|
+
const c = text[j];
|
|
36
|
+
if (quote) { if (c === quote) quote = ''; } else if (c === '"' || c === "'") quote = c; else if (c === '>' || c === '<') break;
|
|
37
|
+
}
|
|
38
|
+
const finished = text[j] === '>';
|
|
39
|
+
const to = finished ? j + 1 : j;
|
|
40
|
+
const kind = closing ? 'close' : finished && text[j - 1] === '/' ? 'empty' : 'open';
|
|
41
|
+
tags.push({ kind, name, from: i, nameFrom, nameTo: nameFrom + name.length, to });
|
|
42
|
+
i = finished ? to : Math.max(j, i + 1);
|
|
43
|
+
}
|
|
44
|
+
return tags;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Pairs of open and close tags, by index into tags, matched like a parser would. */
|
|
48
|
+
export function pairs(tags: Tag[]): Map<number, number> {
|
|
49
|
+
const stack: number[] = [];
|
|
50
|
+
const pair = new Map<number, number>();
|
|
51
|
+
tags.forEach((t, i) => {
|
|
52
|
+
if (t.kind === 'open') stack.push(i);
|
|
53
|
+
else if (t.kind === 'close') {
|
|
54
|
+
// close the nearest open tag of the same name; anything above it was left open
|
|
55
|
+
const k = stack.map(s => tags[s].name).lastIndexOf(t.name);
|
|
56
|
+
if (k < 0) return;
|
|
57
|
+
pair.set(stack[k], i);
|
|
58
|
+
pair.set(i, stack[k]);
|
|
59
|
+
stack.length = k;
|
|
60
|
+
}
|
|
61
|
+
});
|
|
62
|
+
return pair;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** The name ranges of the tag whose name holds offset and its partner, for renaming both at once. */
|
|
66
|
+
export function matchingTags(text: string, offset: number): { from: number; to: number }[] | null {
|
|
67
|
+
const tags = scanTags(text);
|
|
68
|
+
const at = tags.findIndex(t => t.kind !== 'empty' && t.nameFrom <= offset && offset <= t.nameTo);
|
|
69
|
+
if (at < 0) return null;
|
|
70
|
+
const other = pairs(tags).get(at);
|
|
71
|
+
if (other === undefined) return null;
|
|
72
|
+
return [at, other].sort((a, b) => a - b).map(i => ({ from: tags[i].nameFrom, to: tags[i].nameTo }));
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** The innermost element still open at offset. */
|
|
76
|
+
export function openElementAt(text: string, offset: number): string | undefined {
|
|
77
|
+
const tags = scanTags(text.slice(0, offset));
|
|
78
|
+
const pair = pairs(tags);
|
|
79
|
+
for (let i = tags.length - 1; i >= 0; i--) {
|
|
80
|
+
if (tags[i].kind === 'open' && !pair.has(i) && tags[i].to <= offset && text[tags[i].to - 1] === '>') return tags[i].name;
|
|
81
|
+
}
|
|
82
|
+
return undefined;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* What to insert at offset, just after the user typed a character, to close a tag:
|
|
87
|
+
* after the '>' of a start tag its end tag, after '</' the name of the open element.
|
|
88
|
+
*/
|
|
89
|
+
export function closeTagAt(text: string, offset: number): string | undefined {
|
|
90
|
+
const before = text.slice(0, offset);
|
|
91
|
+
if (before.endsWith('</')) {
|
|
92
|
+
const name = openElementAt(text, offset - 2);
|
|
93
|
+
if (!name) return undefined;
|
|
94
|
+
return text.slice(offset).startsWith('>') ? name : `${name}>`;
|
|
95
|
+
}
|
|
96
|
+
if (!before.endsWith('>') || before.endsWith('/>')) return undefined;
|
|
97
|
+
const tags = scanTags(before);
|
|
98
|
+
const last = tags[tags.length - 1];
|
|
99
|
+
if (!last || last.kind !== 'open' || last.to !== offset || !last.name) return undefined;
|
|
100
|
+
const end = `</${last.name}>`;
|
|
101
|
+
// already closed right after the cursor, e.g. when a '>' is retyped
|
|
102
|
+
if (text.slice(offset).startsWith(end)) return undefined;
|
|
103
|
+
return end;
|
|
104
|
+
}
|
package/src/core/toml.ts
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
// ── opm.toml: write the keys the page controls, read the few it needs ─────
|
|
2
|
+
// Reading parses the whole file with smol-toml (TOML 1.0). Writing does not
|
|
3
|
+
// serialize: the edits leave every other line of the file, comments included, as it is.
|
|
4
|
+
import { parse } from 'smol-toml';
|
|
5
|
+
|
|
6
|
+
export type TomlValue = string | string[];
|
|
7
|
+
export type TomlConfig = Record<string, Record<string, TomlValue>>;
|
|
8
|
+
|
|
9
|
+
const q = (s: string) => JSON.stringify(s);
|
|
10
|
+
const sectionEnd = (lines: string[], head: number) => {
|
|
11
|
+
for (let i = head + 1; i < lines.length; i++) if (/^\s*\[/.test(lines[i])) return i;
|
|
12
|
+
return lines.length;
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
/** Set section.key = value in place, keeping everything else in the file as it is. */
|
|
16
|
+
export function setToml(text: string, section: string, key: string, value: string): string {
|
|
17
|
+
const line = `${key} = ${q(value)}`, lines = text ? text.split('\n') : [];
|
|
18
|
+
const head = lines.findIndex(l => l.trim() === `[${section}]`);
|
|
19
|
+
if (head < 0) return (text && !text.endsWith('\n') ? text + '\n' : text) + (text ? '\n' : '') + `[${section}]\n${line}\n`;
|
|
20
|
+
const end = sectionEnd(lines, head), re = new RegExp(`^\\s*${key}\\s*=`);
|
|
21
|
+
for (let i = head + 1; i < end; i++) if (re.test(lines[i])) { lines[i] = line; return lines.join('\n'); }
|
|
22
|
+
lines.splice(head + 1, 0, line);
|
|
23
|
+
return lines.join('\n');
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Drop section.key, leaving the rest of the file as it is. */
|
|
27
|
+
export function unsetToml(text: string, section: string, key: string): string {
|
|
28
|
+
const lines = text.split('\n'), head = lines.findIndex(l => l.trim() === `[${section}]`);
|
|
29
|
+
if (head < 0) return text;
|
|
30
|
+
const end = sectionEnd(lines, head), re = new RegExp(`^\\s*${key}\\s*=`);
|
|
31
|
+
for (let i = head + 1; i < end; i++) if (re.test(lines[i])) { lines.splice(i, 1); break; }
|
|
32
|
+
return lines.join('\n');
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* The string and string-array values of a TOML file, by table: `[transform.web] template = …`,
|
|
37
|
+
* `[transform] web.template = …` and `transform.web.template = …` all end up under
|
|
38
|
+
* cfg['transform.web'].template. Other values and arrays of tables are left out.
|
|
39
|
+
* A file that is not valid TOML gives no values, as opm would not run with it either.
|
|
40
|
+
*/
|
|
41
|
+
export function readToml(text: string): TomlConfig {
|
|
42
|
+
let doc: Record<string, unknown>;
|
|
43
|
+
try { doc = parse(text); } catch { return {}; }
|
|
44
|
+
const cfg: TomlConfig = {};
|
|
45
|
+
const walk = (table: Record<string, unknown>, path: string[]) => {
|
|
46
|
+
for (const [key, v] of Object.entries(table)) {
|
|
47
|
+
if (typeof v === 'string' || (Array.isArray(v) && v.length && v.every(x => typeof x === 'string'))) {
|
|
48
|
+
(cfg[path.join('.')] ||= {})[key] = v as TomlValue;
|
|
49
|
+
} else if (Array.isArray(v) && !v.length) {
|
|
50
|
+
(cfg[path.join('.')] ||= {})[key] = [];
|
|
51
|
+
} else if (v && typeof v === 'object' && !Array.isArray(v) && !(v instanceof Date)) {
|
|
52
|
+
walk(v as Record<string, unknown>, [...path, key]);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
walk(doc, []);
|
|
57
|
+
return cfg;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** A string value from the config, or '' when it is missing or not a string. */
|
|
61
|
+
export const tomlString = (cfg: TomlConfig, section: string, key: string): string => {
|
|
62
|
+
const v = cfg[section]?.[key];
|
|
63
|
+
return typeof v === 'string' ? v : '';
|
|
64
|
+
};
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
// ── RELAX NG validation of one XML text with salve, errors as text ranges ──
|
|
2
|
+
// Pure, so tests run it without a worker; runtime/validator.ts is the worker around it.
|
|
3
|
+
import {
|
|
4
|
+
AnyName, AttributeNameError, AttributeValueError, ChoiceError, DefaultNameResolver, Name, NameChoice, NsName,
|
|
5
|
+
type BaseName, type Grammar, type ValidationError,
|
|
6
|
+
} from 'salve-annos';
|
|
7
|
+
import { SaxesParser, type SaxesTagNS } from 'saxes';
|
|
8
|
+
|
|
9
|
+
export interface Problem { from: number; to: number; message: string }
|
|
10
|
+
|
|
11
|
+
/** More would only slow the editor down; the first ones are what needs fixing. */
|
|
12
|
+
const MAX = 200;
|
|
13
|
+
|
|
14
|
+
/** A name as the document would write it: prefixed where it declares one for the namespace. */
|
|
15
|
+
function nameText(n: BaseName, resolver: DefaultNameResolver, attribute: boolean): string {
|
|
16
|
+
if (n instanceof Name) {
|
|
17
|
+
if (!n.ns || (attribute && n.ns === '')) return n.name;
|
|
18
|
+
const q = resolver.unresolveName(n.ns, n.name);
|
|
19
|
+
return q ?? `${n.name} (${n.ns})`;
|
|
20
|
+
}
|
|
21
|
+
if (n instanceof NameChoice) return `${nameText(n.a, resolver, attribute)} or ${nameText(n.b, resolver, attribute)}`;
|
|
22
|
+
if (n instanceof NsName) return `any name in ${n.ns}`;
|
|
23
|
+
if (n instanceof AnyName) return 'any name';
|
|
24
|
+
return String(n);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** salve's messages, worded as the editor shows them; `value` is the attribute value just checked. */
|
|
28
|
+
function messageOf(e: ValidationError, resolver: DefaultNameResolver, value?: string): string {
|
|
29
|
+
const attribute = e instanceof AttributeNameError || e instanceof AttributeValueError;
|
|
30
|
+
const names = e.getNames().map(n => nameText(n, resolver, attribute));
|
|
31
|
+
const one = names.join(', ');
|
|
32
|
+
switch (e.msg) {
|
|
33
|
+
case 'tag not allowed here': return `<${one}> is not allowed here`;
|
|
34
|
+
case 'tag required': return `<${one}> is required here`;
|
|
35
|
+
case 'unexpected end tag': return `</${one}> was not expected here`;
|
|
36
|
+
case 'attribute not allowed here': return `@${one} is not allowed here`;
|
|
37
|
+
case 'attribute missing': return `Required attribute @${one} is missing`;
|
|
38
|
+
case 'invalid attribute value': return value === undefined ? `Invalid value for @${one}` : `"${value}" is not a valid value for @${one}`;
|
|
39
|
+
case 'text not allowed here': return 'Text is not allowed here';
|
|
40
|
+
}
|
|
41
|
+
if (e instanceof ChoiceError) return `Expected one of: ${names.map(n => `<${n}>`).join(', ')}`;
|
|
42
|
+
const text = e.toStringWithNames(names);
|
|
43
|
+
return text.charAt(0).toUpperCase() + text.slice(1);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Validate xml against grammar: well-formedness first, then the schema, stopping at the first syntax error. */
|
|
47
|
+
export function validate(grammar: Grammar, xml: string): Problem[] {
|
|
48
|
+
const resolver = new DefaultNameResolver();
|
|
49
|
+
const walker = grammar.newWalker(resolver);
|
|
50
|
+
const parser = new SaxesParser({ xmlns: true, position: true });
|
|
51
|
+
const problems: Problem[] = [];
|
|
52
|
+
let broken = false;
|
|
53
|
+
|
|
54
|
+
// where the parser last was: tags are located from there, backwards to their '<'
|
|
55
|
+
let tagFrom = 0, tagTo = 0, textFrom = 0;
|
|
56
|
+
let text = '';
|
|
57
|
+
const report = (r: ReturnType<typeof walker.fireEvent>, from: number, to: number, value?: string) => {
|
|
58
|
+
if (!r) return;
|
|
59
|
+
for (const e of r) if (problems.length < MAX) problems.push({ from, to, message: messageOf(e, resolver, value) });
|
|
60
|
+
};
|
|
61
|
+
const flush = () => {
|
|
62
|
+
if (text === '') return;
|
|
63
|
+
// whitespace between elements is never an error worth showing
|
|
64
|
+
if (text.trim() !== '') report(walker.fireEvent('text', [text]), textFrom, tagFrom);
|
|
65
|
+
text = '';
|
|
66
|
+
};
|
|
67
|
+
/** The span of a tag's name, given where its '<' is. */
|
|
68
|
+
const nameSpan = (from: number, name: string, closing: boolean) => {
|
|
69
|
+
const start = from + (closing ? 2 : 1);
|
|
70
|
+
return [start, start + name.length] as const;
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
parser.on('opentag', (node: SaxesTagNS) => {
|
|
74
|
+
if (broken) return;
|
|
75
|
+
tagTo = parser.position;
|
|
76
|
+
tagFrom = xml.lastIndexOf('<', tagTo - 1);
|
|
77
|
+
flush();
|
|
78
|
+
resolver.enterContext();
|
|
79
|
+
for (const [qn, a] of Object.entries(node.attributes)) {
|
|
80
|
+
if (qn === 'xmlns') resolver.definePrefix('', a.value);
|
|
81
|
+
else if (a.prefix === 'xmlns') resolver.definePrefix(a.local, a.value);
|
|
82
|
+
}
|
|
83
|
+
const [nf, nt] = nameSpan(tagFrom, node.name, false);
|
|
84
|
+
report(walker.fireEvent('enterStartTag', [node.uri, node.local]), nf, nt);
|
|
85
|
+
const tag = xml.slice(tagFrom, tagTo);
|
|
86
|
+
for (const [qn, a] of Object.entries(node.attributes)) {
|
|
87
|
+
if (qn === 'xmlns' || a.prefix === 'xmlns') continue;
|
|
88
|
+
const at = tag.search(new RegExp(`\\s${qn.replace(/[.*+?^${}()|[\]\\-]/g, '\\$&')}\\s*=`));
|
|
89
|
+
const af = at < 0 ? nf : tagFrom + at + 1, aend = at < 0 ? nt : af + qn.length;
|
|
90
|
+
report(walker.fireEvent('attributeName', [a.uri, a.local]), af, aend);
|
|
91
|
+
report(walker.fireEvent('attributeValue', [a.value]), af, aend, a.value);
|
|
92
|
+
}
|
|
93
|
+
report(walker.fireEvent('leaveStartTag', []), nf, nt);
|
|
94
|
+
if (node.isSelfClosing) return;
|
|
95
|
+
textFrom = tagTo;
|
|
96
|
+
});
|
|
97
|
+
parser.on('closetag', (node: SaxesTagNS) => {
|
|
98
|
+
if (broken) return;
|
|
99
|
+
if (node.isSelfClosing) {
|
|
100
|
+
// the start tag was the whole element
|
|
101
|
+
report(walker.fireEvent('endTag', [node.uri, node.local]), ...nameSpan(tagFrom, node.name, false));
|
|
102
|
+
} else {
|
|
103
|
+
tagTo = parser.position;
|
|
104
|
+
tagFrom = xml.lastIndexOf('</', tagTo - 1);
|
|
105
|
+
flush();
|
|
106
|
+
report(walker.fireEvent('endTag', [node.uri, node.local]), ...nameSpan(tagFrom, node.name, true));
|
|
107
|
+
}
|
|
108
|
+
resolver.leaveContext();
|
|
109
|
+
textFrom = tagTo;
|
|
110
|
+
});
|
|
111
|
+
parser.on('text', s => { text += s; });
|
|
112
|
+
parser.on('cdata', s => { text += s; });
|
|
113
|
+
parser.on('error', e => {
|
|
114
|
+
if (broken) return;
|
|
115
|
+
broken = true;
|
|
116
|
+
const at = Math.min(parser.position, xml.length);
|
|
117
|
+
problems.push({ from: Math.max(0, at - 1), to: at, message: e.message.replace(/^(?:[^:\n]*:)?\d+:\d+: /, '') });
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
// saxes keeps going after an error, but the walker would only report the fallout:
|
|
121
|
+
// the handlers above stop, and what came before the error stays reported
|
|
122
|
+
try { parser.write(xml).close(); } catch { /* reported through 'error' */ }
|
|
123
|
+
if (broken) return problems;
|
|
124
|
+
|
|
125
|
+
const end = walker.end();
|
|
126
|
+
report(end, tagFrom, tagTo);
|
|
127
|
+
return problems;
|
|
128
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// ── well-formedness alone, for documents without a schema ─────────────────
|
|
2
|
+
import { SaxesParser } from 'saxes';
|
|
3
|
+
import type { Problem } from './validate.ts';
|
|
4
|
+
|
|
5
|
+
/** The first syntax error in xml, if any, as validate() reports it. */
|
|
6
|
+
export function wellFormed(xml: string): Problem[] {
|
|
7
|
+
const parser = new SaxesParser({ xmlns: true, position: true });
|
|
8
|
+
const problems: Problem[] = [];
|
|
9
|
+
parser.on('error', e => {
|
|
10
|
+
if (problems.length) return;
|
|
11
|
+
const at = Math.min(parser.position, xml.length);
|
|
12
|
+
problems.push({ from: Math.max(0, at - 1), to: at, message: e.message.replace(/^(?:[^:\n]*:)?\d+:\d+: /, '') });
|
|
13
|
+
});
|
|
14
|
+
try { parser.write(xml).close(); } catch { /* reported through 'error' */ }
|
|
15
|
+
return problems;
|
|
16
|
+
}
|
package/src/edit.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// Light helpers for editors, without salve: tag matching and closing, schema association, xml-model and opm.toml edits.
|
|
2
|
+
export { scanTags, pairs, matchingTags, openElementAt, closeTagAt, type Tag } from './core/tags.ts';
|
|
3
|
+
export {
|
|
4
|
+
schemaFor, projectRoot, isOdd, xmlModels, isRngModel, xmlModelEdits, relativeHref, RNG_NS, DEFAULT_SCHEMA_FILES, PUBLIC_SCHEMA_URLS, publicSchema, vocabulary,
|
|
5
|
+
type Files, type Defaults, type SchemaChoice, type TextEdit,
|
|
6
|
+
} from './core/association.ts';
|
|
7
|
+
export { readToml, setToml, unsetToml, tomlString, type TomlConfig, type TomlValue } from './core/toml.ts';
|
|
8
|
+
export {
|
|
9
|
+
elements, elementsAround, elementAround, selectElement, removeElementTags, splitElement, surroundWithElement,
|
|
10
|
+
type Element, type ElementEdit, type Selection,
|
|
11
|
+
} from './core/elements.ts';
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// Editor-independent core: what opm studio and ODDity share.
|
|
2
|
+
export { validate, type Problem } from './core/validate.ts';
|
|
3
|
+
export { possibleAt, described, type Possible, type Suggestion } from './core/complete.ts';
|
|
4
|
+
export { wellFormed } from './core/wellformed.ts';
|
|
5
|
+
export { Grammars, type ReadText } from './core/schema.ts';
|
|
6
|
+
export {
|
|
7
|
+
schemaFor, projectRoot, vocabulary, isOdd, xmlModels, isRngModel, xmlModelEdits, relativeHref, RNG_NS, DEFAULT_SCHEMA_FILES, PUBLIC_SCHEMA_URLS, publicSchema,
|
|
8
|
+
type Files, type Defaults, type SchemaChoice, type TextEdit,
|
|
9
|
+
} from './core/association.ts';
|
|
10
|
+
export { scanTags, pairs, matchingTags, openElementAt, closeTagAt, type Tag } from './core/tags.ts';
|
|
11
|
+
export { oddOutline, teiOutline, elementOutline, Kind, type OutlineSymbol } from './core/outline.ts';
|
|
12
|
+
export { readToml, setToml, unsetToml, tomlString, type TomlConfig, type TomlValue } from './core/toml.ts';
|
|
13
|
+
export {
|
|
14
|
+
elements, elementsAround, elementAround, selectElement, removeElementTags, splitElement, surroundWithElement,
|
|
15
|
+
type Element, type ElementEdit, type Selection,
|
|
16
|
+
} from './core/elements.ts';
|
package/src/node.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Node entry: run with --node-ipc (VS Code) or --stdio.
|
|
3
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
4
|
+
import { readFile } from 'node:fs/promises';
|
|
5
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
6
|
+
import { createConnection, ProposedFeatures } from 'vscode-languageserver/node';
|
|
7
|
+
import { startServer, type Host } from './server/server.ts';
|
|
8
|
+
import { DEFAULT_SCHEMA_FILES } from './core/association.ts';
|
|
9
|
+
|
|
10
|
+
const local = (url: string | URL) => {
|
|
11
|
+
const u = typeof url === 'string' ? new URL(url) : url;
|
|
12
|
+
return u.protocol === 'file:' ? fileURLToPath(u) : undefined;
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
const host: Host = {
|
|
16
|
+
files: {
|
|
17
|
+
exists: url => { const p = local(url); return !!p && existsSync(p); },
|
|
18
|
+
read: url => {
|
|
19
|
+
const p = local(url);
|
|
20
|
+
try { return p ? readFileSync(p, 'utf8') : undefined; } catch { return undefined; }
|
|
21
|
+
},
|
|
22
|
+
},
|
|
23
|
+
async readText(url) {
|
|
24
|
+
const p = local(url);
|
|
25
|
+
if (p) return readFile(p, 'utf8');
|
|
26
|
+
const r = await fetch(url);
|
|
27
|
+
if (!r.ok) throw new Error(`${url} could not be loaded: ${r.status}`);
|
|
28
|
+
return r.text();
|
|
29
|
+
},
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
// The schemas shipped with the package, beside dist/ (or the bundle that includes this file).
|
|
33
|
+
const schemaDir = process.env.ODDITY_LS_SCHEMAS;
|
|
34
|
+
if (schemaDir) {
|
|
35
|
+
const base = pathToFileURL(schemaDir.endsWith('/') ? schemaDir : `${schemaDir}/`);
|
|
36
|
+
host.defaults = Object.fromEntries(Object.entries(DEFAULT_SCHEMA_FILES).map(([k, f]) => [k, new URL(f, base).href]));
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
startServer(createConnection(ProposedFeatures.all), host);
|
|
@@ -0,0 +1,248 @@
|
|
|
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,
|
|
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
|
+
|
|
19
|
+
export const SOURCE = 'oddity-ls';
|
|
20
|
+
|
|
21
|
+
/** What the host gives the server: file access. */
|
|
22
|
+
export interface Host {
|
|
23
|
+
files: Files;
|
|
24
|
+
readText: ReadText;
|
|
25
|
+
/** Default schemas used when the client does not name its own. */
|
|
26
|
+
defaults?: Defaults;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface InitOptions {
|
|
30
|
+
/** Default schema URL by vocabulary, e.g. { odd: 'file:///…/teipublisher_odds.rng', tei: 'file:///…/tei_all.rng' }. */
|
|
31
|
+
defaultSchemas?: Defaults;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Custom request: the schema a document uses, or null. */
|
|
35
|
+
export const SCHEMA_FOR = 'oddity/schemaFor';
|
|
36
|
+
/** Custom notification to the client whenever a document's schema is known or changes. */
|
|
37
|
+
export const SCHEMA_CHANGED = 'oddity/schemaChanged';
|
|
38
|
+
/** Custom request: the elements the schema allows at an offset, [{ name, detail }], or null without a schema. */
|
|
39
|
+
export const ALLOWED_ELEMENTS = 'oddity/allowedElements';
|
|
40
|
+
|
|
41
|
+
const DELAY = 250;
|
|
42
|
+
|
|
43
|
+
export function startServer(connection: Connection, host: Host): void {
|
|
44
|
+
const documents = new TextDocuments(TextDocument);
|
|
45
|
+
const grammars = new Grammars(host.readText);
|
|
46
|
+
let defaults: Defaults = { ...host.defaults };
|
|
47
|
+
let stops: string[] = [];
|
|
48
|
+
const timers = new Map<string, ReturnType<typeof setTimeout>>();
|
|
49
|
+
const announced = new Map<string, string>();
|
|
50
|
+
|
|
51
|
+
const choiceOf = (doc: TextDocument): SchemaChoice | null => schemaFor(doc.uri, doc.getText(), host.files, defaults, stops);
|
|
52
|
+
|
|
53
|
+
connection.onInitialize((params): InitializeResult => {
|
|
54
|
+
const options = (params.initializationOptions ?? {}) as InitOptions;
|
|
55
|
+
defaults = { ...defaults, ...options.defaultSchemas };
|
|
56
|
+
stops = (params.workspaceFolders ?? []).map(f => f.uri);
|
|
57
|
+
return {
|
|
58
|
+
capabilities: {
|
|
59
|
+
textDocumentSync: TextDocumentSyncKind.Incremental,
|
|
60
|
+
completionProvider: { triggerCharacters: ['<', ' ', '"', "'"] },
|
|
61
|
+
linkedEditingRangeProvider: true,
|
|
62
|
+
documentSymbolProvider: true,
|
|
63
|
+
selectionRangeProvider: true,
|
|
64
|
+
},
|
|
65
|
+
serverInfo: { name: 'oddity-language-server' },
|
|
66
|
+
};
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
async function grammarOf(choice: SchemaChoice | null): Promise<{ grammar?: Grammar; error?: string }> {
|
|
70
|
+
if (!choice) return {};
|
|
71
|
+
try {
|
|
72
|
+
return { grammar: await grammars.get(choice.url) };
|
|
73
|
+
} catch (err) {
|
|
74
|
+
return { error: err instanceof Error ? err.message : String(err) };
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const toDiagnostic = (doc: TextDocument, p: Problem, code: string): Diagnostic => ({
|
|
79
|
+
range: { start: doc.positionAt(p.from), end: doc.positionAt(p.to) },
|
|
80
|
+
message: p.message,
|
|
81
|
+
severity: DiagnosticSeverity.Error,
|
|
82
|
+
source: SOURCE,
|
|
83
|
+
code,
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
async function check(uri: string): Promise<void> {
|
|
87
|
+
const doc = documents.get(uri);
|
|
88
|
+
if (!doc) return;
|
|
89
|
+
const version = doc.version, text = doc.getText();
|
|
90
|
+
const choice = choiceOf(doc);
|
|
91
|
+
const key = choice ? `${choice.via} ${choice.url}` : '';
|
|
92
|
+
if (announced.get(uri) !== key) {
|
|
93
|
+
announced.set(uri, key);
|
|
94
|
+
void connection.sendNotification(SCHEMA_CHANGED, { uri, schema: choice });
|
|
95
|
+
}
|
|
96
|
+
const syntax = wellFormed(text);
|
|
97
|
+
let diagnostics: Diagnostic[];
|
|
98
|
+
if (syntax.length) {
|
|
99
|
+
diagnostics = syntax.map(p => toDiagnostic(doc, p, 'well-formedness'));
|
|
100
|
+
} else {
|
|
101
|
+
const { grammar, error } = await grammarOf(choice);
|
|
102
|
+
if (documents.get(uri)?.version !== version) return;
|
|
103
|
+
if (error) {
|
|
104
|
+
diagnostics = [{
|
|
105
|
+
range: { start: { line: 0, character: 0 }, end: { line: 0, character: 0 } },
|
|
106
|
+
message: `The schema ${choice!.url} could not be loaded: ${error}`,
|
|
107
|
+
severity: DiagnosticSeverity.Warning, source: SOURCE, code: 'schema-load',
|
|
108
|
+
}];
|
|
109
|
+
} else {
|
|
110
|
+
diagnostics = grammar ? validate(grammar, text).map(p => toDiagnostic(doc, p, 'schema')) : [];
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
if (documents.get(uri)?.version !== version) return;
|
|
114
|
+
void connection.sendDiagnostics({ uri, version, diagnostics });
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function schedule(uri: string, delay = DELAY): void {
|
|
118
|
+
clearTimeout(timers.get(uri));
|
|
119
|
+
timers.set(uri, setTimeout(() => {
|
|
120
|
+
timers.delete(uri);
|
|
121
|
+
check(uri).catch(err => connection.console.error(`Checking ${uri} failed: ${err instanceof Error ? err.stack : err}`));
|
|
122
|
+
}, delay));
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const recheckAll = () => { for (const d of documents.all()) schedule(d.uri, 0); };
|
|
126
|
+
|
|
127
|
+
documents.onDidOpen(e => schedule(e.document.uri, 0));
|
|
128
|
+
documents.onDidChangeContent(e => schedule(e.document.uri));
|
|
129
|
+
documents.onDidClose(e => {
|
|
130
|
+
clearTimeout(timers.get(e.document.uri));
|
|
131
|
+
timers.delete(e.document.uri);
|
|
132
|
+
announced.delete(e.document.uri);
|
|
133
|
+
void connection.sendDiagnostics({ uri: e.document.uri, diagnostics: [] });
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
connection.onDidChangeWatchedFiles(({ changes }) => {
|
|
137
|
+
for (const c of changes) if (/\.rng$/i.test(c.uri)) grammars.invalidate(c.uri);
|
|
138
|
+
recheckAll();
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
connection.onCompletion(async ({ textDocument, position, context }) => {
|
|
142
|
+
const doc = documents.get(textDocument.uri);
|
|
143
|
+
if (!doc) return [];
|
|
144
|
+
const { grammar } = await grammarOf(choiceOf(doc));
|
|
145
|
+
if (!grammar) return [];
|
|
146
|
+
const at = doc.offsetAt(position);
|
|
147
|
+
const possible = possibleAt(grammar, doc.getText(), at);
|
|
148
|
+
if (!possible) return [];
|
|
149
|
+
const manual = context?.triggerKind !== CompletionTriggerKind.TriggerCharacter;
|
|
150
|
+
// between tags elements are offered only on request, not on every space or quote
|
|
151
|
+
if (!possible.inTag && !manual) return [];
|
|
152
|
+
const range = { start: doc.positionAt(possible.from), end: position };
|
|
153
|
+
return possible.suggestions.map((s, i): CompletionItem => {
|
|
154
|
+
const item: CompletionItem = {
|
|
155
|
+
label: s.label,
|
|
156
|
+
// shown beside every entry of the list, as opm studio does; detail only in the expanded pane
|
|
157
|
+
labelDetails: s.detail ? { description: s.detail } : undefined,
|
|
158
|
+
detail: s.detail,
|
|
159
|
+
documentation: s.info ? { kind: MarkupKind.PlainText, value: s.info } : undefined,
|
|
160
|
+
sortText: String(i).padStart(5, '0'),
|
|
161
|
+
};
|
|
162
|
+
if (s.kind === 'element') {
|
|
163
|
+
item.kind = CompletionItemKind.Class;
|
|
164
|
+
item.textEdit = possible.inTag
|
|
165
|
+
? { range, newText: s.label }
|
|
166
|
+
: { range, newText: `<${s.label}>$0</${s.label}>` };
|
|
167
|
+
if (!possible.inTag) { item.insertTextFormat = InsertTextFormat.Snippet; item.filterText = s.label; }
|
|
168
|
+
} else if (s.kind === 'attribute') {
|
|
169
|
+
item.kind = CompletionItemKind.Property;
|
|
170
|
+
item.textEdit = { range, newText: `${s.label}="$1"` };
|
|
171
|
+
item.insertTextFormat = InsertTextFormat.Snippet;
|
|
172
|
+
item.command = { title: 'Suggest values', command: 'editor.action.triggerSuggest' };
|
|
173
|
+
} else {
|
|
174
|
+
item.kind = CompletionItemKind.Value;
|
|
175
|
+
item.textEdit = { range, newText: s.label };
|
|
176
|
+
}
|
|
177
|
+
return item;
|
|
178
|
+
});
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
connection.languages.onLinkedEditingRange(({ textDocument, position }) => {
|
|
182
|
+
const doc = documents.get(textDocument.uri);
|
|
183
|
+
if (!doc) return null;
|
|
184
|
+
const ranges = matchingTags(doc.getText(), doc.offsetAt(position));
|
|
185
|
+
if (!ranges) return null;
|
|
186
|
+
return {
|
|
187
|
+
ranges: ranges.map(r => ({ start: doc.positionAt(r.from), end: doc.positionAt(r.to) })),
|
|
188
|
+
wordPattern: '[^\\s<>/="\']+',
|
|
189
|
+
};
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
connection.onDocumentSymbol(({ textDocument }) => {
|
|
193
|
+
const doc = documents.get(textDocument.uri);
|
|
194
|
+
if (!doc) return [];
|
|
195
|
+
const text = doc.getText();
|
|
196
|
+
let symbols: OutlineSymbol[];
|
|
197
|
+
try {
|
|
198
|
+
symbols = isOdd(doc.uri) ? oddOutline(text) : vocabulary(text) === 'tei' ? teiOutline(text) : elementOutline(text);
|
|
199
|
+
} catch {
|
|
200
|
+
return [];
|
|
201
|
+
}
|
|
202
|
+
const convert = (s: OutlineSymbol): DocumentSymbol => ({
|
|
203
|
+
name: s.name || ' ',
|
|
204
|
+
detail: s.detail,
|
|
205
|
+
kind: s.kind as DocumentSymbol['kind'],
|
|
206
|
+
range: { start: doc.positionAt(s.from), end: doc.positionAt(s.to) },
|
|
207
|
+
selectionRange: { start: doc.positionAt(s.nameFrom), end: doc.positionAt(s.nameTo) },
|
|
208
|
+
children: s.children.map(convert),
|
|
209
|
+
});
|
|
210
|
+
return symbols.map(convert);
|
|
211
|
+
});
|
|
212
|
+
|
|
213
|
+
// Expand Selection steps through the enclosing elements
|
|
214
|
+
connection.onSelectionRanges(({ textDocument, positions }) => {
|
|
215
|
+
const doc = documents.get(textDocument.uri);
|
|
216
|
+
if (!doc) return [];
|
|
217
|
+
const text = doc.getText();
|
|
218
|
+
return positions.map(position => {
|
|
219
|
+
const at = doc.offsetAt(position);
|
|
220
|
+
// built from the outermost element in, so each range's parent is the next larger one
|
|
221
|
+
let range: SelectionRange | undefined;
|
|
222
|
+
for (const e of elementsAround(text, at).reverse()) {
|
|
223
|
+
range = { range: { start: doc.positionAt(e.from), end: doc.positionAt(e.to) }, parent: range };
|
|
224
|
+
}
|
|
225
|
+
return range ?? { range: { start: position, end: position } };
|
|
226
|
+
});
|
|
227
|
+
});
|
|
228
|
+
|
|
229
|
+
connection.onRequest(ALLOWED_ELEMENTS, async ({ uri, offset }: { uri: string; offset: number }) => {
|
|
230
|
+
const doc = documents.get(uri);
|
|
231
|
+
if (!doc) return null;
|
|
232
|
+
const { grammar } = await grammarOf(choiceOf(doc));
|
|
233
|
+
if (!grammar) return null;
|
|
234
|
+
// what may start here: the text before, as if an element were begun at offset
|
|
235
|
+
const before = doc.getText().slice(0, offset);
|
|
236
|
+
const possible = possibleAt(grammar, before, offset);
|
|
237
|
+
if (!possible) return null;
|
|
238
|
+
return possible.suggestions.filter(s => s.kind === 'element').map(s => ({ name: s.label, detail: s.detail }));
|
|
239
|
+
});
|
|
240
|
+
|
|
241
|
+
connection.onRequest(SCHEMA_FOR, ({ uri }: { uri: string }) => {
|
|
242
|
+
const doc = documents.get(uri);
|
|
243
|
+
return doc ? choiceOf(doc) : null;
|
|
244
|
+
});
|
|
245
|
+
|
|
246
|
+
documents.listen(connection);
|
|
247
|
+
connection.listen();
|
|
248
|
+
}
|