@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.
Files changed (59) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +48 -2
  3. package/dist/edit.js +313 -0
  4. package/dist/edit.js.map +7 -0
  5. package/dist/index.js +803 -0
  6. package/dist/index.js.map +7 -0
  7. package/dist/node.cjs +44962 -0
  8. package/dist/node.cjs.map +7 -0
  9. package/package.json +74 -4
  10. package/schema/README.md +41 -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/tei/tei_all.rng +23212 -0
  47. package/src/core/association.ts +155 -0
  48. package/src/core/complete.ts +147 -0
  49. package/src/core/elements.ts +86 -0
  50. package/src/core/outline.ts +156 -0
  51. package/src/core/schema.ts +55 -0
  52. package/src/core/tags.ts +104 -0
  53. package/src/core/toml.ts +64 -0
  54. package/src/core/validate.ts +128 -0
  55. package/src/core/wellformed.ts +16 -0
  56. package/src/edit.ts +11 -0
  57. package/src/index.ts +16 -0
  58. package/src/node.ts +39 -0
  59. package/src/server/server.ts +248 -0
@@ -0,0 +1,155 @@
1
+ // ── which RELAX NG schema an XML file gets ────────────────────────────────
2
+ // The same order as opm studio (src/ui/xmlSchema.ts there):
3
+ // 1. a local RNG named by the document's <?xml-model?>
4
+ // 2. for documents other than ODDs, [editor] schema in the nearest opm.toml
5
+ // 3. a default by vocabulary: TEI Publisher's ODD schema for ODDs, tei_all for TEI,
6
+ // DocBook 5.2 and JATS 1.3 Archiving
7
+ // Everything is a URL, so relative paths resolve the same way on every platform.
8
+ import { readToml, tomlString } from './toml.ts';
9
+
10
+ export const RNG_NS = 'http://relaxng.org/ns/structure/1.0';
11
+
12
+ /** What association needs to know about files: synchronous, as the files are small or only checked. */
13
+ export interface Files {
14
+ exists(url: string): boolean;
15
+ read(url: string): string | undefined;
16
+ }
17
+
18
+ /** Default schema URL by vocabulary ('odd', 'tei', …). */
19
+ export type Defaults = Record<string, string | undefined>;
20
+
21
+ export interface SchemaChoice {
22
+ /** URL of the main RNG. */
23
+ url: string;
24
+ /** Where the choice came from. */
25
+ via: 'xml-model' | 'project' | 'default';
26
+ }
27
+
28
+ export const isOdd = (url: string) => /\.odd$/i.test(new URL(url).pathname);
29
+
30
+ /** The main file of each default schema, relative to the schema folder shipped with the package. */
31
+ export const DEFAULT_SCHEMA_FILES: Record<string, string> = {
32
+ odd: 'odd/teipublisher_odds.rng',
33
+ tei: 'tei/tei_all.rng',
34
+ docbook: 'docbook/docbook.rng',
35
+ jats: 'jats/JATS-archivearticle1-3-mathml3.rng',
36
+ };
37
+
38
+ /** Where each default schema is published; documents often name these in their <?xml-model?>. */
39
+ export const PUBLIC_SCHEMA_URLS: Record<string, string> = {
40
+ tei: 'https://tei-c.org/release/xml/tei/custom/schema/relaxng/tei_all.rng',
41
+ docbook: 'https://cdn.docbook.org/schema/5.2/rng/docbook.rng',
42
+ jats: 'https://jats.nlm.nih.gov/archiving/1.3/rng/JATS-archivearticle1-3-mathml3.rng',
43
+ };
44
+
45
+ /**
46
+ * The default schema a published schema URL stands for, so that the bundled copy is used
47
+ * instead of fetching it. Any JATS tag set maps to Archiving, the loosest of them.
48
+ */
49
+ export function publicSchema(url: string): string | undefined {
50
+ if (/^https?:\/\/(www\.)?tei-c\.org\/.*\/tei_all\.rng$/i.test(url)) return 'tei';
51
+ if (/^https?:\/\/([\w-]+\.)?docbook\.org\/.*\/docbook\.rng$/i.test(url)) return 'docbook';
52
+ if (/^https?:\/\/jats\.nlm\.nih\.gov\/.*\.rng$/i.test(url)) return 'jats';
53
+ return undefined;
54
+ }
55
+
56
+ /** The vocabulary of a document by namespace, root element or doctype; '' for none we know. */
57
+ export function vocabulary(text: string): string {
58
+ const head = text.slice(0, 5000);
59
+ if (head.includes('http://www.tei-c.org/ns/1.0') || /<(TEI|teiCorpus)[\s>]/.test(head)) return 'tei';
60
+ if (head.includes('http://docbook.org/ns/docbook')) return 'docbook';
61
+ // JATS has no namespace: its doctype, or an <article> without one (DocBook's has its own)
62
+ // that says it is JATS by @dtd-version, @article-type or its <front>
63
+ if (/<!DOCTYPE\s+article\s+PUBLIC\s+"-\/\/NLM\/\/DTD/.test(head)) return 'jats';
64
+ const article = head.match(/<article(?=[\s>])[^>]*>/)?.[0];
65
+ if (article && !/\sxmlns\s*=/.test(article) && (/\s(dtd-version|article-type)\s*=/.test(article) || /<front[\s>]/.test(head))) return 'jats';
66
+ return '';
67
+ }
68
+
69
+ /** The <?xml-model?> processing instructions in the head of a document, with their pseudo-attributes. */
70
+ export function xmlModels(text: string): { from: number; to: number; href?: string; schematypens?: string; raw: string }[] {
71
+ const out = [];
72
+ for (const m of text.slice(0, 5000).matchAll(/<\?xml-model\s([^?]*)\?>/g)) {
73
+ const pseudo = (name: string) => m[1].match(new RegExp(`\\b${name}\\s*=\\s*["']([^"']*)["']`))?.[1];
74
+ out.push({ from: m.index!, to: m.index! + m[0].length, href: pseudo('href'), schematypens: pseudo('schematypens'), raw: m[0] });
75
+ }
76
+ return out;
77
+ }
78
+
79
+ /** True for an xml-model PI that points at a RELAX NG schema (not Schematron). */
80
+ export const isRngModel = (pi: { href?: string; schematypens?: string; raw: string }) =>
81
+ pi.schematypens === RNG_NS || (!pi.schematypens && !!pi.href && /\.rng$/i.test(pi.href) && !/schematron/i.test(pi.raw));
82
+
83
+ /** URL of the folder (ending in '/') holding the nearest opm.toml above url, stopping at any of stops. */
84
+ export function projectRoot(url: string, files: Files, stops: string[] = []): string | undefined {
85
+ let dir = new URL('./', url);
86
+ for (;;) {
87
+ if (files.exists(new URL('opm.toml', dir).href)) return dir.href;
88
+ const parent = new URL('../', dir);
89
+ if (parent.href === dir.href || stops.some(s => sameDir(s, dir.href))) return undefined;
90
+ dir = parent;
91
+ }
92
+ }
93
+
94
+ const sameDir = (a: string, b: string) => a.replace(/\/?$/, '/') === b.replace(/\/?$/, '/');
95
+
96
+ /** The schema of the document at url with text, or null when it has none. */
97
+ export function schemaFor(url: string, text: string, files: Files, defaults: Defaults, stops: string[] = []): SchemaChoice | null {
98
+ for (const pi of xmlModels(text)) {
99
+ if (!isRngModel(pi) || !pi.href) continue;
100
+ // a published default schema is used from the bundled copy; other remote ones are left alone
101
+ if (/^(https?|ftp):/i.test(pi.href)) {
102
+ const bundled = defaults[publicSchema(pi.href) ?? ''];
103
+ if (bundled) return { url: bundled, via: 'xml-model' };
104
+ continue;
105
+ }
106
+ const target = new URL(pi.href, url).href;
107
+ if (files.exists(target)) return { url: target, via: 'xml-model' };
108
+ }
109
+ const odd = isOdd(url);
110
+ if (!odd) {
111
+ const root = projectRoot(url, files, stops);
112
+ const toml = root && files.read(new URL('opm.toml', root).href);
113
+ const configured = toml ? tomlString(readToml(toml), 'editor', 'schema') : '';
114
+ if (configured && /\.rng$/i.test(configured)) {
115
+ const bundled = defaults[publicSchema(configured) ?? ''];
116
+ if (bundled) return { url: bundled, via: 'project' };
117
+ const target = new URL(configured, root).href;
118
+ if (files.exists(target)) return { url: target, via: 'project' };
119
+ }
120
+ }
121
+ const fallback = defaults[odd ? 'odd' : vocabulary(text)];
122
+ return fallback ? { url: fallback, via: 'default' } : null;
123
+ }
124
+
125
+ /** A relative href from the document at `from` to `to`, or `to` itself when they share no root. */
126
+ export function relativeHref(from: string, to: string): string {
127
+ const a = new URL(from), b = new URL(to);
128
+ if (a.protocol !== b.protocol || a.host !== b.host) return to;
129
+ const dir = a.pathname.split('/').slice(0, -1), target = b.pathname.split('/');
130
+ let i = 0;
131
+ while (i < dir.length && i < target.length - 1 && dir[i] === target[i]) i++;
132
+ return [...Array(dir.length - i).fill('..'), ...target.slice(i)].join('/');
133
+ }
134
+
135
+ export interface TextEdit { from: number; to: number; insert: string }
136
+
137
+ /**
138
+ * The edit that makes text associate with the RNG at href: it replaces the first RELAX NG
139
+ * xml-model PI, or adds one after the XML declaration. With href null it removes them all.
140
+ */
141
+ export function xmlModelEdits(text: string, href: string | null): TextEdit[] {
142
+ const nl = text.includes('\r\n') ? '\r\n' : '\n';
143
+ const models = xmlModels(text).filter(isRngModel);
144
+ const pi = href && `<?xml-model href="${href.replace(/&/g, '&amp;').replace(/"/g, '&quot;')}" type="application/xml" schematypens="${RNG_NS}"?>`;
145
+ const removal = (m: { from: number; to: number }): TextEdit => {
146
+ const after = text.slice(m.to).match(/^\r?\n/)?.[0].length ?? 0;
147
+ return { from: m.from, to: m.to + after, insert: '' };
148
+ };
149
+ if (!pi) return models.map(removal);
150
+ if (models.length) return [{ from: models[0].from, to: models[0].to, insert: pi }, ...models.slice(1).map(removal)];
151
+ const decl = text.match(/^?<\?xml\s[^?]*\?>/);
152
+ if (decl) return [{ from: decl[0].length, to: decl[0].length, insert: nl + pi }];
153
+ const bom = text.startsWith('') ? 1 : 0;
154
+ return [{ from: bom, to: bom, insert: pi + nl }];
155
+ }
@@ -0,0 +1,147 @@
1
+ // ── what the schema allows at the cursor, from salve's walker ─────────────
2
+ // Pure, like validate.ts: the worker (runtime/validator.ts) runs it, tests call it directly.
3
+ // The text before the cursor is fed to the walker, which then knows what may come next,
4
+ // in document order: after <TEI> only <teiHeader>, inside <hi only its attributes.
5
+ import { DefaultNameResolver, Name, NameChoice, type BaseName, type Grammar } from 'salve-annos';
6
+ import { SaxesParser, type SaxesTagNS } from 'saxes';
7
+
8
+ export interface Suggestion { kind: 'element' | 'attribute' | 'value'; label: string; detail?: string; info?: string }
9
+ /** Suggestions for the text from `from` to the cursor; `inTag` is false between tags, where they are only offered on request. */
10
+ export interface Possible { from: number; inTag: boolean; suggestions: Suggestion[] }
11
+
12
+ /** A detail longer than this is cut at a word. */
13
+ const DETAIL_MAX = 80;
14
+
15
+ /**
16
+ * detail and info from an a:documentation. TEI's open with the gloss in parentheses,
17
+ * "(paragraph) marks paragraphs in prose. [3.1. Paragraphs]": the gloss becomes the detail,
18
+ * the chapters cited at the end are dropped. Otherwise the detail is the first sentence.
19
+ */
20
+ export function described(doc: string | undefined): Pick<Suggestion, 'detail' | 'info'> {
21
+ const text = (doc ?? '').replace(/\s+/g, ' ').trim().replace(/\s*\[\d+(?:\.\d+)*\.\s[^[\]]*\]$/, '');
22
+ if (!text) return {};
23
+ const gloss = text.match(/^\(([^()]+)\)\s*(.*)$/);
24
+ if (gloss) return gloss[2] ? { detail: gloss[1], info: gloss[2] } : { detail: gloss[1] };
25
+ let detail = text.split(/(?<=[.;:])\s/, 1)[0].replace(/[.;:]$/, '');
26
+ if (detail.length > DETAIL_MAX) detail = detail.slice(0, DETAIL_MAX).replace(/\s\S*$/, '') + '…';
27
+ return detail === text ? { detail } : { detail, info: text };
28
+ }
29
+
30
+ /** The names a name pattern stands for, as the document can write them: in a namespace it has a prefix (or the default) for. */
31
+ function names(n: BaseName, resolver: DefaultNameResolver, attribute: boolean): { label: string; doc?: string }[] {
32
+ if (n instanceof NameChoice) return [...names(n.a, resolver, attribute), ...names(n.b, resolver, attribute)];
33
+ if (!(n instanceof Name)) return []; // any name, or any in a namespace: nothing to offer by name
34
+ const label = attribute && n.ns === '' ? n.name : resolver.unresolveName(n.ns, n.name);
35
+ return label ? [{ label, doc: n.documentation }] : [];
36
+ }
37
+
38
+ const ATTR = /\s([^\s=/>]+)\s*=\s*("[^"]*"|'[^']*')/g;
39
+
40
+ /** Where the cursor is: in a start tag's name, among its attributes, in a value, or between tags. */
41
+ function context(before: string) {
42
+ // a '<' in a comment, CDATA section or processing instruction is not a tag
43
+ for (const [open, close] of [['<!--', '-->'], ['<![CDATA[', ']]>'], ['<?', '?>']]) {
44
+ if (before.lastIndexOf(open) > before.lastIndexOf(close)) return null;
45
+ }
46
+ const lt = before.lastIndexOf('<');
47
+ if (lt <= before.lastIndexOf('>')) return { at: 'text' as const, tagStart: before.length };
48
+ const tag = before.slice(lt);
49
+ if (/^<[/!?]/.test(tag)) return null;
50
+ const partialName = tag.match(/^<([^\s/>]*)$/);
51
+ if (partialName) return { at: 'name' as const, tagStart: lt, typed: partialName[1] };
52
+ const name = tag.match(/^<([^\s/>]+)/)?.[1];
53
+ if (!name) return null;
54
+ const done = [...tag.matchAll(ATTR)];
55
+ const tail = tag.slice(done.length ? done[done.length - 1].index! + done[done.length - 1][0].length : name.length + 1);
56
+ const attrs = done.map(m => ({ name: m[1], value: m[2].slice(1, -1) }));
57
+ const inValue = tail.match(/\s([^\s=/>]+)\s*=\s*(["'])([^"']*)$/);
58
+ if (inValue) return { at: 'value' as const, tagStart: lt, name, attrs, attr: inValue[1], typed: inValue[3] };
59
+ const inName = tail.match(/\s([^\s=/>]*)$/);
60
+ if (inName) return { at: 'attribute' as const, tagStart: lt, name, attrs, typed: inName[1] };
61
+ return null;
62
+ }
63
+
64
+ /** What may be written at position `at` of xml. */
65
+ export function possibleAt(grammar: Grammar, xml: string, at: number): Possible | null {
66
+ const before = xml.slice(0, at);
67
+ const ctx = context(before);
68
+ if (!ctx) return null;
69
+
70
+ const resolver = new DefaultNameResolver();
71
+ const walker = grammar.newWalker(resolver);
72
+ const parser = new SaxesParser({ xmlns: true });
73
+ let text = '';
74
+ const flush = () => { if (text.trim() !== '') walker.fireEvent('text', [text]); text = ''; };
75
+ // the text before the cursor is rarely valid, or even finished: errors are ignored, the walker goes on
76
+ parser.on('error', () => {});
77
+ parser.on('opentag', (node: SaxesTagNS) => {
78
+ flush();
79
+ resolver.enterContext();
80
+ for (const [qn, a] of Object.entries(node.attributes)) {
81
+ if (qn === 'xmlns') resolver.definePrefix('', a.value);
82
+ else if (a.prefix === 'xmlns') resolver.definePrefix(a.local, a.value);
83
+ }
84
+ walker.fireEvent('enterStartTag', [node.uri, node.local]);
85
+ for (const [qn, a] of Object.entries(node.attributes)) {
86
+ if (qn === 'xmlns' || a.prefix === 'xmlns') continue;
87
+ walker.fireEvent('attributeName', [a.uri, a.local]);
88
+ walker.fireEvent('attributeValue', [a.value]);
89
+ }
90
+ walker.fireEvent('leaveStartTag', []);
91
+ });
92
+ parser.on('closetag', (node: SaxesTagNS) => { flush(); walker.fireEvent('endTag', [node.uri, node.local]); resolver.leaveContext(); });
93
+ parser.on('text', s => { text += s; });
94
+ parser.on('cdata', s => { text += s; });
95
+ try { parser.write(xml.slice(0, ctx.tagStart)); } catch { /* ignored, as above */ }
96
+ flush();
97
+
98
+ const seen = new Set<string>();
99
+ const suggestions: Suggestion[] = [];
100
+ const add = (kind: Suggestion['kind'], label: string, doc?: string) => {
101
+ if (seen.has(label)) return;
102
+ seen.add(label);
103
+ suggestions.push({ kind, label, ...described(doc) });
104
+ };
105
+
106
+ if (ctx.at === 'text' || ctx.at === 'name') {
107
+ for (const ev of walker.possible()) {
108
+ if (ev.name === 'enterStartTag') for (const n of names(ev.param, resolver, false)) add('element', n.label, n.doc);
109
+ }
110
+ return { from: at - (ctx.at === 'name' ? ctx.typed.length : 0), inTag: ctx.at === 'name', suggestions };
111
+ }
112
+
113
+ // inside a start tag: enter it with the attributes already written, then ask
114
+ resolver.enterContext();
115
+ for (const a of ctx.attrs) {
116
+ if (a.name === 'xmlns') resolver.definePrefix('', a.value);
117
+ else if (a.name.startsWith('xmlns:')) resolver.definePrefix(a.name.slice(6), a.value);
118
+ }
119
+ const element = resolver.resolveName(ctx.name);
120
+ if (!element) return null;
121
+ walker.fireEvent('enterStartTag', [element.ns, element.name]);
122
+ const written = new Set<string>();
123
+ for (const a of ctx.attrs) {
124
+ written.add(a.name);
125
+ if (a.name === 'xmlns' || a.name.startsWith('xmlns:') || (ctx.at === 'value' && a.name === ctx.attr)) continue;
126
+ const n = resolver.resolveName(a.name, true);
127
+ if (!n) continue;
128
+ walker.fireEvent('attributeName', [n.ns, n.name]);
129
+ walker.fireEvent('attributeValue', [a.value]);
130
+ }
131
+
132
+ if (ctx.at === 'attribute') {
133
+ for (const ev of walker.possible()) {
134
+ if (ev.name !== 'attributeName') continue;
135
+ for (const n of names(ev.param, resolver, true)) if (!written.has(n.label)) add('attribute', n.label, n.doc);
136
+ }
137
+ return { from: at - ctx.typed.length, inTag: true, suggestions };
138
+ }
139
+
140
+ const n = resolver.resolveName(ctx.attr, true);
141
+ if (!n) return null;
142
+ walker.fireEvent('attributeName', [n.ns, n.name]);
143
+ for (const ev of walker.possible()) {
144
+ if (ev.name === 'attributeValue' && typeof ev.param === 'string') add('value', ev.param, ev.documentation);
145
+ }
146
+ return { from: at - ctx.typed.length, inTag: true, suggestions };
147
+ }
@@ -0,0 +1,86 @@
1
+ // ── element editing: select, remove tags, split, surround ─────────────────
2
+ // The commands of opm studio's src/ui/xmlCommands.ts, on plain text: each takes
3
+ // the text and one selection and returns the changes plus the selection after them.
4
+ import { pairs, scanTags, type Tag } from './tags.ts';
5
+ import type { TextEdit } from './association.ts';
6
+
7
+ export interface Element {
8
+ name: string;
9
+ from: number;
10
+ to: number;
11
+ open: Tag;
12
+ /** Missing for a self-closing element. */
13
+ close?: Tag;
14
+ }
15
+
16
+ export interface Selection { anchor: number; head: number }
17
+
18
+ /** The result of a command for one selection: changes and the selection after them (counting only these changes). */
19
+ export interface ElementEdit { changes: TextEdit[]; selection: Selection }
20
+
21
+ /** Every complete element in text, in document order of their start tags. */
22
+ export function elements(text: string): Element[] {
23
+ const tags = scanTags(text), pair = pairs(tags), out: Element[] = [];
24
+ tags.forEach((t, i) => {
25
+ if (t.kind === 'empty') out.push({ name: t.name, from: t.from, to: t.to, open: t });
26
+ else if (t.kind === 'open' && pair.has(i)) {
27
+ const close = tags[pair.get(i)!];
28
+ out.push({ name: t.name, from: t.from, to: close.to, open: t, close });
29
+ }
30
+ });
31
+ return out;
32
+ }
33
+
34
+ /** The elements holding from..to, innermost first. */
35
+ export function elementsAround(text: string, from: number, to = from): Element[] {
36
+ return elements(text).filter(e => e.from <= from && e.to >= to).sort((a, b) => (a.to - a.from) - (b.to - b.from));
37
+ }
38
+
39
+ /**
40
+ * The element around a range. With `outer`, one that is larger than the range,
41
+ * so that selecting the element again moves on to its parent.
42
+ */
43
+ export function elementAround(text: string, from: number, to: number, outer: boolean): Element | undefined {
44
+ return elementsAround(text, from, to).find(e => !outer || from === to || e.from < from || e.to > to);
45
+ }
46
+
47
+ /** Select the element around the selection; again for its parent. */
48
+ export function selectElement(text: string, from: number, to: number): ElementEdit | null {
49
+ const e = elementAround(text, from, to, true);
50
+ return e ? { changes: [], selection: { anchor: e.from, head: e.to } } : null;
51
+ }
52
+
53
+ /** Remove the tags of the element around the selection, keeping its content selected. */
54
+ export function removeElementTags(text: string, from: number, to: number): ElementEdit | null {
55
+ const e = elementAround(text, from, to, false);
56
+ if (!e) return null;
57
+ const { open, close } = e;
58
+ if (!close) return { changes: [{ from: open.from, to: open.to, insert: '' }], selection: { anchor: open.from, head: open.from } };
59
+ const length = open.to - open.from;
60
+ return {
61
+ changes: [{ from: open.from, to: open.to, insert: '' }, { from: close.from, to: close.to, insert: '' }],
62
+ selection: { anchor: open.from, head: close.from - length },
63
+ };
64
+ }
65
+
66
+ /**
67
+ * Split the element around the cursor in two at the cursor: its end tag, then its
68
+ * start tag again, with the same attributes but for an id, which has to stay unique.
69
+ */
70
+ export function splitElement(text: string, pos: number): ElementEdit | null {
71
+ // the innermost element whose content holds the cursor, not one whose tag does
72
+ const e = elementsAround(text, pos).find(x => x.close && pos >= x.open.to && pos <= x.close.from);
73
+ if (!e) return null;
74
+ const start = text.slice(e.open.from, e.open.to).replace(/\s(xml:)?id\s*=\s*("[^"]*"|'[^']*')/g, '');
75
+ const insert = `</${e.name}>${start}`;
76
+ return { changes: [{ from: pos, to: pos, insert }], selection: { anchor: pos + insert.length, head: pos + insert.length } };
77
+ }
78
+
79
+ /** Wrap from..to in an element; `tag` is its name, optionally followed by attributes. The text stays selected. */
80
+ export function surroundWithElement(from: number, to: number, tag: string): ElementEdit {
81
+ const start = `<${tag.trim()}>`, end = `</${tag.trim().split(/\s/)[0]}>`;
82
+ return {
83
+ changes: [{ from, to: from, insert: start }, { from: to, to, insert: end }],
84
+ selection: { anchor: from + start.length, head: to + start.length },
85
+ };
86
+ }
@@ -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
+ }