@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,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, '&').replace(/"/g, '"')}" 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
|
+
}
|