@diegopluna/narvi 0.1.0 → 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.
Files changed (259) hide show
  1. package/README.md +102 -41
  2. package/dist/base.css +2 -2
  3. package/dist/color.d.ts +1 -1
  4. package/dist/color.js +1 -1
  5. package/dist/components/activity/ActivityContent.svelte +3 -15
  6. package/dist/components/activity/ActivityStep.svelte +12 -12
  7. package/dist/components/activity/ActivityThought.svelte +4 -4
  8. package/dist/components/activity/ActivityTrigger.svelte +3 -3
  9. package/dist/components/app-shell/AppShellBar.svelte +89 -0
  10. package/dist/components/app-shell/AppShellBar.svelte.d.ts +20 -0
  11. package/dist/components/app-shell/AppShellHeader.svelte +17 -16
  12. package/dist/components/app-shell/AppShellHeader.svelte.d.ts +2 -2
  13. package/dist/components/app-shell/AppShellMain.svelte +4 -20
  14. package/dist/components/app-shell/AppShellPanel.svelte +21 -19
  15. package/dist/components/app-shell/AppShellPanes.svelte +58 -0
  16. package/dist/components/app-shell/AppShellPanes.svelte.d.ts +11 -0
  17. package/dist/components/app-shell/AppShellRail.svelte +85 -0
  18. package/dist/components/app-shell/AppShellRail.svelte.d.ts +11 -0
  19. package/dist/components/app-shell/AppShellRoot.svelte +50 -24
  20. package/dist/components/app-shell/AppShellRoot.svelte.d.ts +8 -6
  21. package/dist/components/app-shell/AppShellSheet.svelte +95 -0
  22. package/dist/components/app-shell/AppShellSheet.svelte.d.ts +17 -0
  23. package/dist/components/app-shell/AppShellSidebar.svelte +37 -61
  24. package/dist/components/app-shell/AppShellSidebar.svelte.d.ts +1 -5
  25. package/dist/components/app-shell/AppShellToggle.svelte +62 -23
  26. package/dist/components/app-shell/AppShellToggle.svelte.d.ts +2 -0
  27. package/dist/components/app-shell/context.d.ts +6 -0
  28. package/dist/components/app-shell/index.d.ts +9 -1
  29. package/dist/components/app-shell/index.js +5 -1
  30. package/dist/components/approval/Approval.svelte +91 -19
  31. package/dist/components/approval/Approval.svelte.d.ts +7 -0
  32. package/dist/components/avatar/AvatarFallback.svelte +1 -2
  33. package/dist/components/avatar/AvatarRoot.svelte +2 -2
  34. package/dist/components/badge/Badge.svelte +5 -5
  35. package/dist/components/button/Button.svelte +219 -40
  36. package/dist/components/button/Button.svelte.d.ts +38 -2
  37. package/dist/components/card/Card.svelte +15 -26
  38. package/dist/components/change-stats/ChangeStats.svelte +1 -2
  39. package/dist/components/changes-summary/ChangesSummary.svelte +14 -15
  40. package/dist/components/checkbox/Checkbox.svelte +18 -15
  41. package/dist/components/checkbox/Checkbox.svelte.d.ts +5 -0
  42. package/dist/components/code/Code.svelte +1 -2
  43. package/dist/components/collapsible/CollapsibleTrigger.svelte +2 -2
  44. package/dist/components/command/CommandItem.svelte +1 -1
  45. package/dist/components/command/styles.d.ts +3 -2
  46. package/dist/components/command/styles.js +13 -10
  47. package/dist/components/composer/ComposerAttachButton.svelte +1 -1
  48. package/dist/components/composer/ComposerAttachment.svelte +9 -12
  49. package/dist/components/composer/ComposerModelPicker.svelte +18 -20
  50. package/dist/components/composer/ComposerRoot.svelte +8 -7
  51. package/dist/components/composer/ComposerSubmit.svelte +8 -15
  52. package/dist/components/composer/ComposerTextarea.svelte +1 -1
  53. package/dist/components/composer/ComposerToggle.svelte +9 -11
  54. package/dist/components/composer/ComposerTray.svelte +78 -0
  55. package/dist/components/composer/ComposerTray.svelte.d.ts +15 -0
  56. package/dist/components/composer/index.d.ts +3 -1
  57. package/dist/components/composer/index.js +3 -2
  58. package/dist/components/conversation/ConversationContent.svelte +3 -2
  59. package/dist/components/conversation/ConversationEmpty.svelte +1 -1
  60. package/dist/components/conversation/ConversationScrollButton.svelte +3 -3
  61. package/dist/components/dialog/ConfirmDialog.svelte +1 -1
  62. package/dist/components/dialog/styles.d.ts +2 -3
  63. package/dist/components/dialog/styles.js +5 -6
  64. package/dist/components/divider/Divider.svelte +3 -3
  65. package/dist/components/empty-state/EmptyState.svelte +4 -5
  66. package/dist/components/field/Field.svelte +4 -4
  67. package/dist/components/frame/Frame.svelte +6 -7
  68. package/dist/components/frame/Frame.svelte.d.ts +1 -1
  69. package/dist/components/heading/Heading.svelte +2 -2
  70. package/dist/components/kbd/Kbd.svelte +12 -7
  71. package/dist/components/link/Link.svelte +7 -3
  72. package/dist/components/link/Link.svelte.d.ts +4 -1
  73. package/dist/components/markdown/Markdown.svelte +714 -0
  74. package/dist/components/markdown/Markdown.svelte.d.ts +80 -0
  75. package/dist/components/markdown/MarkdownBlock.svelte +231 -0
  76. package/dist/components/markdown/MarkdownBlock.svelte.d.ts +11 -0
  77. package/dist/components/markdown/MarkdownBlocks.svelte +115 -0
  78. package/dist/components/markdown/MarkdownBlocks.svelte.d.ts +15 -0
  79. package/dist/components/markdown/MarkdownCode.svelte +583 -0
  80. package/dist/components/markdown/MarkdownCode.svelte.d.ts +23 -0
  81. package/dist/components/markdown/MarkdownDiagram.svelte +310 -0
  82. package/dist/components/markdown/MarkdownDiagram.svelte.d.ts +6 -0
  83. package/dist/components/markdown/MarkdownFile.svelte +134 -0
  84. package/dist/components/markdown/MarkdownFile.svelte.d.ts +19 -0
  85. package/dist/components/markdown/MarkdownFootnotes.svelte +61 -0
  86. package/dist/components/markdown/MarkdownFootnotes.svelte.d.ts +8 -0
  87. package/dist/components/markdown/MarkdownFresh.svelte +69 -0
  88. package/dist/components/markdown/MarkdownFresh.svelte.d.ts +6 -0
  89. package/dist/components/markdown/MarkdownHtml.svelte +72 -0
  90. package/dist/components/markdown/MarkdownHtml.svelte.d.ts +7 -0
  91. package/dist/components/markdown/MarkdownImage.svelte +150 -0
  92. package/dist/components/markdown/MarkdownImage.svelte.d.ts +8 -0
  93. package/dist/components/markdown/MarkdownInlines.svelte +225 -0
  94. package/dist/components/markdown/MarkdownInlines.svelte.d.ts +7 -0
  95. package/dist/components/markdown/MarkdownLink.svelte +120 -0
  96. package/dist/components/markdown/MarkdownLink.svelte.d.ts +25 -0
  97. package/dist/components/markdown/MarkdownMath.svelte +138 -0
  98. package/dist/components/markdown/MarkdownMath.svelte.d.ts +7 -0
  99. package/dist/components/markdown/MarkdownTable.svelte +265 -0
  100. package/dist/components/markdown/MarkdownTable.svelte.d.ts +17 -0
  101. package/dist/components/markdown/caret.d.ts +14 -0
  102. package/dist/components/markdown/caret.js +67 -0
  103. package/dist/components/markdown/context.d.ts +93 -0
  104. package/dist/components/markdown/context.js +128 -0
  105. package/dist/components/markdown/copy.d.ts +13 -0
  106. package/dist/components/markdown/copy.js +74 -0
  107. package/dist/components/markdown/hidden.d.ts +12 -0
  108. package/dist/components/markdown/hidden.js +31 -0
  109. package/dist/components/markdown/kept.d.ts +32 -0
  110. package/dist/components/markdown/kept.js +71 -0
  111. package/dist/components/markdown/labels.d.ts +46 -0
  112. package/dist/components/markdown/labels.js +35 -0
  113. package/dist/components/markdown/save.d.ts +11 -0
  114. package/dist/components/markdown/save.js +58 -0
  115. package/dist/components/markdown/scrollable.d.ts +24 -0
  116. package/dist/components/markdown/scrollable.js +152 -0
  117. package/dist/components/markdown/static.d.ts +37 -0
  118. package/dist/components/markdown/static.js +233 -0
  119. package/dist/components/markdown/styles.d.ts +328 -0
  120. package/dist/components/markdown/styles.js +302 -0
  121. package/dist/components/menu/MenuRadioItem.svelte +3 -3
  122. package/dist/components/menu/index.d.ts +23 -0
  123. package/dist/components/menu/index.js +3 -1
  124. package/dist/components/message/MessageAction.svelte +22 -2
  125. package/dist/components/message/MessageAction.svelte.d.ts +9 -0
  126. package/dist/components/message/MessageContent.svelte +2 -3
  127. package/dist/components/message/MessageCopy.svelte +62 -3
  128. package/dist/components/message/MessageCopy.svelte.d.ts +17 -1
  129. package/dist/components/message/MessageHeader.svelte +3 -3
  130. package/dist/components/message/MessagePending.svelte +1 -1
  131. package/dist/components/message/MessageTime.svelte +1 -1
  132. package/dist/components/notice/Notice.svelte +14 -10
  133. package/dist/components/plan/Plan.svelte +22 -17
  134. package/dist/components/progress/Progress.svelte +31 -33
  135. package/dist/components/questionnaire/Questionnaire.svelte +19 -22
  136. package/dist/components/queued-message/QueuedMessage.svelte +14 -7
  137. package/dist/components/rail/RailItem.svelte +37 -34
  138. package/dist/components/rail/RailItem.svelte.d.ts +3 -1
  139. package/dist/components/rail/RailRoot.svelte +18 -4
  140. package/dist/components/rail/RailRoot.svelte.d.ts +1 -1
  141. package/dist/components/rail/RailSeparator.svelte +17 -0
  142. package/dist/components/rail/RailSeparator.svelte.d.ts +18 -0
  143. package/dist/components/rail/index.d.ts +2 -1
  144. package/dist/components/rail/index.js +2 -1
  145. package/dist/components/reasoning/ReasoningContent.svelte +4 -8
  146. package/dist/components/reasoning/ReasoningTrigger.svelte +2 -2
  147. package/dist/components/resize-handle/ResizeHandle.svelte +2 -3
  148. package/dist/components/segmented/SegmentedControl.svelte +7 -8
  149. package/dist/components/select/Select.svelte +1 -1
  150. package/dist/components/separator/Separator.svelte +1 -1
  151. package/dist/components/settings-row/SettingsRow.svelte +5 -5
  152. package/dist/components/shimmer/Shimmer.svelte +34 -21
  153. package/dist/components/sidebar/SidebarContent.svelte +1 -1
  154. package/dist/components/sidebar/SidebarFolder.svelte +142 -0
  155. package/dist/components/sidebar/SidebarFolder.svelte.d.ts +19 -0
  156. package/dist/components/sidebar/SidebarFooter.svelte +1 -1
  157. package/dist/components/sidebar/SidebarGroup.svelte +36 -32
  158. package/dist/components/sidebar/SidebarGroup.svelte.d.ts +3 -3
  159. package/dist/components/sidebar/SidebarHeader.svelte +12 -6
  160. package/dist/components/sidebar/SidebarHeader.svelte.d.ts +4 -1
  161. package/dist/components/sidebar/SidebarItem.svelte +26 -32
  162. package/dist/components/sidebar/SidebarRoot.svelte +62 -0
  163. package/dist/components/sidebar/SidebarRoot.svelte.d.ts +14 -0
  164. package/dist/components/sidebar/index.d.ts +5 -1
  165. package/dist/components/sidebar/index.js +3 -1
  166. package/dist/components/skeleton/Skeleton.svelte +26 -15
  167. package/dist/components/slider/Slider.svelte +11 -10
  168. package/dist/components/spinner/Spinner.svelte +4 -11
  169. package/dist/components/status-indicator/StatusIndicator.svelte +1 -1
  170. package/dist/components/suggestions/SuggestionsItem.svelte +5 -5
  171. package/dist/components/switch/Switch.svelte +9 -14
  172. package/dist/components/tab-strip/TabStrip.svelte +340 -0
  173. package/dist/components/tab-strip/TabStrip.svelte.d.ts +31 -0
  174. package/dist/components/tabs/Tabs.svelte +13 -9
  175. package/dist/components/tabs/Tabs.svelte.d.ts +4 -0
  176. package/dist/components/text/Text.svelte +31 -23
  177. package/dist/components/text/Text.svelte.d.ts +8 -4
  178. package/dist/components/toast/Toaster.svelte +5 -5
  179. package/dist/components/tool/ToolContent.svelte +3 -8
  180. package/dist/components/tool/ToolSection.svelte +4 -5
  181. package/dist/components/tool/ToolTrigger.svelte +10 -9
  182. package/dist/components/tooltip/TooltipContent.svelte +3 -3
  183. package/dist/components/work-fold/WorkFold.svelte +5 -9
  184. package/dist/index.d.ts +16 -8
  185. package/dist/index.js +17 -10
  186. package/dist/internal/Code.svelte +3 -4
  187. package/dist/internal/Glyph.svelte +16 -0
  188. package/dist/internal/Glyph.svelte.d.ts +6 -0
  189. package/dist/internal/Tile.svelte +17 -37
  190. package/dist/internal/control.d.ts +4 -4
  191. package/dist/internal/control.js +20 -17
  192. package/dist/internal/layer.d.ts +3 -5
  193. package/dist/internal/layer.js +10 -12
  194. package/dist/internal/markers.stylex.d.ts +8 -0
  195. package/dist/internal/markers.stylex.js +4 -0
  196. package/dist/internal/plugin-order.d.ts +8 -0
  197. package/dist/internal/plugin-order.js +16 -0
  198. package/dist/internal/roving.js +5 -2
  199. package/dist/internal/shared.d.ts +8 -1
  200. package/dist/internal/shared.js +21 -5
  201. package/dist/internal/sx.d.ts +1 -1
  202. package/dist/internal/toggle.d.ts +1 -2
  203. package/dist/internal/toggle.js +8 -12
  204. package/dist/internal/visible.d.ts +32 -0
  205. package/dist/internal/visible.js +44 -0
  206. package/dist/markdown/ast.d.ts +209 -0
  207. package/dist/markdown/ast.js +10 -0
  208. package/dist/markdown/blocks.d.ts +177 -0
  209. package/dist/markdown/blocks.js +1489 -0
  210. package/dist/markdown/code-info.d.ts +10 -0
  211. package/dist/markdown/code-info.js +16 -0
  212. package/dist/markdown/common.d.ts +25 -0
  213. package/dist/markdown/common.js +107 -0
  214. package/dist/markdown/diagrams.d.ts +2 -0
  215. package/dist/markdown/diagrams.js +18 -0
  216. package/dist/markdown/file-paths.d.ts +29 -0
  217. package/dist/markdown/file-paths.js +80 -0
  218. package/dist/markdown/files.d.ts +16 -0
  219. package/dist/markdown/files.js +133 -0
  220. package/dist/markdown/highlight.d.ts +30 -0
  221. package/dist/markdown/highlight.js +127 -0
  222. package/dist/markdown/html.d.ts +23 -0
  223. package/dist/markdown/html.js +289 -0
  224. package/dist/markdown/images.d.ts +15 -0
  225. package/dist/markdown/images.js +45 -0
  226. package/dist/markdown/index.d.ts +12 -0
  227. package/dist/markdown/index.js +5 -0
  228. package/dist/markdown/inlines.d.ts +48 -0
  229. package/dist/markdown/inlines.js +1714 -0
  230. package/dist/markdown/math.d.ts +2 -0
  231. package/dist/markdown/math.js +22 -0
  232. package/dist/markdown/parse.d.ts +81 -0
  233. package/dist/markdown/parse.js +204 -0
  234. package/dist/markdown/plugin.d.ts +178 -0
  235. package/dist/markdown/plugin.js +160 -0
  236. package/dist/markdown/sanitize.d.ts +78 -0
  237. package/dist/markdown/sanitize.js +522 -0
  238. package/dist/markdown/share.d.ts +12 -0
  239. package/dist/markdown/share.js +59 -0
  240. package/dist/markdown/table.d.ts +13 -0
  241. package/dist/markdown/table.js +60 -0
  242. package/dist/preset.d.ts +40 -16
  243. package/dist/preset.js +169 -51
  244. package/dist/tokens.stylex.d.ts +55 -37
  245. package/dist/tokens.stylex.js +107 -62
  246. package/dist/typography.d.ts +48 -0
  247. package/dist/typography.js +55 -0
  248. package/dist/vite.d.ts +7 -1
  249. package/dist/vite.js +27 -2
  250. package/package.json +53 -6
  251. package/skills/building-ui/SKILL.md +242 -0
  252. package/skills/building-ui/references/components.md +207 -0
  253. package/skills/markdown/SKILL.md +452 -0
  254. package/skills/markdown/references/plugins.md +103 -0
  255. package/skills/setup/SKILL.md +191 -0
  256. package/skills/styling/SKILL.md +269 -0
  257. package/skills/theming/SKILL.md +184 -0
  258. package/dist/internal/loop.d.ts +0 -35
  259. package/dist/internal/loop.js +0 -72
@@ -0,0 +1,1714 @@
1
+ import { ENTITY, ESCAPABLE, decodeEntity, normalizeReference, normalizeUri, rePunctuation, reHtmlTag, reUnicodeWhitespace, unescapeString } from './common.js';
2
+ const C_NEWLINE = 10;
3
+ const C_ASTERISK = 42;
4
+ const C_UNDERSCORE = 95;
5
+ const C_TILDE = 126;
6
+ const C_BACKTICK = 96;
7
+ const C_OPEN_BRACKET = 91;
8
+ const C_CLOSE_BRACKET = 93;
9
+ const C_LESSTHAN = 60;
10
+ const C_BANG = 33;
11
+ const C_BACKSLASH = 92;
12
+ const C_AMPERSAND = 38;
13
+ const C_OPEN_PAREN = 40;
14
+ const C_CLOSE_PAREN = 41;
15
+ const C_COLON = 58;
16
+ const reEscapable = new RegExp('^' + ESCAPABLE);
17
+ const reEntityHere = new RegExp('^' + ENTITY, 'i');
18
+ const reTicks = /`+/;
19
+ const reTicksHere = /^`+/;
20
+ const reWhitespaceChar = /^[ \t\n\x0b\x0c\x0d]/;
21
+ const reInitialSpace = /^ */;
22
+ const reSpaceAtEndOfLine = /^ *(?:\n|$)/;
23
+ const reLinkLabel = /^\[(?:[^\\[\]]|\\.){0,1000}\]/s;
24
+ // Chinese, Japanese and Korean letters, and the punctuation and full-width forms set with them
25
+ const reCjk = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\u3000-\u303f\uff00-\uffef]/u;
26
+ /** The characters that end a run of plain text: each may start something else. */
27
+ const SPECIAL = new Uint8Array(128);
28
+ for (const ch of '\n`[]\\!<&*_~')
29
+ SPECIAL[ch.charCodeAt(0)] = 1;
30
+ const C_DOLLAR = 36;
31
+ const reEmailAutolink = /^<([a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)>/;
32
+ const reAutolink = /^<[A-Za-z][A-Za-z0-9.+-]{1,31}:[^<>\x00-\x20]*>/;
33
+ const reLinkDestinationBraces = /^(?:<(?:[^<>\n\\\x00]|\\.)*>)/;
34
+ class INode {
35
+ type;
36
+ value = '';
37
+ url = '';
38
+ title = null;
39
+ kind = 'inline';
40
+ label = '';
41
+ display = false;
42
+ parent = null;
43
+ firstChild = null;
44
+ lastChild = null;
45
+ prev = null;
46
+ next = null;
47
+ constructor(type, value = '') {
48
+ this.type = type;
49
+ this.value = value;
50
+ }
51
+ appendChild(child) {
52
+ child.unlink();
53
+ child.parent = this;
54
+ if (this.lastChild) {
55
+ this.lastChild.next = child;
56
+ child.prev = this.lastChild;
57
+ this.lastChild = child;
58
+ }
59
+ else {
60
+ this.firstChild = child;
61
+ this.lastChild = child;
62
+ }
63
+ }
64
+ insertAfter(sibling) {
65
+ sibling.unlink();
66
+ sibling.next = this.next;
67
+ if (sibling.next)
68
+ sibling.next.prev = sibling;
69
+ sibling.prev = this;
70
+ this.next = sibling;
71
+ sibling.parent = this.parent;
72
+ if (!sibling.next && sibling.parent)
73
+ sibling.parent.lastChild = sibling;
74
+ }
75
+ insertBefore(sibling) {
76
+ sibling.unlink();
77
+ sibling.prev = this.prev;
78
+ if (sibling.prev)
79
+ sibling.prev.next = sibling;
80
+ sibling.next = this;
81
+ this.prev = sibling;
82
+ sibling.parent = this.parent;
83
+ if (!sibling.prev && sibling.parent)
84
+ sibling.parent.firstChild = sibling;
85
+ }
86
+ unlink() {
87
+ if (this.prev)
88
+ this.prev.next = this.next;
89
+ else if (this.parent)
90
+ this.parent.firstChild = this.next;
91
+ if (this.next)
92
+ this.next.prev = this.prev;
93
+ else if (this.parent)
94
+ this.parent.lastChild = this.prev;
95
+ this.parent = null;
96
+ this.next = null;
97
+ this.prev = null;
98
+ }
99
+ }
100
+ function text(s) {
101
+ return new INode('text', s);
102
+ }
103
+ /** Normalizes a link label for lookup, or null when it is not a valid label. */
104
+ /**
105
+ * The `^label` between two places, when that is all there is between them: a caret and then
106
+ * no space or bracket. Read a character at a time and given up at the first that does not
107
+ * fit, so a thousand nested `[^` are not each read to their end.
108
+ */
109
+ function footnoteLabelAt(s, from, to) {
110
+ if (s.charCodeAt(from) !== 94 || to - from < 2 || to - from > 1000)
111
+ return null;
112
+ for (let i = from + 1; i < to; i++) {
113
+ const code = s.charCodeAt(i);
114
+ // `]`, `[`'s partner aside, and any white space
115
+ if (code === 93 || code === 32 || code === 9 || code === 10 || code === 13 || code === 12)
116
+ return null;
117
+ if (code > 127 && /\s/.test(s.charAt(i)))
118
+ return null;
119
+ }
120
+ return s.slice(from, to);
121
+ }
122
+ function labelKey(raw) {
123
+ // A label has at most 999 characters between its brackets
124
+ if (raw.length > 1001)
125
+ return null;
126
+ const key = normalizeReference(raw);
127
+ return key.length > 0 ? key : null;
128
+ }
129
+ class InlineParser {
130
+ context;
131
+ subject = '';
132
+ pos = 0;
133
+ delimiters = null;
134
+ brackets = null;
135
+ missed = new Set();
136
+ // From these positions on, the end mark of a kind of tag or formula is known to be missing
137
+ noGt = Infinity;
138
+ noCommentEnd = Infinity;
139
+ noInstructionEnd = Infinity;
140
+ noCdataEnd = Infinity;
141
+ noParenEnd = Infinity;
142
+ noBracketEnd = Infinity;
143
+ /** Where the next `\\)` and `\\]` are, once looked for; -1 before that. */
144
+ parenEnd = -1;
145
+ bracketEnd = -1;
146
+ /** Where the next `>` is, once looked for. */
147
+ gtAt = -1;
148
+ noDollarsEnd = Infinity;
149
+ /** Emphasis openers left without a closer: where their remaining delimiters start, and what they are. */
150
+ unclosed = [];
151
+ constructor(context) {
152
+ this.context = context;
153
+ }
154
+ match(re) {
155
+ const m = re.exec(this.subject.slice(this.pos));
156
+ if (m === null)
157
+ return null;
158
+ this.pos += m.index + m[0].length;
159
+ return m[0];
160
+ }
161
+ peek() {
162
+ return this.pos < this.subject.length ? this.subject.charCodeAt(this.pos) : -1;
163
+ }
164
+ spnl() {
165
+ this.match(/^ *(?:\n *)?/);
166
+ return true;
167
+ }
168
+ parseBackticks(block) {
169
+ const ticks = this.match(reTicksHere);
170
+ if (ticks === null)
171
+ return false;
172
+ const afterOpenTicks = this.pos;
173
+ let matched;
174
+ while ((matched = this.match(reTicks)) !== null) {
175
+ if (matched === ticks) {
176
+ let contents = this.subject
177
+ .slice(afterOpenTicks, this.pos - ticks.length)
178
+ .replace(/\n/gm, ' ');
179
+ if (contents.length > 0 &&
180
+ /[^ ]/.test(contents) &&
181
+ contents[0] === ' ' &&
182
+ contents[contents.length - 1] === ' ') {
183
+ contents = contents.slice(1, contents.length - 1);
184
+ }
185
+ block.appendChild(new INode('inlineCode', contents));
186
+ return true;
187
+ }
188
+ }
189
+ // No closing run: the opening backticks are text
190
+ this.pos = afterOpenTicks;
191
+ block.appendChild(text(ticks));
192
+ return true;
193
+ }
194
+ parseBackslash(block) {
195
+ const subj = this.subject;
196
+ if (this.context.math && this.parseBackslashMath(block))
197
+ return true;
198
+ this.pos += 1;
199
+ if (this.peek() === C_NEWLINE) {
200
+ this.pos += 1;
201
+ block.appendChild(new INode('break'));
202
+ }
203
+ else if (reEscapable.test(subj.charAt(this.pos))) {
204
+ block.appendChild(text(subj.charAt(this.pos)));
205
+ this.pos += 1;
206
+ }
207
+ else {
208
+ block.appendChild(text('\\'));
209
+ }
210
+ return true;
211
+ }
212
+ /** `\\(x\\)` in running text, and `\\[x\\]` as a displayed formula. */
213
+ parseBackslashMath(block) {
214
+ const subj = this.subject;
215
+ const next = subj.charAt(this.pos + 1);
216
+ if (next !== '(' && next !== '[')
217
+ return false;
218
+ const paren = next === '(';
219
+ // Right after a letter or a digit, `\\(` is an escaped bracket: `f\\(x\\)` is "f(x)"
220
+ if (paren && this.pos > 0 && /[A-Za-z0-9]/.test(subj.charAt(this.pos - 1)))
221
+ return false;
222
+ // Once a closer is known to be missing after some point, later openers need not look
223
+ if (this.pos >= (paren ? this.noParenEnd : this.noBracketEnd))
224
+ return false;
225
+ // The next closer is the same one for every opener before it: found once, not once each
226
+ let end = paren ? this.parenEnd : this.bracketEnd;
227
+ if (end < this.pos + 2) {
228
+ end = subj.indexOf(paren ? '\\)' : '\\]', this.pos + 2);
229
+ if (paren)
230
+ this.parenEnd = end;
231
+ else
232
+ this.bracketEnd = end;
233
+ }
234
+ if (end < 0) {
235
+ if (paren)
236
+ this.noParenEnd = this.pos;
237
+ else
238
+ this.noBracketEnd = this.pos;
239
+ return false;
240
+ }
241
+ // A formula does not open another of its kind: of `\\(a \\(b\\)`, the inner one is it
242
+ const inner = subj.indexOf(paren ? '\\(' : '\\[', this.pos + 2);
243
+ if (inner >= 0 && inner < end)
244
+ return false;
245
+ const value = subj.slice(this.pos + 2, end).trim();
246
+ if (value === '' || !(paren ? looksLikeInlineTex(value) : looksLikeTex(value)))
247
+ return false;
248
+ // `\\[a-z\\]` and `\\[^0-9\\]` are escaped brackets around a regex's character class
249
+ if (!paren && reCharClass.test(value))
250
+ return false;
251
+ const node = new INode('inlineMath', value);
252
+ node.display = !paren;
253
+ block.appendChild(node);
254
+ this.pos = end + 2;
255
+ return true;
256
+ }
257
+ /**
258
+ * `$x$` and `$$x$$`. A dollar sign is far more often money, a shell variable or a template
259
+ * than math, so it opens a formula only under rules that grew out of Pandoc's and of what
260
+ * LLM renderers learned since:
261
+ *
262
+ * - before the opening dollar: the start, a space, or an opening mark such as `(`; never a
263
+ * letter, a digit, another dollar, or a symbol such as the `+` of a regex `+$`;
264
+ * - after it: not a space, a comma, `{` or `(` (`${HOME}`, `$(pwd)`);
265
+ * - the closing dollar is on the same line, with no space or comma before it and no
266
+ * letter, digit, `(` or `{` after it;
267
+ * - nothing between them is a backtick or `://`, and what is between them, when it has
268
+ * spaces, reads as TeX: "$5 and 10$" does not.
269
+ */
270
+ parseDollar(block) {
271
+ const subj = this.subject;
272
+ const start = this.pos;
273
+ const prev = start > 0 ? subj.charAt(start - 1) : '';
274
+ if (subj.startsWith('$$', start)) {
275
+ const literal = () => {
276
+ this.pos = start + 2;
277
+ block.appendChild(text('$$'));
278
+ return true;
279
+ };
280
+ if (start >= this.noDollarsEnd || /[A-Za-z0-9$]/.test(prev))
281
+ return literal();
282
+ const end = subj.indexOf('$$', start + 2);
283
+ if (end < 0) {
284
+ this.noDollarsEnd = start;
285
+ return literal();
286
+ }
287
+ const value = subj.slice(start + 2, end).trim();
288
+ // A formula has something in it to typeset, and nothing word-like runs on after it.
289
+ // With spaces in it, it has to read as TeX: `echo $$ > pidfile; kill $$` does not.
290
+ if (!/[A-Za-z0-9\\]/.test(value) ||
291
+ /[A-Za-z0-9$]/.test(subj.charAt(end + 2)) ||
292
+ (/[ \t]/.test(value) && !looksLikeTex(value)))
293
+ return literal();
294
+ const node = new INode('inlineMath', value);
295
+ node.display = true;
296
+ block.appendChild(node);
297
+ this.pos = end + 2;
298
+ return true;
299
+ }
300
+ const literal = () => {
301
+ this.pos = start + 1;
302
+ block.appendChild(text('$'));
303
+ return true;
304
+ };
305
+ if (prev !== '' && !/[\s([{"'‘“—–*_~|>,;:-]/.test(prev))
306
+ return literal();
307
+ const first = subj.charAt(start + 1);
308
+ if (first === '' || /[\s,$({]/.test(first))
309
+ return literal();
310
+ for (let i = start + 1; i < subj.length; i++) {
311
+ const ch = subj.charAt(i);
312
+ if (ch === '\n' || ch === '`')
313
+ return literal();
314
+ if (ch === '\\') {
315
+ i++;
316
+ continue;
317
+ }
318
+ if (ch !== '$')
319
+ continue;
320
+ const value = subj.slice(start + 1, i);
321
+ const before = subj.charAt(i - 1);
322
+ const after = subj.charAt(i + 1);
323
+ if (/[\s,]/.test(before) ||
324
+ /[A-Za-z0-9({]/.test(after) ||
325
+ value.includes('://') ||
326
+ (/\s/.test(value) && !looksLikeTex(value)))
327
+ return literal();
328
+ const node = new INode('inlineMath', value);
329
+ block.appendChild(node);
330
+ this.pos = i + 1;
331
+ return true;
332
+ }
333
+ return literal();
334
+ }
335
+ parseAutolink(block) {
336
+ let m;
337
+ if ((m = this.match(reEmailAutolink))) {
338
+ const dest = m.slice(1, m.length - 1);
339
+ const node = new INode('link');
340
+ node.url = normalizeUri('mailto:' + dest);
341
+ node.kind = 'autolink';
342
+ node.appendChild(text(dest));
343
+ block.appendChild(node);
344
+ return true;
345
+ }
346
+ if ((m = this.match(reAutolink))) {
347
+ const dest = m.slice(1, m.length - 1);
348
+ const node = new INode('link');
349
+ node.url = normalizeUri(dest);
350
+ node.kind = 'autolink';
351
+ node.appendChild(text(dest));
352
+ block.appendChild(node);
353
+ return true;
354
+ }
355
+ return false;
356
+ }
357
+ parseHtmlTag(block) {
358
+ const subj = this.subject;
359
+ const p = this.pos;
360
+ // Every kind of tag ends with `>`, and the longer kinds with their own end mark. When
361
+ // one is known to be missing from some point on, nothing after that point is tried:
362
+ // without this, `<!a<!a<!a…` scans to the end of the text once per `<`.
363
+ if (p >= this.noGt)
364
+ return false;
365
+ // The next `>` is the same one for every `<` before it
366
+ if (this.gtAt < p)
367
+ this.gtAt = subj.indexOf('>', p);
368
+ if (this.gtAt < 0) {
369
+ this.noGt = p;
370
+ return false;
371
+ }
372
+ if (subj.startsWith('<!--', p)) {
373
+ if (p >= this.noCommentEnd)
374
+ return false;
375
+ if (subj.indexOf('-->', p + 2) < 0) {
376
+ this.noCommentEnd = p;
377
+ return false;
378
+ }
379
+ }
380
+ else if (subj.startsWith('<?', p)) {
381
+ if (p >= this.noInstructionEnd)
382
+ return false;
383
+ if (subj.indexOf('?>', p + 2) < 0) {
384
+ this.noInstructionEnd = p;
385
+ return false;
386
+ }
387
+ }
388
+ else if (subj.startsWith('<![CDATA[', p)) {
389
+ if (p >= this.noCdataEnd)
390
+ return false;
391
+ if (subj.indexOf(']]>', p + 9) < 0) {
392
+ this.noCdataEnd = p;
393
+ return false;
394
+ }
395
+ }
396
+ const m = this.match(reHtmlTag);
397
+ if (m === null)
398
+ return false;
399
+ block.appendChild(new INode('inlineHtml', m));
400
+ return true;
401
+ }
402
+ /** How many delimiters there are at the position, and whether they can open or close emphasis. */
403
+ scanDelims(cc) {
404
+ let numdelims = 0;
405
+ const startpos = this.pos;
406
+ while (this.peek() === cc) {
407
+ numdelims++;
408
+ this.pos++;
409
+ }
410
+ if (numdelims === 0)
411
+ return null;
412
+ const before = startpos === 0 ? '\n' : String.fromCodePoint(this.subject.codePointAt(startpos - 1));
413
+ // The character before may be the second half of a surrogate pair
414
+ const charBefore = startpos >= 2 && /[\uDC00-\uDFFF]/.test(this.subject.charAt(startpos - 1))
415
+ ? this.subject.slice(startpos - 2, startpos)
416
+ : before;
417
+ const ccAfter = this.peek();
418
+ const charAfter = ccAfter === -1 ? '\n' : String.fromCodePoint(this.subject.codePointAt(this.pos));
419
+ const afterIsWhitespace = reUnicodeWhitespace.test(charAfter);
420
+ const afterIsPunctuation = rePunctuation.test(charAfter);
421
+ const beforeIsWhitespace = reUnicodeWhitespace.test(charBefore);
422
+ const beforeIsPunctuation = rePunctuation.test(charBefore);
423
+ // CommonMark's rules, with one addition for text written without spaces between words:
424
+ // beside a Chinese, Japanese or Korean character, punctuation does not stop a run from
425
+ // opening or closing. By the rules alone the second `**` of `**テスト。**次` closes
426
+ // nothing, as `。` is punctuation and `次` is not a space, and the reader sees the
427
+ // asterisks. (The same amendment as markdown-cjk-friendly.)
428
+ const leftFlanking = !afterIsWhitespace &&
429
+ (!afterIsPunctuation || beforeIsWhitespace || beforeIsPunctuation || reCjk.test(charBefore));
430
+ const rightFlanking = !beforeIsWhitespace &&
431
+ (!beforeIsPunctuation || afterIsWhitespace || afterIsPunctuation || reCjk.test(charAfter));
432
+ let canOpen;
433
+ let canClose;
434
+ if (cc === C_UNDERSCORE) {
435
+ canOpen = leftFlanking && (!rightFlanking || beforeIsPunctuation);
436
+ canClose = rightFlanking && (!leftFlanking || afterIsPunctuation);
437
+ }
438
+ else {
439
+ canOpen = leftFlanking;
440
+ canClose = rightFlanking;
441
+ }
442
+ this.pos = startpos;
443
+ return { numdelims, canOpen, canClose };
444
+ }
445
+ handleDelim(cc, block) {
446
+ const res = this.scanDelims(cc);
447
+ if (!res)
448
+ return false;
449
+ const numdelims = res.numdelims;
450
+ const startpos = this.pos;
451
+ this.pos += numdelims;
452
+ const node = text(this.subject.slice(startpos, this.pos));
453
+ block.appendChild(node);
454
+ // GFM strikethrough takes runs of one or two tildes only
455
+ // GFM strikethrough takes two tildes, or one where that is allowed; more are text
456
+ if (cc === C_TILDE && (numdelims > 2 || (numdelims === 1 && !this.context.singleTilde)))
457
+ return true;
458
+ if (res.canOpen || res.canClose) {
459
+ this.delimiters = {
460
+ cc,
461
+ numdelims,
462
+ origdelims: numdelims,
463
+ node,
464
+ previous: this.delimiters,
465
+ next: null,
466
+ canOpen: res.canOpen,
467
+ canClose: res.canClose,
468
+ pos: startpos
469
+ };
470
+ if (this.delimiters.previous)
471
+ this.delimiters.previous.next = this.delimiters;
472
+ }
473
+ return true;
474
+ }
475
+ removeDelimiter(delim) {
476
+ if (delim.previous !== null)
477
+ delim.previous.next = delim.next;
478
+ if (delim.next === null)
479
+ this.delimiters = delim.previous;
480
+ else
481
+ delim.next.previous = delim.previous;
482
+ }
483
+ processEmphasis(stackBottom) {
484
+ const openersBottom = [];
485
+ for (let i = 0; i < 16; i++)
486
+ openersBottom[i] = stackBottom;
487
+ // Nothing above the bottom: nothing to do. Without this, the walk below would go down the
488
+ // whole stack on every link that closes, and a long paragraph of links would crawl.
489
+ if (this.delimiters === stackBottom)
490
+ return;
491
+ let closer = this.delimiters;
492
+ while (closer !== null && closer.previous !== stackBottom)
493
+ closer = closer.previous;
494
+ while (closer !== null) {
495
+ const closercc = closer.cc;
496
+ if (!closer.canClose) {
497
+ closer = closer.next;
498
+ continue;
499
+ }
500
+ let opener = closer.previous;
501
+ let openerFound = false;
502
+ const index = closercc === C_TILDE
503
+ ? 14 + (closer.origdelims === 2 ? 1 : 0)
504
+ : (closercc === C_UNDERSCORE ? 2 : 8) +
505
+ (closer.canOpen ? 3 : 0) +
506
+ (closer.origdelims % 3);
507
+ while (opener !== null && opener !== stackBottom && opener !== openersBottom[index]) {
508
+ if (closercc === C_TILDE) {
509
+ if (opener.cc === C_TILDE && opener.canOpen && opener.origdelims === closer.origdelims) {
510
+ openerFound = true;
511
+ break;
512
+ }
513
+ }
514
+ else {
515
+ const oddMatch = (closer.canOpen || opener.canClose) &&
516
+ closer.origdelims % 3 !== 0 &&
517
+ (opener.origdelims + closer.origdelims) % 3 === 0;
518
+ if (opener.cc === closer.cc && opener.canOpen && !oddMatch) {
519
+ openerFound = true;
520
+ break;
521
+ }
522
+ }
523
+ opener = opener.previous;
524
+ }
525
+ const oldCloser = closer;
526
+ if (!openerFound || opener === null) {
527
+ closer = closer.next;
528
+ }
529
+ else {
530
+ const useDelims = closercc === C_TILDE
531
+ ? closer.numdelims
532
+ : closer.numdelims >= 2 && opener.numdelims >= 2
533
+ ? 2
534
+ : 1;
535
+ const openerInl = opener.node;
536
+ const closerInl = closer.node;
537
+ opener.numdelims -= useDelims;
538
+ closer.numdelims -= useDelims;
539
+ openerInl.value = openerInl.value.slice(0, openerInl.value.length - useDelims);
540
+ closerInl.value = closerInl.value.slice(0, closerInl.value.length - useDelims);
541
+ const emph = new INode(closercc === C_TILDE ? 'delete' : useDelims === 1 ? 'emphasis' : 'strong');
542
+ let tmp = openerInl.next;
543
+ while (tmp && tmp !== closerInl) {
544
+ const next = tmp.next;
545
+ emph.appendChild(tmp);
546
+ tmp = next;
547
+ }
548
+ openerInl.insertAfter(emph);
549
+ // Delimiters between the opener and the closer are spent
550
+ if (opener.next !== closer) {
551
+ opener.next = closer;
552
+ closer.previous = opener;
553
+ }
554
+ if (opener.numdelims === 0) {
555
+ openerInl.unlink();
556
+ this.removeDelimiter(opener);
557
+ }
558
+ if (closer.numdelims === 0) {
559
+ closerInl.unlink();
560
+ const tempstack = closer.next;
561
+ this.removeDelimiter(closer);
562
+ closer = tempstack;
563
+ }
564
+ }
565
+ if (!openerFound) {
566
+ openersBottom[index] = oldCloser.previous;
567
+ if (!oldCloser.canOpen)
568
+ this.removeDelimiter(oldCloser);
569
+ }
570
+ }
571
+ // What could have opened emphasis but found no closer, for tidying a streamed tail
572
+ for (let d = this.delimiters; d !== null && d !== stackBottom; d = d.previous) {
573
+ if (d.canOpen && d.numdelims > 0 && !(d.cc === C_TILDE && d.origdelims === 1)) {
574
+ this.unclosed.push({ pos: d.pos, run: d.node.value.slice(0, d.numdelims) });
575
+ }
576
+ }
577
+ while (this.delimiters !== null && this.delimiters !== stackBottom)
578
+ this.removeDelimiter(this.delimiters);
579
+ }
580
+ parseLinkTitle() {
581
+ // Read by hand: the pattern this replaces took exponential time on an unclosed title
582
+ // with escapes in it
583
+ const subj = this.subject;
584
+ const open = subj.charAt(this.pos);
585
+ const close = open === '"' ? '"' : open === "'" ? "'" : open === '(' ? ')' : '';
586
+ if (close === '')
587
+ return null;
588
+ for (let i = this.pos + 1; i < subj.length; i++) {
589
+ const ch = subj.charAt(i);
590
+ if (ch === '\\') {
591
+ i++;
592
+ }
593
+ else if (ch === close) {
594
+ const raw = subj.slice(this.pos + 1, i);
595
+ this.pos = i + 1;
596
+ return unescapeString(raw);
597
+ }
598
+ else if (ch === '\0' || (open === '(' && ch === '(')) {
599
+ return null;
600
+ }
601
+ }
602
+ return null;
603
+ }
604
+ parseLinkDestination() {
605
+ let res = this.match(reLinkDestinationBraces);
606
+ if (res === null) {
607
+ if (this.peek() === C_LESSTHAN)
608
+ return null;
609
+ // A destination without braces: balanced parentheses, no spaces or controls
610
+ const savepos = this.pos;
611
+ let openparens = 0;
612
+ let c;
613
+ while ((c = this.peek()) !== -1) {
614
+ if (c === C_BACKSLASH && reEscapable.test(this.subject.charAt(this.pos + 1))) {
615
+ this.pos += 1;
616
+ if (this.peek() !== -1)
617
+ this.pos += 1;
618
+ }
619
+ else if (c === C_OPEN_PAREN) {
620
+ this.pos += 1;
621
+ openparens += 1;
622
+ // No address nests brackets this deep; `[a]([a]([a](…` would otherwise read
623
+ // to the end of the text from every `(`
624
+ if (openparens > 32)
625
+ return null;
626
+ }
627
+ else if (c === C_CLOSE_PAREN) {
628
+ if (openparens < 1)
629
+ break;
630
+ this.pos += 1;
631
+ openparens -= 1;
632
+ }
633
+ else if (reWhitespaceChar.test(String.fromCharCode(c)) || c < 0x20 || c === 0x7f) {
634
+ break;
635
+ }
636
+ else {
637
+ this.pos += 1;
638
+ }
639
+ }
640
+ if (this.pos === savepos && c !== C_CLOSE_PAREN)
641
+ return null;
642
+ if (openparens !== 0)
643
+ return null;
644
+ res = this.subject.slice(savepos, this.pos);
645
+ return normalizeUri(unescapeString(res));
646
+ }
647
+ return normalizeUri(unescapeString(res.slice(1, res.length - 1)));
648
+ }
649
+ parseLinkLabel() {
650
+ const m = this.match(reLinkLabel);
651
+ if (m === null || m.length > 1001)
652
+ return 0;
653
+ return m.length;
654
+ }
655
+ parseOpenBracket(block) {
656
+ const startpos = this.pos;
657
+ this.pos += 1;
658
+ const node = text('[');
659
+ block.appendChild(node);
660
+ this.addBracket(node, startpos, false);
661
+ return true;
662
+ }
663
+ parseBang(block) {
664
+ const startpos = this.pos;
665
+ this.pos += 1;
666
+ if (this.peek() === C_OPEN_BRACKET) {
667
+ this.pos += 1;
668
+ const node = text('![');
669
+ block.appendChild(node);
670
+ this.addBracket(node, startpos + 1, true);
671
+ }
672
+ else {
673
+ block.appendChild(text('!'));
674
+ }
675
+ return true;
676
+ }
677
+ parseCloseBracket(block) {
678
+ let url = null;
679
+ let title = null;
680
+ let matched = false;
681
+ let kind = 'inline';
682
+ this.pos += 1;
683
+ const startpos = this.pos;
684
+ const opener = this.brackets;
685
+ if (opener === null) {
686
+ block.appendChild(text(']'));
687
+ return true;
688
+ }
689
+ if (!opener.active) {
690
+ block.appendChild(text(']'));
691
+ this.removeBracket();
692
+ return true;
693
+ }
694
+ const isImage = opener.image;
695
+ const savepos = this.pos;
696
+ // A GFM footnote reference: `[^label]`, with nothing between the brackets but the label.
697
+ // It is a reference whether or not its definition has arrived: the definition usually
698
+ // comes last, and a reference with none is written out as text when the document is.
699
+ if (this.context.gfm && !isImage && this.peek() !== C_OPEN_PAREN) {
700
+ const inner = footnoteLabelAt(this.subject, opener.index + 1, startpos - 1);
701
+ if (inner !== null) {
702
+ // The label is taken as written: marks in it (`[^a_b]`) are not emphasis
703
+ while (this.delimiters !== null && this.delimiters !== opener.previousDelimiter)
704
+ this.removeDelimiter(this.delimiters);
705
+ const ref = new INode('footnoteReference');
706
+ ref.label = inner.slice(1);
707
+ let tmp = opener.node.next;
708
+ while (tmp) {
709
+ const next = tmp.next;
710
+ tmp.unlink();
711
+ tmp = next;
712
+ }
713
+ opener.node.insertAfter(ref);
714
+ opener.node.unlink();
715
+ this.removeBracket();
716
+ return true;
717
+ }
718
+ }
719
+ // An inline link: `[text](destination "title")`
720
+ if (this.peek() === C_OPEN_PAREN) {
721
+ this.pos++;
722
+ if (this.spnl()) {
723
+ const dest = this.parseLinkDestination();
724
+ if (dest !== null && this.spnl()) {
725
+ // A title needs whitespace before it
726
+ if (reWhitespaceChar.test(this.subject.charAt(this.pos - 1)))
727
+ title = this.parseLinkTitle();
728
+ if (this.spnl() && this.peek() === C_CLOSE_PAREN) {
729
+ this.pos += 1;
730
+ url = dest;
731
+ matched = true;
732
+ }
733
+ }
734
+ }
735
+ if (!matched)
736
+ this.pos = savepos;
737
+ }
738
+ if (!matched) {
739
+ // A reference link: `[text][label]`, `[text][]` or `[text]`
740
+ const beforelabel = this.pos;
741
+ const n = this.parseLinkLabel();
742
+ let reflabel;
743
+ if (n > 2) {
744
+ reflabel = this.subject.slice(beforelabel, beforelabel + n);
745
+ }
746
+ else if (!opener.bracketAfter) {
747
+ // A collapsed `[]` or a shortcut: the text is the label
748
+ reflabel = this.subject.slice(opener.index, startpos);
749
+ }
750
+ if (n === 0)
751
+ this.pos = savepos;
752
+ if (reflabel) {
753
+ const key = labelKey(reflabel);
754
+ const link = key === null ? undefined : this.context.definitions.get(key);
755
+ if (link) {
756
+ url = link.url;
757
+ title = link.title;
758
+ matched = true;
759
+ kind = 'reference';
760
+ }
761
+ else if (key !== null) {
762
+ this.missed.add(key);
763
+ }
764
+ }
765
+ }
766
+ if (matched) {
767
+ const node = new INode(isImage ? 'image' : 'link');
768
+ node.url = url;
769
+ node.title = title;
770
+ node.kind = kind;
771
+ let tmp = opener.node.next;
772
+ while (tmp) {
773
+ const next = tmp.next;
774
+ node.appendChild(tmp);
775
+ tmp = next;
776
+ }
777
+ block.appendChild(node);
778
+ this.processEmphasis(opener.previousDelimiter);
779
+ this.removeBracket();
780
+ opener.node.unlink();
781
+ // A bare URL in a link's own text is text: a link cannot hold a link
782
+ if (!isImage)
783
+ unwrapLiteralLinks(node);
784
+ // Links may not contain other links: earlier openers are spent
785
+ if (!isImage) {
786
+ // One that is spent already was spent with all those before it: stop there, or
787
+ // a thousand links after a thousand `[` walk the thousand a thousand times
788
+ let b = this.brackets;
789
+ while (b !== null) {
790
+ if (!b.image) {
791
+ if (!b.active)
792
+ break;
793
+ b.active = false;
794
+ }
795
+ b = b.previous;
796
+ }
797
+ }
798
+ return true;
799
+ }
800
+ this.removeBracket();
801
+ this.pos = startpos;
802
+ block.appendChild(text(']'));
803
+ return true;
804
+ }
805
+ addBracket(node, index, image) {
806
+ if (this.brackets !== null)
807
+ this.brackets.bracketAfter = true;
808
+ this.brackets = {
809
+ node,
810
+ previous: this.brackets,
811
+ previousDelimiter: this.delimiters,
812
+ index,
813
+ image,
814
+ active: true
815
+ };
816
+ }
817
+ removeBracket() {
818
+ this.brackets = this.brackets.previous;
819
+ }
820
+ parseEntity(block) {
821
+ const m = this.match(reEntityHere);
822
+ if (m === null)
823
+ return false;
824
+ block.appendChild(text(decodeEntity(m)));
825
+ return true;
826
+ }
827
+ parseString(block) {
828
+ const subj = this.subject;
829
+ if (this.context.gfm) {
830
+ // A bare URL is read here, before emphasis, so that the `__` of `__init__.py` or the
831
+ // `*` of a glob inside one stays part of the address
832
+ const end = bareUrlAt(subj, this.pos, this.brackets !== null);
833
+ if (end > 0) {
834
+ const label = subj.slice(this.pos, end);
835
+ const node = new INode('link');
836
+ node.url = normalizeUri(/^www\./i.test(label) ? 'http://' + label : label);
837
+ node.kind = 'literal';
838
+ node.appendChild(text(label));
839
+ block.appendChild(node);
840
+ this.pos = end;
841
+ return true;
842
+ }
843
+ }
844
+ // A run of plain text: up to the next character that may start something else, or the
845
+ // start of a bare URL. Read a character at a time, so that a paragraph of a thousand
846
+ // URLs is not searched to its end a thousand times.
847
+ const gfm = this.context.gfm;
848
+ const math = this.context.math;
849
+ const inBrackets = this.brackets !== null;
850
+ const from = this.pos;
851
+ let i = from;
852
+ for (; i < subj.length; i++) {
853
+ const code = subj.charCodeAt(i);
854
+ if (code < 128 && (SPECIAL[code] === 1 || (math && code === 36)))
855
+ break;
856
+ if (gfm && i > from) {
857
+ // h, f or w, in either case: where `http`, `ftp` or `www` would start
858
+ const lower = code | 32;
859
+ if ((lower === 104 || lower === 102 || lower === 119) && bareUrlAt(subj, i, inBrackets) > 0)
860
+ break;
861
+ }
862
+ }
863
+ if (i === from)
864
+ return false;
865
+ this.pos = i;
866
+ block.appendChild(text(subj.slice(from, i)));
867
+ return true;
868
+ }
869
+ parseNewline(block) {
870
+ this.pos += 1;
871
+ const lastc = block.lastChild;
872
+ if (lastc && lastc.type === 'text' && lastc.value[lastc.value.length - 1] === ' ') {
873
+ const hardbreak = lastc.value[lastc.value.length - 2] === ' ';
874
+ let end = lastc.value.length;
875
+ while (end > 0 && lastc.value.charCodeAt(end - 1) === 32)
876
+ end--;
877
+ lastc.value = lastc.value.slice(0, end);
878
+ block.appendChild(new INode(hardbreak ? 'break' : 'softBreak'));
879
+ }
880
+ else {
881
+ block.appendChild(new INode('softBreak'));
882
+ }
883
+ this.match(reInitialSpace);
884
+ return true;
885
+ }
886
+ parseInline(block) {
887
+ const c = this.peek();
888
+ if (c === -1)
889
+ return false;
890
+ let res;
891
+ switch (c) {
892
+ case C_NEWLINE:
893
+ res = this.parseNewline(block);
894
+ break;
895
+ case C_BACKSLASH:
896
+ res = this.parseBackslash(block);
897
+ break;
898
+ case C_DOLLAR:
899
+ res = this.context.math ? this.parseDollar(block) : false;
900
+ break;
901
+ case C_BACKTICK:
902
+ res = this.parseBackticks(block);
903
+ break;
904
+ case C_ASTERISK:
905
+ case C_UNDERSCORE:
906
+ res = this.handleDelim(c, block);
907
+ break;
908
+ case C_TILDE:
909
+ res = this.context.gfm ? this.handleDelim(c, block) : false;
910
+ break;
911
+ case C_OPEN_BRACKET:
912
+ res = this.parseOpenBracket(block);
913
+ break;
914
+ case C_BANG:
915
+ res = this.parseBang(block);
916
+ break;
917
+ case C_CLOSE_BRACKET:
918
+ res = this.parseCloseBracket(block);
919
+ break;
920
+ case C_LESSTHAN:
921
+ res = this.parseAutolink(block) || this.parseHtmlTag(block);
922
+ break;
923
+ case C_AMPERSAND:
924
+ res = this.parseEntity(block);
925
+ break;
926
+ default:
927
+ res = this.parseString(block);
928
+ break;
929
+ }
930
+ if (!res) {
931
+ this.pos += 1;
932
+ block.appendChild(text(String.fromCharCode(c)));
933
+ }
934
+ return true;
935
+ }
936
+ parse(content) {
937
+ const root = new INode('text');
938
+ this.subject = content;
939
+ this.pos = 0;
940
+ this.delimiters = null;
941
+ this.brackets = null;
942
+ this.noGt = this.noCommentEnd = this.noInstructionEnd = this.noCdataEnd = Infinity;
943
+ this.noParenEnd = this.noBracketEnd = this.noDollarsEnd = Infinity;
944
+ this.parenEnd = this.bracketEnd = this.gtAt = -1;
945
+ while (this.parseInline(root)) {
946
+ /* keep going */
947
+ }
948
+ this.processEmphasis(null);
949
+ return root;
950
+ }
951
+ }
952
+ /**
953
+ * Whether text reads as TeX: it has a command, a superscript, an equals sign or a group, and
954
+ * is not an address. `\\[` and `\\]` are also escaped brackets, as in "replace \\[your_key\\]",
955
+ * so what is between them has to look like a formula to be one.
956
+ */
957
+ // A regex's character class, as it reads between escaped brackets: `a-z`, `^0-9`, `A-Za-z0-9_`
958
+ const reCharClass = /^\^?(?:[A-Za-z0-9_.\s-]|\\[dwsDWSbtnr.\\-](?![A-Za-z]))*$/;
959
+ export function looksLikeCharClass(value) {
960
+ return reCharClass.test(value);
961
+ }
962
+ export function looksLikeTex(value) {
963
+ return (!value.includes('://') &&
964
+ /\\[A-Za-z]|[\^={}]|[A-Za-z0-9)] ?[+\-*/<>|] ?[A-Za-z0-9(\\]/.test(value));
965
+ }
966
+ /**
967
+ * The same question for `\\(` … `\\)`, which is also how Markdown escapes parentheses, as
968
+ * in "Program Files \\(x86\\)". A lone letter or digit is a variable; a longer plain word
969
+ * or phrase is prose.
970
+ */
971
+ function looksLikeInlineTex(value) {
972
+ if (/^[A-Za-z0-9]$/.test(value))
973
+ return true;
974
+ if (/^[A-Za-z0-9]{1,2}$/.test(value))
975
+ return !/^[A-Za-z]{2}$/.test(value) || value !== value.toLowerCase();
976
+ return looksLikeTex(value) || /[_|]/.test(value);
977
+ }
978
+ // GFM autolinks without angle brackets, as GitHub reads them: `www.…`, `http(s)://…` and
979
+ // `ftp://…` here, at parse time; email addresses afterwards, in what is left as text.
980
+ const reUrlHere = /^(?:https?:\/\/|ftp:\/\/|www\.)/i;
981
+ function isSpaceChar(ch) {
982
+ return ch === ' ' || ch === '\t' || ch === '\n' || ch === '\r' || ch === '\f';
983
+ }
984
+ /**
985
+ * Where a bare URL that starts at `start` ends, or -1 when none starts there. After `www.`
986
+ * or the scheme comes a domain (letters, digits, `-` and `_`, in parts joined by dots; none
987
+ * of `_` in its last two parts; `www.` needs a second part), then anything up to a space or
988
+ * `<`, less the punctuation a sentence would end with.
989
+ */
990
+ function bareUrlAt(s, start, inBrackets = false) {
991
+ const first = s.charCodeAt(start) | 32;
992
+ if (first !== 104 && first !== 102 && first !== 119)
993
+ return -1; // h, f, w
994
+ const head = reUrlHere.exec(s.slice(start, start + 8));
995
+ if (!head)
996
+ return -1;
997
+ const www = head[0].length === 4;
998
+ // What may come before it: a scheme may follow anything but a letter; `www.` only the
999
+ // start, a space, or one of `( * _ [ ] ~`
1000
+ const prev = start > 0 ? s.charAt(start - 1) : '';
1001
+ if (www ? prev !== '' && !/[\s(*_[\]~]/.test(prev) : /[A-Za-z]/.test(prev))
1002
+ return -1;
1003
+ let i = start + head[0].length;
1004
+ const domainStart = i;
1005
+ for (; i < s.length; i++) {
1006
+ const code = s.charCodeAt(i);
1007
+ const ok = (code >= 48 && code <= 57) ||
1008
+ (code >= 65 && code <= 90) ||
1009
+ (code >= 97 && code <= 122) ||
1010
+ code === 45 ||
1011
+ code === 46 ||
1012
+ code === 95 ||
1013
+ code > 127;
1014
+ if (!ok)
1015
+ break;
1016
+ }
1017
+ let domainEnd = i;
1018
+ // At the end of the address, a `_` is the emphasis around it: `_http://example.com_`
1019
+ const atEnd = i === s.length || isSpaceChar(s.charAt(i)) || s.charAt(i) === '<';
1020
+ while (domainEnd > domainStart) {
1021
+ const code = s.charCodeAt(domainEnd - 1);
1022
+ if (code !== 46 && !(atEnd && code === 95))
1023
+ break;
1024
+ domainEnd--;
1025
+ }
1026
+ const domain = s.slice(domainStart, domainEnd);
1027
+ if (domain === '')
1028
+ return -1;
1029
+ const parts = domain.split('.');
1030
+ if (parts.some((part) => part === ''))
1031
+ return -1;
1032
+ if (parts.slice(-2).some((part) => part.includes('_')))
1033
+ return -1;
1034
+ let brackets = 0;
1035
+ for (; i < s.length; i++) {
1036
+ const ch = s.charAt(i);
1037
+ if (isSpaceChar(ch) || ch === '<')
1038
+ break;
1039
+ // Inside a link's text, the `]` that closes the text ends the URL: `[https://a.b](c)`
1040
+ if (inBrackets) {
1041
+ if (ch === '[')
1042
+ brackets++;
1043
+ else if (ch === ']' && brackets-- === 0)
1044
+ break;
1045
+ }
1046
+ }
1047
+ const end = trimBareUrl(s, start, i);
1048
+ return end > domainStart ? end : -1;
1049
+ }
1050
+ /**
1051
+ * Takes off what GFM leaves out of the end of a bare URL: closing punctuation, a `)` that
1052
+ * has no `(` before it in the URL, and an entity. One pass from the end.
1053
+ */
1054
+ function trimBareUrl(s, start, end) {
1055
+ let open = 0;
1056
+ let close = 0;
1057
+ for (let i = start; i < end; i++) {
1058
+ const code = s.charCodeAt(i);
1059
+ if (code === 40)
1060
+ open++;
1061
+ else if (code === 41)
1062
+ close++;
1063
+ }
1064
+ while (end > start) {
1065
+ const last = s.charAt(end - 1);
1066
+ if ('?!.,:*_~\'"'.includes(last)) {
1067
+ end--;
1068
+ }
1069
+ else if (last === ')') {
1070
+ if (close <= open)
1071
+ break;
1072
+ close--;
1073
+ end--;
1074
+ }
1075
+ else if (last === ';') {
1076
+ // An entity at the end is not part of the URL; nor is a semicolon on its own
1077
+ let k = end - 2;
1078
+ while (k > start && /[A-Za-z0-9]/.test(s.charAt(k)))
1079
+ k--;
1080
+ end = k >= start && s.charAt(k) === '&' && k < end - 2 ? k : end - 1;
1081
+ }
1082
+ else {
1083
+ break;
1084
+ }
1085
+ }
1086
+ return end;
1087
+ }
1088
+ function isEmailLocal(code) {
1089
+ return ((code >= 48 && code <= 57) ||
1090
+ (code >= 65 && code <= 90) ||
1091
+ (code >= 97 && code <= 122) ||
1092
+ code === 46 ||
1093
+ code === 95 ||
1094
+ code === 43 ||
1095
+ code === 45);
1096
+ }
1097
+ /**
1098
+ * The next email address in text, from `from`: letters, digits and `. _ + -`, an `@`, and a
1099
+ * domain of at least two parts that ends with a letter, so that `pkg@1.2.3` is not one. Nor
1100
+ * is the `git@github.com` of `ssh://git@github.com/…`, which follows a slash.
1101
+ */
1102
+ function findEmail(value, from) {
1103
+ let at = value.indexOf('@', from);
1104
+ while (at >= 0) {
1105
+ let start = at;
1106
+ while (start > from && isEmailLocal(value.charCodeAt(start - 1)))
1107
+ start--;
1108
+ let end = at + 1;
1109
+ let dots = 0;
1110
+ for (; end < value.length; end++) {
1111
+ const code = value.charCodeAt(end);
1112
+ if (code === 46) {
1113
+ if (value.charCodeAt(end - 1) === 46 || end === at + 1)
1114
+ break;
1115
+ dots++;
1116
+ }
1117
+ else if (!(isEmailLocal(code) && code !== 43)) {
1118
+ break;
1119
+ }
1120
+ }
1121
+ // A dot at the end is the sentence's. A hyphen or underscore there means it is no address
1122
+ while (end > at + 1 && value.charCodeAt(end - 1) === 46) {
1123
+ dots--;
1124
+ end--;
1125
+ }
1126
+ const before = start > 0 ? value.charAt(start - 1) : '';
1127
+ if (start < at &&
1128
+ dots > 0 &&
1129
+ before !== '/' &&
1130
+ /[A-Za-z]/.test(value.charAt(end - 1)) &&
1131
+ !value
1132
+ .slice(at + 1, end)
1133
+ .split('.')
1134
+ .slice(-2)
1135
+ .some((part) => part.includes('_')))
1136
+ return { start, end };
1137
+ at = value.indexOf('@', at + 1);
1138
+ }
1139
+ return null;
1140
+ }
1141
+ /** Turns email addresses in a node's text into links. Links and images are left alone. */
1142
+ function linkEmails(node) {
1143
+ for (let child = node.firstChild; child;) {
1144
+ const next = child.next;
1145
+ if (child.type === 'link' || child.type === 'image') {
1146
+ child = next;
1147
+ continue;
1148
+ }
1149
+ if (child.type !== 'text') {
1150
+ linkEmails(child);
1151
+ child = next;
1152
+ continue;
1153
+ }
1154
+ // Text split by a mark that came to nothing (the `_` of `a_b@c.d`) is one text again
1155
+ while (child.next && child.next.type === 'text') {
1156
+ child.value += child.next.value;
1157
+ child.next.unlink();
1158
+ }
1159
+ const following = child.next;
1160
+ let current = child;
1161
+ let value = child.value;
1162
+ let found = value.includes('@') ? findEmail(value, 0) : null;
1163
+ while (found) {
1164
+ const address = value.slice(found.start, found.end);
1165
+ const rest = value.slice(found.end);
1166
+ current.value = value.slice(0, found.start);
1167
+ const link = new INode('link');
1168
+ link.url = normalizeUri('mailto:' + address);
1169
+ link.kind = 'literal';
1170
+ link.appendChild(text(address));
1171
+ current.insertAfter(link);
1172
+ const tail = text(rest);
1173
+ link.insertAfter(tail);
1174
+ current = tail;
1175
+ value = rest;
1176
+ found = findEmail(value, 0);
1177
+ }
1178
+ child = following;
1179
+ }
1180
+ }
1181
+ /** Replaces the bare-URL links inside a node by their text. */
1182
+ function unwrapLiteralLinks(node) {
1183
+ const stack = [node];
1184
+ while (stack.length > 0) {
1185
+ const parent = stack.pop();
1186
+ for (let child = parent.firstChild; child;) {
1187
+ const next = child.next;
1188
+ if (child.type === 'link' && child.kind === 'literal') {
1189
+ const label = child.firstChild;
1190
+ if (label)
1191
+ child.insertBefore(label);
1192
+ child.unlink();
1193
+ }
1194
+ else if (child.firstChild) {
1195
+ stack.push(child);
1196
+ }
1197
+ child = next;
1198
+ }
1199
+ }
1200
+ }
1201
+ /** The deepest that emphasis, links and images may nest. Beyond it they are flattened. */
1202
+ const MAX_INLINE_DEPTH = 32;
1203
+ /**
1204
+ * Flattens what nests deeper than any real text does: `*a *a *a …` thousands deep would
1205
+ * otherwise overflow the stack of everything that walks the tree, the renderer included.
1206
+ * Below the limit, a wrapper is replaced by what it wraps.
1207
+ */
1208
+ function limitDepth(root) {
1209
+ const stack = [[root, 0]];
1210
+ while (stack.length > 0) {
1211
+ const [parent, depth] = stack.pop();
1212
+ for (let child = parent.firstChild; child;) {
1213
+ const next = child.next;
1214
+ if (child.firstChild) {
1215
+ if (depth >= MAX_INLINE_DEPTH) {
1216
+ // Its children take its place, and are looked at in turn
1217
+ let moved = child.firstChild;
1218
+ const first = moved;
1219
+ while (moved) {
1220
+ const after = moved.next;
1221
+ child.insertBefore(moved);
1222
+ moved = after;
1223
+ }
1224
+ child.unlink();
1225
+ child = first;
1226
+ continue;
1227
+ }
1228
+ stack.push([child, depth + 1]);
1229
+ }
1230
+ child = next;
1231
+ }
1232
+ }
1233
+ }
1234
+ // Conversion to the public nodes
1235
+ function plainText(node) {
1236
+ let out = '';
1237
+ for (let c = node.firstChild; c; c = c.next) {
1238
+ if (c.type === 'text' || c.type === 'inlineCode' || c.type === 'inlineMath')
1239
+ out += c.value;
1240
+ else if (c.type === 'softBreak' || c.type === 'break')
1241
+ out += '\n';
1242
+ else
1243
+ out += plainText(c);
1244
+ }
1245
+ return out;
1246
+ }
1247
+ function toInlines(node) {
1248
+ const out = [];
1249
+ for (let c = node.firstChild; c; c = c.next) {
1250
+ switch (c.type) {
1251
+ case 'text': {
1252
+ if (c.value === '')
1253
+ break;
1254
+ const last = out[out.length - 1];
1255
+ if (last && last.type === 'text')
1256
+ last.value += c.value;
1257
+ else
1258
+ out.push({ type: 'text', value: c.value });
1259
+ break;
1260
+ }
1261
+ case 'emphasis':
1262
+ case 'strong':
1263
+ case 'delete':
1264
+ out.push({ type: c.type, children: toInlines(c) });
1265
+ break;
1266
+ case 'inlineCode':
1267
+ out.push({ type: 'inlineCode', value: c.value });
1268
+ break;
1269
+ case 'break':
1270
+ case 'softBreak':
1271
+ out.push({ type: c.type });
1272
+ break;
1273
+ case 'inlineHtml':
1274
+ out.push({ type: 'inlineHtml', value: c.value });
1275
+ break;
1276
+ case 'inlineMath':
1277
+ out.push({ type: 'inlineMath', value: c.value, display: c.display });
1278
+ break;
1279
+ case 'link':
1280
+ if (c.url === PENDING_URL)
1281
+ out.push({
1282
+ type: 'link',
1283
+ url: '',
1284
+ title: null,
1285
+ kind: 'inline',
1286
+ pending: true,
1287
+ children: toInlines(c)
1288
+ });
1289
+ else
1290
+ out.push({
1291
+ type: 'link',
1292
+ url: c.url,
1293
+ title: c.title,
1294
+ kind: c.kind,
1295
+ children: toInlines(c)
1296
+ });
1297
+ break;
1298
+ case 'image':
1299
+ out.push({
1300
+ type: 'image',
1301
+ url: c.url,
1302
+ title: c.title,
1303
+ alt: plainText(c),
1304
+ children: toInlines(c)
1305
+ });
1306
+ break;
1307
+ case 'footnoteReference':
1308
+ out.push({ type: 'footnoteReference', label: c.label });
1309
+ break;
1310
+ }
1311
+ }
1312
+ return out;
1313
+ }
1314
+ export function parseInlines(content, context) {
1315
+ const parser = new InlineParser(context);
1316
+ const root = parser.parse(content);
1317
+ limitDepth(root);
1318
+ if (context.gfm)
1319
+ linkEmails(root);
1320
+ return { children: toInlines(root), missed: parser.missed };
1321
+ }
1322
+ // Tidying the end of text that is still being written
1323
+ function trimEndSpaces(s) {
1324
+ let end = s.length;
1325
+ while (end > 0 && (s.charCodeAt(end - 1) === 32 || s.charCodeAt(end - 1) === 9))
1326
+ end--;
1327
+ return end === s.length ? s : s.slice(0, end);
1328
+ }
1329
+ /** Whether the character at `at` is escaped: an odd number of backslashes come before it. */
1330
+ function isEscaped(s, at) {
1331
+ let n = 0;
1332
+ for (let i = at - 1; i >= 0 && s.charCodeAt(i) === 92; i--)
1333
+ n++;
1334
+ return n % 2 === 1;
1335
+ }
1336
+ // The address a tidied preview gives a link whose own is still being written: a character
1337
+ // from the private-use area, which no real address is
1338
+ const PENDING = '\uE000';
1339
+ const PENDING_URL = normalizeUri(PENDING);
1340
+ /** Where something new can start: the beginning, or after a space or an opening mark. */
1341
+ function startsFresh(s, at) {
1342
+ return at === 0 || /[\s(*_~>"'“‘|:]/.test(s.charAt(at - 1));
1343
+ }
1344
+ /**
1345
+ * Makes the end of text that is still being written read as it most likely will: a link
1346
+ * waiting for its destination shows as its text, a half-written tag, entity or image is held
1347
+ * back, an open code span runs to the end, and emphasis that has started is closed. Text
1348
+ * that is complete is returned unchanged. Only ever used on the last, unfinished block.
1349
+ *
1350
+ * Every rule here is a guess about what comes next, so each one fires only where a wrong
1351
+ * guess is unlikely: `a<b` is not a tag, `arr[i` is not a link, and `3*4` is not emphasis.
1352
+ */
1353
+ export function tidyTail(content, context) {
1354
+ // Inside an open code span nothing is Markdown: only the span itself is closed, and the
1355
+ // emphasis around it
1356
+ const span = openCodeSpan(content);
1357
+ if (span) {
1358
+ const head = content.slice(0, span.pos);
1359
+ const code = content.slice(span.pos + span.run.length);
1360
+ if (code.trim() === '')
1361
+ return closeEmphasis(trimEndSpaces(head), '', context);
1362
+ // A span whose code ends with a backtick needs a space before its closing run
1363
+ const pad = code.endsWith('`') ? ' ' : '';
1364
+ const lead = pad && !code.startsWith(' ') ? ' ' : '';
1365
+ return closeEmphasis(head, span.run + lead + code + pad + span.run, context);
1366
+ }
1367
+ return trimEndSpaces(closeEmphasis(holdBack(content, context), '', context));
1368
+ }
1369
+ /** Whether the start of something reads as TeX on its way: looser than a whole formula. */
1370
+ function looksLikeTexSoFar(tail) {
1371
+ return (!tail.includes('://') &&
1372
+ // `$x`, `$n1`: a variable. Not `$5` or `$10`, which are prices far more often
1373
+ (/[\\^_={}+\-*/<>|]/.test(tail) || /^[A-Za-z][A-Za-z0-9]?$/.test(tail)));
1374
+ }
1375
+ const INLINE_TAGS = [
1376
+ 'br',
1377
+ 'sub',
1378
+ 'sup',
1379
+ 'kbd',
1380
+ 'code',
1381
+ 'em',
1382
+ 'strong',
1383
+ 'del',
1384
+ 'ins',
1385
+ 'mark',
1386
+ 'span',
1387
+ 'img',
1388
+ 'small'
1389
+ ];
1390
+ /**
1391
+ * Whether what follows a `<` is the name of a tag people write in running text, or two
1392
+ * letters or more of one on its way: `br`, `su`, `kbd`, `span sty`. One letter is not
1393
+ * enough: `a<b` and `n<i` are comparisons.
1394
+ */
1395
+ function inlineTagSoFar(tail) {
1396
+ const name = /^[A-Za-z][A-Za-z0-9]*/.exec(tail)?.[0].toLowerCase();
1397
+ if (!name || name.length < 2)
1398
+ return false;
1399
+ const rest = tail.slice(name.length);
1400
+ if (rest === '')
1401
+ return INLINE_TAGS.some((tag) => tag.startsWith(name));
1402
+ return /^\s/.test(rest) && INLINE_TAGS.includes(name);
1403
+ }
1404
+ /** Takes off the end what cannot be drawn yet, and shows a link in the making as its text. */
1405
+ function holdBack(content, context) {
1406
+ let s = content;
1407
+ // A backslash with nothing after it
1408
+ if (s.endsWith('\\') && !isEscaped(s, s.length - 1))
1409
+ s = s.slice(0, -1);
1410
+ // An entity on its way: `&am`, `&#12`. Not the `&` of "AT&T"
1411
+ const amp = s.lastIndexOf('&');
1412
+ if (amp >= 0 && s.length - amp <= 34 && startsFresh(s, amp)) {
1413
+ if (/^&(?:#[xX]?[0-9A-Fa-f]*|[A-Za-z][A-Za-z0-9]*)?$/.test(s.slice(amp)))
1414
+ s = s.slice(0, amp);
1415
+ }
1416
+ // A tag or an autolink on its way: `<kb`, `<https://exa`. Not the `<` of "a<b" or "x < y"
1417
+ const lt = s.lastIndexOf('<');
1418
+ if (lt >= 0 && s.length - lt <= 200) {
1419
+ const tail = s.slice(lt);
1420
+ // Right after a word, `<` is more often "less than" (`a<b`, `i<len`). There only what
1421
+ // can be nothing else is held back: an end tag, or the name of a tag written in text
1422
+ const fresh = startsFresh(s, lt) || /^<\/[A-Za-z]/.test(tail) || inlineTagSoFar(tail.slice(1));
1423
+ if (fresh &&
1424
+ !tail.includes('>') &&
1425
+ /^<(?:\/?(?:[A-Za-z][A-Za-z0-9-]*(?:\s[^<>]*)?)?|!(?:-|--[\s\S]*)?|[A-Za-z][A-Za-z0-9+.-]*:\S*)?$/.test(tail))
1426
+ s = s.slice(0, lt);
1427
+ }
1428
+ // An image on its way is held back whole: half an image is nothing
1429
+ const bang = s.lastIndexOf('![');
1430
+ if (bang >= 0 && s.length - bang <= 2000 && !isEscaped(s, bang)) {
1431
+ // Its alt text, then nothing yet, or an address or a title that has not ended. One that
1432
+ // is whole, `![a](b.png)`, is drawn
1433
+ const m = /^!\[[^[\]]*(?:\](\([\s\S]*)?)?$/.exec(s.slice(bang));
1434
+ if (m && (m[1] === undefined || addressUnfinished(m[1].slice(1))))
1435
+ s = s.slice(0, bang);
1436
+ }
1437
+ // A link waiting for the end of its address is a link already, with nowhere to go yet:
1438
+ // `[the docs](https://na` reads as a link from its `(` on, so it does not turn from plain
1439
+ // text into a link when its address ends. (An idea from Pierre's Words.)
1440
+ const paren = s.lastIndexOf('](');
1441
+ if (paren >= 0 && s.length - paren <= 2000 && addressUnfinished(s.slice(paren + 2))) {
1442
+ const open = matchingBracket(s, paren);
1443
+ if (open >= 0 && !isEscaped(s, open) && s.charAt(open - 1) !== '!') {
1444
+ // Emphasis that has started in the link's words is closed inside them
1445
+ const words = closeEmphasis(s.slice(open + 1, paren), '', context);
1446
+ s = `${s.slice(0, open)}[${words}](<${PENDING}>)`;
1447
+ }
1448
+ }
1449
+ // A bracket that has just closed is most likely a link's text, about to get its address:
1450
+ // `[the docs]` shows as it did while it was being written, without its brackets, unless
1451
+ // it is a reference that is defined
1452
+ if (s.endsWith(']') && !isEscaped(s, s.length - 1)) {
1453
+ const start = matchingBracket(s, s.length - 1);
1454
+ if (start >= 0 &&
1455
+ !isEscaped(s, start) &&
1456
+ s.charAt(start - 1) !== '!' &&
1457
+ startsFresh(s, start)) {
1458
+ const inner = s.slice(start + 1, -1);
1459
+ const key = labelKey(`[${inner}]`);
1460
+ if (inner.length <= 300 &&
1461
+ /^[\p{L}`*_]/u.test(inner) &&
1462
+ !inner.includes('\n\n') &&
1463
+ (key === null || !context.definitions.has(key)))
1464
+ s = s.slice(0, start) + inner;
1465
+ }
1466
+ }
1467
+ // A bracket that has opened and not closed
1468
+ const open = lastOpenBracket(s);
1469
+ if (open >= 0 && !isEscaped(s, open)) {
1470
+ const inner = s.slice(open + 1);
1471
+ if (/^\^\S*$/.test(inner) || /^![A-Za-z]*$/.test(inner)) {
1472
+ // A footnote reference or an alert marker in the making
1473
+ s = s.slice(0, open);
1474
+ }
1475
+ else if (inner.length <= 300 &&
1476
+ startsFresh(s, open) &&
1477
+ (inner === '' || /^[\p{L}`*_]/u.test(inner))) {
1478
+ // Most likely a link's text. Not `arr[i`, `x = [1, 2`, or `matrix[i][j`
1479
+ s = s.slice(0, open) + inner;
1480
+ }
1481
+ }
1482
+ // A formula that has opened and not closed is held back, when it reads as one
1483
+ if (context.math) {
1484
+ const at = Math.max(lastUnclosed(s, '\\(', '\\)'), lastUnclosed(s, '\\[', '\\]'));
1485
+ if (at >= 0 && !isEscaped(s, at)) {
1486
+ const tail = s.slice(at + 2).trim();
1487
+ if (tail === '' || looksLikeTexSoFar(tail))
1488
+ s = s.slice(0, at);
1489
+ }
1490
+ const dollars = s.split('$$').length - 1;
1491
+ if (dollars % 2 === 1) {
1492
+ const last = s.lastIndexOf('$$');
1493
+ const tail = s.slice(last + 2).trim();
1494
+ if (tail === '' || looksLikeTexSoFar(tail))
1495
+ s = s.slice(0, last);
1496
+ }
1497
+ else {
1498
+ // A single dollar that would open a formula, with TeX after it
1499
+ const dollar = s.lastIndexOf('$');
1500
+ const line = s.lastIndexOf('\n');
1501
+ if (dollar > line && s.charAt(dollar - 1) !== '$' && startsFresh(s, dollar)) {
1502
+ const before = s.slice(line + 1, dollar);
1503
+ const paired = (before.split('$').length - 1) % 2 === 1;
1504
+ const tail = s.slice(dollar + 1);
1505
+ if (!paired && tail !== '' && !/^[\s,({]/.test(tail) && looksLikeTexSoFar(tail))
1506
+ s = s.slice(0, dollar);
1507
+ }
1508
+ }
1509
+ }
1510
+ return s;
1511
+ }
1512
+ /**
1513
+ * Whether what follows a `](` is a link's address still being written: the address itself,
1514
+ * or the title after it (`https://x.y "The ti`), with the closing `)` yet to come.
1515
+ */
1516
+ function addressUnfinished(tail) {
1517
+ let i = 0;
1518
+ if (tail.charCodeAt(0) === 60) {
1519
+ // `<an address with spaces>`
1520
+ const end = tail.indexOf('>');
1521
+ if (end < 0)
1522
+ return !tail.includes('\n');
1523
+ i = end + 1;
1524
+ }
1525
+ else {
1526
+ let depth = 0;
1527
+ for (; i < tail.length; i++) {
1528
+ const ch = tail.charCodeAt(i);
1529
+ if (ch === 32 || ch === 9 || ch === 10)
1530
+ break;
1531
+ if (ch === 40)
1532
+ depth++;
1533
+ else if (ch === 41 && depth-- === 0)
1534
+ return false;
1535
+ }
1536
+ }
1537
+ const space = /^[ \t]*\n?[ \t]*/.exec(tail.slice(i))[0].length;
1538
+ i += space;
1539
+ if (i >= tail.length)
1540
+ return true;
1541
+ if (space === 0)
1542
+ return false;
1543
+ // A title, in quotes or brackets, that has not closed
1544
+ const quote = tail.charAt(i);
1545
+ if (quote !== '"' && quote !== "'" && quote !== '(')
1546
+ return false;
1547
+ const close = quote === '(' ? ')' : quote;
1548
+ for (let k = i + 1; k < tail.length; k++) {
1549
+ const ch = tail.charAt(k);
1550
+ if (ch === '\\')
1551
+ k++;
1552
+ else if (ch === '\n' && tail.charAt(k + 1) === '\n')
1553
+ return false;
1554
+ else if (ch === close)
1555
+ return /^[ \t]*$/.test(tail.slice(k + 1));
1556
+ }
1557
+ return true;
1558
+ }
1559
+ /** The `[` that the `]` at `close` closes, or -1. */
1560
+ function matchingBracket(s, close) {
1561
+ let depth = 0;
1562
+ for (let i = close - 1; i >= 0 && close - i <= 2000; i--) {
1563
+ const ch = s.charCodeAt(i);
1564
+ if (ch === 93)
1565
+ depth++;
1566
+ else if (ch === 91) {
1567
+ if (depth === 0)
1568
+ return i;
1569
+ depth--;
1570
+ }
1571
+ }
1572
+ return -1;
1573
+ }
1574
+ /** The last `[` with no `]` after it to close it, or -1. */
1575
+ function lastOpenBracket(s) {
1576
+ let depth = 0;
1577
+ for (let i = s.length - 1; i >= 0 && s.length - i <= 2000; i--) {
1578
+ const ch = s.charCodeAt(i);
1579
+ if (ch === 10 && s.charCodeAt(i - 1) === 10)
1580
+ break;
1581
+ if (ch === 93)
1582
+ depth++;
1583
+ else if (ch === 91) {
1584
+ if (depth === 0)
1585
+ return i;
1586
+ depth--;
1587
+ }
1588
+ }
1589
+ return -1;
1590
+ }
1591
+ /**
1592
+ * Closes emphasis that has started in `head`, after `tail` (a closed code span, or nothing).
1593
+ * An opener is closed only where it reads as one: at the start of a word, with a word after
1594
+ * it. The `*` of `3*4`, `char*p` and `ls *.txt` is left as it is.
1595
+ */
1596
+ function closeEmphasis(head, tail, context) {
1597
+ let s = head;
1598
+ if (tail === '') {
1599
+ // A run of marks at the very end has nothing to open yet
1600
+ const run = /(^|[\s(])[*_~]+[ \t]*$/.exec(s.slice(-40));
1601
+ if (run)
1602
+ s = trimEndSpaces(s.slice(0, s.length - run[0].length + run[1].length));
1603
+ // A run right after a word may be a closing run half written: of `**bold*`, the `*` is
1604
+ // the first half of `**`. It is, when what it would close has more marks than it
1605
+ const half = /([*_~])\1*$/.exec(s);
1606
+ if (half && half.index > 0 && !/\s/.test(s.charAt(half.index - 1))) {
1607
+ const without = s.slice(0, half.index);
1608
+ const open = openersIn(without, '', context);
1609
+ const last = open[open.length - 1];
1610
+ if (last && last.run[0] === half[1] && last.run.length > half[0].length)
1611
+ s = without;
1612
+ }
1613
+ }
1614
+ if (!/[*_~]/.test(s))
1615
+ return s + tail;
1616
+ const openers = openersIn(s, tail, context);
1617
+ if (openers.length === 0)
1618
+ return s + tail;
1619
+ let closers = '';
1620
+ // Innermost first. Deeper than any real text nests, the rest are left open
1621
+ for (let i = openers.length - 1; i >= Math.max(0, openers.length - MAX_INLINE_DEPTH); i--)
1622
+ closers += openers[i].run;
1623
+ return (tail === '' ? trimEndSpaces(s) : s + tail) + closers;
1624
+ }
1625
+ // What may follow an opening run for it to read as one: a letter or a digit, an opening
1626
+ // mark, a code span, a formula, or a pictograph (`**✅ Done`)
1627
+ const reAfterOpener = /[\p{L}\p{N}"'([{`<$\\!“‘「『(《〈【\p{Extended_Pictographic}]/u;
1628
+ /** The emphasis runs in `s` that have opened and not closed, where each reads as an opener. */
1629
+ function openersIn(s, tail, context) {
1630
+ const parser = new InlineParser(context);
1631
+ parser.parse(s + tail);
1632
+ return parser.unclosed
1633
+ .filter(({ pos, run }) => {
1634
+ if (pos >= s.length)
1635
+ return false;
1636
+ const before = pos === 0 ? '' : s.charAt(pos - 1);
1637
+ const after = s.charAt(pos + run.length);
1638
+ return (
1639
+ // Not inside a word (`3*4`, `char*p`), but words written without spaces between
1640
+ // them have marks inside them all the time: `中文**加粗`
1641
+ (before === '' || !/[\p{L}\p{N}]/u.test(before) || reCjk.test(before)) &&
1642
+ (after === ''
1643
+ ? tail !== ''
1644
+ : reAfterOpener.test(after) || (pos + run.length === s.length && tail !== '')));
1645
+ })
1646
+ .sort((a, b) => a.pos - b.pos);
1647
+ }
1648
+ /** Where the last `open` with no `close` after it is, or -1. */
1649
+ function lastUnclosed(s, open, close) {
1650
+ const at = s.lastIndexOf(open);
1651
+ return at >= 0 && s.indexOf(close, at + open.length) < 0 ? at : -1;
1652
+ }
1653
+ /** The last backtick run that opens a code span with no closing run, if any. */
1654
+ function openCodeSpan(s) {
1655
+ const re = /`+/g;
1656
+ let open = null;
1657
+ let m;
1658
+ while ((m = re.exec(s))) {
1659
+ // Escaped backticks are text
1660
+ if (!open && isEscaped(s, m.index))
1661
+ continue;
1662
+ if (open === null)
1663
+ open = { pos: m.index, run: m[0] };
1664
+ else if (m[0] === open.run)
1665
+ open = null;
1666
+ }
1667
+ return open;
1668
+ }
1669
+ /**
1670
+ * Reads a link reference definition at the start of `s`: `[label]: destination "title"`.
1671
+ * Returns where it ends (after its line ending), or null when `s` does not start with one.
1672
+ */
1673
+ export function parseReferenceDefinition(s) {
1674
+ const parser = new InlineParser({ definitions: new Map(), footnotes: new Set(), gfm: false });
1675
+ parser.subject = s;
1676
+ parser.pos = 0;
1677
+ const matchChars = parser.parseLinkLabel();
1678
+ if (matchChars === 0)
1679
+ return null;
1680
+ const rawlabel = s.slice(0, matchChars);
1681
+ if (parser.peek() !== C_COLON)
1682
+ return null;
1683
+ parser.pos++;
1684
+ parser.spnl();
1685
+ const dest = parser.parseLinkDestination();
1686
+ if (dest === null)
1687
+ return null;
1688
+ const beforetitle = parser.pos;
1689
+ parser.spnl();
1690
+ let title = null;
1691
+ if (parser.pos !== beforetitle)
1692
+ title = parser.parseLinkTitle();
1693
+ if (title === null)
1694
+ parser.pos = beforetitle;
1695
+ // Nothing but spaces may follow on the line
1696
+ let atLineEnd = true;
1697
+ if (parser.match(reSpaceAtEndOfLine) === null) {
1698
+ if (title === null) {
1699
+ atLineEnd = false;
1700
+ }
1701
+ else {
1702
+ // The title is not part of it after all; try without
1703
+ title = null;
1704
+ parser.pos = beforetitle;
1705
+ atLineEnd = parser.match(reSpaceAtEndOfLine) !== null;
1706
+ }
1707
+ }
1708
+ if (!atLineEnd)
1709
+ return null;
1710
+ const label = labelKey(rawlabel);
1711
+ if (label === null)
1712
+ return null;
1713
+ return { label, url: dest, title, end: parser.pos };
1714
+ }