@treasure-ai/treasure-deck 0.0.0-stage → 2026.10.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 (110) hide show
  1. package/LICENSE.md +5 -0
  2. package/README.md +109 -2
  3. package/dist/analytics.d.ts +34 -0
  4. package/dist/analytics.js +93 -0
  5. package/dist/analytics.js.map +1 -0
  6. package/dist/attrs.d.ts +10 -0
  7. package/dist/attrs.js +22 -0
  8. package/dist/attrs.js.map +1 -0
  9. package/dist/build.d.ts +67 -0
  10. package/dist/build.js +247 -0
  11. package/dist/build.js.map +1 -0
  12. package/dist/check.d.ts +30 -0
  13. package/dist/check.js +142 -0
  14. package/dist/check.js.map +1 -0
  15. package/dist/chrome.d.ts +20 -0
  16. package/dist/chrome.js +162 -0
  17. package/dist/chrome.js.map +1 -0
  18. package/dist/cli.d.ts +2 -0
  19. package/dist/cli.js +246 -0
  20. package/dist/cli.js.map +1 -0
  21. package/dist/dev.d.ts +28 -0
  22. package/dist/dev.js +557 -0
  23. package/dist/dev.js.map +1 -0
  24. package/dist/diagrams.d.ts +18 -0
  25. package/dist/diagrams.js +57 -0
  26. package/dist/diagrams.js.map +1 -0
  27. package/dist/highlight.d.ts +7 -0
  28. package/dist/highlight.js +26 -0
  29. package/dist/highlight.js.map +1 -0
  30. package/dist/hot.d.ts +31 -0
  31. package/dist/hot.js +34 -0
  32. package/dist/hot.js.map +1 -0
  33. package/dist/media.d.ts +24 -0
  34. package/dist/media.js +82 -0
  35. package/dist/media.js.map +1 -0
  36. package/dist/parse.d.ts +109 -0
  37. package/dist/parse.js +313 -0
  38. package/dist/parse.js.map +1 -0
  39. package/dist/patch.d.ts +22 -0
  40. package/dist/patch.js +53 -0
  41. package/dist/patch.js.map +1 -0
  42. package/dist/pdf.d.ts +10 -0
  43. package/dist/pdf.js +53 -0
  44. package/dist/pdf.js.map +1 -0
  45. package/dist/render.d.ts +101 -0
  46. package/dist/render.js +513 -0
  47. package/dist/render.js.map +1 -0
  48. package/dist/scaffold.d.ts +27 -0
  49. package/dist/scaffold.js +83 -0
  50. package/dist/scaffold.js.map +1 -0
  51. package/dist/themecheck.d.ts +34 -0
  52. package/dist/themecheck.js +228 -0
  53. package/dist/themecheck.js.map +1 -0
  54. package/docs/adrs/2026-10-03-chrome-over-devtools.md +29 -0
  55. package/docs/adrs/2026-10-03-fixed-canvas.md +25 -0
  56. package/docs/adrs/2026-10-03-four-layouts-plus-attributes.md +25 -0
  57. package/docs/adrs/2026-10-03-hybrid-pdf-over-devtools.md +25 -0
  58. package/docs/adrs/2026-10-03-keyword-lines-and-one-attribute-syntax.md +36 -0
  59. package/docs/adrs/2026-10-03-one-behavior-instead-of-settings.md +30 -0
  60. package/docs/adrs/2026-10-03-overflow-is-reported-not-hidden.md +27 -0
  61. package/docs/adrs/2026-10-03-single-file-html.md +26 -0
  62. package/docs/adrs/2026-10-03-strict-build-forgiving-preview.md +31 -0
  63. package/docs/adrs/2026-10-04-edit-in-place-by-alignment.md +28 -0
  64. package/docs/adrs/2026-10-04-editor-in-the-deck-page.md +31 -0
  65. package/docs/adrs/2026-10-04-edits-are-line-range-patches.md +35 -0
  66. package/docs/adrs/2026-10-04-per-slide-hot-swap.md +33 -0
  67. package/docs/adrs/2026-10-04-theme-colors-derive-in-css.md +32 -0
  68. package/docs/adrs/2026-10-05-host-owns-undo.md +26 -0
  69. package/docs/adrs/2026-10-07-anonymous-access-metrics.md +38 -0
  70. package/docs/adrs/2026-10-14-dev-links-media-by-url.md +25 -0
  71. package/docs/adrs/2026-10-14-media-dir-for-the-publish-limit.md +28 -0
  72. package/docs/adrs/2026-10-14-videos-are-inlined-images.md +28 -0
  73. package/docs/adrs/2026-10-15-public-npm-under-labs-terms.md +37 -0
  74. package/docs/adrs/README.md +34 -0
  75. package/docs/commands.md +104 -0
  76. package/docs/editor.md +114 -0
  77. package/docs/syntax.md +157 -0
  78. package/docs/themes.md +134 -0
  79. package/package.json +68 -4
  80. package/runtime/base.css +354 -0
  81. package/runtime/edit-core.cjs +877 -0
  82. package/runtime/embed.js +5259 -0
  83. package/runtime/hot.js +136 -0
  84. package/runtime/runtime.js +729 -0
  85. package/skills/treasure-deck/SKILL.md +136 -0
  86. package/templates/deck.md +78 -0
  87. package/templates/specimen/specimen.md +104 -0
  88. package/templates/theme/assets/mark.svg +1 -0
  89. package/templates/theme/theme.css +97 -0
  90. package/templates/theme/theme.yaml +7 -0
  91. package/themes/default/theme.css +183 -0
  92. package/themes/default/theme.yaml +6 -0
  93. package/themes/editorial/theme.css +168 -0
  94. package/themes/editorial/theme.yaml +7 -0
  95. package/themes/gold/assets/gem.svg +130 -0
  96. package/themes/gold/theme.css +303 -0
  97. package/themes/gold/theme.yaml +7 -0
  98. package/themes/pastel/theme.css +187 -0
  99. package/themes/pastel/theme.yaml +6 -0
  100. package/themes/treasure-ai/assets/gem-line.svg +7 -0
  101. package/themes/treasure-ai/assets/gem.png +0 -0
  102. package/themes/treasure-ai/assets/gem.svg +25 -0
  103. package/themes/treasure-ai/assets/glass.svg +12 -0
  104. package/themes/treasure-ai/assets/logo-white.png +0 -0
  105. package/themes/treasure-ai/assets/logo.png +0 -0
  106. package/themes/treasure-ai/theme.css +239 -0
  107. package/themes/treasure-ai/theme.yaml +6 -0
  108. package/themes/wvlet/assets/wvlet-icon.svg +27 -0
  109. package/themes/wvlet/theme.css +238 -0
  110. package/themes/wvlet/theme.yaml +6 -0
@@ -0,0 +1,877 @@
1
+ /* treasure-deck edit core: the source rewrites behind the visual editor's slide toolbar, as patches
2
+ * {start, end, expected, text} on a file's lines (1-based, inclusive; end = start - 1 inserts; text null deletes).
3
+ * Pure functions on an array of lines, shared by the embed bridge (deck editor) and the tests. */
4
+ (function (root) {
5
+ 'use strict';
6
+ var BREAK = /^---(?:\s+(.*))?$/;
7
+
8
+ /** A slide header line `--- columns 3:2 {.dark hide}`: its layout, arguments, and attribute text (inside the braces). */
9
+ function readHeader(line) {
10
+ var m = BREAK.exec(line || '');
11
+ if (!m) return { exists: false, layout: '', args: [], attrs: '' };
12
+ var h = (m[1] || '').trim();
13
+ var brace = h.indexOf('{');
14
+ var attrs = brace >= 0 ? h.slice(brace + 1, h.lastIndexOf('}') > brace ? h.lastIndexOf('}') : h.length).trim() : '';
15
+ var head = (brace >= 0 ? h.slice(0, brace) : h).trim();
16
+ var parts = head ? head.split(/\s+/) : [];
17
+ return { exists: true, layout: parts[0] || '', args: parts.slice(1), attrs: attrs };
18
+ }
19
+
20
+ function writeHeader(h) {
21
+ var parts = ['---'];
22
+ if (h.layout) parts.push(h.layout);
23
+ parts = parts.concat(h.layout ? h.args : []);
24
+ if (h.attrs) parts.push('{' + h.attrs + '}');
25
+ return parts.join(' ');
26
+ }
27
+
28
+ /** Attribute text with a bare flag (`hide`, `fit`) set or cleared, keeping every other token as written. */
29
+ function setFlag(attrs, flag, on) {
30
+ var tokens = attrs ? attrs.split(/\s+/).filter(Boolean) : [];
31
+ var has = tokens.indexOf(flag) >= 0;
32
+ if (on && !has) tokens.push(flag);
33
+ if (!on && has) tokens = tokens.filter(function (t) { return t !== flag; });
34
+ return tokens.join(' ');
35
+ }
36
+
37
+ function range(lines, start, end) {
38
+ return lines.slice(start - 1, end);
39
+ }
40
+ // A bare --- on the first line opens frontmatter (in a deck without any), which would swallow the slide after it;
41
+ // a header that lands there names its layout instead.
42
+ function firstLine(start, text) {
43
+ return start === 1 && text !== null && /^---(\n|$)/.test(text) ? '--- content' + text.slice(3) : text;
44
+ }
45
+ function patch(lines, start, end, text) {
46
+ return { start: start, end: end, expected: range(lines, start, end).join('\n'), text: firstLine(start, text) };
47
+ }
48
+
49
+ /** Rewrite a slide's header, or add one above its first line (a first slide may have none). */
50
+ function rewriteHeader(lines, slide, change) {
51
+ var h = readHeader(lines[slide.start - 1]);
52
+ var next = change({ layout: h.layout, args: h.args.slice(), attrs: h.attrs });
53
+ if (h.exists) return patch(lines, slide.start, slide.start, writeHeader(next));
54
+ return { start: slide.start, end: slide.start - 1, expected: '', text: firstLine(slide.start, writeHeader(next)) };
55
+ }
56
+
57
+ /** Set a slide's layout; `ratio` (like '3:2') only for columns. The content layout is written as a bare ---. */
58
+ function setLayout(lines, slide, layout, ratio) {
59
+ return rewriteHeader(lines, slide, function (h) {
60
+ h.layout = layout === 'content' ? '' : layout;
61
+ h.args = layout === 'columns' && ratio ? [ratio] : [];
62
+ return h;
63
+ });
64
+ }
65
+
66
+ function setHidden(lines, slide, hidden) {
67
+ return rewriteHeader(lines, slide, function (h) {
68
+ h.attrs = setFlag(h.attrs, 'hide', hidden);
69
+ return h;
70
+ });
71
+ }
72
+
73
+ /** Attribute text with `key=value` set (null takes the key out), keeping every other token as written. */
74
+ function setAttr(attrs, key, value) {
75
+ var tokens = attrs ? attrs.split(/\s+/).filter(Boolean) : [];
76
+ var i = tokens.findIndex(function (t) { return t.indexOf(key + '=') === 0; });
77
+ if (value === null) { if (i >= 0) tokens.splice(i, 1); } else if (i >= 0) tokens[i] = key + '=' + value; else tokens.push(key + '=' + value);
78
+ return tokens.join(' ');
79
+ }
80
+
81
+ /** Change a slide's header attributes: `set` keys to values (null takes one out), `flags` (`fit`) on or off. */
82
+ function setSlideAttrs(lines, slide, set, flags) {
83
+ return rewriteHeader(lines, slide, function (h) {
84
+ Object.keys(set || {}).forEach(function (k) { h.attrs = setAttr(h.attrs, k, set[k]); });
85
+ Object.keys(flags || {}).forEach(function (f) { h.attrs = setFlag(h.attrs, f, flags[f]); });
86
+ return h;
87
+ });
88
+ }
89
+
90
+ var SEPARATOR = /^===\s+([A-Za-z]\w*)(?:\s+(\d+(?::\d+)+))?\s*(?:\{.*\})?\s*$/, FENCE = /^\s*(`{3,}|~{3,})/;
91
+ /** A slide's `=== col`, `=== row`, and `=== notes` lines (not those in fenced code): their line numbers, words, and ratios. */
92
+ function separators(lines, slide) {
93
+ var out = [], fence = null;
94
+ for (var n = slide.start; n <= slide.end && n <= lines.length; n++) {
95
+ var f = FENCE.exec(lines[n - 1]);
96
+ if (f) { if (!fence) fence = f[1][0]; else if (f[1][0] === fence) fence = null; continue; }
97
+ var m = !fence && SEPARATOR.exec(lines[n - 1].trim());
98
+ if (m) out.push({ line: n, word: m[1], ratio: m[2] || '' });
99
+ }
100
+ return out;
101
+ }
102
+
103
+ // Make a slide a columns slide with header arguments `args`, and add `added` lines after the content that comes
104
+ // before the first of `words` (`row`, `notes`), or at its end. The blank lines after that content stay where they
105
+ // are. One patch over the slide.
106
+ function addParts(lines, slide, args, added, words) {
107
+ var seps = separators(lines, slide), h = readHeader(lines[slide.start - 1]), body = range(lines, slide.start, slide.end);
108
+ var head = writeHeader({ layout: 'columns', args: args, attrs: h.attrs });
109
+ if (h.exists) body[0] = head; else body.unshift(head);
110
+ var stop = seps.filter(function (x) { return words.indexOf(x.word) >= 0; })[0];
111
+ var at = stop ? stop.line - slide.start + (h.exists ? 0 : 1) : body.length;
112
+ while (at > 1 && !body[at - 1].trim()) at--;
113
+ Array.prototype.splice.apply(body, [at, 0].concat(added));
114
+ if (!h.exists) return { start: slide.start, end: slide.end, expected: range(lines, slide.start, slide.end).join('\n'), text: firstLine(slide.start, body.join('\n')) };
115
+ return patch(lines, slide.start, slide.end, body.join('\n'));
116
+ }
117
+
118
+ /**
119
+ * Make a slide a columns slide of `count` columns, at `ratio` ('' for even widths). In a slide with rows, these are
120
+ * the first row's columns (the header's ratio is the first row's). The columns it lacks are added as empty ones to
121
+ * type in: `=== col` lines after the row's content, before the next row or the notes. One patch over the slide (only
122
+ * its header, when no column is added). Columns are never taken out: their text would have to go somewhere.
123
+ */
124
+ function setColumns(lines, slide, count, ratio) {
125
+ var seps = separators(lines, slide), have = 1;
126
+ for (var i = 0; i < seps.length && seps[i].word === 'col'; i++) have++;
127
+ if (count <= have) return setLayout(lines, slide, 'columns', ratio);
128
+ var added = [];
129
+ for (var k = have; k < count; k++) added.push('', '=== col');
130
+ return addParts(lines, slide, ratio ? [ratio] : [], added, ['row', 'notes']);
131
+ }
132
+
133
+ /**
134
+ * Add a row of `count` empty columns at `ratio` ('' for even widths) below a slide's content, before its notes:
135
+ * `=== row` and `count - 1` `=== col` lines. The slide becomes a columns slide, keeping a columns header's ratio.
136
+ */
137
+ function addRow(lines, slide, count, ratio) {
138
+ var h = readHeader(lines[slide.start - 1]), added = ['', '=== row' + (ratio ? ' ' + ratio : '')];
139
+ for (var k = 1; k < count; k++) added.push('', '=== col');
140
+ return addParts(lines, slide, h.layout === 'columns' ? h.args : [], added, ['notes']);
141
+ }
142
+
143
+ // Frontmatter: the deck's settings, `key: value` lines between a `---` on line 1 and the next `---`.
144
+ function frontmatter(lines) {
145
+ if (!/^---\s*$/.test(lines[0] || '')) return null;
146
+ for (var i = 1; i < lines.length; i++) if (/^---\s*$/.test(lines[i])) return { start: 1, end: i + 1 };
147
+ return null;
148
+ }
149
+ // A value and the comment after it (` # …` outside quotes).
150
+ function splitComment(v) {
151
+ for (var i = 0, q = null; i < v.length; i++) {
152
+ var c = v[i];
153
+ if (q) { if (c === '\\' && q === '"') i++; else if (c === q) q = null; } else if (c === '"' || c === "'") q = c;
154
+ else if (c === '#' && (i === 0 || /\s/.test(v[i - 1]))) return { value: v.slice(0, i).replace(/\s+$/, ''), comment: v.slice(i), gap: /\s*$/.exec(v.slice(0, i))[0] };
155
+ }
156
+ return { value: v.replace(/\s+$/, ''), comment: '', gap: '' };
157
+ }
158
+ var META_KEY = /^([A-Za-z_][\w-]*)(\s*:\s*)(.*)$/;
159
+ // A top-level key's line, and the lines after it that continue its value (indented, or a list's `- ` items).
160
+ function metaLine(lines, fm, key) {
161
+ for (var n = fm.start + 1; n < fm.end; n++) {
162
+ var m = META_KEY.exec(lines[n - 1]);
163
+ if (!m || m[1] !== key) continue;
164
+ var last = n;
165
+ while (last + 1 < fm.end && /^(?:\s+\S|-\s)/.test(lines[last])) last++;
166
+ return { line: n, last: last, sep: m[2], rest: m[3] };
167
+ }
168
+ return null;
169
+ }
170
+
171
+ /**
172
+ * The deck's settings as written: each top-level key's value as a string (quotes taken off, comments left out),
173
+ * and '' for one whose value goes on in the lines after it (a list). Null without frontmatter.
174
+ */
175
+ function readMeta(lines) {
176
+ var fm = frontmatter(lines), out = {};
177
+ if (!fm) return null;
178
+ for (var n = fm.start + 1; n < fm.end; n++) {
179
+ var m = META_KEY.exec(lines[n - 1]);
180
+ if (!m) continue;
181
+ var v = splitComment(m[3]).value;
182
+ if (/^".*"$/.test(v)) { try { v = JSON.parse(v); } catch (e) { v = v.slice(1, -1); } } else if (/^'.*'$/.test(v)) v = v.slice(1, -1).replace(/''/g, "'");
183
+ out[m[1]] = v;
184
+ }
185
+ return out;
186
+ }
187
+
188
+ /** A string as a YAML value: as it is when YAML reads it back as that string (or a YYYY-MM-DD date), else quoted. */
189
+ function yamlScalar(s) {
190
+ if (/^\d{4}-\d{2}-\d{2}$/.test(s)) return s;
191
+ var plain = /^[A-Za-z][^#:'"{}\[\],&*!|>%@`]*$/.test(s) && !/\s$/.test(s) && !/^(?:true|false|yes|no|on|off|null|y|n)$/i.test(s);
192
+ return plain ? s : JSON.stringify(s);
193
+ }
194
+
195
+ /**
196
+ * Set a deck setting: `value` is the YAML text of its value (yamlScalar for a string), or null to take the key out.
197
+ * The key's line is rewritten, keeping its spacing and a comment after it; a new key goes last; a deck without
198
+ * frontmatter gets one. Null when nothing changes.
199
+ */
200
+ function setMeta(lines, key, value) {
201
+ var fm = frontmatter(lines);
202
+ if (!fm) return value === null ? null : { start: 1, end: 0, expected: '', text: '---\n' + key + ': ' + value + '\n---' };
203
+ var at = metaLine(lines, fm, key);
204
+ if (!at) return value === null ? null : { start: fm.end, end: fm.end - 1, expected: '', text: key + ': ' + value };
205
+ if (value === null) return patch(lines, at.line, at.last, null);
206
+ var c = at.line === at.last ? splitComment(at.rest) : { comment: '', gap: '' };
207
+ var line = key + at.sep + value + (c.comment ? (c.gap || ' ') + c.comment : '');
208
+ var p = patch(lines, at.line, at.last, line);
209
+ return p.text === p.expected ? null : p;
210
+ }
211
+
212
+ /** A slide's lines as a block that can stand anywhere: it opens with a --- header line. */
213
+ function block(lines, slide) {
214
+ var b = range(lines, slide.start, slide.end);
215
+ if (!BREAK.test(b[0] || '')) b.unshift('---');
216
+ return b;
217
+ }
218
+ /** Blocks joined with a blank line between them where one doesn't end blank already. */
219
+ function join(blocks) {
220
+ var out = [];
221
+ blocks.forEach(function (b) {
222
+ if (out.length && out[out.length - 1].trim() !== '') out.push('');
223
+ out = out.concat(b);
224
+ });
225
+ return out;
226
+ }
227
+
228
+ /**
229
+ * Swap two slides of one file, `a` before `b` (the lines between them, such as hidden slides, stay after `a`).
230
+ * One patch over the span from `a` through `b`, so it is one undo step.
231
+ */
232
+ function swapSlides(lines, a, b) {
233
+ var between = { start: a.start, end: b.start - 1 };
234
+ var text = join([block(lines, b), block(lines, between)]);
235
+ // At the end of the file, the last line stays as it was (no blank line added after the final slide); before
236
+ // another slide, the blank line separates them.
237
+ if (b.end === lines.length && lines[b.end - 1].trim() !== '' && text[text.length - 1].trim() === '') text.pop();
238
+ return patch(lines, a.start, b.end, text.join('\n'));
239
+ }
240
+
241
+ /**
242
+ * Move a slide of one file to just before slide `to`, or to the end of the file (`to` null): a swap of the slide
243
+ * with the run of slides it passes over, so one patch (one undo step), with swapSlides' care for the file's first
244
+ * and last lines. Null when it wouldn't move.
245
+ */
246
+ function moveSlide(lines, slide, to) {
247
+ if (to && (to.start === slide.start || to.start === slide.end + 1)) return null;
248
+ if (!to) return slide.end >= lines.length ? null : swapSlides(lines, slide, { start: slide.end + 1, end: lines.length });
249
+ if (to.start > slide.start) return swapSlides(lines, slide, { start: slide.end + 1, end: to.start - 1 });
250
+ return swapSlides(lines, { start: to.start, end: slide.start - 1 }, slide);
251
+ }
252
+
253
+ /** A copy of a slide inserted before slide `to`, or at the end of the file (`to` null). */
254
+ function copySlide(lines, slide, to) {
255
+ var copy = block(lines, slide);
256
+ if (!to) return duplicateSlide(lines, { start: lines.length + 1, end: lines.length }, copy);
257
+ var text = copy.slice();
258
+ // On the deck's first line a bare --- would open frontmatter.
259
+ if (to.start === 1 && text[0] === '---') text[0] = '--- content';
260
+ if (text[text.length - 1].trim() !== '') text.push('');
261
+ // Before the deck's first slide, that slide gets a --- of its own, as it now follows another.
262
+ if (!BREAK.test(lines[to.start - 1] || '')) text.push('---');
263
+ return { start: to.start, end: to.start - 1, expected: '', text: text.join('\n') };
264
+ }
265
+
266
+ function duplicateSlide(lines, slide, copied) {
267
+ var copy = copied || block(lines, slide);
268
+ var last = lines[slide.end - 1];
269
+ var text = (last.trim() !== '' ? [''] : []).concat(copy);
270
+ if (slide.end < lines.length && text[text.length - 1].trim() !== '') text.push('');
271
+ return { start: slide.end + 1, end: slide.end, expected: '', text: text.join('\n') };
272
+ }
273
+
274
+ function deleteSlide(lines, slide) {
275
+ // Deleting the deck's first lines would bring the next slide's bare --- to line 1: name its layout too.
276
+ if (slide.start === 1 && lines[slide.end] === '---') return patch(lines, 1, slide.end + 1, '--- content');
277
+ return patch(lines, slide.start, slide.end, null);
278
+ }
279
+
280
+ // A block's own attributes: a {…} closing its line. (Right after an inline element, such as **bold**{.x}, braces
281
+ // belong to that element; the bridge checks the rendered classes before trusting this.)
282
+ var TRAILING_ATTRS = /(\s*)\{([^{}]*)\}\s*$/;
283
+
284
+ // Braces right after an inline element's end (**bold**{.x}, ![a](x.png){w=1}, [span]{.x}, `code`{.x}) belong to it.
285
+ var INLINE_END = /[*_`~\])]$/;
286
+ /** A line's trailing {…} when it styles the block, or null. */
287
+ function blockAttrs(line) {
288
+ var m = TRAILING_ATTRS.exec(line || '');
289
+ return m && !(m[1] === '' && INLINE_END.test(line.slice(0, m.index))) ? m : null;
290
+ }
291
+
292
+ /** The classes in a line's block {…}. */
293
+ function lineClasses(line) {
294
+ var m = blockAttrs(line);
295
+ return m ? m[2].split(/\s+/).filter(function (t) { return t[0] === '.'; }).map(function (t) { return t.slice(1); }) : [];
296
+ }
297
+
298
+ /** Set or clear a class in a one-line block's trailing {…}, adding or removing the braces as needed. */
299
+ function setLineClass(lines, lineNo, cls, on) {
300
+ var line = lines[lineNo - 1];
301
+ var m = blockAttrs(line);
302
+ var next;
303
+ if (m) {
304
+ var tokens = setFlag(m[2], '.' + cls, on);
305
+ next = line.slice(0, m.index) + (tokens ? m[1] + '{' + tokens + '}' : '');
306
+ } else if (on) {
307
+ var base = line.replace(/\s+$/, '');
308
+ // House style writes {.x} right after the text; after an inline element (or its braces) a space keeps it on
309
+ // the block.
310
+ next = base + (INLINE_END.test(base) || /\}$/.test(base) ? ' ' : '') + '{.' + cls + '}';
311
+ } else return null;
312
+ return next === line ? null : patch(lines, lineNo, lineNo, next);
313
+ }
314
+
315
+ // ![alt](src "title"){attrs}, the path bare or in <…> (which allows spaces)
316
+ var IMAGE = /!\[(?:[^\]\\]|\\.)*\]\(\s*(?:<([^>\n]*)>|([^\s)]+))(?:\s+(?:"[^"]*"|'[^']*'))?\s*\)(\{[^{}]*\})?/g;
317
+ // The build reports a path as markdown-it normalized it (percent-encoded); compare both decoded.
318
+ function samePath(a, b) {
319
+ var decode = function (x) { try { return decodeURI(x); } catch (e) { return x; } };
320
+ return a === b || decode(a) === decode(b);
321
+ }
322
+
323
+ /** The nth image (0-based) with source `src` in lines start..end: its line, and where its {…} is or would go. */
324
+ function findImage(lines, start, end, src, nth) {
325
+ var seen = 0;
326
+ for (var n = start; n <= end; n++) {
327
+ var line = lines[n - 1] || '';
328
+ IMAGE.lastIndex = 0;
329
+ for (var m = IMAGE.exec(line); m; m = IMAGE.exec(line)) {
330
+ var attrs = m[3] ? m[3].slice(1, -1).trim() : '';
331
+ // {bg} and {side} images leave the text flow and aren't counted among the block's <img> elements.
332
+ if (!samePath(m[1] !== undefined ? m[1] : m[2], src) || /(^|\s)(bg|side)(=|\s|$)/.test(attrs)) continue;
333
+ if (seen++ < nth) continue;
334
+ var attrsAt = m.index + m[0].length - (m[3] ? m[3].length : 0);
335
+ return { line: n, at: m.index, attrsAt: attrsAt, attrsEnd: m.index + m[0].length, attrs: attrs };
336
+ }
337
+ }
338
+ return null;
339
+ }
340
+
341
+ /**
342
+ * Take out an image found by findImage, with its {…}. An image alone on its line takes the line out (with one blank
343
+ * line, between blank lines); next to text, the spaces left around it close up.
344
+ */
345
+ function removeImage(lines, loc) {
346
+ var line = lines[loc.line - 1], rest = line.slice(0, loc.at).replace(/\s+$/, '') + ' ' + line.slice(loc.attrsEnd).replace(/^\s+/, '');
347
+ if (rest.trim()) return patch(lines, loc.line, loc.line, rest.replace(/^ | $/g, ''));
348
+ var start = loc.line, above = lines[start - 2], below = lines[start];
349
+ if (above !== undefined && !above.trim() && (below === undefined || !below.trim())) start--;
350
+ return patch(lines, start, loc.line, null);
351
+ }
352
+
353
+ /** The value of `key=` in attribute text, or true for a bare flag, or null. */
354
+ function attrValue(attrs, key) {
355
+ var tokens = attrs ? attrs.split(/\s+/) : [];
356
+ for (var i = 0; i < tokens.length; i++) {
357
+ if (tokens[i] === key) return true;
358
+ if (tokens[i].indexOf(key + '=') === 0) return tokens[i].slice(key.length + 1);
359
+ }
360
+ return null;
361
+ }
362
+
363
+ /**
364
+ * Change an image's attributes: `set` keys to values (null removes the key), `flags` on or off. Other tokens keep
365
+ * their order and spelling; new ones go at the end.
366
+ */
367
+ function setImageAttrs(lines, loc, set, flags) {
368
+ var tokens = loc.attrs ? loc.attrs.split(/\s+/).filter(Boolean) : [];
369
+ Object.keys(set || {}).forEach(function (key) {
370
+ var i = tokens.findIndex(function (t) { return t.indexOf(key + '=') === 0; });
371
+ var v = set[key];
372
+ if (v === null) { if (i >= 0) tokens.splice(i, 1); } else if (i >= 0) tokens[i] = key + '=' + v; else tokens.push(key + '=' + v);
373
+ });
374
+ Object.keys(flags || {}).forEach(function (flag) {
375
+ tokens = setFlag(tokens.join(' '), flag, flags[flag]).split(/\s+/).filter(Boolean);
376
+ });
377
+ var line = lines[loc.line - 1];
378
+ var next = line.slice(0, loc.attrsAt) + (tokens.length ? (loc.pad || '') + '{' + tokens.join(' ') + '}' : '') + line.slice(loc.attrsEnd);
379
+ return next === line ? null : patch(lines, loc.line, loc.line, next);
380
+ }
381
+
382
+ /**
383
+ * A code fence's opening line (```mermaid {w=60%}) as a place for setImageAttrs: its {…}, with the space before
384
+ * it, or where they would go. Null when line n doesn't open a fence.
385
+ */
386
+ function fenceAttrs(lines, n) {
387
+ var line = lines[n - 1] || '';
388
+ if (!/^\s*(`{3,}|~{3,})/.test(line)) return null;
389
+ var m = /(\s*)\{([^{}]*)\}\s*$/.exec(line);
390
+ var at = m ? m.index : line.replace(/\s+$/, '').length;
391
+ return { line: n, attrsAt: at, attrsEnd: m ? line.length : at, attrs: m ? m[2].trim() : '', pad: ' ' };
392
+ }
393
+
394
+ // What would turn a block's text into another block: a heading, list item, quote, thematic break, slide header
395
+ // (`---`, `--- columns`), column or notes separator (`=== col`), or code fence. `---x` is none of these.
396
+ var BLOCK_START = /^(?:#{1,6}(?:\s|$)|>|[-*+](?:\s|$)|\d+[.)](?:\s|$)|---(?:\s|$)|(?:-[ \t]*){3,}$|(?:\*[ \t]*){3,}$|(?:_[ \t]*){3,}$|===\s|~{3,}|`{3,})/;
397
+
398
+ /**
399
+ * A block's text after typing: only what changed is escaped, so untouched source stays byte for byte. `map[i]` is
400
+ * where character i of the typed text begins in the result (before its escaping backslash), and map[length] is the
401
+ * end, so a selection of the typed text maps onto the source.
402
+ */
403
+ // Escaping for typed text, shared by plain and formatted text: the characters Markdown would read, and a marker
404
+ // that would make the text start a block.
405
+ var SPECIAL = /[\\`*_~&[\]<>{}]/, SPECIAL_CELL = /[\\`*_~&[\]<>{}|]/;
406
+ function escapeChar(ch, cell) {
407
+ return ((cell ? SPECIAL_CELL : SPECIAL).test(ch) ? '\\' : '') + ch;
408
+ }
409
+ // Where to put a backslash so text that now starts a block (heading, list item, quote) doesn't; -1 for nowhere.
410
+ function blockStartEscape(out, before, cell) {
411
+ if (cell || !BLOCK_START.test(out) || BLOCK_START.test(before)) return -1;
412
+ var num = /^(\d+)([.)])/.exec(out);
413
+ return num ? num[1].length : 0;
414
+ }
415
+
416
+ function spliceTyped(oldText, newText, cell) {
417
+ var p = 0;
418
+ while (p < oldText.length && p < newText.length && oldText[p] === newText[p]) p++;
419
+ var q = 0;
420
+ while (q < oldText.length - p && q < newText.length - p && oldText[oldText.length - 1 - q] === newText[newText.length - 1 - q]) q++;
421
+ var out = oldText.slice(0, p), map = [];
422
+ for (var i = 0; i < p; i++) map.push(i);
423
+ var typed = newText.slice(p, newText.length - q);
424
+ for (var j = 0; j < typed.length; j++) {
425
+ map.push(out.length);
426
+ out += escapeChar(typed[j], cell);
427
+ }
428
+ for (var k = 0; k < q; k++) map.push(out.length + k);
429
+ out += oldText.slice(oldText.length - q);
430
+ map.push(out.length);
431
+ // Text that now starts a block (in a paragraph, or inside a list item or quote) would become one.
432
+ var at = blockStartEscape(out, oldText, cell);
433
+ if (at >= 0) {
434
+ out = out.slice(0, at) + '\\' + out.slice(at);
435
+ map = map.map(function (v) { return v > at ? v + 1 : v; });
436
+ }
437
+ return { text: out, map: map };
438
+ }
439
+
440
+ /**
441
+ * Wrap text[a..b) in Markdown markers, or unwrap it when the markers already surround it (just outside the
442
+ * selection, or as its first and last characters).
443
+ */
444
+ function toggleWrap(text, a, b, open, close) {
445
+ var k = open.length;
446
+ var unwrapOutside = function () {
447
+ return { text: text.slice(0, a - k) + text.slice(a, b) + text.slice(b + close.length), a: a - k, b: b - k };
448
+ };
449
+ var unwrapInside = function () {
450
+ return { text: text.slice(0, a) + text.slice(a + k, b - close.length) + text.slice(b), a: a, b: b - k - close.length };
451
+ };
452
+ var wrap = { text: text.slice(0, a) + open + text.slice(a, b) + close + text.slice(b), a: a + k, b: b + k };
453
+ var run = open === close && /^(.)\1*$/.test(open) ? open[0] : null;
454
+ if (run) {
455
+ // A marker of one repeated character counts as a run: * and _ runs of 1, 2, and 3 are italic, bold, and both;
456
+ // so italic is on at 1 or 3, bold at 2 or 3 (taking its own characters off the run), and ~~ and ` only exactly.
457
+ var on = function (n) { return n === k || ((run === '*' || run === '_') && n === 3 && k < 3); };
458
+ var count = function (i, step) { var n = 0; while (text[i + n * step] === run) n++; return n; };
459
+ if (on(Math.min(count(a - 1, -1), count(b, 1)))) return unwrapOutside();
460
+ if (b - a > 2 * k && on(Math.min(count(a, 1), count(b - 1, -1), Math.floor((b - a) / 2)))) return unwrapInside();
461
+ return wrap;
462
+ }
463
+ if (text.slice(a - k, a) === open && text.slice(b, b + close.length) === close) return unwrapOutside();
464
+ var sel = text.slice(a, b);
465
+ if (sel.length >= k + close.length && sel.indexOf(open) === 0 && sel.slice(sel.length - close.length) === close) return unwrapInside();
466
+ return wrap;
467
+ }
468
+
469
+ /**
470
+ * The inline marks written in a line of Markdown, as the toolbar names them (bold, italic, code, strike, mark, link),
471
+ * each with its extent: s..e with the markers, is..ie the text inside. Close to CommonMark for what the toolbar
472
+ * writes: code spans first (nothing inside them is a mark), then links `[text](url)` and highlights `[text]{.hl}`,
473
+ * `~~` pairs, and `*`/`_` runs matched as emphasis (runs of 1 italic, 2 bold, 3 both).
474
+ */
475
+ function markSpans(text) {
476
+ // Marks stay within a line (the toolbar writes them so): pairs across lines, in list items or a code fence, aren't.
477
+ if (text.indexOf('\n') >= 0) {
478
+ var all = [], off = 0;
479
+ text.split('\n').forEach(function (line) {
480
+ markSpans(line).forEach(function (sp) { all.push({ id: sp.id, s: sp.s + off, e: sp.e + off, is: sp.is + off, ie: sp.ie + off }); });
481
+ off += line.length + 1;
482
+ });
483
+ return all;
484
+ }
485
+ var spans = [], i, m;
486
+ // Code spans first, on the text as written (escapes don't work inside them; an escaped backtick opens none, and a
487
+ // run with no closer of its length is literal). Everything not to read as markers turns into \u0001.
488
+ var masked = '';
489
+ for (i = 0; i < text.length; ) {
490
+ if (text[i] === '\\' && i + 1 < text.length) { masked += '\u0001\u0001'; i += 2; continue; }
491
+ if (text[i] !== '`') { masked += text[i++]; continue; }
492
+ var n0 = /^`+/.exec(text.slice(i))[0].length, j = i + n0, close = -1;
493
+ for (var k = j; k < text.length; ) {
494
+ var len = /^`*/.exec(text.slice(k))[0].length;
495
+ if (len === n0) { close = k; break; }
496
+ k += len || 1;
497
+ }
498
+ if (close < 0) { masked += new Array(n0 + 1).join('\u0001'); i = j; continue; }
499
+ spans.push({ id: 'code', s: i, e: close + n0, is: j, ie: close });
500
+ masked += new Array(close + n0 - i + 1).join('\u0001');
501
+ i = close + n0;
502
+ }
503
+ // Links (with a title, or a URL with parentheses in it) and highlights; not images. A link's target isn't text.
504
+ var re = /(!?)\[([^\[\]\u0001]*)\](\((?:[^()\s]|\([^()\s]*\))*(?:\s+"[^"]*")?\)|\{\.hl\})/g;
505
+ while ((m = re.exec(masked))) {
506
+ var at0 = m.index + m[1].length, textEnd = at0 + 1 + m[2].length;
507
+ if (!m[1]) spans.push({ id: m[3][0] === '(' ? 'link' : 'mark', s: at0, e: m.index + m[0].length, is: at0 + 1, ie: textEnd });
508
+ masked = masked.slice(0, textEnd + 1) + new Array(m[3].length + 1).join('\u0001') + masked.slice(m.index + m[0].length);
509
+ }
510
+ var auto = /<[A-Za-z][\w+.-]*:[^\s<>]*>/g;
511
+ while ((m = auto.exec(masked))) {
512
+ spans.push({ id: 'link', s: m.index, e: m.index + m[0].length, is: m.index + 1, ie: m.index + m[0].length - 1 });
513
+ masked = masked.slice(0, m.index) + new Array(m[0].length + 1).join('\u0001') + masked.slice(m.index + m[0].length);
514
+ }
515
+ var tilde = /~~/g, from = -1;
516
+ while ((m = tilde.exec(masked))) {
517
+ if (from < 0) from = m.index;
518
+ else { spans.push({ id: 'strike', s: from, e: m.index + 2, is: from + 2, ie: m.index }); from = -1; }
519
+ }
520
+ var stack = [], run = /\*+|_+/g;
521
+ while ((m = run.exec(masked))) {
522
+ var c = m[0][0], at = m.index, left = 0, n = m[0].length;
523
+ var before = masked[at - 1] || ' ', after = masked[at + n] || ' ';
524
+ var canOpen = /\S/.test(after), canClose = /\S/.test(before);
525
+ if (c === '_' && /\w/.test(before) && /\w/.test(after)) continue;
526
+ if (canClose) {
527
+ for (i = stack.length - 1; i >= 0 && n - left > 0; i--) {
528
+ var o = stack[i];
529
+ if (o.c !== c) continue;
530
+ stack.length = i + 1;
531
+ while (o.n > 0 && n - left > 0) {
532
+ var use = o.n >= 2 && n - left >= 2 ? 2 : 1;
533
+ o.n -= use;
534
+ spans.push({ id: use === 2 ? 'bold' : 'italic', s: o.at + o.n, e: at + left + use, is: o.at + o.n + use, ie: at + left });
535
+ left += use;
536
+ }
537
+ if (o.n === 0) stack.length = i;
538
+ }
539
+ }
540
+ if (canOpen && n - left > 0) stack.push({ c: c, at: at + left, n: n - left });
541
+ }
542
+ return spans;
543
+ }
544
+
545
+ /**
546
+ * Cut and copy of text[a..b) with its formatting: what goes on the clipboard (the selection with the markers of the
547
+ * marks it is in or cuts through, so it pastes styled: `his` in `**this**` copies as `**his**`), and the text a cut
548
+ * leaves, with the marks it cuts through closed (or opened) again where it was cut, and those it empties taken out.
549
+ * An end inside a marker moves out of it first. `at` is where the caret goes. Null for an empty selection.
550
+ */
551
+ function clipMarks(text, a, b) {
552
+ var spans = markSpans(text), moved = true;
553
+ while (moved) {
554
+ moved = false;
555
+ spans.forEach(function (sp) {
556
+ // Out of the markers, toward the side that keeps the selection's text: a starts before an opener (or after a
557
+ // closer, and at one), b ends after a closer (or before an opener, and at one).
558
+ var na = a > sp.s && a < sp.is ? sp.s : a >= sp.ie && a < sp.e ? sp.e : a;
559
+ var nb = b > sp.ie && b < sp.e ? sp.e : b > sp.s && b <= sp.is ? sp.s : b;
560
+ if (na !== a || nb !== b) { a = na; b = nb; moved = true; }
561
+ });
562
+ }
563
+ if (a >= b) return null;
564
+ var head = function (sp) { return text.slice(sp.s, sp.is); }, tail = function (sp) { return text.slice(sp.ie, sp.e); };
565
+ var outerFirst = function (x, y) { return x.s - y.s || y.e - x.e; };
566
+ // Marks the selection starts in (their opener before it), and ends in (their closer after it).
567
+ var startsIn = spans.filter(function (sp) { return sp.s < a && sp.is <= a && a < sp.ie; }).sort(outerFirst);
568
+ var endsIn = spans.filter(function (sp) { return sp.is < b && b <= sp.ie && b < sp.e; }).sort(outerFirst);
569
+ var copy = startsIn.map(head).join('') + text.slice(a, b) + endsIn.slice().reverse().map(tail).join('');
570
+ // The cut: marks around all of it stay (taken out when it was all their text); a mark it cuts the end off is
571
+ // closed where it was cut, one it cuts the start off opened there, and either goes when nothing is left in it.
572
+ var drop = [], close = '', open = '';
573
+ startsIn.forEach(function (sp) {
574
+ var around = b <= sp.ie;
575
+ if (a === sp.is && (!around || b === sp.ie)) { drop.push([sp.s, sp.is]); if (around) drop.push([sp.ie, sp.e]); }
576
+ else if (!around) close = tail(sp) + close;
577
+ });
578
+ endsIn.forEach(function (sp) {
579
+ if (sp.s < a) return;
580
+ if (b === sp.ie) drop.push([sp.ie, sp.e]);
581
+ else open += head(sp);
582
+ });
583
+ drop.push([a, b]);
584
+ drop.sort(function (x, y) { return x[0] - y[0]; });
585
+ var out = '', from = 0, at = -1;
586
+ drop.forEach(function (d) {
587
+ out += text.slice(from, d[0]);
588
+ if (d[0] === a) { out += close; at = out.length; out += open; }
589
+ from = Math.max(from, d[1]);
590
+ });
591
+ out += text.slice(from);
592
+ return { copy: copy, text: out, at: at, a: a, b: b };
593
+ }
594
+
595
+ /** The marks a selection a..b of a line is in, by name, each the innermost one around it. A caret counts at the
596
+ * text's edges but not outside the markers. */
597
+ function marksAt(text, a, b) {
598
+ var on = {};
599
+ markSpans(text).forEach(function (sp) {
600
+ var inside = a === b ? sp.is <= a && a <= sp.ie : sp.s <= a && b <= sp.e && !(b <= sp.is || a >= sp.ie);
601
+ if (inside && (!on[sp.id] || sp.e - sp.s < on[sp.id].e - on[sp.id].s)) on[sp.id] = sp;
602
+ });
603
+ return on;
604
+ }
605
+
606
+ /** The line with a mark's markers taken off (a link's URL with them), and a..b moved to stay on the same text. */
607
+ function unwrapMark(text, sp, a, b) {
608
+ var head = sp.is - sp.s;
609
+ var shift = function (x) {
610
+ return x <= sp.s ? x : x <= sp.is ? sp.s : x <= sp.ie ? x - head : x <= sp.e ? sp.ie - head : x - (sp.e - sp.s) + (sp.ie - sp.is);
611
+ };
612
+ var out = text.slice(0, sp.s) + text.slice(sp.is, sp.ie) + text.slice(sp.e);
613
+ return { text: out, a: shift(a), b: shift(b) };
614
+ }
615
+
616
+ // A line's block prefix: indent, quote markers, a list marker, heading hashes.
617
+ var PREFIX = /^(\s*)((?:>\s?)*)((?:[-*+]|\d+[.)])\s+)?(#{1,6}\s+)?/;
618
+
619
+ /** p, h1-h6, ul, ol, or quote. */
620
+ function blockKind(line) {
621
+ var m = PREFIX.exec(line);
622
+ if (m[4]) return 'h' + m[4].trim().length;
623
+ if (m[3]) return /\d/.test(m[3]) ? 'ol' : 'ul';
624
+ return m[2] ? 'quote' : 'p';
625
+ }
626
+
627
+ /** The line as another kind of block (`n` numbers an ordered list item), keeping its indent and text. */
628
+ function setBlockKind(line, kind, n) {
629
+ var m = PREFIX.exec(line);
630
+ var heading = /^h[1-6]$/.test(kind);
631
+ var prefix = kind === 'ul' ? '- ' : kind === 'ol' ? (n || 1) + '. ' : kind === 'quote' ? '> ' :
632
+ heading ? new Array(+kind[1] + 1).join('#') + ' ' : '';
633
+ var rest = line.slice(m[0].length);
634
+ // Text that starts like a block (## 1. Introduction as a paragraph, or - x as a list item) would become one;
635
+ // a heading's text is never read that way.
636
+ if (!heading && BLOCK_START.test(rest)) {
637
+ var num = /^(\d+)([.)])/.exec(rest);
638
+ rest = num ? num[1] + '\\' + rest.slice(num[1].length) : '\\' + rest;
639
+ }
640
+ return m[1] + prefix + rest;
641
+ }
642
+
643
+ /** Lines start..end as `kind`; when they all are already, back to paragraphs. Ordered items are numbered from 1. */
644
+ function setLinesKind(lines, start, end, kind) {
645
+ var block = range(lines, start, end);
646
+ var filled = block.filter(function (l) { return l.trim() !== ''; });
647
+ var already = filled.length && filled.every(function (l) { return blockKind(l) === kind; });
648
+ var n = 0;
649
+ var next = block.map(function (l) { return l.trim() === '' ? l : setBlockKind(l, already ? 'p' : kind, ++n); });
650
+ return patch(lines, start, end, next.join('\n'));
651
+ }
652
+
653
+ /**
654
+ * Switch a list's items (those at its first item's indent) between bullets and numbers. A wider or narrower marker
655
+ * moves the item's content column, so the lines under it (nested items, continuations) move with it and stay inside.
656
+ */
657
+ function setListKind(lines, start, end, kind) {
658
+ var indent = null, n = 0, delta = 0;
659
+ var next = range(lines, start, end).map(function (l) {
660
+ var m = /^(\s*)([-*+]|\d+[.)])(\s+)/.exec(l);
661
+ if (m && (indent === null || m[1] === indent)) {
662
+ indent = m[1];
663
+ var marker = kind === 'ol' ? ++n + '.' : '-';
664
+ delta = marker.length - m[2].length;
665
+ return m[1] + marker + m[3] + l.slice(m[0].length);
666
+ }
667
+ var lead = /^\s*/.exec(l)[0].length;
668
+ if (!delta || l.trim() === '' || indent === null || lead <= indent.length) return l;
669
+ return delta > 0 ? new Array(delta + 1).join(' ') + l : l.slice(Math.min(-delta, lead - indent.length));
670
+ });
671
+ return patch(lines, start, end, next.join('\n'));
672
+ }
673
+
674
+ /**
675
+ * Tab on a list item (dir 1): it nests under the item before it, at that item's sub-items' indent (or its content
676
+ * column); Shift+Tab (dir -1): it moves out to its parent item's indent. The lines under it (its own sub-items and
677
+ * continuations) move with it. A numbered item that becomes a new sub-list's first item is numbered 1. Null when
678
+ * there is nothing to nest under or out of, across a blank line (a loose list), or in a quote.
679
+ */
680
+ function indentItem(lines, n, dir) {
681
+ var ITEM = /^( *)([-*+]|\d+[.)])( +|$)/, lead = function (l) { return /^ */.exec(l)[0].length; };
682
+ var m = ITEM.exec(lines[n - 1] || '');
683
+ if (!m) return null;
684
+ var ind = m[1].length, end = n, to = -1, first = false, k;
685
+ while (end < lines.length && lines[end].trim() && lead(lines[end]) > ind) end++;
686
+ for (k = n - 2; k >= 0 && to < 0; k--) {
687
+ var l = lines[k], p = ITEM.exec(l);
688
+ // Not across a blank line, a slide break, or a column or notes divider.
689
+ if (!l.trim() || /^(?:---|===\s)/.test(l) || (!p && lead(l) <= ind && dir > 0)) return null;
690
+ if (dir > 0) {
691
+ if (lead(l) < ind) return null;
692
+ if (p && p[1].length === ind) {
693
+ // Its sub-items, if it has some, set the indent; else its content column does.
694
+ var subs = lines.slice(k + 1, n - 1).filter(function (x) { return ITEM.test(x); }).map(lead);
695
+ first = !subs.length;
696
+ to = first ? p[0].length + (p[3] ? 0 : 1) : Math.min.apply(null, subs);
697
+ }
698
+ } else if (p && p[1].length < ind) to = p[1].length;
699
+ }
700
+ if (to < 0) return null;
701
+ var delta = to - ind;
702
+ var next = range(lines, n, end).map(function (l) {
703
+ return delta > 0 ? new Array(delta + 1).join(' ') + l : l.slice(Math.min(-delta, lead(l)));
704
+ });
705
+ if (first) next[0] = next[0].replace(/^( *)\d+([.)])/, '$11$2');
706
+ return patch(lines, n, end, next.join('\n'));
707
+ }
708
+
709
+ /**
710
+ * Shift+Tab on a top-level list item: it leaves the list as a paragraph, in its place. Its text loses the marker (and
711
+ * its continuation lines their indent), with a blank line before and after it where the lines around it aren't blank;
712
+ * the items under it go on as a list of their own after it, outdented to its level. A paragraph that would read as
713
+ * another block (`# x`, `1. x`) is escaped. Null for a nested item, an item with no text, or one in a quote.
714
+ */
715
+ function unlistItem(lines, n) {
716
+ var ITEM = /^( *)([-*+]|\d+[.)])( +|$)/, lead = function (l) { return /^ */.exec(l)[0].length; };
717
+ var m = ITEM.exec(lines[n - 1] || '');
718
+ if (!m || m[1].length) return null;
719
+ var end = n;
720
+ while (end < lines.length && lines[end].trim() && lead(lines[end]) > 0) end++;
721
+ var own = [lines[n - 1].slice(m[0].length)], k = n;
722
+ for (; k < end && !ITEM.test(lines[k]); k++) own.push(lines[k].replace(/^ +/, ''));
723
+ if (!own.join('').trim()) return null;
724
+ if (BLOCK_START.test(own[0])) own[0] = own[0].replace(/^(\d+)(?=[.)])/, '$1\\').replace(/^(?=[^\d])/, '\\');
725
+ var subs = range(lines, k + 1, end), cut = Math.min.apply(null, subs.filter(function (l) { return ITEM.test(l); }).map(lead));
726
+ subs = subs.map(function (l) { return l.slice(Math.min(cut, lead(l))); });
727
+ var prev = lines[n - 2], next = lines[end], out = [];
728
+ if (prev !== undefined && prev.trim()) out.push('');
729
+ out = out.concat(own);
730
+ if (subs.length) out = out.concat([''], subs);
731
+ else if (next !== undefined && next.trim()) out.push('');
732
+ return patch(lines, n, end, out.join('\n'));
733
+ }
734
+
735
+ /** Whether a line ends in braces of its own (block attributes), not an inline element's. */
736
+ function hasBlockAttrs(line) {
737
+ return !!blockAttrs(line);
738
+ }
739
+
740
+ /**
741
+ * After formatting that ends right before a block's own {…} (# Title{.center} → **Title**{.center}), the braces
742
+ * would style the new inline element: keep a space before them. Only when `before` had block attributes.
743
+ */
744
+ function keepBlockAttrs(before, after) {
745
+ if (!blockAttrs(before) || blockAttrs(after)) return after;
746
+ var m = TRAILING_ATTRS.exec(after);
747
+ return m ? after.slice(0, m.index) + ' ' + after.slice(m.index).replace(/^\s*/, '') : after;
748
+ }
749
+
750
+ // Characters the renderer's typographer writes for ASCII in the source.
751
+ var TYPOGRAPHIC = { '“': ['"'], '”': ['"'], '‘': ["'"], '’': ["'"], '–': ['--'], '—': ['---'], '…': ['...'],
752
+ '©': ['(c)', '(C)'], '®': ['(r)', '(R)'], '™': ['(tm)', '(TM)'], '±': ['+-'] };
753
+ // What may stand between rendered characters: emphasis and code markers, link and span brackets with their target
754
+ // or attributes, autolink brackets.
755
+ var MARKUP = /^(?:\*+|_+|`+|~~|\[|\]\([^)\s]*(?:\s+(?:"[^"]*"|'[^']*'))?\)|\]\{[^{}]*\}|\]|\{[^{}]*\}|<|>)+$/;
756
+ var ESCAPABLE = /[!-\/:-@\[-`{-~]/;
757
+
758
+ /**
759
+ * Line up a block's rendered text with its Markdown source: start[i] and after[i] are where rendered character i
760
+ * begins and ends in the source (an escape, a typographic dash or quote can take more than one source character).
761
+ * Everything between matched characters must be markup, so a misread (a character matched inside a link's target,
762
+ * say) fails rather than misplacing an edit. Null when they don't line up.
763
+ */
764
+ function alignRendered(src, rendered) {
765
+ var start = [], after = [], i = 0, gaps = [];
766
+ for (var j = 0; j < rendered.length; j++) {
767
+ var c = rendered[j], found = -1, len = 1;
768
+ for (var k = i; k < src.length && found < 0; k++) {
769
+ if (src[k] === '\\' && ESCAPABLE.test(src[k + 1] || '')) {
770
+ if (src[k + 1] === c) { found = k; len = 2; }
771
+ else k++;
772
+ continue;
773
+ }
774
+ if (src[k] === c) { found = k; break; }
775
+ var alts = TYPOGRAPHIC[c] || [];
776
+ for (var a = 0; a < alts.length; a++) if (src.substr(k, alts[a].length) === alts[a]) { found = k; len = alts[a].length; break; }
777
+ }
778
+ if (found < 0) return null;
779
+ // Spaces or a backslash before a line break (a hard break, or spaces the renderer drops) are not shown.
780
+ var gap = src.slice(i, found);
781
+ if (c === '\n') gap = gap.replace(/^(?:[ \t]+|\\)$/, '');
782
+ if (gap) gaps.push(gap);
783
+ start.push(found);
784
+ after.push(found + len);
785
+ i = found + len;
786
+ }
787
+ if (i < src.length) gaps.push(src.slice(i));
788
+ for (var g = 0; g < gaps.length; g++) if (!MARKUP.test(gaps[g])) return null;
789
+ return { start: start, after: after };
790
+ }
791
+
792
+ // CommonMark's flanking rules for an emphasis run text[s..e): whether it can open and close emphasis.
793
+ var WS = /\s/, PUNCT = /[!-\/:-@\[-`{-~\u2000-\u206F\u2E00-\u2E7F]/;
794
+ function runFlags(text, s, e) {
795
+ var before = s > 0 ? text[s - 1] : ' ', after = e < text.length ? text[e] : ' ';
796
+ var left = !WS.test(after) && (!PUNCT.test(after) || WS.test(before) || PUNCT.test(before));
797
+ var right = !WS.test(before) && (!PUNCT.test(before) || WS.test(after) || PUNCT.test(after));
798
+ if (text[s] === '_') return (left && (!right || PUNCT.test(before)) ? 'o' : '') + (right && (!left || PUNCT.test(after)) ? 'c' : '');
799
+ return (left ? 'o' : '') + (right ? 'c' : '');
800
+ }
801
+ // The emphasis runs touching text[a..b): one ending at a, one starting at b.
802
+ function edgeRuns(text, a, b) {
803
+ var runs = [], s = a, e = b;
804
+ while (s > 0 && /[*_~]/.test(text[s - 1]) && text[s - 1] === text[a - 1]) s--;
805
+ if (s < a) runs.push(text.slice(s, a) + ':' + runFlags(text, s, a));
806
+ while (e < text.length && /[*_~]/.test(text[e]) && text[e] === text[b]) e++;
807
+ if (e > b) runs.push(text.slice(b, e) + ':' + runFlags(text, b, e));
808
+ return runs.join(' ');
809
+ }
810
+
811
+ /**
812
+ * Replace source characters from..to of a block's text with typed text; null when that can't be written exactly.
813
+ * Typed text is escaped as in spliceTyped (and a ! before a link's [ too, which would make it an image). In a code
814
+ * span (`literal`) it goes in verbatim, and a backtick, which would end the span, is refused. The emphasis markers
815
+ * next to the edit must still open and close as before (a_em_ is no longer italic; neither is * em*), or it is
816
+ * refused rather than changing the formatting.
817
+ */
818
+ function spliceRendered(content, from, to, typed, cell, literal) {
819
+ var text;
820
+ if (literal) {
821
+ if (typed.indexOf('`') >= 0) return null;
822
+ text = typed;
823
+ } else {
824
+ text = typed.split('').map(function (ch) { return escapeChar(ch, cell); }).join('');
825
+ if (/!$/.test(text) && content[to] === '[') text = text.slice(0, -1) + '\\!';
826
+ }
827
+ var out = content.slice(0, from) + text + content.slice(to);
828
+ if (edgeRuns(content, from, to) !== edgeRuns(out, from, from + text.length)) return null;
829
+ var at = from === 0 ? blockStartEscape(out, content, cell) : -1;
830
+ return at >= 0 ? out.slice(0, at) + '\\' + out.slice(at) : out;
831
+ }
832
+
833
+ var core = {
834
+ alignRendered: alignRendered,
835
+ spliceRendered: spliceRendered,
836
+ hasBlockAttrs: hasBlockAttrs,
837
+ keepBlockAttrs: keepBlockAttrs,
838
+ spliceTyped: spliceTyped,
839
+ toggleWrap: toggleWrap,
840
+ marksAt: marksAt,
841
+ unwrapMark: unwrapMark,
842
+ blockKind: blockKind,
843
+ setBlockKind: setBlockKind,
844
+ setLinesKind: setLinesKind,
845
+ setListKind: setListKind,
846
+ indentItem: indentItem,
847
+ unlistItem: unlistItem,
848
+ clipMarks: clipMarks,
849
+ lineClasses: lineClasses,
850
+ setLineClass: setLineClass,
851
+ findImage: findImage,
852
+ removeImage: removeImage,
853
+ attrValue: attrValue,
854
+ setImageAttrs: setImageAttrs,
855
+ readHeader: readHeader,
856
+ writeHeader: writeHeader,
857
+ setFlag: setFlag,
858
+ setLayout: setLayout,
859
+ setHidden: setHidden,
860
+ setAttr: setAttr,
861
+ setSlideAttrs: setSlideAttrs,
862
+ separators: separators,
863
+ setColumns: setColumns,
864
+ addRow: addRow,
865
+ readMeta: readMeta,
866
+ yamlScalar: yamlScalar,
867
+ setMeta: setMeta,
868
+ swapSlides: swapSlides,
869
+ duplicateSlide: duplicateSlide,
870
+ moveSlide: moveSlide,
871
+ copySlide: copySlide,
872
+ deleteSlide: deleteSlide,
873
+ fenceAttrs: fenceAttrs,
874
+ };
875
+ if (typeof module === 'object' && module.exports) module.exports = core;
876
+ else root.deckEditCore = core;
877
+ })(typeof window !== 'undefined' ? window : this);