@rohal12/spindle 0.59.21 → 0.59.23

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.
@@ -2,10 +2,10 @@
2
2
  // compiled to its parser on load (scripts/peggy.ts); parse.ts wraps it.
3
3
  //
4
4
  // Start rules:
5
- // Markup the nested AST (ast.ts): macros with their bodies and branches,
6
- // HTML elements with their children, links, variables, text.
7
- // Tokens the flat token stream (tokens.ts Token), without nesting:
8
- // what the variable checker scans.
5
+ // Tokens the flat token stream (tokens.ts Token), without nesting. The
6
+ // nesting (which closer closes which opener) is pair.ts; the AST
7
+ // is built from the paired tokens (ast.ts).
8
+ // SelectorsPrefix the selectors that start the input.
9
9
  //
10
10
  // options.text selects text mode (HTML attribute values, labels): no links
11
11
  // or HTML, and a backslash run before a brace is paired up.
@@ -28,7 +28,6 @@ const RB = String.fromCharCode(125);
28
28
  const { SIGIL_SCOPES, withSelectors } = shared;
29
29
  const VOID_TAGS = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'param', 'source', 'track', 'wbr']);
30
30
  const BRANCH_PARENT = { elseif: 'if', else: 'if', case: 'switch', default: 'switch', next: 'timed' };
31
- const BRANCHING = new Set(['if', 'switch', 'timed']);
32
31
  const LINK_SEPARATORS = [['|', false], ['->', false], ['<-', true]];
33
32
  const NO_SELECTORS = {};
34
33
  /**
@@ -39,9 +38,10 @@ const EMAIL_AUTOLINK = /^<[a-zA-Z0-9.!#$%&'*+/=?^_`|~-]+@[a-zA-Z0-9](?:[a-zA-Z0-
39
38
 
40
39
  /**
41
40
  * A link's display text and target, from its text `inner` (at `at` in the
42
- * input), with where the target is written.
41
+ * input), with where the target is written. `indexOf(separator)` finds a
42
+ * separator that is written outside markup (see linkSeparatorIndex).
43
43
  */
44
- function parseLink(inner, at) {
44
+ function parseLink(inner, at, indexOf) {
45
45
  /** The trimmed text from `start` to `end` of inner, and where it is. */
46
46
  const part = (start, end) => {
47
47
  const raw = inner.slice(start, end);
@@ -50,19 +50,15 @@ function parseLink(inner, at) {
50
50
  return { value, start: from, end: from + value.length };
51
51
  };
52
52
  for (const [separator, targetFirst] of LINK_SEPARATORS) {
53
- const idx = inner.indexOf(separator);
53
+ const idx = indexOf(separator);
54
54
  if (idx === -1) continue;
55
55
  const before = part(0, idx);
56
56
  const after = part(idx + separator.length, inner.length);
57
57
  const [display, target] = targetFirst ? [after, before] : [before, after];
58
- return { display: display.value, target: target.value, targetStart: target.start, targetEnd: target.end };
58
+ return { display: display.value, displayStart: display.start, displayEnd: display.end, target: target.value, targetStart: target.start, targetEnd: target.end };
59
59
  }
60
60
  const whole = part(0, inner.length);
61
- return { display: whole.value, target: whole.value, targetStart: whole.start, targetEnd: whole.end };
62
- }
63
-
64
- function quoteArg(value) {
65
- return '"' + value.replace(/[\\"]/g, '\\$&') + '"';
61
+ return { display: whole.value, displayStart: whole.start, displayEnd: whole.end, target: whole.value, targetStart: whole.start, targetEnd: whole.end };
66
62
  }
67
63
 
68
64
  function selectorsOf(parts) {
@@ -81,16 +77,6 @@ function label(tag) {
81
77
  if (tag.lex === 'html') return (tag.isClose ? '</' : '<') + tag.tag + '>';
82
78
  return LB + (tag.isClose ? '/' : '') + tag.name + RB;
83
79
  }
84
- function closerOf(tag) {
85
- return tag.lex === 'html' ? '</' + tag.tag + '>' : LB + '/' + tag.name + RB;
86
- }
87
- function at(loc) {
88
- return 'line ' + loc.start.line + ', column ' + loc.start.column;
89
- }
90
- function sameName(open, close) {
91
- return open.lex === close.lex && open.lower === close.lower;
92
- }
93
-
94
80
  /** A lexeme: what one token of the flat stream holds, with its span. */
95
81
  function lexeme(lex, loc, fields) {
96
82
  fields.lex = lex;
@@ -100,38 +86,22 @@ function lexeme(lex, loc, fields) {
100
86
  return fields;
101
87
  }
102
88
 
103
- /** The AST node of a lexeme that stands alone (not a macro or element). */
104
- function nodeOf(x) {
105
- switch (x.lex) {
106
- case 'text':
107
- return x.comment ? { type: 'text', value: x.value, comment: true } : { type: 'text', value: x.value };
108
- case 'link':
109
- return withSelectors({ type: 'macro', name: 'link', rawArgs: quoteArg(x.display) + ' ' + quoteArg(x.target), children: [] }, x);
110
- case 'variable':
111
- return withSelectors({ type: 'variable', name: x.name, scope: x.scope }, x);
112
- case 'expression':
113
- return withSelectors({ type: 'expression', expression: x.expression }, x);
114
- default:
115
- return x; // already a node
116
- }
117
- }
118
-
119
89
  /** The token of a lexeme (tokens.ts Token). */
120
90
  function tokenOf(x) {
121
91
  const span = { start: x.start, end: x.end };
122
92
  switch (x.lex) {
123
93
  case 'text':
124
- return { type: 'text', value: x.value, ...span };
94
+ return x.comment ? { type: 'text', value: x.value, comment: true, ...span } : { type: 'text', value: x.value, ...span };
125
95
  case 'link':
126
- return withSelectors({ type: 'link', display: x.display, target: x.target, targetStart: x.targetStart, targetEnd: x.targetEnd, ...span }, x);
96
+ return withSelectors({ type: 'link', display: x.display, displayStart: x.displayStart, displayEnd: x.displayEnd, target: x.target, targetStart: x.targetStart, targetEnd: x.targetEnd, ...x.selectorSpan, ...span }, x);
127
97
  case 'variable':
128
- return withSelectors({ type: 'variable', name: x.name, scope: x.scope, ...span }, x);
98
+ return withSelectors({ type: 'variable', name: x.name, nameStart: x.nameStart, nameEnd: x.nameEnd, scope: x.scope, ...x.selectorSpan, ...span }, x);
129
99
  case 'expression':
130
- return withSelectors({ type: 'expression', expression: x.expression, ...span }, x);
100
+ return withSelectors({ type: 'expression', expression: x.expression, expressionStart: x.expressionStart, expressionEnd: x.expressionEnd, ...x.selectorSpan, ...span }, x);
131
101
  case 'macro':
132
- return withSelectors({ type: 'macro', name: x.name, rawArgs: x.rawArgs, isClose: x.isClose, ...span }, x);
102
+ return withSelectors({ type: 'macro', name: x.name, nameStart: x.nameStart, nameEnd: x.nameEnd, rawArgs: x.rawArgs, argsStart: x.argsStart, argsEnd: x.argsEnd, isClose: x.isClose, ...x.selectorSpan, ...span }, x);
133
103
  case 'html':
134
- return { type: 'html', tag: x.tag, attributes: x.attributes, isClose: x.isClose, isSelfClose: x.isSelfClose, ...span };
104
+ return { type: 'html', tag: x.tag, tagNameStart: x.tagNameStart, tagNameEnd: x.tagNameEnd, attributes: x.attributes, attributeSpans: x.attributeSpans, isClose: x.isClose, isSelfClose: x.isSelfClose, ...span };
135
105
  }
136
106
  }
137
107
 
@@ -139,7 +109,7 @@ function tokenOf(x) {
139
109
  * Flatten items (lexemes, nodes, arrays of them, nulls) and join adjacent
140
110
  * text, except escaped braces and comments, which stay a text item of their own.
141
111
  */
142
- function joinText(items, convert) {
112
+ function joinText(items) {
143
113
  const out = [];
144
114
  let last = null;
145
115
  const add = (item) => {
@@ -154,7 +124,7 @@ function joinText(items, convert) {
154
124
  last = item;
155
125
  };
156
126
  add(items);
157
- return convert ? out.map(convert) : out;
127
+ return out.map(tokenOf);
158
128
  }
159
129
  }}
160
130
 
@@ -168,17 +138,55 @@ let attrCode = false;
168
138
  /** The macro whose raw body is being read. */
169
139
  let rawName = '';
170
140
 
141
+ /**
142
+ * The index in `inner` (at `at` in the input) of the first `separator` that
143
+ * is not inside a {…} of the label: its code (`{if $a || $b}`, a string with
144
+ * a pipe) belongs to the label, not to the link's syntax.
145
+ */
146
+ function linkSeparatorIndex(inner, at, separator) {
147
+ for (let i = 0; i < inner.length; i++) {
148
+ const c = inner.charAt(i);
149
+ if (c === '\\' && /[{}]/.test(inner.charAt(i + 1))) {
150
+ i++;
151
+ } else if (c === LB) {
152
+ // Selectors, then a macro name or the sigil of a variable or expression
153
+ const head = /^(?:[.#][\w-]*)* ?(\/?[a-zA-Z][\w-]*|(?=[$_@%(!]))/.exec(inner.slice(i + 1));
154
+ if (!head) continue;
155
+ const close = hooks.closeBrace(input, at + i + 1 + head[0].length, at + i + 1);
156
+ // One that does not end inside the label is no markup of it
157
+ if (close !== -1 && close < at + inner.length) i = close - at;
158
+ } else if (inner.startsWith(separator, i)) {
159
+ return i;
160
+ }
161
+ }
162
+ return -1;
163
+ }
164
+ /**
165
+ * Where the selectors `s` are written, from `start` up to `after`, the end of
166
+ * what Selectors consumed (the one space that may follow them is not part of
167
+ * them): the fields of a token; none without selectors.
168
+ */
169
+ function selectorSpan(s, start, after) {
170
+ if (s === NO_SELECTORS) return {};
171
+ return { selectorsStart: start, selectorsEnd: input.charAt(after - 1) === ' ' ? after - 1 : after };
172
+ }
171
173
  function skipTo(end) {
172
174
  skipEnd = end;
173
175
  return end >= 0;
174
176
  }
175
- function fail(message, loc) {
176
- error(message, loc);
177
+ /** Fail with `message` at `loc`; `code` tells the kind of error apart (MarkupError). */
178
+ function fail(message, loc, code) {
179
+ try {
180
+ error(message, loc);
181
+ } catch (e) {
182
+ e.code = code;
183
+ throw e;
184
+ }
177
185
  }
178
186
  function attrs(list) {
179
187
  const attributes = {};
180
188
  const seen = new Set();
181
- for (const [name, value] of list) {
189
+ for (const { name, value } of list) {
182
190
  const lower = name.toLowerCase();
183
191
  if (seen.has(lower)) continue;
184
192
  seen.add(lower);
@@ -186,114 +194,12 @@ function attrs(list) {
186
194
  }
187
195
  return attributes;
188
196
  }
189
-
190
- /** Check the body of a macro or element against its opening tag. */
191
- function checkBody(open, body) {
192
- for (const branch of body.branches) {
193
- const parent = BRANCH_PARENT[branch.tag.lower];
194
- if (open.lex !== 'macro' || open.lower !== parent) {
195
- fail(label(branch.tag) + ' must be directly inside ' + LB + parent + RB + ', not inside ' + label(open), branch.tag.loc);
196
- }
197
- }
198
- if (!body.end) {
199
- fail('Unclosed ' + label(open) + ': no ' + closerOf(open) + ' closes it', open.loc);
200
- }
201
- if (!sameName(open, body.end)) {
202
- fail(label(body.end) + ' found where ' + closerOf(open) + ' should close the ' + label(open) + ' opened at ' + at(open.loc), body.end.loc);
203
- }
204
- }
205
-
206
- function macroNode(tag, body) {
207
- const node = { type: 'macro', name: tag.lower, rawArgs: tag.rawArgs, children: [] };
208
- if (!body) return withSelectors(node, tag);
209
- checkBody(tag, body);
210
- node.children = body.children;
211
- if (BRANCHING.has(tag.lower)) {
212
- node.branches = [withSelectors({ rawArgs: tag.rawArgs, children: body.children }, tag)];
213
- for (const b of body.branches) {
214
- node.branches.push(withSelectors({ rawArgs: b.tag.rawArgs, children: b.children }, b.tag));
215
- }
216
- node.children = [];
217
- } else {
218
- withSelectors(node, tag);
219
- }
220
- return node;
221
197
  }
222
- }
223
-
224
- // ---------------------------------------------------------------- structure
225
-
226
- Markup
227
- = nodes:Content Tail { return nodes; }
228
-
229
- /** What ends the top level: the end, or a closer or branch with no opener. */
230
- Tail
231
- = !.
232
- / tag:BranchTag { fail(label(tag) + ' must be directly inside ' + LB + BRANCH_PARENT[tag.lower] + RB, tag.loc); }
233
- / tag:CloseTag { fail(label(tag) + ' closes nothing: no ' + (tag.lex === 'html' ? '<' + tag.tag + '>' : LB + tag.name + RB) + ' is open here', tag.loc); }
234
-
235
- Content
236
- = items:Item* { return joinText(items, nodeOf); }
237
-
238
- Item
239
- = TextRun
240
- / Escape
241
- / Comment
242
- / LinkLexeme
243
- / EmailAutolink
244
- / HtmlElement
245
- / VoidCloser
246
- / Value
247
- / MacroElement
248
- / Literal
249
-
250
- MacroElement
251
- = tag:MacroTag &{ return tag.kind === 'open'; }
252
- body:( &{ rawName = tag.lower; return hooks.isRaw(rawName); } b:RawBody { return b; }
253
- / &{ return hooks.isBlock(tag.lower); } b:BlockBody { return b; }
254
- / "" { return null; } )
255
- { return macroNode(tag, body); }
256
-
257
- HtmlElement
258
- = &{ return !textMode; } open:HtmlOpen
259
- body:( &{ return !open.isSelfClose; } b:BlockBody { return b; } )?
260
- {
261
- const node = { type: 'html', tag: open.tag, attributes: open.attributes, children: [] };
262
- if (body) {
263
- checkBody(open, body);
264
- node.children = body.children;
265
- }
266
- return node;
267
- }
268
-
269
- BlockBody
270
- = children:Content branches:BranchPart* end:BlockEnd { return { children, branches, end }; }
271
-
272
- BranchPart
273
- = tag:BranchTag children:Content { return { tag, children }; }
274
-
275
- BlockEnd
276
- = CloseTag
277
- / !. { return null; }
278
-
279
- BranchTag
280
- = tag:MacroTag &{ return tag.kind === 'branch'; } { return tag; }
281
-
282
- CloseTag
283
- = tag:MacroTag &{ return tag.kind === 'close'; } { return tag; }
284
- / &{ return !textMode; } tag:HtmlClose { return tag; }
285
-
286
- /** A raw body ({do}): JavaScript up to its closer, kept as one text node. */
287
- RawBody
288
- = start:Here &{ return skipTo(hooks.rawBodyEnd(input, start, rawName)); }
289
- body:$(.|{ return skipEnd - offset(); }|) end:CloseTag
290
- { return { children: body ? [{ type: 'text', value: body }] : [], branches: [], end }; }
291
- / "" { return { children: [], branches: [], end: null }; }
292
198
 
293
199
  // ------------------------------------------------------------- flat tokens
294
200
 
295
201
  Tokens
296
- = items:TokenItem* { return joinText(items, tokenOf); }
202
+ = items:TokenItem* { return joinText(items); }
297
203
 
298
204
  TokenItem
299
205
  = TextRun
@@ -309,6 +215,11 @@ TokenItem
309
215
  { return body ? [tag, body] : tag; }
310
216
  / Literal
311
217
 
218
+ /** The closing tag that ends a raw body. */
219
+ CloseTag
220
+ = tag:MacroTag &{ return tag.kind === 'close'; } { return tag; }
221
+ / &{ return !textMode; } tag:HtmlClose { return tag; }
222
+
312
223
  /** A raw body and its closer, as tokens; nothing if it is unclosed. */
313
224
  RawTokens
314
225
  = start:Here &{ return skipTo(hooks.rawBodyEnd(input, start, rawName)); }
@@ -368,10 +279,12 @@ Literal
368
279
  / "[" { return lexeme('text', location(), { value: '[' }); }
369
280
 
370
281
  LinkLexeme
371
- = &{ return !textMode; } "[[" s:Selectors at:Here inner:$LinkText "]]" {
372
- return withSelectors(lexeme('link', location(), parseLink(inner, at)), s);
282
+ = &{ return !textMode; } "[[" ss:Here s:Selectors at:Here inner:$LinkText "]]" {
283
+ const link = lexeme('link', location(), parseLink(inner, at, (separator) => linkSeparatorIndex(inner, at, separator)));
284
+ link.selectorSpan = selectorSpan(s, ss, at);
285
+ return withSelectors(link, s);
373
286
  }
374
- / &{ return !textMode; } "[[" { fail('Unclosed link: [[ without ]]', location()); }
287
+ / &{ return !textMode; } "[[" { fail('Unclosed link: [[ without ]]', location(), 'unclosed-link'); }
375
288
 
376
289
  /**
377
290
  * A link's text, up to the first ]]. (Nested [[…]] pairs, as the
@@ -399,13 +312,17 @@ SelectorChar
399
312
 
400
313
  /** A variable `{$a.b}` or expression `{$a + 1}`, `{(…)}`, `{!…}`. */
401
314
  Value
402
- = "{" s:Selectors sigil:[$_@%] name:$[a-zA-Z0-9_.]* "}" {
403
- return withSelectors(lexeme('variable', location(), { name, scope: SIGIL_SCOPES[sigil] }), s);
315
+ = "{" ss:Here s:Selectors sigil:[$_@%] nameStart:Here name:$[a-zA-Z0-9_.]* "}" {
316
+ const variable = lexeme('variable', location(), { name, nameStart, nameEnd: nameStart + name.length, scope: SIGIL_SCOPES[sigil] });
317
+ variable.selectorSpan = selectorSpan(s, ss, nameStart - 1);
318
+ return withSelectors(variable, s);
404
319
  }
405
- / "{" s:Selectors &[$_@%(!] expression:CodeToBrace "}" {
406
- return withSelectors(lexeme('expression', location(), { expression }), s);
320
+ / "{" ss:Here s:Selectors after:Here &[$_@%(!] expression:CodeToBrace "}" {
321
+ const node = lexeme('expression', location(), { expression, expressionStart: after, expressionEnd: after + expression.length });
322
+ node.selectorSpan = selectorSpan(s, ss, after);
323
+ return withSelectors(node, s);
407
324
  }
408
- / "{" Selectors &[$_@%(!] { fail('Unclosed ' + LB + input.substr(location().end.offset, 1) + '…: no ' + RB + ' ends it', location()); }
325
+ / "{" Selectors &[$_@%(!] { fail('Unclosed ' + LB + input.substr(location().end.offset, 1) + '…: no ' + RB + ' ends it', location(), 'unclosed-expression'); }
409
326
 
410
327
  /** JavaScript up to the } that ends it: where is up to options.hooks. */
411
328
  CodeToBrace
@@ -413,16 +330,21 @@ CodeToBrace
413
330
 
414
331
  /** A macro tag: `{name args}`, `{/name}`, with selectors on an opener. */
415
332
  MacroTag
416
- = "{" s:Selectors start:Here close:"/"? name:MacroName nameEnd:Here
333
+ = "{" ss:Here s:Selectors start:Here close:"/"? name:MacroName nameEnd:Here
417
334
  tail:( &{ return skipTo(hooks.closeBrace(input, nameEnd, start)); } args:$(.|{ return skipEnd - offset(); }|) "}" { return args; } )? {
418
335
  const loc = location();
419
336
  const lower = name.toLowerCase();
420
337
  const tag = lexeme('macro', loc, { name, lower, rawArgs: '', isClose: !!close });
421
- if (tail === null) fail('Unclosed ' + LB + (close ? '/' : '') + name + '…: no ' + RB + ' ends the macro', loc);
338
+ tag.nameStart = nameEnd - name.length;
339
+ tag.nameEnd = nameEnd;
340
+ tag.selectorSpan = selectorSpan(s, ss, start);
341
+ if (tail === null) fail('Unclosed ' + LB + (close ? '/' : '') + name + '…: no ' + RB + ' ends the macro', loc, 'unclosed-macro');
422
342
  tag.rawArgs = tail.trim();
343
+ tag.argsStart = tag.rawArgs ? nameEnd + tail.length - tail.trimStart().length : nameEnd;
344
+ tag.argsEnd = tag.argsStart + tag.rawArgs.length;
423
345
  if (close) {
424
- if (s !== NO_SELECTORS) fail('A closing tag takes no selectors: ' + label(tag), loc);
425
- if (tag.rawArgs) fail('A closing tag takes no arguments: ' + LB + '/' + name + ' ' + tag.rawArgs + RB, loc);
346
+ if (s !== NO_SELECTORS) fail('A closing tag takes no selectors: ' + label(tag), loc, 'closer-with-selectors');
347
+ if (tag.rawArgs) fail('A closing tag takes no arguments: ' + LB + '/' + name + ' ' + tag.rawArgs + RB, loc, 'closer-with-arguments');
426
348
  tag.kind = 'close';
427
349
  } else {
428
350
  withSelectors(tag, s);
@@ -430,7 +352,7 @@ MacroTag
430
352
  }
431
353
  return tag;
432
354
  }
433
- / "{" s:Selectors "/" { fail('A closing tag starts with a letter after ' + LB + '/', location()); }
355
+ / "{" s:Selectors "/" { fail('A closing tag starts with a letter after ' + LB + '/', location(), 'invalid-closer'); }
434
356
 
435
357
  /** A macro name: a letter, then anything up to whitespace or }. */
436
358
  MacroName
@@ -447,27 +369,23 @@ EmailAutolink
447
369
  &{ return EMAIL_AUTOLINK.test(value); }
448
370
  { return lexeme('text', location(), { value }); }
449
371
 
450
- /** A redundant closer of a void element (</br>), which is dropped. */
451
- VoidCloser
452
- = &{ return !textMode; } tag:HtmlClose &{ return VOID_TAGS.has(tag.lower); } { return null; }
453
-
454
372
  HtmlOpen
455
- = "<" tag:TagName list:Attribute* _ slash:"/"? ">" {
373
+ = "<" tagStart:Here tag:TagName list:Attribute* _ slash:"/"? ">" {
456
374
  const lower = tag.toLowerCase();
457
- return lexeme('html', location(), { tag, lower, attributes: attrs(list), isClose: false, isSelfClose: !!slash || VOID_TAGS.has(lower) });
375
+ return lexeme('html', location(), { tag, lower, tagNameStart: tagStart, tagNameEnd: tagStart + tag.length, attributes: attrs(list), attributeSpans: list, isClose: false, isSelfClose: !!slash || VOID_TAGS.has(lower) });
458
376
  }
459
377
  / "<" tag:TagName &(_c / "/" / ">" / !.) Attribute* _ bad:Here {
460
378
  // Only the offset of a location is used (parse.ts reads line and
461
379
  // column from it).
462
380
  const c = input.charAt(bad);
463
- if (!c) fail('Unclosed tag <' + tag + ': no > ends it (write &lt; for a < that starts no tag)', location());
381
+ if (!c) fail('Unclosed tag <' + tag + ': no > ends it (write &lt; for a < that starts no tag)', location(), 'unclosed-tag');
464
382
  const at = { source: location().source, start: { offset: bad, line: 0, column: 0 }, end: { offset: bad + 1, line: 0, column: 0 } };
465
- fail('Unexpected ' + JSON.stringify(c) + ' in the tag <' + tag + '>: expected an attribute, or > to end the tag', at);
383
+ fail('Unexpected ' + JSON.stringify(c) + ' in the tag <' + tag + '>: expected an attribute, or > to end the tag', at, 'unexpected-character');
466
384
  }
467
385
 
468
386
  HtmlClose
469
- = "</" tag:TagName _ ">" {
470
- return lexeme('html', location(), { tag, lower: tag.toLowerCase(), attributes: {}, isClose: true, isSelfClose: false });
387
+ = "</" tagStart:Here tag:TagName _ ">" {
388
+ return lexeme('html', location(), { tag, lower: tag.toLowerCase(), tagNameStart: tagStart, tagNameEnd: tagStart + tag.length, attributes: {}, attributeSpans: [], isClose: true, isSelfClose: false });
471
389
  }
472
390
 
473
391
  TagName
@@ -478,15 +396,22 @@ TagName
478
396
  * `>`, `/` or `=`; and not `<`, `{` or `}`, which markup can't use there.
479
397
  */
480
398
  Attribute
481
- = _ name:$(!(_c / ["'>/=<{}]) .)+ &{ attrCode = hooks.isCodeAttribute(name); return true; } value:(_ "=" _ v:AttrValue { return v; })? {
482
- return [name, value ?? ''];
399
+ = _ nameStart:Here name:$(!(_c / ["'>/=<{}]) .)+ &{ attrCode = hooks.isCodeAttribute(name); return true; } value:(_ "=" _ v:AttrValue { return v; })? {
400
+ const attribute = { name, value: value ? value.value : '', nameStart, nameEnd: nameStart + name.length };
401
+ if (value) {
402
+ attribute.valueStart = value.start;
403
+ attribute.valueEnd = value.end;
404
+ if (value.quote) attribute.quote = value.quote;
405
+ }
406
+ return attribute;
483
407
  }
484
408
 
409
+ /** An attribute value: its text, where that is written and its quote, if any. */
485
410
  AttrValue
486
- = '"' v:$(ValuePart / [^"])* '"' { return v; }
487
- / "'" v:$(ValuePart / [^'])* "'" { return v; }
488
- / q:["'] { fail('Unclosed attribute value: the ' + q + ' here has no closing ' + q, location()); }
489
- / $[^ \t\n\r\x0B\x0C\u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF>]*
411
+ = '"' start:Here value:$(ValuePart / [^"])* end:Here '"' { return { value, start, end, quote: '"' }; }
412
+ / "'" start:Here value:$(ValuePart / [^'])* end:Here "'" { return { value, start, end, quote: "'" }; }
413
+ / q:["'] { fail('Unclosed attribute value: the ' + q + ' here has no closing ' + q, location(), 'unclosed-attribute'); }
414
+ / start:Here value:$[^ \t\n\r\x0B\x0C\u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF>]* end:Here { return { value, start, end }; }
490
415
 
491
416
  /** Markup in a quoted value, whose quotes don't end the value. */
492
417
  ValuePart
@@ -43,48 +43,88 @@ export function withSelectors<T extends Selectors>(
43
43
  return target;
44
44
  }
45
45
 
46
+ /**
47
+ * Where a part of a token is written: `xStart` up to `xEnd`, for the part
48
+ * named `x` (UTF-16 offsets into the input).
49
+ */
50
+ export type Spans<Part extends string> = Record<
51
+ `${Part}Start` | `${Part}End`,
52
+ number
53
+ >;
54
+
55
+ /**
56
+ * Where the selectors of a token are written, without the space that may
57
+ * follow them. Both are absent for a token without selectors.
58
+ */
59
+ export type SelectorSpan = Partial<Spans<'selectors'>>;
60
+
46
61
  /** Where a token is in the input: from `start` up to `end`. */
47
- interface Span {
62
+ export interface Span {
48
63
  start: number;
49
64
  end: number;
50
65
  }
51
66
 
67
+ /** A token that may start with `.class#id` selectors. */
68
+ interface SelectorToken extends Span, Selectors, SelectorSpan {}
69
+
52
70
  export interface TextToken extends Span {
53
71
  type: 'text';
54
72
  value: string;
73
+ /** A closed HTML comment: markdown drops it, and so does raw rendering. */
74
+ comment?: true;
55
75
  }
56
76
 
57
- export interface LinkToken extends Span, Selectors {
77
+ /** `display` is where the label is written, `target` the target. */
78
+ export interface LinkToken
79
+ extends SelectorToken, Spans<'display'>, Spans<'target'> {
58
80
  type: 'link';
59
81
  display: string;
60
82
  target: string;
61
- /** Where the target is written, from `targetStart` to `targetEnd`. */
62
- targetStart: number;
63
- targetEnd: number;
64
83
  }
65
84
 
66
- export interface MacroToken extends Span, Selectors {
85
+ /**
86
+ * `name` is written after the `{`, the `/` and the selectors; `args`, where
87
+ * `rawArgs` is, is an empty span at `nameEnd` with no arguments.
88
+ */
89
+ export interface MacroToken
90
+ extends SelectorToken, Spans<'name'>, Spans<'args'> {
67
91
  type: 'macro';
68
92
  name: string;
69
93
  rawArgs: string;
70
94
  isClose: boolean;
71
95
  }
72
96
 
73
- export interface VariableToken extends Span, Selectors {
97
+ /** `name` is written without the sigil. */
98
+ export interface VariableToken extends SelectorToken, Spans<'name'> {
74
99
  type: 'variable';
75
100
  name: string;
76
101
  scope: VariableScope;
77
102
  }
78
103
 
79
- export interface ExpressionToken extends Span, Selectors {
104
+ /** `expression` is written after the `{` and the selectors. */
105
+ export interface ExpressionToken extends SelectorToken, Spans<'expression'> {
80
106
  type: 'expression';
81
107
  expression: string;
82
108
  }
83
109
 
84
- export interface HtmlToken extends Span {
110
+ /**
111
+ * An attribute of an HTML tag as it is written, in order. The value is
112
+ * written without its quotes, and absent with no `=`.
113
+ */
114
+ export interface AttributeSpan extends Spans<'name'>, Partial<Spans<'value'>> {
115
+ name: string;
116
+ /** The quote around the value, if it has one. */
117
+ quote?: '"' | "'";
118
+ }
119
+
120
+ /** `tagName` is where the tag name is written. */
121
+ export interface HtmlToken extends Span, Spans<'tagName'> {
85
122
  type: 'html';
86
123
  tag: string;
124
+ /** The attribute values by name; the first of equal names (any case). */
87
125
  attributes: Record<string, string>;
126
+ /** Every attribute as written, in order, duplicates included. */
127
+ attributeSpans: AttributeSpan[];
88
128
  isClose: boolean;
89
129
  isSelfClose: boolean;
90
130
  }