scholarly-parse 0.2.0 → 0.2.1

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 (94) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/README.md +3 -3
  3. package/changelog/0.2.x/0.2.1.md +45 -0
  4. package/dist/formats/html/metadata.d.ts +0 -8
  5. package/dist/formats/html/metadata.d.ts.map +1 -1
  6. package/dist/formats/html/metadata.js +18 -7
  7. package/dist/formats/html/metadata.js.map +1 -1
  8. package/dist/formats/html/references.d.ts.map +1 -1
  9. package/dist/formats/html/references.js +4 -18
  10. package/dist/formats/html/references.js.map +1 -1
  11. package/dist/formats/jats/blocks.d.ts.map +1 -1
  12. package/dist/formats/jats/blocks.js +57 -28
  13. package/dist/formats/jats/blocks.js.map +1 -1
  14. package/dist/formats/jats/fragment.d.ts +8 -2
  15. package/dist/formats/jats/fragment.d.ts.map +1 -1
  16. package/dist/formats/jats/fragment.js +187 -7
  17. package/dist/formats/jats/fragment.js.map +1 -1
  18. package/dist/formats/jats/front.d.ts +0 -5
  19. package/dist/formats/jats/front.d.ts.map +1 -1
  20. package/dist/formats/jats/front.js +49 -34
  21. package/dist/formats/jats/front.js.map +1 -1
  22. package/dist/formats/jats/inline.d.ts +3 -3
  23. package/dist/formats/jats/inline.d.ts.map +1 -1
  24. package/dist/formats/jats/inline.js +96 -40
  25. package/dist/formats/jats/inline.js.map +1 -1
  26. package/dist/formats/jats/parse.js +33 -5
  27. package/dist/formats/jats/parse.js.map +1 -1
  28. package/dist/formats/jats/references.d.ts +0 -5
  29. package/dist/formats/jats/references.d.ts.map +1 -1
  30. package/dist/formats/jats/references.js +153 -47
  31. package/dist/formats/jats/references.js.map +1 -1
  32. package/dist/formats/jats/text.d.ts +16 -0
  33. package/dist/formats/jats/text.d.ts.map +1 -1
  34. package/dist/formats/jats/text.js +77 -1
  35. package/dist/formats/jats/text.js.map +1 -1
  36. package/dist/formats/latexml/parse.d.ts +7 -1
  37. package/dist/formats/latexml/parse.d.ts.map +1 -1
  38. package/dist/formats/latexml/parse.js +42 -14
  39. package/dist/formats/latexml/parse.js.map +1 -1
  40. package/dist/formats/pdf/references.d.ts +0 -6
  41. package/dist/formats/pdf/references.d.ts.map +1 -1
  42. package/dist/formats/pdf/references.js +8 -2
  43. package/dist/formats/pdf/references.js.map +1 -1
  44. package/dist/formats/tei/parse.d.ts.map +1 -1
  45. package/dist/formats/tei/parse.js +39 -27
  46. package/dist/formats/tei/parse.js.map +1 -1
  47. package/dist/model/arxiv.d.ts +51 -0
  48. package/dist/model/arxiv.d.ts.map +1 -0
  49. package/dist/model/arxiv.js +167 -0
  50. package/dist/model/arxiv.js.map +1 -0
  51. package/dist/model/document.d.ts +17 -4
  52. package/dist/model/document.d.ts.map +1 -1
  53. package/dist/model/identifiers.d.ts +32 -0
  54. package/dist/model/identifiers.d.ts.map +1 -0
  55. package/dist/model/identifiers.js +61 -0
  56. package/dist/model/identifiers.js.map +1 -0
  57. package/dist/parse.d.ts +4 -1
  58. package/dist/parse.d.ts.map +1 -1
  59. package/dist/parse.js.map +1 -1
  60. package/dist/render/bare-url.d.ts +29 -0
  61. package/dist/render/bare-url.d.ts.map +1 -0
  62. package/dist/render/bare-url.js +207 -0
  63. package/dist/render/bare-url.js.map +1 -0
  64. package/dist/render/escape.d.ts +55 -9
  65. package/dist/render/escape.d.ts.map +1 -1
  66. package/dist/render/escape.js +217 -16
  67. package/dist/render/escape.js.map +1 -1
  68. package/dist/render/inline.d.ts +38 -55
  69. package/dist/render/inline.d.ts.map +1 -1
  70. package/dist/render/inline.js +682 -150
  71. package/dist/render/inline.js.map +1 -1
  72. package/dist/render/markdown.d.ts.map +1 -1
  73. package/dist/render/markdown.js +18 -6
  74. package/dist/render/markdown.js.map +1 -1
  75. package/dist/render/read-inline.d.ts +70 -0
  76. package/dist/render/read-inline.d.ts.map +1 -0
  77. package/dist/render/read-inline.js +376 -0
  78. package/dist/render/read-inline.js.map +1 -0
  79. package/dist/render/scan.d.ts +54 -0
  80. package/dist/render/scan.d.ts.map +1 -0
  81. package/dist/render/scan.js +145 -0
  82. package/dist/render/scan.js.map +1 -0
  83. package/dist/render/text.d.ts +3 -9
  84. package/dist/render/text.d.ts.map +1 -1
  85. package/dist/render/text.js +5 -160
  86. package/dist/render/text.js.map +1 -1
  87. package/dist/xml/ordered.d.ts.map +1 -1
  88. package/dist/xml/ordered.js +110 -14
  89. package/dist/xml/ordered.js.map +1 -1
  90. package/dist/xml/well-formed.d.ts +11 -3
  91. package/dist/xml/well-formed.d.ts.map +1 -1
  92. package/dist/xml/well-formed.js +25 -7
  93. package/dist/xml/well-formed.js.map +1 -1
  94. package/package.json +12 -8
@@ -4,29 +4,43 @@
4
4
  * TEI, or HTML.
5
5
  * @module src/render/inline
6
6
  */
7
- import { codeSpan, escapeInline, escapeTex, escapeUrl, isSafeUrl } from './escape.js';
7
+ import { bareUrlReader, codeSpan, escapeAutolink, escapeInline, escapeTex, escapeText, escapeUrl, isSafeUrl, oddBackslashesBefore, } from './escape.js';
8
+ import { charClass, readInline, wordSide } from './read-inline.js';
9
+ import { autolinkAt, codeSpanAt, codeSpanCloser, ESCAPABLE, insertBackslashes, pairBrackets, unpadCode, } from './scan.js';
8
10
  /**
9
11
  * Wrap already-rendered Markdown in an emphasis marker (`*`, `**`, `~~`). Whitespace at
10
12
  * the edges moves outside the markers, where CommonMark requires it, and empty content
11
- * renders as itself. The edges are found by trimming, which reads each end once.
13
+ * renders as itself. The edges are found by trimming, which reads each end once; a
14
+ * backslash the trim leaves at the end is escaped, so it does not escape the closer. A
15
+ * marker between punctuation inside and a word outside cannot open or close;
16
+ * `joinInlineSeams` repairs that once the text beside it is known.
12
17
  */
13
18
  export function emphasis(markdown, marker) {
14
19
  const core = markdown.trim();
15
20
  if (!core)
16
21
  return markdown;
17
22
  const lead = markdown.length - markdown.trimStart().length;
18
- return `${markdown.slice(0, lead)}${marker}${core}${marker}${markdown.slice(lead + core.length)}`;
23
+ const rest = markdown.slice(lead + core.length);
24
+ return `${markdown.slice(0, lead)}${marker}${closeBackslash(core)}${marker}${rest}`;
25
+ }
26
+ /** `markdown` with an odd backslash run at its end escaped, so it escapes nothing after it. */
27
+ function closeBackslash(markdown) {
28
+ let backslashes = 0;
29
+ while (markdown.charAt(markdown.length - 1 - backslashes) === '\\')
30
+ backslashes++;
31
+ return backslashes % 2 === 1 ? `${markdown}\\` : markdown;
19
32
  }
20
33
  /**
21
34
  * Two or more citation numbers joined by commas or dashes (`12,13`, `4–7`). A single
22
35
  * number is left alone: `10<sup>5</sup>` is an exponent, not a citation.
23
36
  */
24
- const CITATION_RUN = /^\d+(?:\s*[,\u2012\u2013\u2014-]\s*\d+)+$/;
37
+ const CITATION_RUN = /^\d+(?:\s*[,‒–—-]\s*\d+)+$/;
25
38
  /**
26
39
  * A superscript. Citation numbers become a bracketed marker (`[12,13]`), so they do not
27
40
  * fuse with the word before them; anything else uses TeX-style notation (`10^{-5}`,
28
41
  * `x^2`) that stays readable as plain text. A marker's text is escaped like any source
29
- * text.
42
+ * text, a backslash the trim leaves at the end is escaped, so it escapes nothing after the
43
+ * script, and a bare URL that ends a group is written as a link ({@link scriptGroup}).
30
44
  *
31
45
  * `isCitation` is the parser's judgment that the superscript holds only citation links;
32
46
  * an unlinked run of several citation numbers is recognized from its text.
@@ -38,53 +52,161 @@ export function superscript(markdown, plain, isCitation) {
38
52
  if (isCitation || CITATION_RUN.test(text)) {
39
53
  return `[${escapeInline(text.replace(/^\[|\]$/g, '').replace(/\s+/g, ''))}]`;
40
54
  }
41
- return [...text].length === 1 ? `^${markdown.trim()}` : `^{${markdown.trim()}}`;
55
+ return [...text].length === 1
56
+ ? `^${closeBackslash(markdown.trim())}`
57
+ : `^{${scriptGroup(markdown)}}`;
42
58
  }
43
- /** A subscript in TeX-style notation: `CO_2`, `IC_{50}`. */
59
+ /** A subscript in TeX-style notation: `CO_2`, `IC_{50}`, a group as {@link superscript} writes one. */
44
60
  export function subscript(markdown, plain) {
45
61
  const text = plain.trim();
46
62
  if (!text)
47
63
  return '';
48
- return [...text].length === 1 ? `_${markdown.trim()}` : `_{${markdown.trim()}}`;
64
+ return [...text].length === 1
65
+ ? `_${closeBackslash(markdown.trim())}`
66
+ : `_{${scriptGroup(markdown)}}`;
67
+ }
68
+ /**
69
+ * A sub- or superscript group's content, its bare URL at the end written as a link: GFM
70
+ * would read the group's closing `}` as part of the URL. Read as markup after it, the brace
71
+ * (a backtick standing in for it here) makes `repairSeams` write the URL as a link.
72
+ */
73
+ function scriptGroup(markdown) {
74
+ const content = closeBackslash(markdown.trim());
75
+ return BARE_URL_START.test(content) ? repairSeams(`${content}\``).slice(0, -1) : content;
49
76
  }
50
77
  /**
51
78
  * A link. An unsafe scheme (`javascript:`, `data:`) renders as its text only, or as the
52
- * target as escaped text when there is none; a link whose text is its own URL renders as
53
- * an autolink. A bracket in the text with no partner is escaped, so the link's own
54
- * brackets enclose the whole text.
79
+ * target as escaped text when there is none; a link whose text is its own URL, as written
80
+ * or as `escapeInline` writes it, renders as an autolink. A bracket in the text with no
81
+ * partner, or in a pair a `(` follows, is escaped, and so is a backslash the trim leaves at
82
+ * its end, so the link's own brackets enclose the whole text; a link the text holds is
83
+ * written as its text: links do not nest.
55
84
  */
56
85
  export function link(markdown, url) {
57
86
  const target = url?.trim();
58
87
  if (!target || !isSafeUrl(target))
59
88
  return markdown || escapeInline(target ?? '');
60
89
  const text = markdown.trim();
61
- if (!text || text === target || text === escapeUrlText(target))
62
- return `<${escapeUrl(target)}>`;
63
- return `[${escapeUnpaired(text)}](${escapeUrl(target)})`;
90
+ if (!text || text === target || text === escapeInline(target))
91
+ return `<${escapeAutolink(target)}>`;
92
+ const label = joinTouchingCode(unlinkText(joinTouchingCode(text)));
93
+ return `[${closeBackslash(escapeUnpaired(label))}](${escapeUrl(target)})`;
64
94
  }
65
95
  /**
66
- * Inline Markdown with a backslash before each bracket that {@link pairBrackets} leaves
67
- * unpaired. Brackets inside inline math are TeX, so they are left as written.
96
+ * `markdown` with its touching code spans joined as {@link joinInlineSeams} joins them, so
97
+ * link text reads its code spans, and the links and brackets between them, as the finished
98
+ * text will. A link written as its text can leave two spans touching, so `link` joins again
99
+ * after.
100
+ */
101
+ function joinTouchingCode(markdown) {
102
+ if (!markdown.includes('`'))
103
+ return markdown;
104
+ const out = [];
105
+ const codeSpanEnd = codeSpanCloser(markdown);
106
+ const touchingCode = touchingCodeReader(markdown);
107
+ const special = /[\\`<]/g;
108
+ let at = 0;
109
+ for (let found = special.exec(markdown); found; found = special.exec(markdown)) {
110
+ const start = found.index;
111
+ let end = start + 1;
112
+ if (found[0] === '\\') {
113
+ if (ESCAPABLE.test(markdown.charAt(end)))
114
+ end++;
115
+ }
116
+ else if (found[0] === '<') {
117
+ end = autolinkAt(markdown, start)?.end ?? end;
118
+ }
119
+ else {
120
+ const touching = touchingCode(start);
121
+ if (touching) {
122
+ out.push(markdown.slice(at, start), codeSpan(touching.text));
123
+ at = end = touching.end;
124
+ }
125
+ else {
126
+ end = codeSpanAt(markdown, start, codeSpanEnd).end;
127
+ }
128
+ }
129
+ special.lastIndex = end;
130
+ }
131
+ out.push(markdown.slice(at));
132
+ return out.join('');
133
+ }
134
+ /**
135
+ * Link text with a backslash before each bracket that {@link pairBrackets} leaves unpaired,
136
+ * and before both brackets of a pair a `(` follows: in link text such a pair can only be
137
+ * text that spells a link once the links in it are written as text, and links do not nest.
138
+ * Brackets inside inline math are TeX, so they are left as written.
68
139
  */
69
140
  function escapeUnpaired(markdown) {
70
- return insertBackslashes(markdown, pairBrackets(markdown, { skipMath: true }).unpaired);
141
+ const { pairs, unpaired } = pairBrackets(markdown, { skipMath: true });
142
+ const linkLike = [...pairs].filter(([, close]) => markdown.charAt(close + 1) === '(').flat();
143
+ return insertBackslashes(markdown, [...unpaired, ...linkLike].sort((a, b) => a - b));
71
144
  }
72
- /** `markdown` with a backslash inserted before the character at each of `positions`, in ascending order. */
73
- function insertBackslashes(markdown, positions) {
74
- if (positions.length === 0)
75
- return markdown;
145
+ /** What can start or end a link inside link text, or a span read past. */
146
+ const LINK_IN_TEXT = /[\\`<[\]]/g;
147
+ /**
148
+ * Link text with each autolink in it written as its URL as text, and each link `link`
149
+ * writes (`escapeInline`'s links for bare `www.` URLs among them) as its text. A link
150
+ * inside link text keeps the outer one from forming, which leaves the outer destination
151
+ * as text that GFM can link as a bare URL running into what follows; and GFM links no
152
+ * bare URL inside link text, so the explicit links that keep one from taking in an escape
153
+ * elsewhere are not needed there.
154
+ */
155
+ function unlinkText(markdown) {
156
+ const codeSpanEnd = codeSpanCloser(markdown);
157
+ const { pairs } = pairBrackets(markdown, { skipMath: true });
158
+ /** The `]` of each link being written as its text, and where its destination ends. */
159
+ const destinations = new Map();
160
+ const special = new RegExp(LINK_IN_TEXT);
76
161
  let out = '';
77
162
  let at = 0;
78
- for (const position of positions) {
79
- out += `${markdown.slice(at, position)}\\`;
80
- at = position;
163
+ for (let found = special.exec(markdown); found; found = special.exec(markdown)) {
164
+ const start = found.index;
165
+ let end = start + 1;
166
+ let text;
167
+ switch (found[0]) {
168
+ case '\\':
169
+ if (ESCAPABLE.test(markdown.charAt(end)))
170
+ end++;
171
+ break;
172
+ case '`':
173
+ end = codeSpanAt(markdown, start, codeSpanEnd).end;
174
+ break;
175
+ case '<': {
176
+ const autolink = autolinkAt(markdown, start);
177
+ if (autolink) {
178
+ end = autolink.end;
179
+ text = escapeText(autolink.target);
180
+ }
181
+ break;
182
+ }
183
+ case '[': {
184
+ const close = pairs.get(start);
185
+ if (close === undefined || markdown.charAt(close + 1) !== '(')
186
+ break;
187
+ LINK_DESTINATION.lastIndex = close + 2;
188
+ if (!LINK_DESTINATION.test(markdown))
189
+ break;
190
+ destinations.set(close, LINK_DESTINATION.lastIndex);
191
+ text = '';
192
+ break;
193
+ }
194
+ default: {
195
+ const destinationEnd = destinations.get(start);
196
+ if (destinationEnd === undefined)
197
+ break;
198
+ end = destinationEnd;
199
+ text = '';
200
+ }
201
+ }
202
+ if (text !== undefined) {
203
+ out += markdown.slice(at, start) + text;
204
+ at = end;
205
+ }
206
+ special.lastIndex = end;
81
207
  }
82
208
  return out + markdown.slice(at);
83
209
  }
84
- /** How `escapeInline` would have rendered a bare URL, to recognize link text equal to it. */
85
- function escapeUrlText(url) {
86
- return url.replace(/[*`$~]/g, '\\$&').replace(/_/g, '\\_');
87
- }
88
210
  /**
89
211
  * Where a formula stands that the source publishes only as an image: its content is not
90
212
  * in the text, and the marker keeps the sentence around it from reading as complete.
@@ -93,34 +215,69 @@ export const FORMULA_IMAGE = '[formula]';
93
215
  /** Inline math: `$tex$`. Empty TeX renders nothing. */
94
216
  export function inlineMath(tex) {
95
217
  const expression = tex.replace(/\s+/g, ' ').trim();
96
- return expression ? `$${escapeTex(expression)}$` : '';
97
- }
98
- /** What can start a seam to repair, or a span the seam pass leaves alone. */
99
- const SEAM = /[\\`<$\]]/g;
100
- /** ASCII punctuation, which a backslash escapes. */
101
- export const ESCAPABLE = /^[!-/:-@[-`{-~]$/;
102
- /** A destination `link` writes: a URL with a scheme it allows, then the closing parenthesis. */
103
- const LINK_DESTINATION = /(?:https?|ftp|mailto):[^\s()]*\)/iy;
218
+ return expression ? `$${escapeTex(expression, { inline: true })}$` : '';
219
+ }
220
+ /** What can start a seam to repair, a span the seam pass leaves alone, or a bare URL. */
221
+ const SEAM = /[\\`<$[\]]|https?:\/\/|www\./gi;
222
+ /**
223
+ * A destination `link` writes: a URL with a scheme it allows, as `escapeUrl` writes it, then
224
+ * the closing parenthesis. `escapeUrl` leaves no space, parenthesis, angle bracket, or
225
+ * backtick, writes every `$` as `\$`, and writes a backslash before punctuation only as `\\`
226
+ * or before `&` or `$`; a destination that runs into a code span, an autolink, or a formula
227
+ * another piece wrote is none it writes.
228
+ */
229
+ const LINK_DESTINATION = /(?:https?|ftp|mailto):(?:[^\s()<>`$\\]|\\[\\&$]|\\(?![!-/:-@[-`{-~]))*\)/iy;
104
230
  /**
105
231
  * Inline Markdown assembled from separately escaped pieces, with the seams between them
106
232
  * repaired: the escaping of each piece cannot see what the next one adds.
107
233
  *
108
234
  * - Touching inline formulas join into one (`$a$$b$` would read as a display-math
109
235
  * delimiter), with a space where the TeX at the joint would open an HTML tag or a link,
110
- * as `escapeTex` writes it. Source text never yields `$$` (its dollar signs are
111
- * escaped), so every `$$` is such a seam.
112
- * - A `](` that `link` did not write, one not followed by a web or mail destination, is
113
- * escaped, so no link forms with any other destination.
236
+ * as `escapeTex` writes it, or where a control word (`\alpha`) would take in the letters
237
+ * after it. Source text never yields `$$` (its dollar signs are escaped), so every `$$`
238
+ * is such a seam.
239
+ * - Touching code spans join into one (`touchingCodeReader`): their fences would meet as
240
+ * one run that closes neither.
241
+ * - A `](` that `link` did not write, one not followed by a web or mail destination as
242
+ * `escapeUrl` writes one, is escaped, so no link forms with any other destination, nor
243
+ * one that runs into a code span, autolink, or formula written after it.
244
+ * - A bare URL that an escape, a marker, or a link after it would join is written as an
245
+ * explicit link to the URL as the source has it (`bareUrlReader`), unless it stands inside
246
+ * link text, where GFM links no bare URL.
114
247
  * - A `!` before a link is escaped, so the link does not read as an image.
248
+ * - Two emphasis, strong, or strikethrough spans of one kind that touch, whose markers GFM
249
+ * reads as one run, join into one span ({@link joinTouchingSpans}): `**K****-step**`
250
+ * becomes `**K-step**`.
251
+ * - An emphasis, strong, or strikethrough pair that cannot form because punctuation at
252
+ * the emphasized text's edge meets a word outside the marker is repaired
253
+ * ({@link repairStuckMarkers}): the punctuation moves outside the marker
254
+ * (`*daf-16-*dependent` becomes `*daf-16*-dependent`), or, where that cannot work, the
255
+ * markers are dropped and the text kept.
115
256
  *
116
257
  * Code spans, autolinks, and link destinations are left as written, and a backslash
117
- * escapes only the one character after it, so an escaped backslash escapes nothing. The
118
- * text is read once, plus once more when it holds a `![`.
258
+ * escapes only the one character after it, so an escaped backslash escapes nothing. A
259
+ * joint or a repair can put a character GFM starts a bare URL after before a `www.`
260
+ * (`x*-www.` becomes `x-*www.`), and the backslash before a `](` can meet the bare URL
261
+ * that ends there (`https://a.co/x\](`), so the seams are read again wherever the text
262
+ * changed. The text is read once, plus once more when it holds a `![`, up to four times
263
+ * more when spans touch, up to four times more when a marker stands between punctuation
264
+ * and a word, and once more after any change.
119
265
  */
120
266
  export function joinInlineSeams(markdown) {
267
+ const joined = repairSeams(markdown);
268
+ const imaged = joined.includes('![') ? escapeImageOpeners(joined) : joined;
269
+ const repaired = repairStuckMarkers(joinTouchingSpans(imaged));
270
+ return repaired !== markdown ? repairSeams(repaired) : repaired;
271
+ }
272
+ /** The seams of `markdown` repaired, as {@link joinInlineSeams} lists them, up to its image openers and stuck markers. */
273
+ function repairSeams(markdown) {
121
274
  const out = [];
122
275
  const codeSpanEnd = codeSpanCloser(markdown);
276
+ const touchingCode = touchingCodeReader(markdown);
277
+ const bareUrlAt = bareUrlReader(markdown, linkOpeners(markdown));
123
278
  const seam = new RegExp(SEAM);
279
+ /** The `[` GFM has read and not yet closed: no bare URL links inside one. */
280
+ let labels = 0;
124
281
  let at = 0;
125
282
  for (let found = seam.exec(markdown); found; found = seam.exec(markdown)) {
126
283
  const start = found.index;
@@ -130,9 +287,17 @@ export function joinInlineSeams(markdown) {
130
287
  if (ESCAPABLE.test(markdown.charAt(end)))
131
288
  end++;
132
289
  break;
133
- case '`':
134
- end = codeSpanAt(markdown, start, codeSpanEnd).end;
290
+ case '`': {
291
+ const touching = touchingCode(start);
292
+ if (touching) {
293
+ out.push(markdown.slice(at, start), codeSpan(touching.text));
294
+ at = end = touching.end;
295
+ }
296
+ else {
297
+ end = codeSpanAt(markdown, start, codeSpanEnd).end;
298
+ }
135
299
  break;
300
+ }
136
301
  case '<':
137
302
  end = autolinkAt(markdown, start)?.end ?? end;
138
303
  break;
@@ -142,23 +307,120 @@ export function joinInlineSeams(markdown) {
142
307
  at = end = start + 2;
143
308
  }
144
309
  break;
145
- default:
146
- if (markdown.charAt(end) !== '(')
310
+ case '[':
311
+ labels++;
312
+ break;
313
+ case ']':
314
+ if (markdown.charAt(end) !== '(') {
315
+ labels = Math.max(0, labels - 1);
147
316
  break;
148
- LINK_DESTINATION.lastIndex = start + 2;
149
- if (LINK_DESTINATION.test(markdown)) {
150
- end = LINK_DESTINATION.lastIndex;
151
317
  }
152
- else {
318
+ LINK_DESTINATION.lastIndex = start + 2;
319
+ if (!LINK_DESTINATION.test(markdown)) {
153
320
  out.push(markdown.slice(at, start), '\\');
154
321
  at = start;
155
322
  }
323
+ else if (labels > 0) {
324
+ labels--;
325
+ end = LINK_DESTINATION.lastIndex;
326
+ }
327
+ break;
328
+ default: {
329
+ const url = labels === 0 ? bareUrlAt(start) : undefined;
330
+ if (!url)
331
+ break;
332
+ if (url.written !== markdown.slice(start, url.end)) {
333
+ out.push(markdown.slice(at, start), url.written);
334
+ at = url.end;
335
+ }
336
+ end = url.end;
337
+ }
156
338
  }
157
339
  seam.lastIndex = end;
158
340
  }
159
341
  out.push(markdown.slice(at));
160
- const joined = out.join('');
161
- return joined.includes('![') ? escapeImageOpeners(joined) : joined;
342
+ return out.join('');
343
+ }
344
+ /**
345
+ * Where each link `link` writes opens: a `[` GFM pairs with a `]` that a web or mail
346
+ * destination follows. Read only when the text holds a bare URL's start and a `[`.
347
+ */
348
+ function linkOpeners(markdown) {
349
+ const openers = new Set();
350
+ if (!markdown.includes('[') || !BARE_URL_START.test(markdown))
351
+ return openers;
352
+ for (const [open, close] of pairBrackets(markdown).pairs) {
353
+ if (markdown.charAt(close + 1) !== '(')
354
+ continue;
355
+ LINK_DESTINATION.lastIndex = close + 2;
356
+ if (LINK_DESTINATION.test(markdown))
357
+ openers.add(open);
358
+ }
359
+ return openers;
360
+ }
361
+ /** Where a bare URL can start. */
362
+ const BARE_URL_START = /https?:\/\/|www\./i;
363
+ /**
364
+ * A reader of the code spans in `markdown` that touch, read as `inlineCode` writes them:
365
+ * a span's fence is longer than any backtick run inside it, so it closes at the first run
366
+ * at least as long. Where one span's closing fence and the next one's opening fence meet,
367
+ * GFM reads them as one run that closes neither (`` `a``` `b` `` ``). Given where a span
368
+ * opens, the reader returns, when that span touches the next, the text of the touching
369
+ * spans joined, each as GFM reads a span's content, and where the last one ends. A run
370
+ * whose first backtick a backslash escapes opens one backtick later, with one fewer. Each
371
+ * fence is found once, and a span's closer by skipping runs too short to close it.
372
+ */
373
+ function touchingCodeReader(markdown) {
374
+ const starts = [];
375
+ const lengths = [];
376
+ const index = new Map();
377
+ /** Runs whose first backtick is escaped, by where the rest of the run starts. */
378
+ const escaped = new Map();
379
+ for (const { 0: run, index: start } of markdown.matchAll(/`+/g)) {
380
+ index.set(start, starts.length);
381
+ if (run.length > 1 && oddBackslashesBefore(markdown, start))
382
+ escaped.set(start + 1, starts.length);
383
+ starts.push(start);
384
+ lengths.push(run.length);
385
+ }
386
+ /** For each run, the next one at least as long, or the run count. */
387
+ const longer = new Array(starts.length).fill(starts.length);
388
+ const waiting = [];
389
+ for (let i = 0; i < starts.length; i++) {
390
+ while (waiting.length > 0 && (lengths[waiting.at(-1) ?? 0] ?? 0) <= (lengths[i] ?? 0))
391
+ longer[waiting.pop() ?? 0] = i;
392
+ waiting.push(i);
393
+ }
394
+ /** The first run after `after` at least `length` long. */
395
+ const closer = (after, length) => {
396
+ let at = after + 1;
397
+ while (at < starts.length && (lengths[at] ?? 0) < length)
398
+ at = longer[at] ?? starts.length;
399
+ return at;
400
+ };
401
+ return (start) => {
402
+ const unescaped = index.get(start);
403
+ const first = unescaped ?? escaped.get(start);
404
+ if (first === undefined)
405
+ return;
406
+ let fence = (lengths[first] ?? 0) - (unescaped === undefined ? 1 : 0);
407
+ let run = first;
408
+ let from = start + fence;
409
+ const parts = [];
410
+ for (;;) {
411
+ const close = closer(run, fence);
412
+ const closeStart = starts[close];
413
+ const closeLength = lengths[close] ?? 0;
414
+ if (closeStart === undefined)
415
+ return;
416
+ parts.push(unpadCode(markdown.slice(from, closeStart)));
417
+ if (closeLength === fence)
418
+ return run === first ? undefined : { end: closeStart + fence, text: parts.join('') };
419
+ run = close;
420
+ from = closeStart + closeLength;
421
+ fence = closeLength - fence;
422
+ }
423
+ };
162
424
  }
163
425
  /**
164
426
  * Inline Markdown as one finished run: whitespace collapsed and trimmed, then the seams
@@ -169,15 +431,35 @@ export function collapseInline(markdown) {
169
431
  }
170
432
  /**
171
433
  * What replaces the `$$` at `at` that joins two formulas: a space where the TeX on its two
172
- * sides would meet as `<` and a tag's first character or as `](`, and nothing elsewhere.
434
+ * sides would meet as `<` and a tag's first character, as `](`, or as a control word and
435
+ * a letter, and nothing elsewhere.
173
436
  */
174
437
  function mathJoint(markdown, at) {
175
438
  const before = markdown.charAt(at - 1);
176
439
  const after = markdown.charAt(at + 2);
177
- return (before === '<' && /[A-Za-z/!?]/.test(after)) || (before === ']' && after === '(')
440
+ return (before === '<' && /[A-Za-z/!?]/.test(after)) ||
441
+ (before === ']' && after === '(') ||
442
+ (ASCII_LETTER.test(after) && endsInControlWord(markdown, at))
178
443
  ? ' '
179
444
  : '';
180
445
  }
446
+ const ASCII_LETTER = /^[A-Za-z]$/;
447
+ /**
448
+ * True when the text before `end` ends in a TeX control word: ASCII letters after an odd
449
+ * run of backslashes (`\alpha`; in `\\b` the backslashes are a control symbol, and `b` a
450
+ * letter after it). Reads back only over that word, which no other joint reads.
451
+ */
452
+ function endsInControlWord(markdown, end) {
453
+ let at = end;
454
+ while (ASCII_LETTER.test(markdown.charAt(at - 1)))
455
+ at--;
456
+ if (at === end)
457
+ return false;
458
+ let backslashes = 0;
459
+ while (markdown.charAt(at - 1 - backslashes) === '\\')
460
+ backslashes++;
461
+ return backslashes % 2 === 1;
462
+ }
181
463
  /**
182
464
  * Markdown with a backslash before each `!` that would make the link after it an image,
183
465
  * its brackets paired as a renderer with math support pairs them or as one without does.
@@ -198,123 +480,373 @@ function escapeImageOpeners(markdown) {
198
480
  }
199
481
  return insertBackslashes(markdown, [...bangs].sort((a, b) => a - b));
200
482
  }
483
+ /** Where two spans can touch: a `*` run of two or more, or a `~` run of four or more, with no space on either side. */
484
+ function mayTouch(markdown) {
485
+ for (const { 0: run, index } of markdown.matchAll(/\*+|~+/g)) {
486
+ if (run.length >= (run.startsWith('*') ? 2 : 4) &&
487
+ charClass(markdown.charAt(index - 1)) !== 'space' &&
488
+ charClass(markdown.charAt(index + run.length)) !== 'space')
489
+ return true;
490
+ }
491
+ return false;
492
+ }
201
493
  /**
202
- * Each `[` paired with its `]` as CommonMark pairs them, in one pass: a bracket a
203
- * backslash escapes, or one inside a code span or an autolink, does not count, and nested
204
- * pairs balance on a stack. Inline math gets no special treatment, as in CommonMark,
205
- * unless `skipMath` asks for `$…$` to be read as a span too, as `stripInline` reads it.
206
- * `pairs` maps each paired `[` to its `]`; `unpaired` holds the rest, in ascending order.
494
+ * Markdown with each two spans of one kind that touch joined into one. Their markers meet
495
+ * as one run, which GFM cannot read as a closer and an opener: `**K****-step**` pairs `K`
496
+ * and leaves `-step**`, and `*a**b*` emphasizes `a**b`. Read as the pieces meant them
497
+ * (`readInline`'s `intended`), such a run closes the spans before it and opens those after
498
+ * it; the outermost on each side give up as many markers as the smaller of them holds, so
499
+ * `**K-step**`, `*ab*`, and `***a****b*` becomes `***a**b*`. Every character but the
500
+ * dropped markers stays. A run GFM already pairs as meant is left alone, and so is every
501
+ * run when a join would not pair the spans it joins or would leave more markers unpaired.
207
502
  */
208
- export function pairBrackets(markdown, { skipMath = false } = {}) {
209
- const pairs = new Map();
210
- const unpaired = [];
211
- const open = [];
212
- const codeSpanEnd = codeSpanCloser(markdown);
213
- const special = skipMath ? /[\\`<[\]$]/g : /[\\`<[\]]/g;
214
- let mathCloses = true;
215
- for (let found = special.exec(markdown); found; found = special.exec(markdown)) {
216
- const start = found.index;
217
- let end = start + 1;
218
- switch (found[0]) {
219
- case '\\':
220
- if (ESCAPABLE.test(markdown.charAt(end)))
221
- end++;
222
- break;
223
- case '`':
224
- end = codeSpanAt(markdown, start, codeSpanEnd).end;
225
- break;
226
- case '<':
227
- end = autolinkAt(markdown, start)?.end ?? end;
228
- break;
229
- case '$': {
230
- const close = mathCloses ? unescapedDollar(markdown, end) : -1;
231
- if (close === -1)
232
- mathCloses = false;
233
- if (close > end)
234
- end = close + 1;
235
- break;
236
- }
237
- case '[':
238
- open.push(start);
239
- break;
240
- default: {
241
- const opener = open.pop();
242
- if (opener === undefined)
243
- unpaired.push(start);
244
- else
245
- pairs.set(opener, start);
503
+ function joinTouchingSpans(markdown) {
504
+ if (!mayTouch(markdown))
505
+ return markdown;
506
+ const { runs } = readInline(markdown);
507
+ const written = new Map(runs.map((run) => [run.start, run]));
508
+ const joins = [];
509
+ for (const run of readInline(markdown, { intended: true }).runs) {
510
+ let opener = -1;
511
+ let closer = -1;
512
+ for (const other of run.partners.keys()) {
513
+ if (other > run.start)
514
+ closer = Math.max(closer, other);
515
+ else if (opener === -1 || other < opener)
516
+ opener = other;
517
+ }
518
+ if (opener === -1 || closer === -1 || samePairs(written.get(run.start), run))
519
+ continue;
520
+ const used = Math.min(run.partners.get(opener) ?? 0, run.partners.get(closer) ?? 0);
521
+ joins.push({ closer, opener, run, used });
522
+ }
523
+ if (joins.length === 0)
524
+ return markdown;
525
+ let out = '';
526
+ let at = 0;
527
+ /** Each joined run's start, and how many markers were dropped up to and in it. */
528
+ const starts = [];
529
+ const dropped = [];
530
+ for (const { run, used } of joins) {
531
+ out += markdown.slice(at, run.start) + run.char.repeat(run.length - 2 * used);
532
+ at = run.start + run.length;
533
+ starts.push(run.start);
534
+ dropped.push((dropped.at(-1) ?? 0) + 2 * used);
535
+ }
536
+ out += markdown.slice(at);
537
+ const moved = (position) => {
538
+ let low = 0;
539
+ let high = starts.length;
540
+ while (low < high) {
541
+ const middle = (low + high) >> 1;
542
+ if ((starts[middle] ?? 0) < position)
543
+ low = middle + 1;
544
+ else
545
+ high = middle;
546
+ }
547
+ return position - (dropped[low - 1] ?? 0);
548
+ };
549
+ const reread = readInline(out).runs;
550
+ const now = new Map(reread.map((run) => [run.start, run]));
551
+ const joined = joins.every(({ closer, opener, used }) => (now.get(moved(opener))?.partners.get(moved(closer)) ?? 0) >= used);
552
+ return joined && unpaired(reread) <= unpaired(runs) ? out : markdown;
553
+ }
554
+ /** True when `run` pairs with the same runs, by as many markers, in both readings. */
555
+ function samePairs(written, run) {
556
+ if (written?.partners.size !== run.partners.size)
557
+ return false;
558
+ for (const [other, used] of run.partners)
559
+ if (written.partners.get(other) !== used)
560
+ return false;
561
+ return true;
562
+ }
563
+ /**
564
+ * Markdown with each emphasis, strong, or strikethrough pair repaired that a word beside
565
+ * one of its markers keeps from forming. A run with a word on one side and punctuation on
566
+ * the other ({@link wordSide}) can take only one role: with a word before it, it cannot
567
+ * open (`a**(x)**`); with a word after it, it cannot close (`*daf-16-*dependent`). There the
568
+ * punctuation at the emphasized text's edge moves outside the marker, which then stands
569
+ * between it and the text: `a(**x**)b`, `*daf-16*-dependent`. Every character is kept, in
570
+ * the same order. An inline formula at the edge moves whole. Where the edge holds nothing
571
+ * that can move, or nothing but punctuation is emphasized, or the moved markers still do
572
+ * not pair, the pair's markers are dropped.
573
+ *
574
+ * A run can hold the markers of more than one pair (`**a *(b)***c`, where `***` closes
575
+ * both). Punctuation moves across all of a run's closing markers, or all of its opening
576
+ * ones, and a dropped pair takes only its own markers: `**Table 1*.***` becomes
577
+ * `**Table 1.**`.
578
+ *
579
+ * Pairs form as GFM forms them once each run with that shape may take either role, and
580
+ * are taken up starting from the runs that have no whole partner as written (GFM leaves
581
+ * them unpaired, or they share one): each pair one of them is in, then the pairs the
582
+ * written partners of either of its runs are in, and so on. Runs that pair whole with each
583
+ * other as written, and that no such chain reaches, keep their pairs. A repair that would
584
+ * break a pair GFM forms as written between runs no repair touches is not made, nor any
585
+ * other.
586
+ */
587
+ function repairStuckMarkers(markdown) {
588
+ const stuck = new Set();
589
+ for (const { 0: run, index } of markdown.matchAll(/\*+|~+/g)) {
590
+ if (wordSide(markdown, index, index + run.length))
591
+ stuck.add(index);
592
+ }
593
+ if (stuck.size === 0)
594
+ return markdown;
595
+ const { math, runs } = readInline(markdown);
596
+ const written = new Map(runs.map((run) => [run.start, run]));
597
+ /** Runs whose pairing as written gives way, each reached once. */
598
+ const reached = runs.filter((run) => !partnerOf(written, run));
599
+ if (reached.length === 0)
600
+ return markdown;
601
+ const freed = new Map(readInline(markdown, { unstick: stuck }).runs.map((run) => [run.start, run]));
602
+ const seen = new Set(reached.map((run) => run.start));
603
+ const pairs = [];
604
+ /** For each opener a pair is taken up for, the closers it is taken up with. */
605
+ const taken = new Map();
606
+ /** Runs a repair re-pairs. */
607
+ const repaired = new Set();
608
+ // The loop also visits the runs it adds.
609
+ for (const run of reached) {
610
+ for (const [other, used] of freed.get(run.start)?.partners ?? []) {
611
+ const self = freed.get(run.start);
612
+ const partner = freed.get(other);
613
+ if (!self || !partner || written.get(run.start)?.partners.get(other) === used)
614
+ continue;
615
+ const [opener, closer] = run.start < other ? [self, partner] : [partner, self];
616
+ const closers = taken.get(opener.start) ?? new Set();
617
+ if (closers.has(closer.start))
618
+ continue;
619
+ taken.set(opener.start, closers.add(closer.start));
620
+ const pair = stuckPair(markdown, math, opener, closer, used);
621
+ if (!pair)
622
+ continue;
623
+ pairs.push(pair);
624
+ for (const member of [opener, closer]) {
625
+ repaired.add(member.start);
626
+ for (const given of written.get(member.start)?.partners.keys() ?? []) {
627
+ const givenRun = written.get(given);
628
+ if (givenRun && !seen.has(given)) {
629
+ seen.add(given);
630
+ reached.push(givenRun);
631
+ }
632
+ }
246
633
  }
247
634
  }
248
- special.lastIndex = end;
249
635
  }
250
- return { pairs, unpaired: [...unpaired, ...open].sort((a, b) => a - b) };
636
+ if (pairs.length === 0)
637
+ return markdown;
638
+ const moves = pairs.filter((pair) => !pair.drop);
639
+ let result;
640
+ if (moves.length > 0) {
641
+ const moved = applyRepairs(markdown, moves);
642
+ const movedRuns = readInline(moved).runs;
643
+ const reread = new Map(movedRuns.map((run) => [run.start, run]));
644
+ const at = markerRuns(movedRuns);
645
+ const edges = runRepairs(moves);
646
+ for (const pair of moves) {
647
+ const { lead } = edges.get(pair.opener.start) ?? { lead: 0 };
648
+ const { trail } = edges.get(pair.closer.start) ?? { trail: 0 };
649
+ // Moves keep the length, so a run's closing markers start where its trail begins.
650
+ const opener = at.get(pair.opener.start + pair.opener.closed + lead);
651
+ const closer = at.get(pair.closer.start - trail);
652
+ if (!opener || !closer || (opener.partners.get(closer.start) ?? 0) < pair.used)
653
+ pair.drop = true;
654
+ }
655
+ // Moves keep the length, so runs no repair touches start where they did.
656
+ for (const run of written.values()) {
657
+ const partner = partnerOf(written, run);
658
+ if (!partner || repaired.has(run.start) || repaired.has(partner.start))
659
+ continue;
660
+ if (partnerOf(reread, run)?.start !== partner.start)
661
+ return markdown;
662
+ }
663
+ if (!pairs.some((pair) => pair.drop))
664
+ result = { markdown: moved, runs: movedRuns };
665
+ }
666
+ if (!result) {
667
+ const dropped = applyRepairs(markdown, pairs);
668
+ result = { markdown: dropped, runs: readInline(dropped).runs };
669
+ }
670
+ // Dropping markers can change how the runs beside them flank.
671
+ return unpaired(result.runs) <= unpaired(runs) ? result.markdown : markdown;
672
+ }
673
+ /** Each marker character's position mapped to the run it is in. */
674
+ function markerRuns(runs) {
675
+ const at = new Map();
676
+ for (const run of runs)
677
+ for (let i = 0; i < run.length; i++)
678
+ at.set(run.start + i, run);
679
+ return at;
680
+ }
681
+ /** How many marker characters `runs` leave without a partner. */
682
+ function unpaired(runs) {
683
+ return runs.reduce((sum, run) => sum + run.left, 0);
684
+ }
685
+ /**
686
+ * The run `run` pairs with whole in `runs`, where each run is the other's only partner and
687
+ * both are used up; undefined where it has none, or shares one.
688
+ */
689
+ function partnerOf(runs, run) {
690
+ const self = runs.get(run.start);
691
+ if (self?.left !== 0 || self.partners.size !== 1)
692
+ return;
693
+ const [start] = self.partners.keys();
694
+ const partner = runs.get(start ?? -1);
695
+ return partner?.left === 0 && partner.partners.size === 1 ? partner : undefined;
696
+ }
697
+ /**
698
+ * The repair of the pair `opener`…`closer`, which takes `used` markers from each: the edge
699
+ * punctuation each blocked marker moves past, or `drop` when a blocked marker has none to
700
+ * move past, when the moves would empty the emphasized text, or when a marker would come
701
+ * to touch another run of its character. Undefined when neither marker is blocked: the
702
+ * pair fails because of another pair.
703
+ */
704
+ function stuckPair(markdown, math, opener, closer, used) {
705
+ const blockedOpener = wordSide(markdown, opener.start, opener.start + opener.length) === 'before';
706
+ const blockedCloser = wordSide(markdown, closer.start, closer.start + closer.length) === 'after';
707
+ if (!blockedOpener && !blockedCloser)
708
+ return;
709
+ const from = opener.start + opener.length;
710
+ const to = closer.start;
711
+ const lead = blockedOpener ? leadingEdge(markdown, math, from, to) : 0;
712
+ const trail = blockedCloser ? trailingEdge(markdown, math, from + lead, to) : 0;
713
+ const drop = (blockedOpener && (lead === 0 || markdown.charAt(from + lead) === opener.char)) ||
714
+ (blockedCloser && (trail === 0 || markdown.charAt(to - trail - 1) === closer.char)) ||
715
+ from + lead >= to - trail;
716
+ return { closer, drop, lead, opener, trail, used };
717
+ }
718
+ /**
719
+ * Punctuation a marker does not move past: markup this package writes (markers, code,
720
+ * math, autolinks, links, an image's `!`), an entity's `&`, and the `_`, `^`, and braces
721
+ * of sub- and superscripts. A backslash moves only with the character it escapes, and a
722
+ * `$` only with the formula it opens or closes.
723
+ */
724
+ const STAYS = new Set(['*', '~', '`', '$', '<', '>', '[', ']', '!', '&', '\\', '_', '^', '{', '}']);
725
+ /** True when the character at `at` can move across a marker: whitespace, or punctuation not in {@link STAYS}, nor a `)` that ends a link. */
726
+ function movable(markdown, at) {
727
+ const char = markdown.charAt(at);
728
+ const kind = charClass(char);
729
+ if (kind === 'space')
730
+ return true;
731
+ return kind === 'punctuation' && !STAYS.has(char) && !(char === ')' && endsLink(markdown, at));
251
732
  }
733
+ const PARENTHESIS_OR_SPACE = /^[()\s]$/;
252
734
  /**
253
- * The backtick run at `start`, and the code span it opens: `content` is undefined, and
254
- * `end` the end of the run, when no run of its length closes it.
735
+ * True when the `)` at `at` ends a link's destination: a `](` comes before it with
736
+ * nothing but a destination's characters between. Reads back only over that destination,
737
+ * which holds no parenthesis, so no other `)` reads the same stretch.
255
738
  */
256
- export function codeSpanAt(markdown, start, codeSpanEnd) {
257
- let open = start + 1;
258
- while (markdown.charAt(open) === '`')
259
- open++;
260
- const close = codeSpanEnd(open - start, open);
261
- if (close === undefined)
262
- return { end: open };
263
- return { content: markdown.slice(open, close), end: close + open - start };
739
+ function endsLink(markdown, at) {
740
+ let open = at - 1;
741
+ while (open >= 0 && !PARENTHESIS_OR_SPACE.test(markdown.charAt(open)))
742
+ open--;
743
+ if (markdown.charAt(open) !== '(' || markdown.charAt(open - 1) !== ']')
744
+ return false;
745
+ let backslashes = 0;
746
+ while (markdown.charAt(open - 2 - backslashes) === '\\')
747
+ backslashes++;
748
+ return backslashes % 2 === 0;
264
749
  }
265
750
  /**
266
- * A finder of code-span closers for `markdown`: the start of the first run of exactly
267
- * `length` backticks at or after `from`, which a run of that length opening before
268
- * `from` closes. Runs are found once, and the search for each length only moves forward,
269
- * as the text is read.
751
+ * How many characters from `from` on, before `to`, can move before an opener at `from`. A
752
+ * backslash escape moves whole, and so does an inline formula right at the edge (`math`
753
+ * maps each one's first `$` to its last); past moved punctuation, the marker can stand
754
+ * beside a formula's `$`.
270
755
  */
271
- export function codeSpanCloser(markdown) {
272
- const starts = new Map();
273
- for (const run of markdown.matchAll(/`+/g)) {
274
- const list = starts.get(run[0].length);
275
- if (list)
276
- list.push(run.index);
277
- else
278
- starts.set(run[0].length, [run.index]);
756
+ function leadingEdge(markdown, math, from, to) {
757
+ let at = from;
758
+ while (at < to) {
759
+ const char = markdown.charAt(at);
760
+ const formulaEnd = char === '$' ? (math.get(at) ?? at) : at;
761
+ if (char === '\\') {
762
+ if (!ESCAPABLE.test(markdown.charAt(at + 1)))
763
+ break;
764
+ at += 2;
765
+ }
766
+ else if (at === from && formulaEnd > at && formulaEnd < to) {
767
+ at = formulaEnd + 1;
768
+ }
769
+ else if (movable(markdown, at)) {
770
+ at++;
771
+ }
772
+ else {
773
+ break;
774
+ }
279
775
  }
280
- const next = new Map();
281
- return (length, from) => {
282
- const list = starts.get(length) ?? [];
283
- let i = next.get(length) ?? 0;
284
- while (i < list.length && (list[i] ?? from) < from)
285
- i++;
286
- next.set(length, i);
287
- return list[i];
288
- };
776
+ return at - from;
289
777
  }
290
778
  /**
291
- * The first `$` at or after `from` that no odd run of backslashes escapes, counting none
292
- * before `from`, or -1. When there is none, there is none after a later `$` either.
779
+ * How many characters before `to`, after `from`, can move after a closer at `to`. A
780
+ * backslash escape moves whole, with any escaped backslashes before it, and so does an
781
+ * inline formula right at the edge.
293
782
  */
294
- export function unescapedDollar(markdown, from) {
295
- for (let at = markdown.indexOf('$', from); at !== -1; at = markdown.indexOf('$', at + 1)) {
783
+ function trailingEdge(markdown, math, from, to) {
784
+ let at = to;
785
+ while (at > from) {
786
+ const char = markdown.charAt(at - 1);
787
+ const formulaStart = char === '$' ? (math.get(at - 1) ?? at) : at;
296
788
  let backslashes = 0;
297
- for (let i = at - 1; i >= from && markdown.charAt(i) === '\\'; i--)
789
+ while (at - 2 - backslashes >= from && markdown.charAt(at - 2 - backslashes) === '\\')
298
790
  backslashes++;
299
- if (backslashes % 2 === 0)
300
- return at;
791
+ if (char === '\\' || (backslashes % 2 === 1 && ESCAPABLE.test(char))) {
792
+ // Escaped backslashes, or a character a backslash escapes: what comes after a run
793
+ // of backslashes is never escaped by an odd one, or the marker would be.
794
+ at -= backslashes + 1;
795
+ }
796
+ else if (at === to && formulaStart < at - 1 && formulaStart >= from) {
797
+ at = formulaStart;
798
+ }
799
+ else if (movable(markdown, at - 1)) {
800
+ at--;
801
+ }
802
+ else {
803
+ break;
804
+ }
301
805
  }
302
- return -1;
806
+ return to - at;
807
+ }
808
+ /** Each run the pairs are in, by where it starts, with what its pairs ask of it. */
809
+ function runRepairs(pairs) {
810
+ const repairs = new Map();
811
+ const of = (run) => {
812
+ const repair = repairs.get(run.start) ?? { closing: 0, lead: 0, opening: 0, run, trail: 0 };
813
+ repairs.set(run.start, repair);
814
+ return repair;
815
+ };
816
+ for (const { closer, drop, lead, opener, trail, used } of pairs) {
817
+ if (drop) {
818
+ of(opener).opening += used;
819
+ of(closer).closing += used;
820
+ }
821
+ else {
822
+ of(opener).lead = Math.max(of(opener).lead, lead);
823
+ of(closer).trail = Math.max(of(closer).trail, trail);
824
+ }
825
+ }
826
+ return repairs;
303
827
  }
304
- /** An autolink's target: a URL with a scheme `link` writes as one. */
305
- const AUTOLINK_TARGET = /^(?:https?|ftp|mailto):[\s\S]/i;
306
828
  /**
307
- * An autolink at `start`: its target up to the next `>`, which no `<` comes before (a
308
- * written URL has its angle brackets percent-encoded).
829
+ * `markdown` with each pair's repair written: its edge punctuation moved across its runs'
830
+ * opening or closing markers, or its markers dropped. Moves never overlap: punctuation
831
+ * moves only up to the next run, and a pair whose emphasized text is all such punctuation
832
+ * is dropped, not moved.
309
833
  */
310
- export function autolinkAt(markdown, start) {
311
- const angle = /[<>]/g;
312
- angle.lastIndex = start + 1;
313
- const close = angle.exec(markdown);
314
- if (close?.[0] !== '>')
315
- return;
316
- const target = markdown.slice(start + 1, close.index);
317
- return AUTOLINK_TARGET.test(target) ? { end: close.index + 1, target } : undefined;
834
+ function applyRepairs(markdown, pairs) {
835
+ const edits = [...runRepairs(pairs).values()].sort((a, b) => a.run.start - b.run.start);
836
+ let out = '';
837
+ let at = 0;
838
+ for (const { closing, lead, opening, run, trail } of edits) {
839
+ const start = run.start - trail;
840
+ const end = run.start + run.length;
841
+ out +=
842
+ markdown.slice(at, start) +
843
+ run.char.repeat(run.closed - closing) +
844
+ markdown.slice(start, run.start) +
845
+ markdown.slice(end, end + lead) +
846
+ run.char.repeat(run.length - run.closed - opening);
847
+ at = end + lead;
848
+ }
849
+ return out + markdown.slice(at);
318
850
  }
319
851
  /** Inline code. */
320
852
  export function inlineCode(text) {