@usememos/editor 26.10.15 → 26.10.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -139,11 +139,19 @@ function quoteKind(block3) {
139
139
  }
140
140
  function sameQuote(a, b) {
141
141
  const kind = quoteKind(a);
142
- return kind !== null && kind === quoteKind(b);
142
+ return kind !== null && kind === quoteKind(b) && !startsQuote(b);
143
+ }
144
+ function startsQuote(block3) {
145
+ return (block3?.type === "quote" || block3?.type === "listItem") && block3.quoteStart === true;
146
+ }
147
+ function keepQuoteStart(from, to) {
148
+ if (!startsQuote(from) || quoteKind(to) === null || startsQuote(to)) return to;
149
+ return { ...to, quoteStart: true };
143
150
  }
144
151
  function withQuote(item, kind) {
145
- const { quote: _quote, callout: _callout, ...rest } = item;
152
+ const { quote: _quote, callout: _callout, quoteStart, ...rest } = item;
146
153
  if (!kind) return rest;
154
+ if (quoteStart) return kind === "quote" ? { ...rest, quote: true, quoteStart } : { ...rest, quote: true, callout: kind, quoteStart };
147
155
  return kind === "quote" ? { ...rest, quote: true } : { ...rest, quote: true, callout: kind };
148
156
  }
149
157
  function unquote(block3) {
@@ -211,7 +219,10 @@ function sameMarks(a, b) {
211
219
  return a.length === b.length && a.every((m, i) => m === b[i]);
212
220
  }
213
221
  function sameFormat(a, b) {
214
- return !a.image && !b.image && a.link === b.link && a.token === b.token && sameMarks(a.marks, b.marks);
222
+ return !a.image && !b.image && sameLink(a, b) && a.token === b.token && sameMarks(a.marks, b.marks);
223
+ }
224
+ function sameLink(a, b) {
225
+ return a.link === b?.link && a.linkTitle === b?.linkTitle;
215
226
  }
216
227
  function inlineText(inline3) {
217
228
  return inline3.map((s) => s.text).join("");
@@ -266,13 +277,17 @@ function formatAt(inline3, offset) {
266
277
  const marks = marksAt(inline3, offset);
267
278
  const before = offset > 0 ? spanAt(inline3, offset - 1) : void 0;
268
279
  const after = spanAt(inline3, offset);
269
- const link = before?.link && before.link === after?.link ? before.link : void 0;
280
+ const link = before?.link && sameLink(before, after) ? before : void 0;
270
281
  const token = before?.token && before.token === after?.token ? before.token : void 0;
271
- const format = link ? { marks, link } : { marks };
282
+ const format = link ? { marks, ...linkOf(link) } : { marks };
272
283
  return token ? { ...format, token } : format;
273
284
  }
285
+ function linkOf(s) {
286
+ if (!s.link) return {};
287
+ return s.linkTitle === void 0 ? { link: s.link } : { link: s.link, linkTitle: s.linkTitle };
288
+ }
274
289
  function insertInline(inline3, offset, text, format) {
275
- let span = format.link ? { text, marks: format.marks, link: format.link } : { text, marks: format.marks };
290
+ let span = { text, marks: format.marks, ...linkOf(format) };
276
291
  if (format.token) span = { ...span, token: format.token };
277
292
  return concatInline(sliceInline(inline3, 0, offset), [span], sliceInline(inline3, offset));
278
293
  }
@@ -294,10 +309,12 @@ function setTokenInRange(inline3, from, to, token) {
294
309
  return concatInline(sliceInline(inline3, 0, from), middle, sliceInline(inline3, to));
295
310
  }
296
311
  function setLinkInRange(inline3, from, to, href) {
297
- const middle = sliceInline(inline3, from, to).map((s) => {
312
+ const slice = sliceInline(inline3, from, to);
313
+ const title = slice.find((s) => s.link !== void 0 && !s.image)?.linkTitle;
314
+ const middle = slice.map((s) => {
298
315
  if (s.image) return s;
299
- const { link: _old, ...rest } = s;
300
- return href ? { ...rest, link: href } : rest;
316
+ const { link: _old, linkTitle: _title, ...rest } = s;
317
+ return href ? { ...rest, ...linkOf({ link: href, linkTitle: title }) } : rest;
301
318
  });
302
319
  return concatInline(sliceInline(inline3, 0, from), middle, sliceInline(inline3, to));
303
320
  }
@@ -320,7 +337,7 @@ function linkAt(inline3, offset) {
320
337
  const runs = [];
321
338
  for (const s of inline3) {
322
339
  const end = pos + s.text.length;
323
- if (s.link === href) {
340
+ if (sameLink(s, span)) {
324
341
  const last = runs[runs.length - 1];
325
342
  if (last && last.to === pos) last.to = end;
326
343
  else runs.push({ from: pos, to: end });
@@ -374,13 +391,13 @@ function endOf(block3) {
374
391
  return { blockId: block3.id, offset: inlineLength(block3.content) };
375
392
  }
376
393
  function clampSelection(doc, sel) {
377
- const clamp = (p) => {
394
+ const clamp2 = (p) => {
378
395
  const block3 = doc.blocks.find((b) => b.id === p.blockId);
379
396
  if (!block3) return startOf(doc.blocks[0]);
380
397
  const content = containerContent(block3, p.cell);
381
398
  return { ...p, offset: Math.min(p.offset, content ? inlineLength(content) : 0) };
382
399
  };
383
- return { anchor: clamp(sel.anchor), focus: clamp(sel.focus) };
400
+ return { anchor: clamp2(sel.anchor), focus: clamp2(sel.focus) };
384
401
  }
385
402
  function createState(doc) {
386
403
  const blocks = doc.blocks.length > 0 ? doc.blocks : [paragraph()];
@@ -390,78 +407,99 @@ function createState(doc) {
390
407
  }
391
408
 
392
409
  // src/markdown/autolink.ts
393
- var reDomain = /(?:[\p{L}\p{N}_-]+)(?:\.[\p{L}\p{N}_-]+)*/uy;
394
- var reWww = /www\./iy;
395
410
  var reScheme = /(?:https?|ftp):\/\//iy;
396
- var reEmail = /[A-Za-z0-9._+-]+@[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)+/g;
397
- var TRAILING = "?!.,:*_~";
398
- function isLiteralBoundary(prev) {
399
- return prev === void 0 || /[\s*_~(]/.test(prev);
411
+ var reAsciiAlnum = /[A-Za-z0-9]/;
412
+ var TRAILING = `?!.,:*_~'"`;
413
+ function isLiteralBoundary(prev, www) {
414
+ if (prev === void 0) return true;
415
+ return www ? /[ \t\n\r*_~(]/.test(prev) : !/[A-Za-z]/.test(prev);
400
416
  }
401
417
  function domainEnd(text, pos, requirePeriod) {
402
- reDomain.lastIndex = pos;
403
- const m = reDomain.exec(text);
404
- if (!m) return -1;
405
- const domain = m[0].replace(/_+$/, "");
406
- const segments = domain.split(".");
407
- if (segments.some((s) => s === "")) return -1;
408
- if (requirePeriod && segments.length < 2) return -1;
409
- if (segments.slice(-2).some((s) => s.includes("_"))) return -1;
410
- return pos + domain.length;
418
+ let periods = 0;
419
+ let underscoresBefore = 0;
420
+ let underscores = 0;
421
+ let i = pos + 1;
422
+ for (; i < text.length - 1; i++) {
423
+ if (text[i] === "\\" && i < text.length - 2) i++;
424
+ const c = text[i];
425
+ if (c === "_") underscores++;
426
+ else if (c === ".") {
427
+ underscoresBefore = underscores;
428
+ underscores = 0;
429
+ periods++;
430
+ } else if (!reAsciiAlnum.test(c) && c !== "-") break;
431
+ }
432
+ if ((underscoresBefore > 0 || underscores > 0) && periods <= 10) return -1;
433
+ if (requirePeriod && periods === 0) return -1;
434
+ return i;
411
435
  }
412
436
  function trimEnd(text, start, end) {
413
- for (; ; ) {
437
+ let open = 0;
438
+ let close = 0;
439
+ for (let i = start; i < end; i++) {
440
+ if (text[i] === "(") open++;
441
+ else if (text[i] === ")") close++;
442
+ }
443
+ while (end > start) {
414
444
  const ch = text[end - 1];
415
445
  if (TRAILING.includes(ch)) {
416
446
  end--;
417
447
  } else if (ch === ")") {
418
- let open = 0;
419
- let close = 0;
420
- for (let i = start; i < end; i++) {
421
- if (text[i] === "(") open++;
422
- else if (text[i] === ")") close++;
423
- }
424
448
  if (close <= open) return end;
449
+ close--;
425
450
  end--;
426
451
  } else if (ch === ";") {
427
452
  let i = end - 2;
428
- while (i >= start && /[A-Za-z0-9]/.test(text[i])) i--;
429
- end = i >= start && text[i] === "&" && i < end - 2 ? i : end - 1;
453
+ while (i > start && /[A-Za-z]/.test(text[i])) i--;
454
+ end = i < end - 2 && text[i] === "&" ? i : end - 1;
430
455
  } else {
431
456
  return end;
432
457
  }
433
- if (end <= start) return end;
434
458
  }
459
+ return end;
435
460
  }
436
461
  function urlLiteralAt(text, pos) {
437
- let afterPrefix;
438
- let www = false;
439
- reWww.lastIndex = pos;
440
- if (reWww.test(text)) {
441
- afterPrefix = pos;
442
- www = true;
462
+ let domainStart;
463
+ const www = text.slice(pos, pos + 4).toLowerCase() === "www.";
464
+ if (www) {
465
+ domainStart = pos;
443
466
  } else {
444
467
  reScheme.lastIndex = pos;
445
468
  if (!reScheme.test(text)) return null;
446
- afterPrefix = reScheme.lastIndex;
469
+ domainStart = reScheme.lastIndex;
470
+ if (!/[\p{L}\p{N}]/u.test(text[domainStart] ?? "")) return null;
447
471
  }
448
- const domain = domainEnd(text, afterPrefix, true);
472
+ const domain = domainEnd(text, domainStart, www);
449
473
  if (domain < 0) return null;
450
474
  let end = domain;
451
- while (end < text.length && !/[\s<]/.test(text[end])) end++;
475
+ while (end < text.length && !/[ \t\n\r<]/.test(text[end])) end++;
452
476
  end = trimEnd(text, pos, end);
453
- if (end < domain || end <= afterPrefix) return null;
477
+ if (end <= domainStart) return null;
454
478
  const literal = text.slice(pos, end);
455
479
  return { end, href: www ? "http://" + literal : literal };
456
480
  }
457
481
  function emailLiterals(text) {
458
- if (!text.includes("@")) return [];
459
482
  const out = [];
460
- reEmail.lastIndex = 0;
461
- for (const m of text.matchAll(reEmail)) {
462
- const last = m[0][m[0].length - 1];
463
- if (last === "-" || last === "_") continue;
464
- out.push({ from: m.index, to: m.index + m[0].length });
483
+ let done = 0;
484
+ for (let at = text.indexOf("@"); at !== -1; at = text.indexOf("@", at + 1)) {
485
+ let from = at;
486
+ while (from > done && /[A-Za-z0-9.+\-_]/.test(text[from - 1])) from--;
487
+ if (from === at) continue;
488
+ let to = at;
489
+ let ats = 0;
490
+ let periods = 0;
491
+ for (; to < text.length; to++) {
492
+ const c = text[to];
493
+ if (reAsciiAlnum.test(c)) continue;
494
+ if (c === "@") {
495
+ if (++ats > 1) break;
496
+ } else if (c === "." && reAsciiAlnum.test(text[to + 1] ?? "")) periods++;
497
+ else if (c !== "-" && c !== "_") break;
498
+ }
499
+ if (to - at < 2 || ats !== 1 || periods === 0 || !/[A-Za-z]/.test(text[to - 1])) continue;
500
+ out.push({ from, to });
501
+ done = to;
502
+ at = to - 1;
465
503
  }
466
504
  return out;
467
505
  }
@@ -645,7 +683,7 @@ function deleteBackward(state) {
645
683
  return { ...state, selection: caret(block3.id, inlineLength(contentOf(block3, prevCell)), prevCell) };
646
684
  }
647
685
  if (block3.type === "listItem" && block3.indent > 0) return replaceBlock(state, { ...block3, indent: block3.indent - 1 });
648
- if (block3.type === "listItem" && block3.quote) return replaceBlock(state, quote(block3.content, block3.id, block3.callout));
686
+ if (block3.type === "listItem" && block3.quote) return replaceBlock(state, keepQuoteStart(block3, quote(block3.content, block3.id, block3.callout)));
649
687
  if (block3.type !== "paragraph") return replaceBlock(state, paragraph(block3.content, block3.id));
650
688
  const prev = state.doc.blocks[index - 1];
651
689
  if (!prev) return state;
@@ -779,7 +817,7 @@ function splitBlock(state) {
779
817
  return replaceBlock(s, code, caret(code.id, 0));
780
818
  }
781
819
  if (length === 0 && block3.type === "listItem") {
782
- const next = block3.indent > 0 ? { ...block3, indent: block3.indent - 1 } : block3.quote ? quote([], block3.id, block3.callout) : paragraph([], block3.id);
820
+ const next = block3.indent > 0 ? { ...block3, indent: block3.indent - 1 } : block3.quote ? keepQuoteStart(block3, quote([], block3.id, block3.callout)) : paragraph([], block3.id);
783
821
  return replaceBlock(s, next);
784
822
  }
785
823
  if (length === 0 && block3.type === "quote") return replaceBlock(s, paragraph([], block3.id));
@@ -790,6 +828,10 @@ function splitBlock(state) {
790
828
  return withBlocks(s, blocks, s.selection);
791
829
  }
792
830
  if (pos.offset === 0 && length > 0) {
831
+ if (block3.type !== "heading" && block3.type !== "paragraph" && block3.quoteStart) {
832
+ const { quoteStart: _start, ...rest } = block3;
833
+ return withBlocks(s, splice(s, index, 1, keepQuoteStart(block3, emptyLike(block3)), rest), s.selection);
834
+ }
793
835
  return withBlocks(s, splice(s, index, 0, emptyLike(block3)), s.selection);
794
836
  }
795
837
  const left = withContent(block3, sliceInline(block3.content, 0, pos.offset));
@@ -912,7 +954,7 @@ function keepIfSame(before, after) {
912
954
  for (let i = 0; i < before.length; i++) {
913
955
  const x = before[i];
914
956
  const y = after[i];
915
- if (x.text !== y.text || x.link !== y.link || x.token !== y.token || x.image !== y.image || !sameMarks(x.marks, y.marks)) return after;
957
+ if (x.text !== y.text || !sameLink(x, y) || x.token !== y.token || x.image !== y.image || !sameMarks(x.marks, y.marks)) return after;
916
958
  }
917
959
  return before;
918
960
  }
@@ -1019,6 +1061,9 @@ function updateImage(state, pos, change) {
1019
1061
  return replaceBlock(state, withContainerContent(block3, pos.cell, next), selected);
1020
1062
  }
1021
1063
  function convert(block3, spec) {
1064
+ return keepQuoteStart(block3, convertType(block3, spec));
1065
+ }
1066
+ function convertType(block3, spec) {
1022
1067
  const content = block3.content;
1023
1068
  switch (spec.type) {
1024
1069
  case "paragraph":
@@ -1090,8 +1135,8 @@ function quoteRun(state, blockId) {
1090
1135
  if (quoteKind(block3) === null) return null;
1091
1136
  let start = index;
1092
1137
  let end = index;
1093
- while (sameQuote(block3, blocks[start - 1])) start--;
1094
- while (sameQuote(block3, blocks[end + 1])) end++;
1138
+ while (sameQuote(blocks[start - 1], blocks[start])) start--;
1139
+ while (sameQuote(blocks[end], blocks[end + 1])) end++;
1095
1140
  return { start, end };
1096
1141
  }
1097
1142
  function setCallout(state, blockId, callout) {
@@ -1100,7 +1145,7 @@ function setCallout(state, blockId, callout) {
1100
1145
  const blocks = state.doc.blocks.slice(run.start, run.end + 1);
1101
1146
  if (blocks.every((b) => quoteKind(b) === (callout ?? "quote"))) return state;
1102
1147
  const updated = blocks.map(
1103
- (b) => b.type === "listItem" ? withQuote(b, callout ?? "quote") : b.type === "quote" ? quote(b.content, b.id, callout ?? void 0) : b
1148
+ (b) => b.type === "listItem" ? withQuote(b, callout ?? "quote") : b.type === "quote" ? keepQuoteStart(b, quote(b.content, b.id, callout ?? void 0)) : b
1104
1149
  );
1105
1150
  const doc = { blocks: splice(state, run.start, updated.length, ...updated) };
1106
1151
  return { doc, selection: state.selection, storedMarks: state.storedMarks };
@@ -1133,7 +1178,7 @@ function toggleBlockType(state, spec) {
1133
1178
  const off = { type: "paragraph" };
1134
1179
  return convertSelected(state, off, (b) => {
1135
1180
  if (b.type === "listItem" && spec.type === "quote") return withQuote(b, null);
1136
- if (b.type === "listItem" && b.quote && spec.type === "listItem") return quote(b.content, b.id, b.callout);
1181
+ if (b.type === "listItem" && b.quote && spec.type === "listItem") return keepQuoteStart(b, quote(b.content, b.id, b.callout));
1137
1182
  return convert(b, off);
1138
1183
  });
1139
1184
  }
@@ -1409,7 +1454,7 @@ function applyBlockInputRules(state, dialect = {}) {
1409
1454
  start: converted.listType === "ordered" && start ? Number(start[1]) : void 0,
1410
1455
  quote: quoteKind(converted)
1411
1456
  });
1412
- next = replaceBlock(next, updated, next.selection);
1457
+ next = replaceBlock(next, keepQuoteStart(converted, updated), next.selection);
1413
1458
  }
1414
1459
  return next;
1415
1460
  }
@@ -1545,7 +1590,7 @@ function applyAutolinkInputRule(state) {
1545
1590
  const word = text.slice(start, end);
1546
1591
  let found = null;
1547
1592
  for (const m of word.matchAll(/www\.|(?:https?|ftp):\/\//gi)) {
1548
- if (!isLiteralBoundary(m.index === 0 ? void 0 : word[m.index - 1])) continue;
1593
+ if (!isLiteralBoundary(m.index === 0 ? void 0 : word[m.index - 1], m[0].toLowerCase() === "www.")) continue;
1549
1594
  const url = urlLiteralAt(word, m.index);
1550
1595
  if (url) {
1551
1596
  found = { from: start + m.index, to: start + url.end, href: url.href };
@@ -1679,6 +1724,10 @@ function insertAsBlocks(state, fragment, target) {
1679
1724
  const head = withContent(block3, sliceInline(block3.content, 0, target.offset));
1680
1725
  let tail = { ...withContent(block3, sliceInline(block3.content, target.offset)), id: createId() };
1681
1726
  if (tail.type === "listItem" && tail.start !== void 0) tail = { ...tail, start: void 0 };
1727
+ if ((tail.type === "quote" || tail.type === "listItem") && tail.quoteStart) {
1728
+ const { quoteStart: _start, ...rest } = tail;
1729
+ tail = rest;
1730
+ }
1682
1731
  return end(splice(state, index, 1, head, ...fragment, tail), last, startOf(tail));
1683
1732
  }
1684
1733
 
@@ -1787,11 +1836,12 @@ function inlineHtml(inline3) {
1787
1836
  let out = "";
1788
1837
  let i = 0;
1789
1838
  while (i < inline3.length) {
1790
- const link = inline3[i].link;
1839
+ const { link, linkTitle: linkTitle2 } = inline3[i];
1791
1840
  let j = i;
1792
1841
  let inner = "";
1793
- while (j < inline3.length && inline3[j].link === link) inner += spanHtml(inline3[j++]);
1794
- out += link === void 0 ? inner : `<a href="${escapeHtml(link)}">${inner}</a>`;
1842
+ while (j < inline3.length && sameLink(inline3[j], inline3[i])) inner += spanHtml(inline3[j++]);
1843
+ const title = linkTitle2 ? ` title="${escapeHtml(linkTitle2)}"` : "";
1844
+ out += link === void 0 ? inner : `<a href="${escapeHtml(link)}"${title}>${inner}</a>`;
1795
1845
  i = j;
1796
1846
  }
1797
1847
  return out;
@@ -1824,6 +1874,15 @@ function htmlToDoc(html, parser) {
1824
1874
  converter.blocks(dom.body, ROOT_FORMAT);
1825
1875
  return { blocks: converter.finish() };
1826
1876
  }
1877
+ var STYLED_TEXT_TAGS = /* @__PURE__ */ new Set(["html", "body", "meta", "div", "span", "br", "font"]);
1878
+ var reFormattingStyle = /font-weight\s*:\s*(?:bold|[6-9]00)|font-style\s*:\s*italic|text-decoration[^;"']*line-through/i;
1879
+ function isStyledText(html) {
1880
+ const body = html.replace(/<!--[\s\S]*?-->/g, "").replace(/<(style|script|head|title)\b[\s\S]*?<\/\1\s*>/gi, "");
1881
+ for (const m of body.matchAll(/<([A-Za-z][A-Za-z0-9-]*)\b([^>]*)>/g)) {
1882
+ if (!STYLED_TEXT_TAGS.has(m[1].toLowerCase()) || reFormattingStyle.test(m[2])) return false;
1883
+ }
1884
+ return true;
1885
+ }
1827
1886
  var ELEMENT_NODE = 1;
1828
1887
  var TEXT_NODE = 3;
1829
1888
  var SKIPPED = /* @__PURE__ */ new Set([
@@ -2189,6 +2248,7 @@ var Converter = class _Converter {
2189
2248
  const inner = new _Converter();
2190
2249
  inner.blocks(el, format, callout ? (child) => hasClass(child, "markdown-alert-title") : void 0);
2191
2250
  const blocks = inner.finish();
2251
+ const start = this.out.length;
2192
2252
  for (const block3 of blocks) {
2193
2253
  switch (block3.type) {
2194
2254
  case "paragraph":
@@ -2205,6 +2265,10 @@ var Converter = class _Converter {
2205
2265
  this.out.push(block3);
2206
2266
  }
2207
2267
  }
2268
+ const first = this.out[start];
2269
+ if ((first?.type === "quote" || first?.type === "listItem") && quoteKind(first) !== null && quoteKind(this.out[start - 1]) === quoteKind(first)) {
2270
+ this.out[start] = { ...first, quoteStart: true };
2271
+ }
2208
2272
  }
2209
2273
  table(el, format) {
2210
2274
  const rows = Array.from(el.querySelectorAll("tr")).filter((tr) => tr.closest("table") === el);
@@ -2277,6 +2341,10 @@ function alignOf(cell) {
2277
2341
  var GROUP_MS = 1e3;
2278
2342
  var LIMIT = 500;
2279
2343
  var History = class {
2344
+ /** `source` reads the source current when an entry is recorded. */
2345
+ constructor(source) {
2346
+ this.source = source;
2347
+ }
2280
2348
  undoStack = [];
2281
2349
  redoStack = [];
2282
2350
  lastKind = null;
@@ -2285,7 +2353,7 @@ var History = class {
2285
2353
  record(before, kind, now = Date.now()) {
2286
2354
  const extendsGroup = kind === "typing" && this.lastKind === "typing" && now - this.lastTime < GROUP_MS;
2287
2355
  if (!extendsGroup) {
2288
- this.undoStack.push({ doc: before.doc, selection: before.selection });
2356
+ this.undoStack.push({ doc: before.doc, selection: before.selection, source: this.source() });
2289
2357
  if (this.undoStack.length > LIMIT) this.undoStack.shift();
2290
2358
  }
2291
2359
  this.redoStack = [];
@@ -2311,9 +2379,9 @@ var History = class {
2311
2379
  step(current, from, to) {
2312
2380
  const entry = from.pop();
2313
2381
  if (!entry) return null;
2314
- to.push({ doc: current.doc, selection: current.selection });
2382
+ to.push({ doc: current.doc, selection: current.selection, source: this.source() });
2315
2383
  this.lastKind = null;
2316
- return { doc: entry.doc, selection: entry.selection, storedMarks: null };
2384
+ return { state: { doc: entry.doc, selection: entry.selection, storedMarks: null }, source: entry.source };
2317
2385
  }
2318
2386
  };
2319
2387
 
@@ -2643,13 +2711,17 @@ function resolveMarkdown(options) {
2643
2711
  }
2644
2712
 
2645
2713
  // src/markdown/lower.ts
2646
- function lowerTopLevel(node, options, source) {
2647
- return lowerIfFits(node, options) ?? [rawBlock("markdown", source)];
2714
+ function lowerTopLevel(node, options, source, before) {
2715
+ return lowerIfFits(node, options, before) ?? [rawBlock("markdown", source)];
2648
2716
  }
2649
- function lowerIfFits(node, options) {
2717
+ function lowerIfFits(node, options, before) {
2650
2718
  if (!fitsModel(node, 0)) return null;
2651
2719
  const blocks = [];
2652
2720
  lowerBlock(node, blocks, options);
2721
+ const first = blocks[0];
2722
+ if (node.type === "blockQuote" && (first?.type === "quote" || first?.type === "listItem") && quoteKind(before) === quoteKind(first)) {
2723
+ blocks[0] = { ...first, quoteStart: true };
2724
+ }
2653
2725
  return blocks;
2654
2726
  }
2655
2727
  function fitsModel(node, depth) {
@@ -2668,12 +2740,12 @@ function fitsModel(node, depth) {
2668
2740
  }
2669
2741
  function lowerInlines(nodes, options = DEFAULT_MARKDOWN) {
2670
2742
  const out = [];
2671
- lowerInto(nodes, [], void 0, out, options.breaks ? "\n" : " ");
2743
+ lowerInto(nodes, [], {}, out, options.breaks ? "\n" : " ");
2672
2744
  return normalizeInline(out);
2673
2745
  }
2674
2746
  var NESTED_MARK = { emphasis: "italic", strong: "bold", strike: "strike" };
2675
2747
  function lowerInto(nodes, marks, link, out, soft) {
2676
- const push = (span) => out.push(link === void 0 ? span : { ...span, link });
2748
+ const push = (span) => out.push(link.link === void 0 ? span : { ...span, ...link });
2677
2749
  for (const node of nodes) {
2678
2750
  switch (node.type) {
2679
2751
  case "text":
@@ -2698,7 +2770,7 @@ function lowerInto(nodes, marks, link, out, soft) {
2698
2770
  lowerInto(node.children, withMark(marks, NESTED_MARK[node.type]), link, out, soft);
2699
2771
  break;
2700
2772
  case "link":
2701
- lowerInto(node.children, marks, node.destination, out, soft);
2773
+ lowerInto(node.children, marks, node.title ? { link: node.destination, linkTitle: node.title } : { link: node.destination }, out, soft);
2702
2774
  break;
2703
2775
  case "image":
2704
2776
  push({ text: ATOM_CHAR, marks, image: imageAtom(node) });
@@ -2731,7 +2803,7 @@ function lowerBlock(node, out, o) {
2731
2803
  case "paragraph": {
2732
2804
  const content = lowerInlines(node.children, o);
2733
2805
  if (isEmptyLine(content)) out.push(paragraph());
2734
- else if (content.length > 0) out.push(paragraph(content));
2806
+ else if (content.length > 0 || node.children.length > 0) out.push(paragraph(content));
2735
2807
  break;
2736
2808
  }
2737
2809
  case "heading":
@@ -2789,9 +2861,10 @@ function lowerQuote(children, out, o) {
2789
2861
  children.forEach((child, i) => {
2790
2862
  if (child.type === "list") lowerList(child, 0, out, o, callout ?? "quote");
2791
2863
  if (child.type !== "paragraph") return;
2792
- const content = lowerInlines(i === 0 && alert ? alert.rest : child.children, o);
2864
+ const inlines = i === 0 && alert ? alert.rest : child.children;
2865
+ const content = lowerInlines(inlines, o);
2793
2866
  if (isEmptyLine(content)) out.push(quote([], void 0, callout));
2794
- else if (content.length > 0) out.push(quote(content, void 0, callout));
2867
+ else if (content.length > 0 || inlines.length > 0) out.push(quote(content, void 0, callout));
2795
2868
  });
2796
2869
  if (callout && out.length === start) out.push(quote([], void 0, callout));
2797
2870
  }
@@ -2983,7 +3056,7 @@ var Node2 = class {
2983
3056
  var MAX_INLINE_NESTING = 100;
2984
3057
  function innerDepth(from, to) {
2985
3058
  let depth = 0;
2986
- for (let n = from.next; n && n !== to; n = n.next) if (n.depth >= depth) depth = n.depth + 1;
3059
+ for (let n = from.next; n && n !== to && depth < MAX_INLINE_NESTING; n = n.next) if (n.depth >= depth) depth = n.depth + 1;
2987
3060
  return depth;
2988
3061
  }
2989
3062
  function escapedText(value) {
@@ -3067,6 +3140,8 @@ var InlineParser = class {
3067
3140
  backticksAfter = /* @__PURE__ */ new Map();
3068
3141
  /** Per opening quote character, a position from which no link title can close. */
3069
3142
  titleFailedFrom = /* @__PURE__ */ new Map();
3143
+ /** The last index of each end of raw HTML (`-->`, `?>`, `]]>`, `>`) in the subject, found once. */
3144
+ lastEnds = /* @__PURE__ */ new Map();
3070
3145
  /** Inline syntax extensions by trigger character code. */
3071
3146
  triggers = /* @__PURE__ */ new Map();
3072
3147
  /** A run of characters that cannot start any construct, including extension triggers. */
@@ -3154,7 +3229,7 @@ var InlineParser = class {
3154
3229
  const reCandidate = /www\.|(?:https?|ftp):\/\//gi;
3155
3230
  for (const c of m[0].matchAll(reCandidate)) {
3156
3231
  const at = start + c.index;
3157
- if (!isLiteralBoundary(this.subject[at - 1])) continue;
3232
+ if (!isLiteralBoundary(this.subject[at - 1], c[0].toLowerCase() === "www.")) continue;
3158
3233
  const url = urlLiteralAt(this.subject, at);
3159
3234
  if (!url) continue;
3160
3235
  if (at > start) block3.append(new Node2("text", this.subject.slice(start, at)));
@@ -3259,11 +3334,30 @@ var InlineParser = class {
3259
3334
  return false;
3260
3335
  }
3261
3336
  parseHtmlTag(block3) {
3337
+ const s = this.subject;
3338
+ const p = this.pos;
3339
+ if (s.startsWith("<!--", p)) {
3340
+ if (this.lastEnd("-->") < p + 2) return false;
3341
+ } else if (s.startsWith("<?", p)) {
3342
+ if (this.lastEnd("?>") < p + 1) return false;
3343
+ } else if (s.startsWith("<![CDATA[", p)) {
3344
+ if (this.lastEnd("]]>") < p + 9) return false;
3345
+ } else if (s.startsWith("<!", p) && this.lastEnd(">") < p) {
3346
+ return false;
3347
+ }
3262
3348
  const m = this.match(reHtmlTag);
3263
3349
  if (!m) return false;
3264
3350
  block3.append(new Node2("html", m[0]));
3265
3351
  return true;
3266
3352
  }
3353
+ lastEnd(end) {
3354
+ let at = this.lastEnds.get(end);
3355
+ if (at === void 0) {
3356
+ at = this.subject.lastIndexOf(end);
3357
+ this.lastEnds.set(end, at);
3358
+ }
3359
+ return at;
3360
+ }
3267
3361
  parseEntity(block3) {
3268
3362
  const start = this.pos;
3269
3363
  const m = this.match(reEntityHere);
@@ -3291,14 +3385,16 @@ var InlineParser = class {
3291
3385
  const beforePunct = isUnicodePunctuation(before);
3292
3386
  const leftFlanking = !afterWs && (!afterPunct || beforeWs || beforePunct);
3293
3387
  const rightFlanking = !beforeWs && (!beforePunct || afterWs || afterPunct);
3294
- let canOpen;
3295
- let canClose;
3388
+ let canOpen = leftFlanking;
3389
+ let canClose = rightFlanking;
3390
+ if (cc !== C_TILDE) {
3391
+ if (after === "~") canOpen = true;
3392
+ if (before === "~") canClose = true;
3393
+ }
3296
3394
  if (cc === C_UNDERSCORE) {
3297
- canOpen = leftFlanking && (!rightFlanking || beforePunct);
3298
- canClose = rightFlanking && (!leftFlanking || afterPunct);
3299
- } else {
3300
- canOpen = leftFlanking;
3301
- canClose = rightFlanking;
3395
+ const open = canOpen;
3396
+ canOpen = open && (beforeWs || beforePunct || !canClose);
3397
+ canClose = canClose && (afterWs || afterPunct || !open);
3302
3398
  }
3303
3399
  if (cc === C_TILDE && count > 2) canOpen = canClose = false;
3304
3400
  const node = new Node2("text", this.subject.slice(start, this.pos));
@@ -3365,7 +3461,9 @@ var InlineParser = class {
3365
3461
  opener.count -= use;
3366
3462
  closer.count -= use;
3367
3463
  const literal = innerDepth(openerNode, closerNode) >= MAX_INLINE_NESTING;
3368
- if (!literal) {
3464
+ if (literal) {
3465
+ openerNode.depth = closerNode.depth = MAX_INLINE_NESTING;
3466
+ } else {
3369
3467
  openerNode.value = openerNode.value.slice(0, openerNode.value.length - use);
3370
3468
  closerNode.value = closerNode.value.slice(0, closerNode.value.length - use);
3371
3469
  const wrapper = new Node2(type);
@@ -3586,19 +3684,16 @@ var InlineParser = class {
3586
3684
  this.spnl();
3587
3685
  let title = null;
3588
3686
  if (this.pos !== beforeTitle) title = this.parseLinkTitle();
3589
- if (title === null) {
3590
- title = "";
3591
- this.pos = beforeTitle;
3592
- }
3687
+ if (title === null) this.pos = beforeTitle;
3593
3688
  if (!this.match(reSpaceAtEndOfLine)) {
3594
- if (title === "") return 0;
3595
- title = "";
3689
+ if (title === null) return 0;
3690
+ title = null;
3596
3691
  this.pos = beforeTitle;
3597
3692
  if (!this.match(reSpaceAtEndOfLine)) return 0;
3598
3693
  }
3599
3694
  const label = normalizeLabel(rawLabel);
3600
3695
  if (label === "") return 0;
3601
- if (!this.refs.has(label)) this.refs.set(label, { destination: dest, title });
3696
+ if (!this.refs.has(label)) this.refs.set(label, { destination: dest, title: title ?? "" });
3602
3697
  return this.pos;
3603
3698
  }
3604
3699
  };
@@ -3628,6 +3723,7 @@ function parseAst(src, options = DEFAULT_MARKDOWN) {
3628
3723
  }
3629
3724
  var CODE_INDENT2 = 4;
3630
3725
  var MAX_NESTING = 100;
3726
+ var MIN_FILLED_CELLS = 65536;
3631
3727
  var reHtmlBlockOpen = [
3632
3728
  /^$/,
3633
3729
  // unused: block types are numbered from 1
@@ -3660,7 +3756,7 @@ var reATXHeadingMarker = /^#{1,6}(?:[ \t]+|$)/;
3660
3756
  var reClosingCodeFence = /^(?:`{3,}|~{3,})(?=[ \t]*$)/;
3661
3757
  var reSetextHeadingLine = /^(?:=+|-+)[ \t]*$/;
3662
3758
  var reTableDelimiterCell = /^:?-+:?$/;
3663
- var reTaskMarker = /^\[([ xX])\](?:[ \t\n]+|$)/;
3759
+ var reTaskMarker = /^\[([ \t\nxX])\](?:[ \t\n]+|$)/;
3664
3760
  var BNode = class {
3665
3761
  constructor(type, startLine) {
3666
3762
  this.type = type;
@@ -3738,6 +3834,9 @@ var BlockParser = class {
3738
3834
  lastMatchedContainer = this.doc;
3739
3835
  refs = /* @__PURE__ */ new Map();
3740
3836
  definitions = [];
3837
+ /** Empty cells added to short table rows so far, and how many the document may have. */
3838
+ filledCells = 0;
3839
+ maxFilledCells = 0;
3741
3840
  // State for the current line.
3742
3841
  line = "";
3743
3842
  lineNumber = 0;
@@ -3751,7 +3850,8 @@ var BlockParser = class {
3751
3850
  partiallyConsumedTab = false;
3752
3851
  allClosed = true;
3753
3852
  parse(src) {
3754
- const lines = src.split(/\r\n|\n|\r/);
3853
+ const lines = (src.charCodeAt(0) === 65279 ? src.slice(1) : src).split(/\r\n|\n|\r/);
3854
+ this.maxFilledCells = Math.max(MIN_FILLED_CELLS, src.length);
3755
3855
  let count = lines.length;
3756
3856
  if (src.endsWith("\n") || src.endsWith("\r")) count -= 1;
3757
3857
  for (let i = 0; i < count; i++) this.incorporateLine(lines[i]);
@@ -3905,7 +4005,17 @@ var BlockParser = class {
3905
4005
  }
3906
4006
  } else if (type === "table") {
3907
4007
  if (!this.blank && this.offset < this.line.length) {
3908
- container.rows.push(fitRow(splitRow(this.line.slice(this.offset)), container.align.length));
4008
+ const cells = splitRow(this.line.slice(this.offset));
4009
+ const filled = Math.max(0, container.align.length - cells.length);
4010
+ if (this.filledCells + filled <= this.maxFilledCells) {
4011
+ this.filledCells += filled;
4012
+ container.rows.push(fitRow(cells, container.align.length));
4013
+ } else {
4014
+ this.finalize(container, this.lineNumber - 1);
4015
+ this.addChild("paragraph");
4016
+ this.advanceNextNonspace();
4017
+ this.addLine();
4018
+ }
3909
4019
  }
3910
4020
  } else if (this.offset < this.line.length && !this.blank) {
3911
4021
  this.addChild("paragraph");
@@ -3932,7 +4042,7 @@ var BlockParser = class {
3932
4042
  const data = block3.list;
3933
4043
  if (this.blank) {
3934
4044
  if (block3.children.length === 0) return 1 /* Failed */;
3935
- this.advanceNextNonspace();
4045
+ this.advanceOffset(Math.min(this.indent, data.markerOffset + data.padding), true);
3936
4046
  } else if (this.indent >= data.markerOffset + data.padding) {
3937
4047
  this.advanceOffset(data.markerOffset + data.padding, true);
3938
4048
  } else {
@@ -4026,7 +4136,7 @@ var BlockParser = class {
4026
4136
  tryStarts(container) {
4027
4137
  const rest = this.line.slice(this.nextNonspace);
4028
4138
  const nest = container.depth < MAX_NESTING;
4029
- return nest && this.startBlockQuote(rest) || this.startAtxHeading(rest) || this.startSyntaxBlock(container, rest) || this.startFencedCode(rest) || this.startHtmlBlock(container, rest) || this.startSetextHeading(container, rest) || this.startTable(container, rest) || this.startThematicBreak(rest) || nest && this.startListItem(container, rest) || this.startIndentedCode();
4139
+ return nest && this.startBlockQuote(rest) || this.startAtxHeading(rest) || this.startSyntaxBlock(container, rest) || this.startFencedCode(rest) || this.startHtmlBlock(container, rest) || this.startSetextHeading(container, rest) || this.startThematicBreak(rest) || nest && this.startListItem(container, rest) || this.startTable(container, rest) || this.startIndentedCode();
4030
4140
  }
4031
4141
  startBlockQuote(rest) {
4032
4142
  if (this.indented || rest[0] !== ">") return 0 /* None */;
@@ -4121,12 +4231,14 @@ var BlockParser = class {
4121
4231
  /**
4122
4232
  * GFM table: a delimiter row (`| --- | :-: |`) under a paragraph whose last
4123
4233
  * line has the same number of cells. That line becomes the header row; any
4124
- * earlier lines stay a paragraph. We require a `|` in the delimiter row so
4125
- * that it cannot be confused with a setext underline or a list.
4234
+ * earlier lines stay a paragraph. As in cmark-gfm, it is tried after setext
4235
+ * underlines, thematic breaks and list items, so `- |` is a list item and
4236
+ * `:-:` with no pipe is a delimiter row. Without setext headings, a setext
4237
+ * underline (`-`) stays paragraph text rather than making a table.
4126
4238
  */
4127
4239
  startTable(container, rest) {
4128
4240
  if (this.indented || container.type !== "paragraph") return 0 /* None */;
4129
- if (!rest.includes("|")) return 0 /* None */;
4241
+ if (!rest.includes("|") && reSetextHeadingLine.test(rest)) return 0 /* None */;
4130
4242
  const align = parseDelimiterRow(rest);
4131
4243
  if (!align) return 0 /* None */;
4132
4244
  container.content = this.extractReferences(container.content);
@@ -4285,7 +4397,7 @@ var BlockParser = class {
4285
4397
  const m = reTaskMarker.exec(first.content);
4286
4398
  if (m) {
4287
4399
  task = true;
4288
- checked = m[1] !== " ";
4400
+ checked = m[1] === "x" || m[1] === "X";
4289
4401
  first.content = first.content.slice(m[0].length);
4290
4402
  }
4291
4403
  }
@@ -4337,7 +4449,7 @@ function splitRow(line) {
4337
4449
  }
4338
4450
  }
4339
4451
  if (!endsWithPipe || cells.length === 0) cells.push(cell);
4340
- if (s.startsWith("|") && cells.length > 1) cells.shift();
4452
+ if (s.startsWith("|")) cells.shift();
4341
4453
  return cells.map((c) => c.replace(/^[ \t]+|[ \t]+$/g, ""));
4342
4454
  }
4343
4455
  function fitRow(cells, length) {
@@ -4463,7 +4575,7 @@ function splitHtmlSection(source, options = DEFAULT_MARKDOWN) {
4463
4575
  ${slotMarker(slots.length - 1)}
4464
4576
  `);
4465
4577
  }
4466
- slot.push(...lowerTopLevel(node, options, textOf(i)));
4578
+ slot.push(...lowerTopLevel(node, options, textOf(i), slot[slot.length - 1]));
4467
4579
  });
4468
4580
  return { html: parts.join("\n"), slots };
4469
4581
  }
@@ -4653,7 +4765,7 @@ var STRATEGIES = [
4653
4765
  function sameInline(a, b) {
4654
4766
  return a.length === b.length && a.every((s, i) => {
4655
4767
  const t = b[i];
4656
- return s.text === t.text && s.link === t.link && sameMarks(s.marks, t.marks) && s.image?.src === t.image?.src && s.image?.alt === t.image?.alt && s.image?.title === t.image?.title && s.image?.align === t.image?.align && s.image?.width === t.image?.width && s.image?.height === t.image?.height;
4768
+ return s.text === t.text && sameLink(s, t) && sameMarks(s.marks, t.marks) && s.image?.src === t.image?.src && s.image?.alt === t.image?.alt && s.image?.title === t.image?.title && s.image?.align === t.image?.align && s.image?.width === t.image?.width && s.image?.height === t.image?.height;
4657
4769
  });
4658
4770
  }
4659
4771
  var reSpecWhitespace = /^[\t\n\f\r\p{Zs}]+|[\t\n\f\r\p{Zs}]+$/gu;
@@ -4796,7 +4908,7 @@ function tokenize(spans, ctx, italic, bare) {
4796
4908
  continue;
4797
4909
  }
4798
4910
  let j = i;
4799
- while (j < spans.length && spans[j].link === span.link) j++;
4911
+ while (j < spans.length && sameLink(spans[j], span)) j++;
4800
4912
  const common = EMPHASIS.filter((m) => spans.slice(i, j).every((s) => s.marks.includes(m)));
4801
4913
  closeExcept(common, 0);
4802
4914
  openMarks(common, i, spans.length);
@@ -4808,7 +4920,7 @@ function tokenize(spans, ctx, italic, bare) {
4808
4920
  const base = stack.length;
4809
4921
  for (let k = i; k < j; k++) emitSpan(spans[k], base, k, j, true);
4810
4922
  closeTo(base);
4811
- tokens.push({ kind: "raw", text: `](${linkDestination(span.link)})` });
4923
+ tokens.push({ kind: "raw", text: `](${linkDestination(span.link)}${linkTitle(span.linkTitle)})` });
4812
4924
  }
4813
4925
  i = j;
4814
4926
  }
@@ -4878,22 +4990,30 @@ function flanking(ch, before, after) {
4878
4990
  function render(spans, ctx, strategy, bare = false) {
4879
4991
  const tokens = tokenize(spans, ctx, strategy.italic, bare);
4880
4992
  fixFlanking(tokens, strategy.encodeAll);
4881
- let out = "";
4993
+ const out = [];
4994
+ let last;
4995
+ const write = (text) => {
4996
+ if (text === "") return;
4997
+ out.push(text);
4998
+ last = text[text.length - 1];
4999
+ };
4882
5000
  tokens.forEach((tok, i) => {
4883
- if (tok.kind === "delim") out += tok.ch.repeat(tok.count);
5001
+ if (tok.kind === "delim") write(tok.ch.repeat(tok.count));
4884
5002
  else if (tok.kind === "raw") {
4885
- if (ctx.lineStart && out.endsWith("\n") && interruptsParagraph(tok.text)) out += " ";
4886
- out += tok.text;
5003
+ if (ctx.lineStart && last === "\n" && interruptsParagraph(tok.text)) write(" ");
5004
+ write(tok.text);
4887
5005
  } else {
4888
- out += escapeText(tok, ctx, {
4889
- before: out ? out[out.length - 1] : void 0,
4890
- after: edgeChar(tokens[i + 1], "first"),
4891
- lineStart: out === "" || out.endsWith("\n"),
4892
- atEnd: i === tokens.length - 1
4893
- });
5006
+ write(
5007
+ escapeText(tok, ctx, {
5008
+ before: last,
5009
+ after: edgeChar(tokens[i + 1], "first"),
5010
+ lineStart: last === void 0 || last === "\n",
5011
+ atEnd: i === tokens.length - 1
5012
+ })
5013
+ );
4894
5014
  }
4895
5015
  });
4896
- return out;
5016
+ return out.join("");
4897
5017
  }
4898
5018
  var ALNUM = /[\p{L}\p{N}]/u;
4899
5019
  var ASCII_PUNCT = /[!-/:-@[-`{-~]/;
@@ -4943,7 +5063,7 @@ function escapeLine(line, o) {
4943
5063
  if (o.encodeFirst || o.startsLine && (line[0] === " " || line[0] === " ")) encodeAt.add(0);
4944
5064
  if (o.encodeLast || o.endsLine && (line[lastIndex] === " " || line[lastIndex] === " ")) encodeAt.add(lastIndex);
4945
5065
  const blockEscape = o.blockSyntax && !encodeAt.has(0) ? blockSyntaxEscapeIndex(line) : -1;
4946
- const urlEscapes = o.autolinks ? literalEscapes(line, o.before) : null;
5066
+ const urlEscapes = o.autolinks ? literalEscapes(line, o.before, o.after) : null;
4947
5067
  let out = "";
4948
5068
  for (let i = 0; i < line.length; i++) {
4949
5069
  if (encodeAt.has(i)) {
@@ -4990,14 +5110,16 @@ function escapeLine(line, o) {
4990
5110
  }
4991
5111
  return out;
4992
5112
  }
4993
- function literalEscapes(line, before) {
5113
+ function literalEscapes(line, before, after) {
4994
5114
  const emails = emailLiterals(line);
4995
5115
  if (!emails.length && !/www\.|:\/\//i.test(line)) return null;
4996
5116
  const out = /* @__PURE__ */ new Set();
5117
+ const text = line + (after ?? "");
4997
5118
  for (const c of line.matchAll(/www\.|(?:https?|ftp):\/\//gi)) {
4998
5119
  const at = c.index;
4999
- if (!isLiteralBoundary(at > 0 ? line[at - 1] : before) || !urlLiteralAt(line, at)) continue;
5000
- out.add(at + c[0].indexOf(c[0].startsWith("w") || c[0].startsWith("W") ? "." : ":"));
5120
+ const www = c[0].toLowerCase() === "www.";
5121
+ if (!isLiteralBoundary(at > 0 ? line[at - 1] : before, www) || !urlLiteralAt(text, at)) continue;
5122
+ out.add(at + c[0].indexOf(www ? "." : ":"));
5001
5123
  }
5002
5124
  for (const { from } of emails) out.add(line.indexOf("@", from));
5003
5125
  return out;
@@ -5017,15 +5139,15 @@ function codeSpan(text) {
5017
5139
  return pad ? `${fence} ${text} ${fence}` : `${fence}${text}${fence}`;
5018
5140
  }
5019
5141
  var reAutolinkUri = new RegExp(`^${AUTOLINK_URI}$`);
5020
- var reEmail2 = new RegExp(`^${AUTOLINK_EMAIL}$`);
5142
+ var reEmail = new RegExp(`^${AUTOLINK_EMAIL}$`);
5021
5143
  function isBareLink(span) {
5022
- if (span.link === void 0 || span.image || span.token || span.marks.includes("code") || span.marks.includes("html")) return false;
5144
+ if (span.link === void 0 || span.linkTitle !== void 0 || span.image || span.token || span.marks.includes("code") || span.marks.includes("html")) return false;
5023
5145
  return literalHref(span.text) === span.link;
5024
5146
  }
5025
5147
  function autolink(span) {
5026
- if (span.image || span.marks.includes("code") || span.marks.includes("html") || span.link === void 0) return null;
5148
+ if (span.image || span.marks.includes("code") || span.marks.includes("html") || span.link === void 0 || span.linkTitle !== void 0) return null;
5027
5149
  if (span.text === span.link && reAutolinkUri.test(span.link)) return `<${span.link}>`;
5028
- if (span.link === "mailto:" + span.text && reEmail2.test(span.text)) return `<${span.text}>`;
5150
+ if (span.link === "mailto:" + span.text && reEmail.test(span.text)) return `<${span.text}>`;
5029
5151
  return null;
5030
5152
  }
5031
5153
  function escapeEntities(s) {
@@ -5046,6 +5168,10 @@ function linkDestination(url) {
5046
5168
  }
5047
5169
  return escapeEntities(url.replace(/\\/g, "\\\\"));
5048
5170
  }
5171
+ function linkTitle(title) {
5172
+ if (!title) return "";
5173
+ return ` "${escapeEntities(title.replace(/\n(?:[ \t]*\n)+/g, "\n").replace(/["\\]/g, "\\$&"))}"`;
5174
+ }
5049
5175
  function imageMarkdown(image, ctx) {
5050
5176
  const altCtx = ctx.newline === "soft" ? { ...ctx, newline: "break" } : ctx;
5051
5177
  const alt = escapeText({ text: image.alt, encodeFirst: false, encodeLast: false }, altCtx, {
@@ -5054,7 +5180,7 @@ function imageMarkdown(image, ctx) {
5054
5180
  lineStart: false,
5055
5181
  atEnd: false
5056
5182
  });
5057
- const title = image.title ? ` "${escapeEntities(image.title.replace(/["\\]/g, "\\$&"))}"` : "";
5183
+ const title = linkTitle(image.title);
5058
5184
  const suffix = imageSuffixText(image);
5059
5185
  const read = imageSuffix(alt + suffix);
5060
5186
  const same = read ? read.index === alt.length && imageSuffixText(read) === suffix : !suffix;
@@ -5086,7 +5212,7 @@ function loadMarkdown(text, options) {
5086
5212
  const lines = root.lines[last];
5087
5213
  const to = lineEnds[Math.max(lines.start, lines.end) - 1] ?? text.length;
5088
5214
  const source = text.slice(from, to);
5089
- const lowered = section ? [section] : last > i ? [htmlBlock(source)] : lowerTopLevel(node, options ?? DEFAULT_MARKDOWN, source);
5215
+ const lowered = section ? [section] : last > i ? [htmlBlock(source)] : lowerTopLevel(node, options ?? DEFAULT_MARKDOWN, source, blocks[blocks.length - 1]);
5090
5216
  i = last;
5091
5217
  blocks.push(...lowered);
5092
5218
  if (lowered.length === 0 || from < lastEnd || to < from) continue;
@@ -5741,7 +5867,8 @@ function matchToken(scan, { probe = "a", maxLength = 30 } = {}) {
5741
5867
  let lineEnd = text.indexOf("\n", caret2);
5742
5868
  if (lineEnd < 0) lineEnd = text.length;
5743
5869
  const reach = maxLength + 16;
5744
- const from = Math.max(lineStart, caret2 - reach);
5870
+ let from = Math.max(lineStart, caret2 - reach);
5871
+ while (from > lineStart && !/\s/.test(text[from - 1])) from--;
5745
5872
  const to = Math.min(lineEnd + probe.length, caret2 + probe.length + reach);
5746
5873
  for (const token of scan(probed, from, to)) {
5747
5874
  if (token.from >= caret2 || token.to < caret2 + probe.length) continue;
@@ -6275,6 +6402,8 @@ var WidgetImpl = class {
6275
6402
  this.paint();
6276
6403
  }
6277
6404
  blockId;
6405
+ /** In source mode, the text offset the widget sits after. */
6406
+ offset = 0;
6278
6407
  isRemoved = false;
6279
6408
  cleanup = null;
6280
6409
  update(render2) {
@@ -6744,10 +6873,10 @@ function blockClasses(block3, theme) {
6744
6873
  }
6745
6874
  }
6746
6875
  var defaultResolveUrl = (url) => {
6747
- const trimmed = url.trim();
6748
- const scheme = /^([a-z][a-z0-9+.-]*):/i.exec(trimmed);
6749
- if (!scheme) return trimmed;
6750
- return ["http", "https", "mailto", "tel"].includes(scheme[1].toLowerCase()) ? trimmed : null;
6876
+ const read = url.replace(/^[\u0000- ]+|[\u0000- ]+$/g, "").replace(/[\t\n\r]/g, "");
6877
+ const scheme = /^([a-z][a-z0-9+.-]*):/i.exec(read);
6878
+ if (!scheme) return read;
6879
+ return ["http", "https", "mailto", "tel"].includes(scheme[1].toLowerCase()) ? read : null;
6751
6880
  };
6752
6881
  var REVEAL_BLOCK = "block";
6753
6882
  function tokenKey(cell, from) {
@@ -6836,6 +6965,15 @@ function renderBlock(block3, ctx, reveal) {
6836
6965
  break;
6837
6966
  }
6838
6967
  case "code": {
6968
+ if (ctx.source) {
6969
+ root = el("div");
6970
+ root.dir = "auto";
6971
+ root.spellcheck = false;
6972
+ const text = el("div", "mbe-source-text");
6973
+ fillContent(text, block3.content, ctx, block3, void 0, void 0, false);
6974
+ root.appendChild(text);
6975
+ break;
6976
+ }
6839
6977
  const view = reveal?.has(REVEAL_BLOCK) ? null : ctx.view?.(codeViewName(block3.language), inlineText(block3.content), "block");
6840
6978
  if (view) {
6841
6979
  root = view;
@@ -6933,7 +7071,7 @@ function renderBlock(block3, ctx, reveal) {
6933
7071
  }
6934
7072
  }
6935
7073
  root.setAttribute(BLOCK_ATTR, block3.id);
6936
- const name = block3.type === "listItem" ? "list-item" : block3.type === "detailsEnd" ? "details-end" : block3.type;
7074
+ const name = block3.type === "listItem" ? "list-item" : block3.type === "detailsEnd" ? "details-end" : block3.type === "code" && ctx.source ? "source" : block3.type;
6937
7075
  let className = `${root.className ? root.className + " " : ""}mbe-block mbe-${name}`;
6938
7076
  if (block3.type === "listItem" && block3.checked) className += " mbe-checked";
6939
7077
  if ("content" in block3 && inlineLength(block3.content) === 0) className += " mbe-empty";
@@ -6950,7 +7088,7 @@ function fillContent(target, inline3, ctx, block3, reveal, cell, decorated = tru
6950
7088
  target.appendChild(fill(doc));
6951
7089
  return;
6952
7090
  }
6953
- const decorations = block3.type === "code" ? ctx.decorateCode?.(block3) ?? [] : decorated && ctx.decorate ? ctx.decorate(block3, inline3, cell) : [];
7091
+ const decorations = block3.type === "code" ? ctx.source ? [] : ctx.decorateCode?.(block3) ?? [] : decorated && ctx.decorate ? ctx.decorate(block3, inline3, cell) : [];
6954
7092
  const only = inline3.length === 1 ? inline3[0] : null;
6955
7093
  if (only && decorations.length === 0 && only.marks.length === 0 && !only.link && !only.token && !only.image) {
6956
7094
  target.appendChild(doc.createTextNode(only.text));
@@ -7197,8 +7335,9 @@ function renderInline(inline3, parent, ctx, decorations, reveal, cell) {
7197
7335
  const href = ctx.resolveUrl(span.link, "link");
7198
7336
  if (href !== null) a.setAttribute("href", href);
7199
7337
  a.dataset.href = span.link;
7338
+ if (span.linkTitle) a.title = span.linkTitle;
7200
7339
  a.className = classes("mbe-link", ctx.classes.link);
7201
- while (i < pieces.length && pieces[i].span.link === span.link) {
7340
+ while (i < pieces.length && sameLink(pieces[i].span, span)) {
7202
7341
  a.appendChild(render2(pieces[i]));
7203
7342
  i++;
7204
7343
  }
@@ -7331,6 +7470,8 @@ var BlockRenderer = class {
7331
7470
  icon;
7332
7471
  /** Code blocks get a copy button. */
7333
7472
  codeCopy = false;
7473
+ /** Source mode: the code block renders as plain text. Changing it needs a forced render. */
7474
+ source = false;
7334
7475
  /** An image failed to load and now shows as unavailable. */
7335
7476
  onImageError;
7336
7477
  /** Collapsible sections shown collapsed, by the ID of their title block. */
@@ -7364,6 +7505,7 @@ var BlockRenderer = class {
7364
7505
  classes: this.classes,
7365
7506
  icon: this.icon,
7366
7507
  codeCopy: this.codeCopy,
7508
+ source: this.source,
7367
7509
  onImageError: this.onImageError,
7368
7510
  loadedImage: (src) => this.loadedImages.get(src)?.shift()
7369
7511
  };
@@ -7524,6 +7666,7 @@ function markSection(el, depth, hidden, collapsed, labels) {
7524
7666
  }
7525
7667
  function updateNeighborMarks(doc, elementFor, written, collapsed, labels) {
7526
7668
  const counters = [];
7669
+ let topOrdered;
7527
7670
  const sections2 = [];
7528
7671
  doc.blocks.forEach((block3, i) => {
7529
7672
  const before = doc.blocks[i - 1];
@@ -7535,14 +7678,14 @@ function updateNeighborMarks(doc, elementFor, written, collapsed, labels) {
7535
7678
  setFlag(el, QUOTE_JOINED_ATTR, sameQuote(before, block3));
7536
7679
  setFlag(el, QUOTE_CONTINUED_ATTR, sameQuote(block3, doc.blocks[i + 1]));
7537
7680
  }
7538
- if (block3.type !== "listItem" || before?.type !== "listItem" || quoteKind(before) !== quoteKind(block3)) counters.length = 0;
7681
+ if (block3.type !== "listItem" || before?.type !== "listItem" || quoteKind(before) !== quoteKind(block3)) {
7682
+ counters.length = 0;
7683
+ topOrdered = void 0;
7684
+ }
7539
7685
  if (block3.type !== "listItem") return;
7540
7686
  const ordered = block3.listType === "ordered";
7541
- setFlag(
7542
- el,
7543
- LIST_START_ATTR,
7544
- counters.length === 0 || block3.indent === 0 && before?.type === "listItem" && ordered !== (before.listType === "ordered")
7545
- );
7687
+ setFlag(el, LIST_START_ATTR, counters.length === 0 || block3.indent === 0 && topOrdered !== void 0 && ordered !== topOrdered);
7688
+ if (block3.indent === 0) topOrdered = ordered;
7546
7689
  counters.length = block3.indent + 1;
7547
7690
  if (!ordered) {
7548
7691
  counters[block3.indent] = void 0;
@@ -7814,7 +7957,7 @@ var LinkCard = class {
7814
7957
  };
7815
7958
  const open = button("openLink", (e) => actions.open(this.target, e));
7816
7959
  this.copyButton = button("copyLink", () => this.copy());
7817
- const edit = button("editLink", () => {
7960
+ const edit2 = button("editLink", () => {
7818
7961
  const target = this.target;
7819
7962
  this.hide();
7820
7963
  actions.edit(target);
@@ -7826,7 +7969,7 @@ var LinkCard = class {
7826
7969
  });
7827
7970
  const sep = doc.createElement("span");
7828
7971
  sep.className = "mbe-tool-sep";
7829
- el.append(this.url, sep, open, this.copyButton, edit, remove);
7972
+ el.append(this.url, sep, open, this.copyButton, edit2, remove);
7830
7973
  const root = editor.root;
7831
7974
  const on = (target, type, fn) => {
7832
7975
  target.addEventListener(type, fn);
@@ -8289,6 +8432,177 @@ function tokenProperties(tokens) {
8289
8432
  return props;
8290
8433
  }
8291
8434
 
8435
+ // src/sourceMode.ts
8436
+ var SOURCE_ID = "mbe-source";
8437
+ function sourceDoc(text) {
8438
+ return { blocks: [codeBlock("", text, SOURCE_ID)] };
8439
+ }
8440
+ function isSourceDoc(doc) {
8441
+ return doc.blocks.length === 1 && doc.blocks[0].id === SOURCE_ID;
8442
+ }
8443
+ function sourceText(doc) {
8444
+ return inlineText(doc.blocks[0].content);
8445
+ }
8446
+ function sourcePosition(offset) {
8447
+ return { blockId: SOURCE_ID, offset };
8448
+ }
8449
+ function sourceState(text, anchor, focus = anchor) {
8450
+ return {
8451
+ doc: sourceDoc(text),
8452
+ selection: { anchor: sourcePosition(clamp(anchor, text)), focus: sourcePosition(clamp(focus, text)) },
8453
+ storedMarks: null
8454
+ };
8455
+ }
8456
+ function clamp(offset, text) {
8457
+ return Math.max(0, Math.min(offset, text.length));
8458
+ }
8459
+ function sourceRange(state) {
8460
+ const a = state.selection.anchor.offset;
8461
+ const f = state.selection.focus.offset;
8462
+ return { from: Math.min(a, f), to: Math.max(a, f) };
8463
+ }
8464
+ function edit(state, from, to, insert, selFrom, selTo = selFrom) {
8465
+ const text = sourceText(state.doc);
8466
+ return sourceState(text.slice(0, from) + insert + text.slice(to), selFrom, selTo);
8467
+ }
8468
+ function insertSourceText(state, insert) {
8469
+ const { from, to } = sourceRange(state);
8470
+ return edit(state, from, to, insert, from + insert.length);
8471
+ }
8472
+ function insertSourceAt(state, offset, insert, block3, keepSelection) {
8473
+ const text = sourceText(state.doc);
8474
+ const at = clamp(offset, text);
8475
+ let piece = insert;
8476
+ if (block3) {
8477
+ if (at > 0 && text[at - 1] !== "\n") piece = "\n" + piece;
8478
+ if (at < text.length && text[at] !== "\n" && !piece.endsWith("\n")) piece += "\n";
8479
+ }
8480
+ if (keepSelection) {
8481
+ const shift = (o) => o >= at ? o + piece.length : o;
8482
+ return sourceState(text.slice(0, at) + piece + text.slice(at), shift(state.selection.anchor.offset), shift(state.selection.focus.offset));
8483
+ }
8484
+ const end = at + piece.length - (block3 && piece.endsWith("\n") && !insert.endsWith("\n") ? 1 : 0);
8485
+ return sourceState(text.slice(0, at) + piece + text.slice(at), end);
8486
+ }
8487
+ function sourceDeleteBackward(state, previous) {
8488
+ const { from, to } = sourceRange(state);
8489
+ if (from !== to) return edit(state, from, to, "", from);
8490
+ if (from === 0) return null;
8491
+ const start = previous(sourceText(state.doc), from);
8492
+ return edit(state, start, from, "", start);
8493
+ }
8494
+ function sourceDeleteForward(state, next) {
8495
+ const { from, to } = sourceRange(state);
8496
+ if (from !== to) return edit(state, from, to, "", from);
8497
+ const text = sourceText(state.doc);
8498
+ if (from === text.length) return null;
8499
+ return edit(state, from, next(text, from), "", from);
8500
+ }
8501
+ function mapOffset(offset, before, after) {
8502
+ if (before === after) return offset;
8503
+ let start = 0;
8504
+ while (start < before.length && start < after.length && before[start] === after[start]) start++;
8505
+ let endBefore = before.length;
8506
+ let endAfter = after.length;
8507
+ while (endBefore > start && endAfter > start && before[endBefore - 1] === after[endAfter - 1]) {
8508
+ endBefore--;
8509
+ endAfter--;
8510
+ }
8511
+ if (offset <= start) return offset;
8512
+ if (offset >= endBefore) return offset + (after.length - before.length);
8513
+ return endAfter;
8514
+ }
8515
+ function blockText(block3) {
8516
+ if (block3.type === "table" || isTextless(block3)) return null;
8517
+ const content = containerContent(block3);
8518
+ return content ? inlineText(content) : null;
8519
+ }
8520
+ function placeBlocks(loaded) {
8521
+ const src = loaded.source.text;
8522
+ const placed = [];
8523
+ let lastEnd = 0;
8524
+ for (const block3 of loaded.doc.blocks) {
8525
+ const group = loaded.source.groupOf.get(block3);
8526
+ const text = blockText(block3);
8527
+ if (!group) {
8528
+ placed.push({ start: lastEnd, end: lastEnd, text });
8529
+ continue;
8530
+ }
8531
+ const first = group.blocks[0] === block3;
8532
+ let cursor = first ? group.from : Math.max(group.from, lastEnd);
8533
+ if (!first) {
8534
+ const nl = src.indexOf("\n", cursor);
8535
+ if (nl !== -1 && nl < group.to) cursor = nl + 1;
8536
+ }
8537
+ let start = cursor;
8538
+ if (text) {
8539
+ const exact = src.indexOf(text, cursor);
8540
+ const head = src.indexOf(text.slice(0, Math.min(text.length, 1)), cursor);
8541
+ if (exact !== -1 && exact <= group.to) start = exact;
8542
+ else if (head !== -1 && head <= group.to) start = head;
8543
+ } else if (block3.type !== "table") {
8544
+ const lineEnd = src.indexOf("\n", cursor);
8545
+ start = Math.min(lineEnd === -1 ? group.to : lineEnd, group.to);
8546
+ }
8547
+ const last = group.blocks[group.blocks.length - 1] === block3;
8548
+ let end = group.to;
8549
+ if (!last) {
8550
+ const nl = src.indexOf("\n", start + (text?.length ?? 0));
8551
+ end = nl === -1 || nl > group.to ? group.to : nl;
8552
+ }
8553
+ placed.push({ start, end, text });
8554
+ lastEnd = end;
8555
+ }
8556
+ return placed;
8557
+ }
8558
+ function toSourceOffset(doc, pos, loaded, placed = placeBlocks(loaded)) {
8559
+ const index = doc.blocks.findIndex((b) => b.id === pos.blockId);
8560
+ const at = placed[Math.max(0, Math.min(index, placed.length - 1))];
8561
+ if (!at) return 0;
8562
+ const block3 = doc.blocks[index];
8563
+ if (!block3 || pos.cell) return at.start;
8564
+ const text = blockText(block3);
8565
+ if (!text) return at.start;
8566
+ const before = text.slice(0, pos.offset);
8567
+ const src = loaded.source.text;
8568
+ if (src.startsWith(before, at.start)) return at.start + before.length;
8569
+ const found = src.indexOf(before, at.start);
8570
+ return found !== -1 && found + before.length <= at.end ? found + before.length : at.start;
8571
+ }
8572
+ function fromSourceOffset(offset, loaded, placed = placeBlocks(loaded)) {
8573
+ const blocks = loaded.doc.blocks;
8574
+ let index = 0;
8575
+ for (let i = 0; i < placed.length; i++) {
8576
+ const p2 = placed[i];
8577
+ const group = loaded.source.groupOf.get(blocks[i]);
8578
+ const from = group && group.blocks[0] === blocks[i] ? group.from : p2.start;
8579
+ if (from <= offset) index = i;
8580
+ else break;
8581
+ }
8582
+ const block3 = blocks[index];
8583
+ const p = placed[index];
8584
+ const text = blockText(block3);
8585
+ if (block3.type === "table") return { blockId: block3.id, offset: 0, cell: { row: 0, col: 0 } };
8586
+ if (!p || !text) return { blockId: block3.id, offset: 0 };
8587
+ const src = loaded.source.text;
8588
+ if (offset <= p.start) return { blockId: block3.id, offset: 0 };
8589
+ const before = src.slice(p.start, offset);
8590
+ return { blockId: block3.id, offset: text.startsWith(before) ? before.length : 0 };
8591
+ }
8592
+ function selectionToSource(doc, sel, loaded) {
8593
+ const placed = placeBlocks(loaded);
8594
+ return { anchor: toSourceOffset(doc, sel.anchor, loaded, placed), focus: toSourceOffset(doc, sel.focus, loaded, placed) };
8595
+ }
8596
+ function selectionFromSource(anchor, focus, loaded) {
8597
+ const placed = placeBlocks(loaded);
8598
+ return { anchor: fromSourceOffset(anchor, loaded, placed), focus: fromSourceOffset(focus, loaded, placed) };
8599
+ }
8600
+ function blockEndOffset(doc, blockId, loaded) {
8601
+ const placed = placeBlocks(loaded);
8602
+ const index = doc.blocks.findIndex((b) => b.id === blockId);
8603
+ return placed[Math.max(0, Math.min(index, placed.length - 1))]?.end ?? loaded.source.text.length;
8604
+ }
8605
+
8292
8606
  // src/editor.ts
8293
8607
  var SLASH_ITEM_IDS = [
8294
8608
  "text",
@@ -8351,7 +8665,11 @@ var Editor = class {
8351
8665
  source;
8352
8666
  /** The Markdown dialect: options plus the syntax of extensions. */
8353
8667
  markdown;
8354
- history = new History();
8668
+ history = new History(() => this.source);
8669
+ /** Rich blocks, or the whole document as text in one block (see sourceMode.ts). */
8670
+ modeValue = "rich";
8671
+ /** A mode switch asked for during a composition, applied when it settles. */
8672
+ pendingMode = null;
8355
8673
  renderer;
8356
8674
  composing = false;
8357
8675
  /**
@@ -8555,6 +8873,7 @@ var Editor = class {
8555
8873
  this.listen(root.ownerDocument, "mouseup", () => this.onMouseUp());
8556
8874
  this.listen(root.ownerDocument, "scroll", () => this.onScroll(), true);
8557
8875
  this.listen(root.ownerDocument, "pointerdown", (e) => this.onDocumentPointerDown(e), true);
8876
+ if (options.mode === "source") this.enterSource();
8558
8877
  this.paint(true, true);
8559
8878
  this.afterRender();
8560
8879
  for (const ext of this.extensions) {
@@ -8567,6 +8886,7 @@ var Editor = class {
8567
8886
  // Content
8568
8887
  /** The document as Markdown. Blocks that were not edited are written exactly as they were loaded. */
8569
8888
  getMarkdown() {
8889
+ if (this.modeValue === "source") return sourceText(this.current.doc);
8570
8890
  return serializeMarkdown(this.current.doc, { ...this.markdown, source: this.source });
8571
8891
  }
8572
8892
  /**
@@ -8577,6 +8897,15 @@ var Editor = class {
8577
8897
  if (this.destroyed) return;
8578
8898
  if (options.history === "keep") this.history.record(this.current, "other");
8579
8899
  else this.history.clear();
8900
+ if (this.modeValue === "source") {
8901
+ this.suggestions.reset();
8902
+ this.current = sourceState(markdown, 0);
8903
+ for (const widget of this.widgets) widget.offset = Math.min(widget.offset, markdown.length);
8904
+ this.paint(true, true);
8905
+ this.afterRender();
8906
+ this.emit("selectionChange", { editor: this });
8907
+ return;
8908
+ }
8580
8909
  const loaded = loadMarkdown(markdown, this.markdown);
8581
8910
  this.source = loaded.source;
8582
8911
  this.blockSel = null;
@@ -8592,6 +8921,7 @@ var Editor = class {
8592
8921
  }
8593
8922
  /** True when the document holds only empty paragraphs. */
8594
8923
  get isEmpty() {
8924
+ if (this.modeValue === "source") return sourceText(this.current.doc) === "";
8595
8925
  return this.current.doc.blocks.every((b) => b.type === "paragraph" && inlineLength(b.content) === 0);
8596
8926
  }
8597
8927
  // -------------------------------------------------------------------------
@@ -8604,6 +8934,10 @@ var Editor = class {
8604
8934
  get isComposing() {
8605
8935
  return this.composing;
8606
8936
  }
8937
+ /** `'rich'` or `'source'`: the mode the editor shows now. */
8938
+ get mode() {
8939
+ return this.pendingMode ?? this.modeValue;
8940
+ }
8607
8941
  get isEditable() {
8608
8942
  return !this.readOnly && !this.destroyed;
8609
8943
  }
@@ -8613,6 +8947,7 @@ var Editor = class {
8613
8947
  }
8614
8948
  /** True if `name` applies at the selection: a mark on the selected text, or the type of the block with the caret. */
8615
8949
  isActive(name, attrs) {
8950
+ if (this.modeValue === "source") return false;
8616
8951
  const s = this.current;
8617
8952
  switch (name) {
8618
8953
  case "bold":
@@ -8637,6 +8972,7 @@ var Editor = class {
8637
8972
  }
8638
8973
  /** Attributes of `name` at the selection: `src`, `alt`, `title`, `align`, `width`, `height` and `block` (true for an image block) for a selected image, `href` for a link, `level` for a heading, `language` for a code block, `checked` for a task, `syntax` for a raw block, `callout` for a callout, `open` (saved as `<details open>`) and `collapsed` (shown collapsed now) for a section title. */
8639
8974
  getAttributes(name) {
8975
+ if (this.modeValue === "source") return {};
8640
8976
  const s = this.current;
8641
8977
  if (name === "link") {
8642
8978
  const link = activeLink(s);
@@ -8725,6 +9061,7 @@ var Editor = class {
8725
9061
  const widget = new WidgetImpl(el, blockId, options.render, (w) => {
8726
9062
  this.widgets = this.widgets.filter((x) => x !== w);
8727
9063
  });
9064
+ if (this.modeValue === "source") widget.offset = options.at === "end" ? sourceText(this.current.doc).length : at.offset;
8728
9065
  this.widgets.push(widget);
8729
9066
  this.paint();
8730
9067
  return widget;
@@ -8784,6 +9121,92 @@ var Editor = class {
8784
9121
  this.applyReadOnly();
8785
9122
  }
8786
9123
  this.applyRuntime(options);
9124
+ if (options.mode !== void 0) this.setMode(options.mode);
9125
+ }
9126
+ // -------------------------------------------------------------------------
9127
+ // Source mode (see sourceMode.ts and docs/architecture.md, "Source mode")
9128
+ /**
9129
+ * Shows the document as blocks or as its Markdown text. The text does not
9130
+ * change, so this emits no `change` and records no undo step. During a
9131
+ * composition the switch waits for it to settle.
9132
+ */
9133
+ setMode(mode) {
9134
+ if (mode !== "rich" && mode !== "source") return;
9135
+ if (this.composing || this.composition) {
9136
+ this.pendingMode = mode === this.modeValue ? null : mode;
9137
+ return;
9138
+ }
9139
+ this.pendingMode = null;
9140
+ if (mode === this.modeValue) return;
9141
+ const hadFocus = this.hasFocus();
9142
+ const caretTop = this.caretRect()?.top;
9143
+ this.blockSel = null;
9144
+ this.shortcut = null;
9145
+ this.suggestions.reset();
9146
+ this.hideUi();
9147
+ this.closeBlockMenu();
9148
+ this.history.breakGroup();
9149
+ if (mode === "source") this.enterSource();
9150
+ else this.leaveSource();
9151
+ this.paint(true, false, hadFocus);
9152
+ this.afterRender();
9153
+ const after = this.caretRect()?.top;
9154
+ if (caretTop !== void 0 && after !== void 0 && Math.abs(after - caretTop) > 1) scrollBy(this.root, after - caretTop);
9155
+ this.emit("selectionChange", { editor: this });
9156
+ }
9157
+ /** Rich blocks to text: the text is `getMarkdown()`; the selection and widgets keep their blocks. */
9158
+ enterSource() {
9159
+ const { doc, selection } = this.current;
9160
+ const text = this.getMarkdown();
9161
+ const loaded = loadMarkdown(text, this.markdown);
9162
+ const sel = selectionToSource(doc, selection, loaded);
9163
+ for (const widget of this.widgets) {
9164
+ widget.offset = blockEndOffset(doc, widget.blockId, loaded);
9165
+ widget.blockId = SOURCE_ID;
9166
+ }
9167
+ this.collapsed.clear();
9168
+ this.current = sourceState(text, sel.anchor, sel.focus);
9169
+ this.modeValue = "source";
9170
+ this.renderer.source = true;
9171
+ this.root.classList.add("mbe-source-mode");
9172
+ }
9173
+ /** Text to rich blocks, loaded as `setMarkdown` does, so the text saves byte for byte. */
9174
+ leaveSource() {
9175
+ const { anchor, focus } = this.current.selection;
9176
+ const loaded = this.loadSource(sourceText(this.current.doc));
9177
+ for (const widget of this.widgets) widget.blockId = fromSourceOffset(widget.offset, loaded).blockId;
9178
+ const sel = selectionFromSource(anchor.offset, focus.offset, loaded);
9179
+ this.current = { doc: loaded.doc, selection: clampSelection(loaded.doc, sel), storedMarks: null };
9180
+ this.modeValue = "rich";
9181
+ this.renderer.source = false;
9182
+ this.root.classList.remove("mbe-source-mode");
9183
+ }
9184
+ /** Loads text as the document's blocks, with an empty paragraph for empty text, and makes its source current. */
9185
+ loadSource(text) {
9186
+ const loaded = loadMarkdown(text, this.markdown);
9187
+ const doc = createState(loaded.doc).doc;
9188
+ this.source = loaded.source;
9189
+ this.collapsed.clear();
9190
+ this.collapseClosedSections(doc);
9191
+ return { doc, source: loaded.source };
9192
+ }
9193
+ /** A history entry, in the current mode: an entry made in the other mode is serialized or loaded. */
9194
+ restore(entry) {
9195
+ const { state } = entry;
9196
+ const isSource = isSourceDoc(state.doc);
9197
+ if (this.modeValue === "source") {
9198
+ if (isSource) return state;
9199
+ const text = serializeMarkdown(state.doc, { ...this.markdown, source: entry.source });
9200
+ const sel2 = selectionToSource(state.doc, state.selection, loadMarkdown(text, this.markdown));
9201
+ return sourceState(text, sel2.anchor, sel2.focus);
9202
+ }
9203
+ if (!isSource) {
9204
+ this.source = entry.source;
9205
+ return state;
9206
+ }
9207
+ const loaded = this.loadSource(sourceText(state.doc));
9208
+ const sel = selectionFromSource(state.selection.anchor.offset, state.selection.focus.offset, loaded);
9209
+ return { doc: loaded.doc, selection: clampSelection(loaded.doc, sel), storedMarks: null };
8787
9210
  }
8788
9211
  /** Subscribes to an event. Returns a function that unsubscribes. */
8789
9212
  on(type, handler) {
@@ -8935,6 +9358,38 @@ var Editor = class {
8935
9358
  return true;
8936
9359
  }
8937
9360
  };
9361
+ const rich = { ...commands };
9362
+ const inSource = (name, fn) => {
9363
+ const richFn = rich[name];
9364
+ commands[name] = (...args) => this.modeValue === "source" ? fn ? fn(...args) : false : richFn(...args);
9365
+ };
9366
+ inSource("indent", () => run((s) => indentCode(s, 1)));
9367
+ inSource("outdent", () => run((s) => indentCode(s, -1)));
9368
+ inSource("insertMarkdown", (markdown, options = {}) => this.insertSourceMarkdown(markdown, options));
9369
+ for (const name of [
9370
+ "toggleBold",
9371
+ "toggleItalic",
9372
+ "toggleStrike",
9373
+ "toggleCode",
9374
+ "setParagraph",
9375
+ "toggleHeading",
9376
+ "toggleBulletList",
9377
+ "toggleOrderedList",
9378
+ "toggleTaskList",
9379
+ "toggleBlockquote",
9380
+ "toggleCallout",
9381
+ "setCallout",
9382
+ "toggleDetails",
9383
+ "toggleCodeBlock",
9384
+ "setLink",
9385
+ "unsetLink",
9386
+ "updateImage",
9387
+ "insertTable",
9388
+ "insertDivider",
9389
+ "selectBlocks"
9390
+ ]) {
9391
+ inSource(name, null);
9392
+ }
8938
9393
  for (const name of Object.keys(commands)) {
8939
9394
  const fn = commands[name];
8940
9395
  commands[name] = (...args) => !this.destroyed && fn(...args);
@@ -8942,20 +9397,44 @@ var Editor = class {
8942
9397
  return commands;
8943
9398
  }
8944
9399
  toggleMark(mark) {
9400
+ if (this.modeValue === "source") return false;
8945
9401
  return this.run((s) => toggleMark(s, mark));
8946
9402
  }
9403
+ /** `insertMarkdown` in source mode: the Markdown is inserted as text. */
9404
+ insertSourceMarkdown(markdown, options) {
9405
+ const at = options.at ?? "selection";
9406
+ const keep = options.select === "keep";
9407
+ const block3 = options.block === true;
9408
+ if (at instanceof WidgetImpl) {
9409
+ if (at.isRemoved) return false;
9410
+ return this.run((s) => insertSourceAt(s, at.offset, markdown, true, keep));
9411
+ }
9412
+ if (at === "selection" && !block3 && !keep) return this.run((s) => insertSourceText(s, markdown));
9413
+ return this.run((s) => {
9414
+ let state = s;
9415
+ let offset;
9416
+ if (at === "selection") {
9417
+ const { from, to } = sourceRange(s);
9418
+ if (from !== to) state = insertSourceText(s, "");
9419
+ offset = from;
9420
+ } else {
9421
+ offset = at === "end" ? sourceText(s.doc).length : at.offset;
9422
+ }
9423
+ return insertSourceAt(state, offset, markdown, block3, keep);
9424
+ });
9425
+ }
8947
9426
  undo() {
8948
9427
  if (this.readOnly) return false;
8949
9428
  const next = this.history.undo(this.current);
8950
9429
  if (!next) return false;
8951
- this.commit(next);
9430
+ this.commit(this.restore(next));
8952
9431
  return true;
8953
9432
  }
8954
9433
  redo() {
8955
9434
  if (this.readOnly) return false;
8956
9435
  const next = this.history.redo(this.current);
8957
9436
  if (!next) return false;
8958
- this.commit(next);
9437
+ this.commit(this.restore(next));
8959
9438
  return true;
8960
9439
  }
8961
9440
  // -------------------------------------------------------------------------
@@ -9042,7 +9521,13 @@ var Editor = class {
9042
9521
  const docChanged = next.doc !== this.state.doc;
9043
9522
  const moved = next.selection !== this.state.selection;
9044
9523
  const hadFocus = this.hasFocus();
9045
- if (docChanged) this.relocateWidgets(this.current.doc, next.doc, false);
9524
+ if (docChanged && this.modeValue === "source") {
9525
+ const before = sourceText(this.current.doc);
9526
+ const after = sourceText(next.doc);
9527
+ for (const widget of this.widgets) widget.offset = mapOffset(widget.offset, before, after);
9528
+ } else if (docChanged) {
9529
+ this.relocateWidgets(this.current.doc, next.doc, false);
9530
+ }
9046
9531
  this.current = next;
9047
9532
  if (this.blockSel) {
9048
9533
  const range = this.blockRange();
@@ -9504,6 +9989,7 @@ var Editor = class {
9504
9989
  }
9505
9990
  this.refreshSelection();
9506
9991
  if ((type === "insertText" || type === "insertReplacementText") && selectedImageBlock(this.state)) return;
9992
+ if (this.modeValue === "source" && this.onSourceInput(type)) return;
9507
9993
  switch (type) {
9508
9994
  case "insertText": {
9509
9995
  const text = e.data ?? "";
@@ -9548,7 +10034,9 @@ var Editor = class {
9548
10034
  if (range && !isCollapsed(range) && range.anchor.blockId === range.focus.blockId) {
9549
10035
  this.run((s) => deleteSelection({ ...s, selection: range }));
9550
10036
  } else {
9551
- this.run(type.endsWith("Backward") ? deleteBackward : deleteForward);
10037
+ this.run(
10038
+ this.modeValue === "source" ? type.endsWith("Backward") ? (s) => sourceDeleteBackward(s, previousGrapheme) : (s) => sourceDeleteForward(s, nextGrapheme) : type.endsWith("Backward") ? deleteBackward : deleteForward
10039
+ );
9552
10040
  }
9553
10041
  return;
9554
10042
  }
@@ -9571,6 +10059,23 @@ var Editor = class {
9571
10059
  return;
9572
10060
  }
9573
10061
  }
10062
+ /** Input that works differently on text in source mode. Returns true when handled. */
10063
+ onSourceInput(type) {
10064
+ switch (type) {
10065
+ case "insertParagraph":
10066
+ case "insertLineBreak":
10067
+ this.run((s) => insertSourceText(s, "\n"));
10068
+ return true;
10069
+ case "deleteContentBackward":
10070
+ this.run((s) => sourceDeleteBackward(s, previousGrapheme));
10071
+ return true;
10072
+ case "deleteContentForward":
10073
+ this.run((s) => sourceDeleteForward(s, nextGrapheme));
10074
+ return true;
10075
+ default:
10076
+ return false;
10077
+ }
10078
+ }
9574
10079
  typeText(text) {
9575
10080
  this.run((s) => insertText(s, text), "typing");
9576
10081
  this.afterTyping(text);
@@ -9589,6 +10094,10 @@ var Editor = class {
9589
10094
  }
9590
10095
  /** Markdown shortcuts and suggestion menus that typing `text` triggers. */
9591
10096
  afterTyping(text) {
10097
+ if (this.modeValue === "source") {
10098
+ this.shortcut = null;
10099
+ return;
10100
+ }
9592
10101
  const typed = this.state;
9593
10102
  if (text === " " || text === "-") this.run((s) => applyBlockInputRules(s, this.markdown));
9594
10103
  if (text.length === 1 && "*_`~".includes(text)) this.run((s) => applyInlineInputRules(s));
@@ -9649,6 +10158,7 @@ var Editor = class {
9649
10158
  this.redecoratePending = false;
9650
10159
  this.afterRender();
9651
10160
  if (composed) this.typedForSuggestion();
10161
+ if (this.pendingMode) this.setMode(this.pendingMode);
9652
10162
  }
9653
10163
  onInput(e) {
9654
10164
  if (this.fromControl(e)) return;
@@ -9830,7 +10340,7 @@ var Editor = class {
9830
10340
  const { selection } = this.state;
9831
10341
  if (isCollapsed(selection) && selection.focus.offset === 0) {
9832
10342
  e.preventDefault();
9833
- this.run(deleteBackward);
10343
+ if (this.modeValue !== "source") this.run(deleteBackward);
9834
10344
  return;
9835
10345
  }
9836
10346
  }
@@ -9844,7 +10354,7 @@ var Editor = class {
9844
10354
  return;
9845
10355
  }
9846
10356
  }
9847
- if (e.key.startsWith("Arrow") && !mod2 && !e.shiftKey && !e.altKey) {
10357
+ if (e.key.startsWith("Arrow") && !mod2 && !e.shiftKey && !e.altKey && this.modeValue === "rich") {
9848
10358
  this.refreshSelection();
9849
10359
  const into = this.blockPast(e.key);
9850
10360
  if (into) {
@@ -9947,7 +10457,7 @@ var Editor = class {
9947
10457
  return;
9948
10458
  }
9949
10459
  this.dropBlockSelection();
9950
- if (target === this.root && e.button === 0 && !this.readOnly && this.clickBelowLastBlock(e)) return;
10460
+ if (target === this.root && e.button === 0 && !this.readOnly && this.modeValue === "rich" && this.clickBelowLastBlock(e)) return;
9951
10461
  const imageEl = e.button === 0 && !e.shiftKey && !this.readOnly ? target.closest?.(".mbe-image") : null;
9952
10462
  const image = imageEl && this.root.contains(imageEl) ? this.imageTarget(imageEl) : null;
9953
10463
  if (image) {
@@ -9961,7 +10471,7 @@ var Editor = class {
9961
10471
  this.revealView(view);
9962
10472
  return;
9963
10473
  }
9964
- if (e.button === 0 && e.detail === 3 && !this.readOnly && this.selectBlockText(target)) {
10474
+ if (e.button === 0 && e.detail === 3 && !this.readOnly && this.modeValue === "rich" && this.selectBlockText(target)) {
9965
10475
  e.preventDefault();
9966
10476
  return;
9967
10477
  }
@@ -10094,6 +10604,15 @@ var Editor = class {
10094
10604
  // Clipboard
10095
10605
  onCopy(e, cut) {
10096
10606
  if (this.fromControl(e)) return;
10607
+ if (this.modeValue === "source") {
10608
+ this.refreshSelection();
10609
+ if (isCollapsed(this.state.selection) || !e.clipboardData) return;
10610
+ e.preventDefault();
10611
+ const { from, to } = sourceRange(this.state);
10612
+ e.clipboardData.setData("text/plain", sourceText(this.state.doc).slice(from, to));
10613
+ if (cut && !this.readOnly) this.run((s) => insertSourceText(s, ""));
10614
+ return;
10615
+ }
10097
10616
  const range = this.blockRange();
10098
10617
  if (range) {
10099
10618
  if (!e.clipboardData) return;
@@ -10119,9 +10638,14 @@ var Editor = class {
10119
10638
  const data = e.clipboardData;
10120
10639
  if (!data) return;
10121
10640
  const text = data.getData("text/plain");
10122
- const html = data.getData("text/html");
10641
+ const rich = data.getData("text/html");
10642
+ const html = data.types.includes("vscode-editor-data") || isStyledText(rich) ? "" : rich;
10123
10643
  const plainOnly = this.plainPasteNext;
10124
10644
  this.plainPasteNext = false;
10645
+ if (this.modeValue === "source") {
10646
+ if (text) this.run((s) => insertSourceText(s, text.replace(/\r\n?/g, "\n")));
10647
+ return;
10648
+ }
10125
10649
  const range = this.blockRange();
10126
10650
  if (range) {
10127
10651
  const fragment2 = this.pastedBlocks(text, html, plainOnly);
@@ -10160,6 +10684,11 @@ var Editor = class {
10160
10684
  for (const ext of this.extensions) if (ext.handleDrop?.({ editor: this, event: e, position })) return;
10161
10685
  const text = e.dataTransfer?.getData("text/plain");
10162
10686
  if (!text || !position) return;
10687
+ if (this.modeValue === "source") {
10688
+ this.focus();
10689
+ this.run((s) => insertSourceAt(s, position.offset, text.replace(/\r\n?/g, "\n"), false, false));
10690
+ return;
10691
+ }
10163
10692
  const fragment = parseMarkdown(text, this.markdown).blocks;
10164
10693
  this.focus();
10165
10694
  this.run((s) => insertFragment(s, fragment, { at: position }));
@@ -10482,6 +11011,7 @@ var Editor = class {
10482
11011
  * or Markdown shortcuts.
10483
11012
  */
10484
11013
  hasBlockMenu(blockId) {
11014
+ if (this.modeValue === "source") return false;
10485
11015
  const block3 = this.state.doc.blocks.find((b) => b.id === blockId);
10486
11016
  return block3?.type === "table" || block3?.type === "code" || isCallout(block3) || !!block3 && isImageBlock(block3);
10487
11017
  }
@@ -10550,6 +11080,7 @@ var Editor = class {
10550
11080
  */
10551
11081
  openLinkPopover() {
10552
11082
  if (this.readOnly) return false;
11083
+ if (this.modeValue === "source") return false;
10553
11084
  const block3 = getBlock(this.state.doc, this.state.selection.focus.blockId);
10554
11085
  if (isPlainTextBlock(block3)) return false;
10555
11086
  if (isCollapsed(this.state.selection) && !activeLink(this.state)) return false;
@@ -10869,6 +11400,16 @@ function taskName(box, fallback) {
10869
11400
  const text = box.closest("[data-block-id]")?.querySelector(".mbe-content")?.textContent?.trim();
10870
11401
  return text || fallback;
10871
11402
  }
11403
+ function scrollBy(el, dy) {
11404
+ for (let node = el.parentElement; node; node = node.parentElement) {
11405
+ const overflow = getComputedStyle(node).overflowY;
11406
+ if ((overflow === "auto" || overflow === "scroll") && node.scrollHeight > node.clientHeight) {
11407
+ node.scrollTop += dy;
11408
+ return;
11409
+ }
11410
+ }
11411
+ el.ownerDocument.defaultView?.scrollBy(0, dy);
11412
+ }
10872
11413
 
10873
11414
  // src/extensions/math.ts
10874
11415
  var DOLLAR = 36;
@@ -10878,11 +11419,16 @@ function isWhitespace(ch) {
10878
11419
  function isDigit(ch) {
10879
11420
  return ch !== void 0 && ch >= "0" && ch <= "9";
10880
11421
  }
11422
+ function escaped(text, i) {
11423
+ let n = 0;
11424
+ while (text.charCodeAt(i - n - 1) === 92) n++;
11425
+ return n % 2 === 1;
11426
+ }
10881
11427
  var inline = {
10882
11428
  name: "math",
10883
11429
  triggers: "$",
10884
11430
  match(text, pos) {
10885
- if (text.charCodeAt(pos - 1) === DOLLAR) return -1;
11431
+ if (text.charCodeAt(pos - 1) === DOLLAR && !escaped(text, pos - 1)) return -1;
10886
11432
  let openEnd = pos;
10887
11433
  while (text.charCodeAt(openEnd) === DOLLAR) openEnd++;
10888
11434
  const size = openEnd - pos;
@@ -11037,60 +11583,117 @@ function textDecorator(options) {
11037
11583
  }
11038
11584
 
11039
11585
  // src/extensions/tags.ts
11040
- var reWordChar = /[\p{L}\p{M}\p{N}_]/u;
11041
- var reTagChar = /[\p{L}\p{M}\p{N}_\-\p{Extended_Pictographic}\p{Emoji_Modifier}‍️]/u;
11042
- var reTagStart = /[\p{L}\p{N}_\p{Extended_Pictographic}]/u;
11043
- var reTagNeeds = /[^\p{Nd}_\-/]/u;
11586
+ var reXidContinue = /\p{XID_Continue}/u;
11587
+ var reIgnorable = /\p{Default_Ignorable_Code_Point}/u;
11588
+ var reCombining = /[\p{Mn}\p{Mc}]/u;
11589
+ var TWITTER_CONTINUE = "\u3003\uFF5E\u301C\u05BE\u05F3\u05F4\u0F0B";
11590
+ var EMOJI_ELEMENT = String.raw`(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}|(?![\p{Regional_Indicator}\p{Emoji_Modifier}])\p{Emoji_Presentation}\uFE0F?|(?![#*0-9])\p{Emoji}\uFE0F|(?!\p{Emoji})(?=\P{Assigned})\p{Extended_Pictographic})`;
11591
+ var reEmoji = new RegExp(
11592
+ String.raw`[#*0-9]\uFE0F\u20E3|\p{Regional_Indicator}{2}|\u{1F3F4}[\u{E0020}-\u{E007E}]+\u{E007F}|${EMOJI_ELEMENT}(?:\u200D${EMOJI_ELEMENT})*`,
11593
+ "uy"
11594
+ );
11044
11595
  function charAt2(text, i) {
11045
11596
  return String.fromCodePoint(text.codePointAt(i));
11046
11597
  }
11047
- function charBefore2(text, i) {
11048
- if (i <= 0) return void 0;
11049
- const c = text.charCodeAt(i - 1);
11050
- return c >= 56320 && c <= 57343 && i > 1 ? text.slice(i - 2, i) : text[i - 1];
11598
+ function emojiAt(text, i, to) {
11599
+ reEmoji.lastIndex = i;
11600
+ const m = reEmoji.exec(text);
11601
+ return m && i + m[0].length <= to ? m[0].length : 0;
11051
11602
  }
11603
+ var isXid = (ch) => reXidContinue.test(ch) && !reIgnorable.test(ch);
11604
+ var isStarter = (ch) => ch === "-" || ch === "+" || ch === "&" || isXid(ch) && !reCombining.test(ch);
11605
+ var isContinuation = (ch) => ch === "-" || ch === "+" || ch === "&" || TWITTER_CONTINUE.includes(ch) || isXid(ch);
11052
11606
  function segmentEnd(text, i, to) {
11053
- if (i >= to || !reTagStart.test(charAt2(text, i))) return i;
11054
11607
  let j = i;
11055
- while (j < to) {
11608
+ for (; ; ) {
11609
+ if (j >= to) return -1;
11610
+ const emoji = emojiAt(text, j, to);
11611
+ if (emoji > 0) {
11612
+ j += emoji;
11613
+ break;
11614
+ }
11056
11615
  const ch = charAt2(text, j);
11057
- if (!reTagChar.test(ch) || j + ch.length > to) break;
11616
+ if (j + ch.length > to) return -1;
11617
+ if (reIgnorable.test(ch) || reXidContinue.test(ch) && reCombining.test(ch)) {
11618
+ j += ch.length;
11619
+ continue;
11620
+ }
11621
+ if (!isStarter(ch)) return -1;
11058
11622
  j += ch.length;
11623
+ break;
11624
+ }
11625
+ let afterXid = j > i && isXid(charBefore2(text, j));
11626
+ while (j < to) {
11627
+ const emoji = emojiAt(text, j, to);
11628
+ if (emoji > 0) {
11629
+ j += emoji;
11630
+ afterXid = false;
11631
+ continue;
11632
+ }
11633
+ const ch = charAt2(text, j);
11634
+ if (j + ch.length > to) break;
11635
+ if (reIgnorable.test(ch)) {
11636
+ j += ch.length;
11637
+ afterXid = false;
11638
+ } else if ((ch === "'" || ch === "\u2019") && afterXid && startsWord(text, j + 1, to)) {
11639
+ j += 1;
11640
+ afterXid = false;
11641
+ } else if (isContinuation(ch)) {
11642
+ j += ch.length;
11643
+ afterXid = isXid(ch);
11644
+ } else {
11645
+ break;
11646
+ }
11059
11647
  }
11060
11648
  return j;
11061
11649
  }
11650
+ function startsWord(text, i, to) {
11651
+ if (i >= to || emojiAt(text, i, to) > 0) return false;
11652
+ const ch = charAt2(text, i);
11653
+ return isXid(ch) && !reCombining.test(ch);
11654
+ }
11655
+ function charBefore2(text, i) {
11656
+ if (i <= 0) return void 0;
11657
+ const c = text.charCodeAt(i - 1);
11658
+ return c >= 56320 && c <= 57343 && i > 1 ? text.slice(i - 2, i) : text[i - 1];
11659
+ }
11062
11660
  function* scanTags(text, from = 0, to = text.length) {
11063
- for (let i = text.indexOf("#", from); i >= 0 && i < to; i = text.indexOf("#", i + 1)) {
11064
- const prev = charBefore2(text, i);
11065
- if (prev !== void 0 && (prev === "#" || reWordChar.test(prev))) continue;
11661
+ let i = from;
11662
+ while (i < to) {
11663
+ const emoji = emojiAt(text, i, to);
11664
+ if (emoji > 0) {
11665
+ i += emoji;
11666
+ continue;
11667
+ }
11668
+ if (text[i] !== "#") {
11669
+ i += charAt2(text, i).length;
11670
+ continue;
11671
+ }
11066
11672
  let end = segmentEnd(text, i + 1, to);
11067
- if (end === i + 1) continue;
11673
+ if (end < 0) {
11674
+ i++;
11675
+ continue;
11676
+ }
11068
11677
  while (text[end] === "/") {
11069
11678
  const next = segmentEnd(text, end + 1, to);
11070
- if (next === end + 1) break;
11679
+ if (next < 0) break;
11071
11680
  end = next;
11072
11681
  }
11073
- if (!reTagNeeds.test(text.slice(i + 1, end))) continue;
11074
11682
  yield { from: i, to: end };
11075
- i = end - 1;
11683
+ i = end;
11076
11684
  }
11077
11685
  }
11078
- var reMentionChar = /[\p{L}\p{M}\p{N}_.\-]/u;
11079
- var reMentionStart = /[\p{L}\p{N}_]/u;
11686
+ var reUsernameChar = /[A-Za-z0-9-]/;
11687
+ var reLatinAccent = /[\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u024f\u0253\u0254\u0256\u0257\u0259\u025b\u0263\u0268\u026f\u0272\u0289\u028b\u02bb\u0300-\u036f\u1e00-\u1eff]/;
11080
11688
  function* scanMentions(text, from = 0, to = text.length) {
11081
11689
  for (let i = text.indexOf("@", from); i >= 0 && i < to; i = text.indexOf("@", i + 1)) {
11082
- const prev = charBefore2(text, i);
11083
- if (prev !== void 0 && (reWordChar.test(prev) || /[.+\-@]/.test(prev))) continue;
11690
+ if (i > from && reUsernameChar.test(text[i - 1])) continue;
11084
11691
  let end = i + 1;
11085
- if (end >= to || !reMentionStart.test(charAt2(text, end))) continue;
11086
- while (end < to) {
11087
- const ch = charAt2(text, end);
11088
- if (!reMentionChar.test(ch) || end + ch.length > to) break;
11089
- end += ch.length;
11090
- }
11091
- while (end > i + 1 && (text[end - 1] === "." || text[end - 1] === "-")) end--;
11092
- yield { from: i, to: end };
11093
- i = end - 1;
11692
+ while (end < to && reUsernameChar.test(text[end])) end++;
11693
+ const name = text.slice(i + 1, end);
11694
+ const valid = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,34}[A-Za-z0-9])?$/.test(name) && !reLatinAccent.test(text[end] ?? "");
11695
+ if (valid) yield { from: i, to: end };
11696
+ if (end > i + 1) i = end - 1;
11094
11697
  }
11095
11698
  }
11096
11699
  function decorate2(scan, cls, attributes) {
@@ -11208,6 +11811,7 @@ export {
11208
11811
  isPlainTextBlock,
11209
11812
  isTextBlock,
11210
11813
  isTextless,
11814
+ keepQuoteStart,
11211
11815
  linkAt,
11212
11816
  listItem,
11213
11817
  loadMarkdown,
@@ -11226,6 +11830,7 @@ export {
11226
11830
  rangeHasMark,
11227
11831
  rawBlock,
11228
11832
  sameCell,
11833
+ sameLink,
11229
11834
  sameMarks,
11230
11835
  samePosition,
11231
11836
  sameQuote,