@usememos/editor 26.10.14 → 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
@@ -90,7 +90,8 @@ function listItem(listType, content = [], opts = {}) {
90
90
  checked: listType === "task" ? opts.checked ?? false : false,
91
91
  content: normalizeInline(content)
92
92
  };
93
- return listType === "ordered" && opts.start !== void 0 && opts.start !== 1 ? { ...block3, start: opts.start } : block3;
93
+ const numbered = listType === "ordered" && opts.start !== void 0 && opts.start !== 1 ? { ...block3, start: opts.start } : block3;
94
+ return opts.quote ? withQuote(numbered, opts.quote) : numbered;
94
95
  }
95
96
  function quote(content = [], id = createId(), callout) {
96
97
  const block3 = { id, type: "quote", content: normalizeInline(content) };
@@ -132,6 +133,31 @@ function detailsEnd(id = createId()) {
132
133
  function plain(text) {
133
134
  return text ? [{ text, marks: [] }] : [];
134
135
  }
136
+ function quoteKind(block3) {
137
+ if (block3?.type === "quote" || block3?.type === "listItem" && block3.quote) return block3.callout ?? "quote";
138
+ return null;
139
+ }
140
+ function sameQuote(a, b) {
141
+ const kind = quoteKind(a);
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 };
150
+ }
151
+ function withQuote(item, kind) {
152
+ const { quote: _quote, callout: _callout, quoteStart, ...rest } = item;
153
+ if (!kind) return rest;
154
+ if (quoteStart) return kind === "quote" ? { ...rest, quote: true, quoteStart } : { ...rest, quote: true, callout: kind, quoteStart };
155
+ return kind === "quote" ? { ...rest, quote: true } : { ...rest, quote: true, callout: kind };
156
+ }
157
+ function unquote(block3) {
158
+ if (block3.type === "quote") return paragraph(block3.content, block3.id);
159
+ return block3.type === "listItem" && block3.quote ? withQuote(block3, null) : block3;
160
+ }
135
161
  function isTextBlock(block3) {
136
162
  return block3.type !== "table" && block3.type !== "divider" && block3.type !== "detailsEnd";
137
163
  }
@@ -193,7 +219,10 @@ function sameMarks(a, b) {
193
219
  return a.length === b.length && a.every((m, i) => m === b[i]);
194
220
  }
195
221
  function sameFormat(a, b) {
196
- 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;
197
226
  }
198
227
  function inlineText(inline3) {
199
228
  return inline3.map((s) => s.text).join("");
@@ -248,13 +277,17 @@ function formatAt(inline3, offset) {
248
277
  const marks = marksAt(inline3, offset);
249
278
  const before = offset > 0 ? spanAt(inline3, offset - 1) : void 0;
250
279
  const after = spanAt(inline3, offset);
251
- const link = before?.link && before.link === after?.link ? before.link : void 0;
280
+ const link = before?.link && sameLink(before, after) ? before : void 0;
252
281
  const token = before?.token && before.token === after?.token ? before.token : void 0;
253
- const format = link ? { marks, link } : { marks };
282
+ const format = link ? { marks, ...linkOf(link) } : { marks };
254
283
  return token ? { ...format, token } : format;
255
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
+ }
256
289
  function insertInline(inline3, offset, text, format) {
257
- let span = format.link ? { text, marks: format.marks, link: format.link } : { text, marks: format.marks };
290
+ let span = { text, marks: format.marks, ...linkOf(format) };
258
291
  if (format.token) span = { ...span, token: format.token };
259
292
  return concatInline(sliceInline(inline3, 0, offset), [span], sliceInline(inline3, offset));
260
293
  }
@@ -276,10 +309,12 @@ function setTokenInRange(inline3, from, to, token) {
276
309
  return concatInline(sliceInline(inline3, 0, from), middle, sliceInline(inline3, to));
277
310
  }
278
311
  function setLinkInRange(inline3, from, to, href) {
279
- 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) => {
280
315
  if (s.image) return s;
281
- const { link: _old, ...rest } = s;
282
- return href ? { ...rest, link: href } : rest;
316
+ const { link: _old, linkTitle: _title, ...rest } = s;
317
+ return href ? { ...rest, ...linkOf({ link: href, linkTitle: title }) } : rest;
283
318
  });
284
319
  return concatInline(sliceInline(inline3, 0, from), middle, sliceInline(inline3, to));
285
320
  }
@@ -302,7 +337,7 @@ function linkAt(inline3, offset) {
302
337
  const runs = [];
303
338
  for (const s of inline3) {
304
339
  const end = pos + s.text.length;
305
- if (s.link === href) {
340
+ if (sameLink(s, span)) {
306
341
  const last = runs[runs.length - 1];
307
342
  if (last && last.to === pos) last.to = end;
308
343
  else runs.push({ from: pos, to: end });
@@ -356,13 +391,13 @@ function endOf(block3) {
356
391
  return { blockId: block3.id, offset: inlineLength(block3.content) };
357
392
  }
358
393
  function clampSelection(doc, sel) {
359
- const clamp = (p) => {
394
+ const clamp2 = (p) => {
360
395
  const block3 = doc.blocks.find((b) => b.id === p.blockId);
361
396
  if (!block3) return startOf(doc.blocks[0]);
362
397
  const content = containerContent(block3, p.cell);
363
398
  return { ...p, offset: Math.min(p.offset, content ? inlineLength(content) : 0) };
364
399
  };
365
- return { anchor: clamp(sel.anchor), focus: clamp(sel.focus) };
400
+ return { anchor: clamp2(sel.anchor), focus: clamp2(sel.focus) };
366
401
  }
367
402
  function createState(doc) {
368
403
  const blocks = doc.blocks.length > 0 ? doc.blocks : [paragraph()];
@@ -372,78 +407,99 @@ function createState(doc) {
372
407
  }
373
408
 
374
409
  // src/markdown/autolink.ts
375
- var reDomain = /(?:[\p{L}\p{N}_-]+)(?:\.[\p{L}\p{N}_-]+)*/uy;
376
- var reWww = /www\./iy;
377
410
  var reScheme = /(?:https?|ftp):\/\//iy;
378
- var reEmail = /[A-Za-z0-9._+-]+@[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)+/g;
379
- var TRAILING = "?!.,:*_~";
380
- function isLiteralBoundary(prev) {
381
- 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);
382
416
  }
383
417
  function domainEnd(text, pos, requirePeriod) {
384
- reDomain.lastIndex = pos;
385
- const m = reDomain.exec(text);
386
- if (!m) return -1;
387
- const domain = m[0].replace(/_+$/, "");
388
- const segments = domain.split(".");
389
- if (segments.some((s) => s === "")) return -1;
390
- if (requirePeriod && segments.length < 2) return -1;
391
- if (segments.slice(-2).some((s) => s.includes("_"))) return -1;
392
- 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;
393
435
  }
394
436
  function trimEnd(text, start, end) {
395
- 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) {
396
444
  const ch = text[end - 1];
397
445
  if (TRAILING.includes(ch)) {
398
446
  end--;
399
447
  } else if (ch === ")") {
400
- let open = 0;
401
- let close = 0;
402
- for (let i = start; i < end; i++) {
403
- if (text[i] === "(") open++;
404
- else if (text[i] === ")") close++;
405
- }
406
448
  if (close <= open) return end;
449
+ close--;
407
450
  end--;
408
451
  } else if (ch === ";") {
409
452
  let i = end - 2;
410
- while (i >= start && /[A-Za-z0-9]/.test(text[i])) i--;
411
- 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;
412
455
  } else {
413
456
  return end;
414
457
  }
415
- if (end <= start) return end;
416
458
  }
459
+ return end;
417
460
  }
418
461
  function urlLiteralAt(text, pos) {
419
- let afterPrefix;
420
- let www = false;
421
- reWww.lastIndex = pos;
422
- if (reWww.test(text)) {
423
- afterPrefix = pos;
424
- www = true;
462
+ let domainStart;
463
+ const www = text.slice(pos, pos + 4).toLowerCase() === "www.";
464
+ if (www) {
465
+ domainStart = pos;
425
466
  } else {
426
467
  reScheme.lastIndex = pos;
427
468
  if (!reScheme.test(text)) return null;
428
- afterPrefix = reScheme.lastIndex;
469
+ domainStart = reScheme.lastIndex;
470
+ if (!/[\p{L}\p{N}]/u.test(text[domainStart] ?? "")) return null;
429
471
  }
430
- const domain = domainEnd(text, afterPrefix, true);
472
+ const domain = domainEnd(text, domainStart, www);
431
473
  if (domain < 0) return null;
432
474
  let end = domain;
433
- while (end < text.length && !/[\s<]/.test(text[end])) end++;
475
+ while (end < text.length && !/[ \t\n\r<]/.test(text[end])) end++;
434
476
  end = trimEnd(text, pos, end);
435
- if (end < domain || end <= afterPrefix) return null;
477
+ if (end <= domainStart) return null;
436
478
  const literal = text.slice(pos, end);
437
479
  return { end, href: www ? "http://" + literal : literal };
438
480
  }
439
481
  function emailLiterals(text) {
440
- if (!text.includes("@")) return [];
441
482
  const out = [];
442
- reEmail.lastIndex = 0;
443
- for (const m of text.matchAll(reEmail)) {
444
- const last = m[0][m[0].length - 1];
445
- if (last === "-" || last === "_") continue;
446
- 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;
447
503
  }
448
504
  return out;
449
505
  }
@@ -532,7 +588,7 @@ function contentOf(block3, cell) {
532
588
  function emptyLike(block3) {
533
589
  switch (block3.type) {
534
590
  case "listItem":
535
- return listItem(block3.listType, [], { indent: block3.indent });
591
+ return listItem(block3.listType, [], { indent: block3.indent, quote: quoteKind(block3) });
536
592
  case "quote":
537
593
  return quote([], void 0, block3.callout);
538
594
  default:
@@ -627,6 +683,7 @@ function deleteBackward(state) {
627
683
  return { ...state, selection: caret(block3.id, inlineLength(contentOf(block3, prevCell)), prevCell) };
628
684
  }
629
685
  if (block3.type === "listItem" && block3.indent > 0) return replaceBlock(state, { ...block3, indent: block3.indent - 1 });
686
+ if (block3.type === "listItem" && block3.quote) return replaceBlock(state, keepQuoteStart(block3, quote(block3.content, block3.id, block3.callout)));
630
687
  if (block3.type !== "paragraph") return replaceBlock(state, paragraph(block3.content, block3.id));
631
688
  const prev = state.doc.blocks[index - 1];
632
689
  if (!prev) return state;
@@ -760,7 +817,7 @@ function splitBlock(state) {
760
817
  return replaceBlock(s, code, caret(code.id, 0));
761
818
  }
762
819
  if (length === 0 && block3.type === "listItem") {
763
- const next = block3.indent > 0 ? { ...block3, indent: block3.indent - 1 } : 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);
764
821
  return replaceBlock(s, next);
765
822
  }
766
823
  if (length === 0 && block3.type === "quote") return replaceBlock(s, paragraph([], block3.id));
@@ -771,6 +828,10 @@ function splitBlock(state) {
771
828
  return withBlocks(s, blocks, s.selection);
772
829
  }
773
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
+ }
774
835
  return withBlocks(s, splice(s, index, 0, emptyLike(block3)), s.selection);
775
836
  }
776
837
  const left = withContent(block3, sliceInline(block3.content, 0, pos.offset));
@@ -893,7 +954,7 @@ function keepIfSame(before, after) {
893
954
  for (let i = 0; i < before.length; i++) {
894
955
  const x = before[i];
895
956
  const y = after[i];
896
- 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;
897
958
  }
898
959
  return before;
899
960
  }
@@ -1000,6 +1061,9 @@ function updateImage(state, pos, change) {
1000
1061
  return replaceBlock(state, withContainerContent(block3, pos.cell, next), selected);
1001
1062
  }
1002
1063
  function convert(block3, spec) {
1064
+ return keepQuoteStart(block3, convertType(block3, spec));
1065
+ }
1066
+ function convertType(block3, spec) {
1003
1067
  const content = block3.content;
1004
1068
  switch (spec.type) {
1005
1069
  case "paragraph":
@@ -1010,9 +1074,12 @@ function convert(block3, spec) {
1010
1074
  return listItem(spec.listType, content, {
1011
1075
  id: block3.id,
1012
1076
  indent: block3.type === "listItem" ? block3.indent : 0,
1013
- checked: block3.type === "listItem" ? block3.checked : false
1077
+ checked: block3.type === "listItem" ? block3.checked : false,
1078
+ start: block3.type === "listItem" && block3.listType === spec.listType ? block3.start : void 0,
1079
+ quote: quoteKind(block3)
1014
1080
  });
1015
1081
  case "quote":
1082
+ if (block3.type === "listItem") return withQuote(block3, spec.callout ?? (block3.quote ? block3.callout ?? "quote" : "quote"));
1016
1083
  return quote(content, block3.id, spec.callout);
1017
1084
  case "code":
1018
1085
  return codeBlock(spec.language ?? (block3.type === "code" ? block3.language : ""), inlineText(toPlain(content)), block3.id);
@@ -1025,12 +1092,15 @@ function isConvertible(block3) {
1025
1092
  }
1026
1093
  function setBlockType(state, spec) {
1027
1094
  if (spec.type === "table" || spec.type === "divider" || spec.type === "details") return insertBlock(state, spec);
1095
+ return convertSelected(state, spec, (b) => convert(b, spec));
1096
+ }
1097
+ function convertSelected(state, spec, convertBlock) {
1028
1098
  const { from, to } = orderedRange(state.doc, state.selection);
1029
1099
  const start = blockIndex(state.doc, from.blockId);
1030
1100
  const end = blockIndex(state.doc, to.blockId);
1031
1101
  const range = state.doc.blocks.slice(start, end + 1);
1032
1102
  if (spec.type === "code" && range.filter(isConvertible).length > 1) return mergeIntoCode(state, start, range, spec.language);
1033
- const updated = range.map((b) => isConvertible(b) ? convert(b, spec) : b);
1103
+ const updated = range.map((b) => isConvertible(b) ? convertBlock(b) : b);
1034
1104
  const doc = { blocks: splice(state, start, updated.length, ...updated) };
1035
1105
  return { doc, selection: clampSelection(doc, state.selection), storedMarks: null };
1036
1106
  }
@@ -1062,20 +1132,21 @@ function quoteRun(state, blockId) {
1062
1132
  const blocks = state.doc.blocks;
1063
1133
  const index = blockIndex(state.doc, blockId);
1064
1134
  const block3 = blocks[index];
1065
- if (block3?.type !== "quote") return null;
1066
- const same = (b) => b?.type === "quote" && b.callout === block3.callout;
1135
+ if (quoteKind(block3) === null) return null;
1067
1136
  let start = index;
1068
1137
  let end = index;
1069
- while (same(blocks[start - 1])) start--;
1070
- while (same(blocks[end + 1])) end++;
1138
+ while (sameQuote(blocks[start - 1], blocks[start])) start--;
1139
+ while (sameQuote(blocks[end], blocks[end + 1])) end++;
1071
1140
  return { start, end };
1072
1141
  }
1073
1142
  function setCallout(state, blockId, callout) {
1074
1143
  const run = quoteRun(state, blockId);
1075
1144
  if (!run) return state;
1076
1145
  const blocks = state.doc.blocks.slice(run.start, run.end + 1);
1077
- if (blocks.every((b) => (b.callout ?? null) === callout)) return state;
1078
- const updated = blocks.map((b) => quote(b.content, b.id, callout ?? void 0));
1146
+ if (blocks.every((b) => quoteKind(b) === (callout ?? "quote"))) return state;
1147
+ const updated = blocks.map(
1148
+ (b) => b.type === "listItem" ? withQuote(b, callout ?? "quote") : b.type === "quote" ? keepQuoteStart(b, quote(b.content, b.id, callout ?? void 0)) : b
1149
+ );
1079
1150
  const doc = { blocks: splice(state, run.start, updated.length, ...updated) };
1080
1151
  return { doc, selection: state.selection, storedMarks: state.storedMarks };
1081
1152
  }
@@ -1091,8 +1162,10 @@ function hasType(block3, spec) {
1091
1162
  return block3.type === "listItem" && block3.listType === spec.listType;
1092
1163
  case "code":
1093
1164
  return block3.type === "code";
1094
- case "quote":
1095
- return block3.type === "quote" && (!spec.callout || block3.callout === spec.callout);
1165
+ case "quote": {
1166
+ const kind = quoteKind(block3);
1167
+ return kind !== null && (!spec.callout || kind === spec.callout);
1168
+ }
1096
1169
  default:
1097
1170
  return block3.type === spec.type;
1098
1171
  }
@@ -1101,7 +1174,13 @@ function toggleBlockType(state, spec) {
1101
1174
  const text = convertibleBlocks(state);
1102
1175
  if (text.length === 0) return state;
1103
1176
  const on = text.every((b) => hasType(b, spec));
1104
- return setBlockType(state, on ? { type: "paragraph" } : spec);
1177
+ if (!on) return setBlockType(state, spec);
1178
+ const off = { type: "paragraph" };
1179
+ return convertSelected(state, off, (b) => {
1180
+ if (b.type === "listItem" && spec.type === "quote") return withQuote(b, null);
1181
+ if (b.type === "listItem" && b.quote && spec.type === "listItem") return keepQuoteStart(b, quote(b.content, b.id, b.callout));
1182
+ return convert(b, off);
1183
+ });
1105
1184
  }
1106
1185
  function insertBlock(state, spec) {
1107
1186
  const pos = state.selection.focus;
@@ -1144,8 +1223,7 @@ function indentListItems(state, delta2) {
1144
1223
  for (let i = start; i <= end; i++) {
1145
1224
  const b = blocks[i];
1146
1225
  if (b.type !== "listItem") continue;
1147
- const prev = blocks[i - 1];
1148
- const max = prev?.type === "listItem" ? Math.min(MAX_INDENT, prev.indent + 1) : 0;
1226
+ const max = maxIndent(blocks[i - 1], b);
1149
1227
  const indent = Math.max(0, Math.min(max, b.indent + delta2));
1150
1228
  if (indent !== b.indent) {
1151
1229
  blocks[i] = { ...b, indent };
@@ -1217,12 +1295,14 @@ function deleteBlock(state, blockId) {
1217
1295
  function spanBlocks(blocks, range) {
1218
1296
  return { anchor: startOf(blocks[range.from]), focus: endOf(blocks[range.to]) };
1219
1297
  }
1298
+ function maxIndent(prev, item) {
1299
+ return prev?.type === "listItem" && quoteKind(prev) === quoteKind(item) ? Math.min(MAX_INDENT, prev.indent + 1) : 0;
1300
+ }
1220
1301
  function fitIndents(blocks, index) {
1221
1302
  for (let i = Math.max(0, index); i < blocks.length; i++) {
1222
1303
  const block3 = blocks[i];
1223
1304
  if (block3.type !== "listItem") return;
1224
- const prev = blocks[i - 1];
1225
- const max = prev?.type === "listItem" ? Math.min(MAX_INDENT, prev.indent + 1) : 0;
1305
+ const max = maxIndent(blocks[i - 1], block3);
1226
1306
  if (block3.indent <= max) return;
1227
1307
  blocks[i] = { ...block3, indent: max };
1228
1308
  }
@@ -1357,7 +1437,7 @@ function applyBlockInputRules(state, dialect = {}) {
1357
1437
  const spec = toSpec(m);
1358
1438
  if (spec.type === "quote" && spec.callout && dialect.callouts === false || spec.type === "details" && dialect.details === false) continue;
1359
1439
  if (block3.type === "listItem" && !(spec.type === "listItem" && spec.listType === "task")) continue;
1360
- if (block3.type === "quote") {
1440
+ if (block3.type === "quote" && spec.type !== "listItem") {
1361
1441
  if (spec.type !== "quote" || !spec.callout) continue;
1362
1442
  return setCallout(deleteRange(state, { blockId: block3.id, offset: 0 }, pos), block3.id, spec.callout);
1363
1443
  }
@@ -1371,9 +1451,10 @@ function applyBlockInputRules(state, dialect = {}) {
1371
1451
  id: converted.id,
1372
1452
  indent: converted.indent,
1373
1453
  checked,
1374
- start: converted.listType === "ordered" && start ? Number(start[1]) : void 0
1454
+ start: converted.listType === "ordered" && start ? Number(start[1]) : void 0,
1455
+ quote: quoteKind(converted)
1375
1456
  });
1376
- next = replaceBlock(next, updated, next.selection);
1457
+ next = replaceBlock(next, keepQuoteStart(converted, updated), next.selection);
1377
1458
  }
1378
1459
  return next;
1379
1460
  }
@@ -1469,10 +1550,8 @@ function clampListIndents(state, before) {
1469
1550
  let blocks = null;
1470
1551
  let max = 0;
1471
1552
  state.doc.blocks.forEach((block3, i) => {
1472
- if (block3.type !== "listItem") {
1473
- max = 0;
1474
- return;
1475
- }
1553
+ if (block3.type !== "listItem" || quoteKind(block3) !== quoteKind(state.doc.blocks[i - 1])) max = 0;
1554
+ if (block3.type !== "listItem") return;
1476
1555
  if (block3.indent > max) (blocks ??= [...state.doc.blocks])[i] = { ...block3, indent: max };
1477
1556
  max = Math.min(block3.indent, max) + 1;
1478
1557
  });
@@ -1511,7 +1590,7 @@ function applyAutolinkInputRule(state) {
1511
1590
  const word = text.slice(start, end);
1512
1591
  let found = null;
1513
1592
  for (const m of word.matchAll(/www\.|(?:https?|ftp):\/\//gi)) {
1514
- 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;
1515
1594
  const url = urlLiteralAt(word, m.index);
1516
1595
  if (url) {
1517
1596
  found = { from: start + m.index, to: start + url.end, href: url.href };
@@ -1645,6 +1724,10 @@ function insertAsBlocks(state, fragment, target) {
1645
1724
  const head = withContent(block3, sliceInline(block3.content, 0, target.offset));
1646
1725
  let tail = { ...withContent(block3, sliceInline(block3.content, target.offset)), id: createId() };
1647
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
+ }
1648
1731
  return end(splice(state, index, 1, head, ...fragment, tail), last, startOf(tail));
1649
1732
  }
1650
1733
 
@@ -1655,18 +1738,16 @@ function docToHtml(doc) {
1655
1738
  let i = 0;
1656
1739
  while (i < blocks.length) {
1657
1740
  const block3 = blocks[i];
1658
- if (block3.type === "listItem") {
1659
- let j = i;
1660
- while (j < blocks.length && blocks[j].type === "listItem") j++;
1661
- out += listHtml(blocks.slice(i, j));
1741
+ const kind = quoteKind(block3);
1742
+ if (kind) {
1743
+ let j = i + 1;
1744
+ while (j < blocks.length && sameQuote(block3, blocks[j])) j++;
1745
+ out += quoteHtml(kind === "quote" ? void 0 : kind, docToHtml({ blocks: blocks.slice(i, j).map(unquote) }));
1662
1746
  i = j;
1663
- } else if (block3.type === "quote") {
1747
+ } else if (block3.type === "listItem") {
1664
1748
  let j = i;
1665
- let inner = "";
1666
- for (let next = blocks[j]; next?.type === "quote" && next.callout === block3.callout; next = blocks[++j]) {
1667
- inner += `<p>${inlineHtml(next.content)}</p>`;
1668
- }
1669
- out += quoteHtml(block3.callout, inner);
1749
+ while (j < blocks.length && blocks[j].type === "listItem" && quoteKind(blocks[j]) === null) j++;
1750
+ out += listHtml(blocks.slice(i, j));
1670
1751
  i = j;
1671
1752
  } else {
1672
1753
  out += blockHtml(block3);
@@ -1709,9 +1790,8 @@ function blockHtml(block3) {
1709
1790
  return html + "</table>";
1710
1791
  }
1711
1792
  case "listItem":
1712
- return listHtml([block3]);
1713
1793
  case "quote":
1714
- return quoteHtml(block3.callout, `<p>${inlineHtml(block3.content)}</p>`);
1794
+ return docToHtml({ blocks: [block3] });
1715
1795
  }
1716
1796
  }
1717
1797
  function quoteHtml(callout, inner) {
@@ -1756,11 +1836,12 @@ function inlineHtml(inline3) {
1756
1836
  let out = "";
1757
1837
  let i = 0;
1758
1838
  while (i < inline3.length) {
1759
- const link = inline3[i].link;
1839
+ const { link, linkTitle: linkTitle2 } = inline3[i];
1760
1840
  let j = i;
1761
1841
  let inner = "";
1762
- while (j < inline3.length && inline3[j].link === link) inner += spanHtml(inline3[j++]);
1763
- 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>`;
1764
1845
  i = j;
1765
1846
  }
1766
1847
  return out;
@@ -1793,6 +1874,15 @@ function htmlToDoc(html, parser) {
1793
1874
  converter.blocks(dom.body, ROOT_FORMAT);
1794
1875
  return { blocks: converter.finish() };
1795
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
+ }
1796
1886
  var ELEMENT_NODE = 1;
1797
1887
  var TEXT_NODE = 3;
1798
1888
  var SKIPPED = /* @__PURE__ */ new Set([
@@ -2158,6 +2248,7 @@ var Converter = class _Converter {
2158
2248
  const inner = new _Converter();
2159
2249
  inner.blocks(el, format, callout ? (child) => hasClass(child, "markdown-alert-title") : void 0);
2160
2250
  const blocks = inner.finish();
2251
+ const start = this.out.length;
2161
2252
  for (const block3 of blocks) {
2162
2253
  switch (block3.type) {
2163
2254
  case "paragraph":
@@ -2167,15 +2258,17 @@ var Converter = class _Converter {
2167
2258
  case "raw":
2168
2259
  this.out.push(quote(block3.content, void 0, callout));
2169
2260
  break;
2170
- case "listItem": {
2171
- const marker = block3.listType === "ordered" ? "1. " : block3.listType === "task" ? block3.checked ? "- [x] " : "- [ ] " : "- ";
2172
- this.out.push(quote([...plain(marker), ...block3.content], void 0, callout));
2261
+ case "listItem":
2262
+ this.out.push(withQuote(block3, callout ?? "quote"));
2173
2263
  break;
2174
- }
2175
2264
  default:
2176
2265
  this.out.push(block3);
2177
2266
  }
2178
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
+ }
2179
2272
  }
2180
2273
  table(el, format) {
2181
2274
  const rows = Array.from(el.querySelectorAll("tr")).filter((tr) => tr.closest("table") === el);
@@ -2248,6 +2341,10 @@ function alignOf(cell) {
2248
2341
  var GROUP_MS = 1e3;
2249
2342
  var LIMIT = 500;
2250
2343
  var History = class {
2344
+ /** `source` reads the source current when an entry is recorded. */
2345
+ constructor(source) {
2346
+ this.source = source;
2347
+ }
2251
2348
  undoStack = [];
2252
2349
  redoStack = [];
2253
2350
  lastKind = null;
@@ -2256,7 +2353,7 @@ var History = class {
2256
2353
  record(before, kind, now = Date.now()) {
2257
2354
  const extendsGroup = kind === "typing" && this.lastKind === "typing" && now - this.lastTime < GROUP_MS;
2258
2355
  if (!extendsGroup) {
2259
- this.undoStack.push({ doc: before.doc, selection: before.selection });
2356
+ this.undoStack.push({ doc: before.doc, selection: before.selection, source: this.source() });
2260
2357
  if (this.undoStack.length > LIMIT) this.undoStack.shift();
2261
2358
  }
2262
2359
  this.redoStack = [];
@@ -2282,9 +2379,9 @@ var History = class {
2282
2379
  step(current, from, to) {
2283
2380
  const entry = from.pop();
2284
2381
  if (!entry) return null;
2285
- to.push({ doc: current.doc, selection: current.selection });
2382
+ to.push({ doc: current.doc, selection: current.selection, source: this.source() });
2286
2383
  this.lastKind = null;
2287
- return { doc: entry.doc, selection: entry.selection, storedMarks: null };
2384
+ return { state: { doc: entry.doc, selection: entry.selection, storedMarks: null }, source: entry.source };
2288
2385
  }
2289
2386
  };
2290
2387
 
@@ -2614,16 +2711,23 @@ function resolveMarkdown(options) {
2614
2711
  }
2615
2712
 
2616
2713
  // src/markdown/lower.ts
2617
- function lowerTopLevel(node, options, source) {
2618
- if (!fitsModel(node, 0)) return [rawBlock("markdown", source)];
2714
+ function lowerTopLevel(node, options, source, before) {
2715
+ return lowerIfFits(node, options, before) ?? [rawBlock("markdown", source)];
2716
+ }
2717
+ function lowerIfFits(node, options, before) {
2718
+ if (!fitsModel(node, 0)) return null;
2619
2719
  const blocks = [];
2620
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
+ }
2621
2725
  return blocks;
2622
2726
  }
2623
2727
  function fitsModel(node, depth) {
2624
2728
  switch (node.type) {
2625
2729
  case "blockQuote":
2626
- return node.children.every((child) => child.type === "paragraph");
2730
+ return node.children.every((child) => child.type === "paragraph" || child.type === "list" && fitsModel(child, 0));
2627
2731
  case "list":
2628
2732
  return depth <= MAX_INDENT && node.items.every(
2629
2733
  (item) => item.children.every(
@@ -2636,12 +2740,12 @@ function fitsModel(node, depth) {
2636
2740
  }
2637
2741
  function lowerInlines(nodes, options = DEFAULT_MARKDOWN) {
2638
2742
  const out = [];
2639
- lowerInto(nodes, [], void 0, out, options.breaks ? "\n" : " ");
2743
+ lowerInto(nodes, [], {}, out, options.breaks ? "\n" : " ");
2640
2744
  return normalizeInline(out);
2641
2745
  }
2642
2746
  var NESTED_MARK = { emphasis: "italic", strong: "bold", strike: "strike" };
2643
2747
  function lowerInto(nodes, marks, link, out, soft) {
2644
- const push = (span) => out.push(link === void 0 ? span : { ...span, link });
2748
+ const push = (span) => out.push(link.link === void 0 ? span : { ...span, ...link });
2645
2749
  for (const node of nodes) {
2646
2750
  switch (node.type) {
2647
2751
  case "text":
@@ -2666,7 +2770,7 @@ function lowerInto(nodes, marks, link, out, soft) {
2666
2770
  lowerInto(node.children, withMark(marks, NESTED_MARK[node.type]), link, out, soft);
2667
2771
  break;
2668
2772
  case "link":
2669
- 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);
2670
2774
  break;
2671
2775
  case "image":
2672
2776
  push({ text: ATOM_CHAR, marks, image: imageAtom(node) });
@@ -2699,7 +2803,7 @@ function lowerBlock(node, out, o) {
2699
2803
  case "paragraph": {
2700
2804
  const content = lowerInlines(node.children, o);
2701
2805
  if (isEmptyLine(content)) out.push(paragraph());
2702
- else if (content.length > 0) out.push(paragraph(content));
2806
+ else if (content.length > 0 || node.children.length > 0) out.push(paragraph(content));
2703
2807
  break;
2704
2808
  }
2705
2809
  case "heading":
@@ -2735,7 +2839,7 @@ function listTypeOf(list, item) {
2735
2839
  if (item.task) return "task";
2736
2840
  return list.ordered ? "ordered" : "bullet";
2737
2841
  }
2738
- function lowerList(list, depth, out, o) {
2842
+ function lowerList(list, depth, out, o, quoted) {
2739
2843
  list.items.forEach((item, index) => {
2740
2844
  const first = item.children[0];
2741
2845
  const listType = listTypeOf(list, item);
@@ -2743,10 +2847,11 @@ function lowerList(list, depth, out, o) {
2743
2847
  listItem(listType, first?.type === "paragraph" ? lowerInlines(first.children, o) : [], {
2744
2848
  indent: Math.min(depth, MAX_INDENT),
2745
2849
  checked: item.checked,
2746
- start: index === 0 && listType === "ordered" ? list.start : void 0
2850
+ start: index === 0 && listType === "ordered" ? list.start : void 0,
2851
+ quote: quoted
2747
2852
  })
2748
2853
  );
2749
- for (const child of item.children) if (child.type === "list") lowerList(child, depth + 1, out, o);
2854
+ for (const child of item.children) if (child.type === "list") lowerList(child, depth + 1, out, o, quoted);
2750
2855
  });
2751
2856
  }
2752
2857
  function lowerQuote(children, out, o) {
@@ -2754,10 +2859,12 @@ function lowerQuote(children, out, o) {
2754
2859
  const callout = alert?.type;
2755
2860
  const start = out.length;
2756
2861
  children.forEach((child, i) => {
2862
+ if (child.type === "list") lowerList(child, 0, out, o, callout ?? "quote");
2757
2863
  if (child.type !== "paragraph") return;
2758
- 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);
2759
2866
  if (isEmptyLine(content)) out.push(quote([], void 0, callout));
2760
- 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));
2761
2868
  });
2762
2869
  if (callout && out.length === start) out.push(quote([], void 0, callout));
2763
2870
  }
@@ -2949,7 +3056,7 @@ var Node2 = class {
2949
3056
  var MAX_INLINE_NESTING = 100;
2950
3057
  function innerDepth(from, to) {
2951
3058
  let depth = 0;
2952
- 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;
2953
3060
  return depth;
2954
3061
  }
2955
3062
  function escapedText(value) {
@@ -3033,6 +3140,8 @@ var InlineParser = class {
3033
3140
  backticksAfter = /* @__PURE__ */ new Map();
3034
3141
  /** Per opening quote character, a position from which no link title can close. */
3035
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();
3036
3145
  /** Inline syntax extensions by trigger character code. */
3037
3146
  triggers = /* @__PURE__ */ new Map();
3038
3147
  /** A run of characters that cannot start any construct, including extension triggers. */
@@ -3120,7 +3229,7 @@ var InlineParser = class {
3120
3229
  const reCandidate = /www\.|(?:https?|ftp):\/\//gi;
3121
3230
  for (const c of m[0].matchAll(reCandidate)) {
3122
3231
  const at = start + c.index;
3123
- if (!isLiteralBoundary(this.subject[at - 1])) continue;
3232
+ if (!isLiteralBoundary(this.subject[at - 1], c[0].toLowerCase() === "www.")) continue;
3124
3233
  const url = urlLiteralAt(this.subject, at);
3125
3234
  if (!url) continue;
3126
3235
  if (at > start) block3.append(new Node2("text", this.subject.slice(start, at)));
@@ -3225,11 +3334,30 @@ var InlineParser = class {
3225
3334
  return false;
3226
3335
  }
3227
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
+ }
3228
3348
  const m = this.match(reHtmlTag);
3229
3349
  if (!m) return false;
3230
3350
  block3.append(new Node2("html", m[0]));
3231
3351
  return true;
3232
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
+ }
3233
3361
  parseEntity(block3) {
3234
3362
  const start = this.pos;
3235
3363
  const m = this.match(reEntityHere);
@@ -3257,14 +3385,16 @@ var InlineParser = class {
3257
3385
  const beforePunct = isUnicodePunctuation(before);
3258
3386
  const leftFlanking = !afterWs && (!afterPunct || beforeWs || beforePunct);
3259
3387
  const rightFlanking = !beforeWs && (!beforePunct || afterWs || afterPunct);
3260
- let canOpen;
3261
- 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
+ }
3262
3394
  if (cc === C_UNDERSCORE) {
3263
- canOpen = leftFlanking && (!rightFlanking || beforePunct);
3264
- canClose = rightFlanking && (!leftFlanking || afterPunct);
3265
- } else {
3266
- canOpen = leftFlanking;
3267
- canClose = rightFlanking;
3395
+ const open = canOpen;
3396
+ canOpen = open && (beforeWs || beforePunct || !canClose);
3397
+ canClose = canClose && (afterWs || afterPunct || !open);
3268
3398
  }
3269
3399
  if (cc === C_TILDE && count > 2) canOpen = canClose = false;
3270
3400
  const node = new Node2("text", this.subject.slice(start, this.pos));
@@ -3331,7 +3461,9 @@ var InlineParser = class {
3331
3461
  opener.count -= use;
3332
3462
  closer.count -= use;
3333
3463
  const literal = innerDepth(openerNode, closerNode) >= MAX_INLINE_NESTING;
3334
- if (!literal) {
3464
+ if (literal) {
3465
+ openerNode.depth = closerNode.depth = MAX_INLINE_NESTING;
3466
+ } else {
3335
3467
  openerNode.value = openerNode.value.slice(0, openerNode.value.length - use);
3336
3468
  closerNode.value = closerNode.value.slice(0, closerNode.value.length - use);
3337
3469
  const wrapper = new Node2(type);
@@ -3552,19 +3684,16 @@ var InlineParser = class {
3552
3684
  this.spnl();
3553
3685
  let title = null;
3554
3686
  if (this.pos !== beforeTitle) title = this.parseLinkTitle();
3555
- if (title === null) {
3556
- title = "";
3557
- this.pos = beforeTitle;
3558
- }
3687
+ if (title === null) this.pos = beforeTitle;
3559
3688
  if (!this.match(reSpaceAtEndOfLine)) {
3560
- if (title === "") return 0;
3561
- title = "";
3689
+ if (title === null) return 0;
3690
+ title = null;
3562
3691
  this.pos = beforeTitle;
3563
3692
  if (!this.match(reSpaceAtEndOfLine)) return 0;
3564
3693
  }
3565
3694
  const label = normalizeLabel(rawLabel);
3566
3695
  if (label === "") return 0;
3567
- 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 ?? "" });
3568
3697
  return this.pos;
3569
3698
  }
3570
3699
  };
@@ -3594,6 +3723,7 @@ function parseAst(src, options = DEFAULT_MARKDOWN) {
3594
3723
  }
3595
3724
  var CODE_INDENT2 = 4;
3596
3725
  var MAX_NESTING = 100;
3726
+ var MIN_FILLED_CELLS = 65536;
3597
3727
  var reHtmlBlockOpen = [
3598
3728
  /^$/,
3599
3729
  // unused: block types are numbered from 1
@@ -3626,7 +3756,7 @@ var reATXHeadingMarker = /^#{1,6}(?:[ \t]+|$)/;
3626
3756
  var reClosingCodeFence = /^(?:`{3,}|~{3,})(?=[ \t]*$)/;
3627
3757
  var reSetextHeadingLine = /^(?:=+|-+)[ \t]*$/;
3628
3758
  var reTableDelimiterCell = /^:?-+:?$/;
3629
- var reTaskMarker = /^\[([ xX])\](?:[ \t\n]+|$)/;
3759
+ var reTaskMarker = /^\[([ \t\nxX])\](?:[ \t\n]+|$)/;
3630
3760
  var BNode = class {
3631
3761
  constructor(type, startLine) {
3632
3762
  this.type = type;
@@ -3704,6 +3834,9 @@ var BlockParser = class {
3704
3834
  lastMatchedContainer = this.doc;
3705
3835
  refs = /* @__PURE__ */ new Map();
3706
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;
3707
3840
  // State for the current line.
3708
3841
  line = "";
3709
3842
  lineNumber = 0;
@@ -3717,7 +3850,8 @@ var BlockParser = class {
3717
3850
  partiallyConsumedTab = false;
3718
3851
  allClosed = true;
3719
3852
  parse(src) {
3720
- 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);
3721
3855
  let count = lines.length;
3722
3856
  if (src.endsWith("\n") || src.endsWith("\r")) count -= 1;
3723
3857
  for (let i = 0; i < count; i++) this.incorporateLine(lines[i]);
@@ -3871,7 +4005,17 @@ var BlockParser = class {
3871
4005
  }
3872
4006
  } else if (type === "table") {
3873
4007
  if (!this.blank && this.offset < this.line.length) {
3874
- 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
+ }
3875
4019
  }
3876
4020
  } else if (this.offset < this.line.length && !this.blank) {
3877
4021
  this.addChild("paragraph");
@@ -3898,7 +4042,7 @@ var BlockParser = class {
3898
4042
  const data = block3.list;
3899
4043
  if (this.blank) {
3900
4044
  if (block3.children.length === 0) return 1 /* Failed */;
3901
- this.advanceNextNonspace();
4045
+ this.advanceOffset(Math.min(this.indent, data.markerOffset + data.padding), true);
3902
4046
  } else if (this.indent >= data.markerOffset + data.padding) {
3903
4047
  this.advanceOffset(data.markerOffset + data.padding, true);
3904
4048
  } else {
@@ -3992,7 +4136,7 @@ var BlockParser = class {
3992
4136
  tryStarts(container) {
3993
4137
  const rest = this.line.slice(this.nextNonspace);
3994
4138
  const nest = container.depth < MAX_NESTING;
3995
- 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();
3996
4140
  }
3997
4141
  startBlockQuote(rest) {
3998
4142
  if (this.indented || rest[0] !== ">") return 0 /* None */;
@@ -4087,12 +4231,14 @@ var BlockParser = class {
4087
4231
  /**
4088
4232
  * GFM table: a delimiter row (`| --- | :-: |`) under a paragraph whose last
4089
4233
  * line has the same number of cells. That line becomes the header row; any
4090
- * earlier lines stay a paragraph. We require a `|` in the delimiter row so
4091
- * 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.
4092
4238
  */
4093
4239
  startTable(container, rest) {
4094
4240
  if (this.indented || container.type !== "paragraph") return 0 /* None */;
4095
- if (!rest.includes("|")) return 0 /* None */;
4241
+ if (!rest.includes("|") && reSetextHeadingLine.test(rest)) return 0 /* None */;
4096
4242
  const align = parseDelimiterRow(rest);
4097
4243
  if (!align) return 0 /* None */;
4098
4244
  container.content = this.extractReferences(container.content);
@@ -4251,7 +4397,7 @@ var BlockParser = class {
4251
4397
  const m = reTaskMarker.exec(first.content);
4252
4398
  if (m) {
4253
4399
  task = true;
4254
- checked = m[1] !== " ";
4400
+ checked = m[1] === "x" || m[1] === "X";
4255
4401
  first.content = first.content.slice(m[0].length);
4256
4402
  }
4257
4403
  }
@@ -4303,7 +4449,7 @@ function splitRow(line) {
4303
4449
  }
4304
4450
  }
4305
4451
  if (!endsWithPipe || cells.length === 0) cells.push(cell);
4306
- if (s.startsWith("|") && cells.length > 1) cells.shift();
4452
+ if (s.startsWith("|")) cells.shift();
4307
4453
  return cells.map((c) => c.replace(/^[ \t]+|[ \t]+$/g, ""));
4308
4454
  }
4309
4455
  function fitRow(cells, length) {
@@ -4429,7 +4575,7 @@ function splitHtmlSection(source, options = DEFAULT_MARKDOWN) {
4429
4575
  ${slotMarker(slots.length - 1)}
4430
4576
  `);
4431
4577
  }
4432
- slot.push(...lowerTopLevel(node, options, textOf(i)));
4578
+ slot.push(...lowerTopLevel(node, options, textOf(i), slot[slot.length - 1]));
4433
4579
  });
4434
4580
  return { html: parts.join("\n"), slots };
4435
4581
  }
@@ -4447,29 +4593,38 @@ function serializeBlocks(blocks, options) {
4447
4593
  let out = "";
4448
4594
  let prev = null;
4449
4595
  const lists = new ListState(ctx.paragraph);
4450
- for (const block3 of blocks) {
4596
+ for (let i = 0; i < blocks.length; i++) {
4597
+ const block3 = blocks[i];
4451
4598
  let text;
4452
4599
  let separator = "\n\n";
4600
+ const kind = quoteKind(block3);
4601
+ if (kind) {
4602
+ let end = i + 1;
4603
+ while (end < blocks.length && sameQuote(block3, blocks[end])) end++;
4604
+ const inner = blocks.slice(i, end).map(unquote);
4605
+ let body = serializeBlocks(inner, options);
4606
+ if (kind !== "quote") body = `[!${kind.toUpperCase()}]
4607
+ ${interrupts(inner[0]) ? "" : "\n"}${body}`;
4608
+ if (out) out += separator;
4609
+ out += prefixLines(body, "> ", ">");
4610
+ prev = blocks[end - 1];
4611
+ i = end - 1;
4612
+ continue;
4613
+ }
4453
4614
  switch (block3.type) {
4454
4615
  case "paragraph":
4455
4616
  text = block3.content.length === 0 ? "&nbsp;" : inlineToMarkdown(block3.content, ctx.paragraph);
4456
4617
  break;
4457
- case "quote": {
4458
- let body = block3.content.length === 0 ? "&nbsp;" : inlineToMarkdown(block3.content, ctx.paragraph);
4459
- const joined = prev?.type === "quote" && prev.callout === block3.callout;
4460
- if (block3.callout && !joined) body = `[!${block3.callout.toUpperCase()}]
4461
- ${body}`;
4462
- text = prefixLines(body, "> ", ">");
4463
- if (joined) separator = "\n>\n";
4464
- break;
4465
- }
4618
+ case "quote":
4619
+ continue;
4466
4620
  case "heading":
4467
4621
  text = serializeHeading(block3.level, block3.content, ctx.heading);
4468
4622
  break;
4469
4623
  case "listItem": {
4470
- const item = lists.next(block3, prev?.type === "listItem" ? prev : null);
4624
+ const before = prev?.type === "listItem" && !prev.quote ? prev : null;
4625
+ const item = lists.next(block3, before);
4471
4626
  text = item.text;
4472
- if (prev?.type === "listItem" && !item.blankLineBefore) separator = "\n";
4627
+ if (before && !item.blankLineBefore) separator = "\n";
4473
4628
  break;
4474
4629
  }
4475
4630
  case "code":
@@ -4500,6 +4655,11 @@ ${body}`;
4500
4655
  }
4501
4656
  return out;
4502
4657
  }
4658
+ function interrupts(block3) {
4659
+ if (block3.type !== "listItem") return true;
4660
+ if (block3.listType === "task") return true;
4661
+ return block3.content.length > 0 && (block3.start ?? 1) === 1;
4662
+ }
4503
4663
  function isEmptyParagraph(block3) {
4504
4664
  return block3.type === "paragraph" && block3.content.length === 0;
4505
4665
  }
@@ -4605,7 +4765,7 @@ var STRATEGIES = [
4605
4765
  function sameInline(a, b) {
4606
4766
  return a.length === b.length && a.every((s, i) => {
4607
4767
  const t = b[i];
4608
- 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;
4609
4769
  });
4610
4770
  }
4611
4771
  var reSpecWhitespace = /^[\t\n\f\r\p{Zs}]+|[\t\n\f\r\p{Zs}]+$/gu;
@@ -4748,7 +4908,7 @@ function tokenize(spans, ctx, italic, bare) {
4748
4908
  continue;
4749
4909
  }
4750
4910
  let j = i;
4751
- while (j < spans.length && spans[j].link === span.link) j++;
4911
+ while (j < spans.length && sameLink(spans[j], span)) j++;
4752
4912
  const common = EMPHASIS.filter((m) => spans.slice(i, j).every((s) => s.marks.includes(m)));
4753
4913
  closeExcept(common, 0);
4754
4914
  openMarks(common, i, spans.length);
@@ -4760,7 +4920,7 @@ function tokenize(spans, ctx, italic, bare) {
4760
4920
  const base = stack.length;
4761
4921
  for (let k = i; k < j; k++) emitSpan(spans[k], base, k, j, true);
4762
4922
  closeTo(base);
4763
- tokens.push({ kind: "raw", text: `](${linkDestination(span.link)})` });
4923
+ tokens.push({ kind: "raw", text: `](${linkDestination(span.link)}${linkTitle(span.linkTitle)})` });
4764
4924
  }
4765
4925
  i = j;
4766
4926
  }
@@ -4830,22 +4990,30 @@ function flanking(ch, before, after) {
4830
4990
  function render(spans, ctx, strategy, bare = false) {
4831
4991
  const tokens = tokenize(spans, ctx, strategy.italic, bare);
4832
4992
  fixFlanking(tokens, strategy.encodeAll);
4833
- 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
+ };
4834
5000
  tokens.forEach((tok, i) => {
4835
- if (tok.kind === "delim") out += tok.ch.repeat(tok.count);
5001
+ if (tok.kind === "delim") write(tok.ch.repeat(tok.count));
4836
5002
  else if (tok.kind === "raw") {
4837
- if (ctx.lineStart && out.endsWith("\n") && interruptsParagraph(tok.text)) out += " ";
4838
- out += tok.text;
5003
+ if (ctx.lineStart && last === "\n" && interruptsParagraph(tok.text)) write(" ");
5004
+ write(tok.text);
4839
5005
  } else {
4840
- out += escapeText(tok, ctx, {
4841
- before: out ? out[out.length - 1] : void 0,
4842
- after: edgeChar(tokens[i + 1], "first"),
4843
- lineStart: out === "" || out.endsWith("\n"),
4844
- atEnd: i === tokens.length - 1
4845
- });
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
+ );
4846
5014
  }
4847
5015
  });
4848
- return out;
5016
+ return out.join("");
4849
5017
  }
4850
5018
  var ALNUM = /[\p{L}\p{N}]/u;
4851
5019
  var ASCII_PUNCT = /[!-/:-@[-`{-~]/;
@@ -4895,7 +5063,7 @@ function escapeLine(line, o) {
4895
5063
  if (o.encodeFirst || o.startsLine && (line[0] === " " || line[0] === " ")) encodeAt.add(0);
4896
5064
  if (o.encodeLast || o.endsLine && (line[lastIndex] === " " || line[lastIndex] === " ")) encodeAt.add(lastIndex);
4897
5065
  const blockEscape = o.blockSyntax && !encodeAt.has(0) ? blockSyntaxEscapeIndex(line) : -1;
4898
- const urlEscapes = o.autolinks ? literalEscapes(line, o.before) : null;
5066
+ const urlEscapes = o.autolinks ? literalEscapes(line, o.before, o.after) : null;
4899
5067
  let out = "";
4900
5068
  for (let i = 0; i < line.length; i++) {
4901
5069
  if (encodeAt.has(i)) {
@@ -4942,14 +5110,16 @@ function escapeLine(line, o) {
4942
5110
  }
4943
5111
  return out;
4944
5112
  }
4945
- function literalEscapes(line, before) {
5113
+ function literalEscapes(line, before, after) {
4946
5114
  const emails = emailLiterals(line);
4947
5115
  if (!emails.length && !/www\.|:\/\//i.test(line)) return null;
4948
5116
  const out = /* @__PURE__ */ new Set();
5117
+ const text = line + (after ?? "");
4949
5118
  for (const c of line.matchAll(/www\.|(?:https?|ftp):\/\//gi)) {
4950
5119
  const at = c.index;
4951
- if (!isLiteralBoundary(at > 0 ? line[at - 1] : before) || !urlLiteralAt(line, at)) continue;
4952
- 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 ? "." : ":"));
4953
5123
  }
4954
5124
  for (const { from } of emails) out.add(line.indexOf("@", from));
4955
5125
  return out;
@@ -4969,15 +5139,15 @@ function codeSpan(text) {
4969
5139
  return pad ? `${fence} ${text} ${fence}` : `${fence}${text}${fence}`;
4970
5140
  }
4971
5141
  var reAutolinkUri = new RegExp(`^${AUTOLINK_URI}$`);
4972
- var reEmail2 = new RegExp(`^${AUTOLINK_EMAIL}$`);
5142
+ var reEmail = new RegExp(`^${AUTOLINK_EMAIL}$`);
4973
5143
  function isBareLink(span) {
4974
- 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;
4975
5145
  return literalHref(span.text) === span.link;
4976
5146
  }
4977
5147
  function autolink(span) {
4978
- 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;
4979
5149
  if (span.text === span.link && reAutolinkUri.test(span.link)) return `<${span.link}>`;
4980
- 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}>`;
4981
5151
  return null;
4982
5152
  }
4983
5153
  function escapeEntities(s) {
@@ -4998,6 +5168,10 @@ function linkDestination(url) {
4998
5168
  }
4999
5169
  return escapeEntities(url.replace(/\\/g, "\\\\"));
5000
5170
  }
5171
+ function linkTitle(title) {
5172
+ if (!title) return "";
5173
+ return ` "${escapeEntities(title.replace(/\n(?:[ \t]*\n)+/g, "\n").replace(/["\\]/g, "\\$&"))}"`;
5174
+ }
5001
5175
  function imageMarkdown(image, ctx) {
5002
5176
  const altCtx = ctx.newline === "soft" ? { ...ctx, newline: "break" } : ctx;
5003
5177
  const alt = escapeText({ text: image.alt, encodeFirst: false, encodeLast: false }, altCtx, {
@@ -5006,7 +5180,7 @@ function imageMarkdown(image, ctx) {
5006
5180
  lineStart: false,
5007
5181
  atEnd: false
5008
5182
  });
5009
- const title = image.title ? ` "${escapeEntities(image.title.replace(/["\\]/g, "\\$&"))}"` : "";
5183
+ const title = linkTitle(image.title);
5010
5184
  const suffix = imageSuffixText(image);
5011
5185
  const read = imageSuffix(alt + suffix);
5012
5186
  const same = read ? read.index === alt.length && imageSuffixText(read) === suffix : !suffix;
@@ -5038,7 +5212,7 @@ function loadMarkdown(text, options) {
5038
5212
  const lines = root.lines[last];
5039
5213
  const to = lineEnds[Math.max(lines.start, lines.end) - 1] ?? text.length;
5040
5214
  const source = text.slice(from, to);
5041
- 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]);
5042
5216
  i = last;
5043
5217
  blocks.push(...lowered);
5044
5218
  if (lowered.length === 0 || from < lastEnd || to < from) continue;
@@ -5054,7 +5228,7 @@ function isOpen(source, options) {
5054
5228
  return parseAst(source + "\n\nx", options).children.length < 2;
5055
5229
  }
5056
5230
  function joins(a, b) {
5057
- if (a?.type === "quote" && b?.type === "quote") return a.callout === b.callout;
5231
+ if (quoteKind(a) !== null || quoteKind(b) !== null) return sameQuote(a, b);
5058
5232
  return a?.type === "listItem" && b?.type === "listItem";
5059
5233
  }
5060
5234
  function saveWithSource(blocks, source, options) {
@@ -5151,7 +5325,7 @@ function saveWithSource(blocks, source, options) {
5151
5325
  }
5152
5326
  return out + ending;
5153
5327
  }
5154
- var reTaskLine = /^([ \t]*(?:[-+*]|\d{1,9}[.)])[ \t]+\[)([ xX])(?=\][ \t]|\]$)/gm;
5328
+ var reTaskLine = /^((?:[ \t]*>)*[ \t]*(?:[-+*]|\d{1,9}[.)])[ \t]+\[)([ xX])(?=\][ \t]|\]$)/gm;
5155
5329
  function tickedGroup(blocks, i, firstBlocks, source, options) {
5156
5330
  const loaded = firstBlocks.get(blocks[i].id);
5157
5331
  if (!loaded || loaded.open) return null;
@@ -5693,7 +5867,8 @@ function matchToken(scan, { probe = "a", maxLength = 30 } = {}) {
5693
5867
  let lineEnd = text.indexOf("\n", caret2);
5694
5868
  if (lineEnd < 0) lineEnd = text.length;
5695
5869
  const reach = maxLength + 16;
5696
- 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--;
5697
5872
  const to = Math.min(lineEnd + probe.length, caret2 + probe.length + reach);
5698
5873
  for (const token of scan(probed, from, to)) {
5699
5874
  if (token.from >= caret2 || token.to < caret2 + probe.length) continue;
@@ -6227,6 +6402,8 @@ var WidgetImpl = class {
6227
6402
  this.paint();
6228
6403
  }
6229
6404
  blockId;
6405
+ /** In source mode, the text offset the widget sits after. */
6406
+ offset = 0;
6230
6407
  isRemoved = false;
6231
6408
  cleanup = null;
6232
6409
  update(render2) {
@@ -6326,7 +6503,7 @@ function blockState(editor) {
6326
6503
  allHeadings: some && blocks.every((b) => b.type === "heading"),
6327
6504
  listType: every((b) => b.type === "listItem" ? b.listType : null),
6328
6505
  allListItems: some && blocks.every((b) => b.type === "listItem"),
6329
- allQuotes: some && blocks.every((b) => b.type === "quote")
6506
+ allQuotes: some && blocks.every((b) => quoteKind(b) !== null)
6330
6507
  };
6331
6508
  }
6332
6509
  var FormatToolbar = class {
@@ -6655,6 +6832,7 @@ var FILL_ATTR = "data-mbe-fill";
6655
6832
  var ATOM_ATTR = "data-atom";
6656
6833
  var LIST_START_ATTR = "data-list-start";
6657
6834
  var QUOTE_JOINED_ATTR = "data-quote-joined";
6835
+ var QUOTE_CONTINUED_ATTR = "data-quote-continued";
6658
6836
  var SECTION_HIDDEN_ATTR = "data-section-hidden";
6659
6837
  var SECTION_COLLAPSED_ATTR = "data-collapsed";
6660
6838
  var SECTION_INSIDE_ATTR = "data-in-section";
@@ -6678,7 +6856,7 @@ function blockClasses(block3, theme) {
6678
6856
  case "quote":
6679
6857
  return theme.blockquote;
6680
6858
  case "listItem":
6681
- return theme[`${block3.listType}List`];
6859
+ return block3.quote ? classes(theme[`${block3.listType}List`], theme.blockquote) || void 0 : theme[`${block3.listType}List`];
6682
6860
  case "code":
6683
6861
  return theme.codeBlock;
6684
6862
  case "table":
@@ -6695,10 +6873,10 @@ function blockClasses(block3, theme) {
6695
6873
  }
6696
6874
  }
6697
6875
  var defaultResolveUrl = (url) => {
6698
- const trimmed = url.trim();
6699
- const scheme = /^([a-z][a-z0-9+.-]*):/i.exec(trimmed);
6700
- if (!scheme) return trimmed;
6701
- 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;
6702
6880
  };
6703
6881
  var REVEAL_BLOCK = "block";
6704
6882
  function tokenKey(cell, from) {
@@ -6725,19 +6903,23 @@ function renderCallout(block3, type, ctx, reveal) {
6725
6903
  const root = doc.createElement("blockquote");
6726
6904
  root.dir = "auto";
6727
6905
  root.dataset.callout = type;
6728
- const name = calloutName(type);
6729
- const title = doc.createElement("div");
6730
- title.className = "mbe-callout-title";
6731
- title.contentEditable = "false";
6732
- const icon = ctx.icon?.(name);
6733
- if (icon) title.appendChild(icon);
6734
- title.appendChild(doc.createTextNode(ctx.labels[name]));
6735
6906
  const content = doc.createElement("div");
6736
6907
  content.className = "mbe-content";
6737
6908
  fillContent(content, block3.content, ctx, block3, reveal);
6738
- root.append(title, content);
6909
+ root.append(calloutIcon(type, ctx), content);
6739
6910
  return root;
6740
6911
  }
6912
+ function calloutIcon(type, ctx) {
6913
+ const name = calloutName(type);
6914
+ const icon = ctx.doc.createElement("div");
6915
+ icon.className = "mbe-callout-icon";
6916
+ icon.contentEditable = "false";
6917
+ icon.setAttribute("role", "img");
6918
+ icon.setAttribute("aria-label", ctx.labels[name]);
6919
+ const glyph = ctx.icon?.(name);
6920
+ if (glyph) icon.appendChild(glyph);
6921
+ return icon;
6922
+ }
6741
6923
  function renderBlock(block3, ctx, reveal) {
6742
6924
  const { doc, labels } = ctx;
6743
6925
  const el = (tag, className2) => {
@@ -6760,7 +6942,11 @@ function renderBlock(block3, ctx, reveal) {
6760
6942
  if (block3.type === "paragraph") markImageBlock(root, block3);
6761
6943
  break;
6762
6944
  case "listItem": {
6763
- root = el("div");
6945
+ root = el(block3.quote ? "blockquote" : "div");
6946
+ if (block3.callout) {
6947
+ root.dataset.callout = block3.callout;
6948
+ root.appendChild(calloutIcon(block3.callout, ctx));
6949
+ }
6764
6950
  root.dir = "auto";
6765
6951
  root.dataset.listType = block3.listType;
6766
6952
  root.dataset.indent = String(block3.indent);
@@ -6779,6 +6965,15 @@ function renderBlock(block3, ctx, reveal) {
6779
6965
  break;
6780
6966
  }
6781
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
+ }
6782
6977
  const view = reveal?.has(REVEAL_BLOCK) ? null : ctx.view?.(codeViewName(block3.language), inlineText(block3.content), "block");
6783
6978
  if (view) {
6784
6979
  root = view;
@@ -6809,7 +7004,8 @@ function renderBlock(block3, ctx, reveal) {
6809
7004
  case "raw": {
6810
7005
  const source = inlineText(block3.content);
6811
7006
  const section = block3.syntax === "html" && !reveal?.has(REVEAL_BLOCK) && ctx.views?.has("html") ? splitHtmlSection(source, ctx.markdown) : null;
6812
- const view = reveal?.has(REVEAL_BLOCK) ? null : ctx.view?.(block3.syntax, section ? section.html : source, "block");
7007
+ const nested = block3.syntax === "markdown" && !reveal?.has(REVEAL_BLOCK) && ctx.views?.get("markdown") === MARKDOWN_VIEW;
7008
+ const view = reveal?.has(REVEAL_BLOCK) ? null : nested ? renderMarkdown(source, ctx) : ctx.view?.(block3.syntax, section ? section.html : source, "block");
6813
7009
  if (view) {
6814
7010
  root = view;
6815
7011
  root.classList.add("mbe-view-block");
@@ -6875,7 +7071,7 @@ function renderBlock(block3, ctx, reveal) {
6875
7071
  }
6876
7072
  }
6877
7073
  root.setAttribute(BLOCK_ATTR, block3.id);
6878
- 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;
6879
7075
  let className = `${root.className ? root.className + " " : ""}mbe-block mbe-${name}`;
6880
7076
  if (block3.type === "listItem" && block3.checked) className += " mbe-checked";
6881
7077
  if ("content" in block3 && inlineLength(block3.content) === 0) className += " mbe-empty";
@@ -6892,7 +7088,7 @@ function fillContent(target, inline3, ctx, block3, reveal, cell, decorated = tru
6892
7088
  target.appendChild(fill(doc));
6893
7089
  return;
6894
7090
  }
6895
- 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) : [];
6896
7092
  const only = inline3.length === 1 ? inline3[0] : null;
6897
7093
  if (only && decorations.length === 0 && only.marks.length === 0 && !only.link && !only.token && !only.image) {
6898
7094
  target.appendChild(doc.createTextNode(only.text));
@@ -6947,6 +7143,11 @@ function fillSlots(root, count, content, doc) {
6947
7143
  function renderFlow(blocks, ctx) {
6948
7144
  const flow = ctx.doc.createElement("div");
6949
7145
  flow.className = "mbe-flow";
7146
+ appendBlocks(flow, blocks, ctx);
7147
+ makeInert(flow);
7148
+ return flow;
7149
+ }
7150
+ function appendBlocks(flow, blocks, ctx) {
6950
7151
  const elements = /* @__PURE__ */ new Map();
6951
7152
  for (const block3 of blocks) {
6952
7153
  const el = renderBlock(block3, ctx);
@@ -6954,6 +7155,73 @@ function renderFlow(blocks, ctx) {
6954
7155
  flow.appendChild(el);
6955
7156
  }
6956
7157
  updateNeighborMarks({ blocks }, (id) => elements.get(id), /* @__PURE__ */ new WeakMap(), /* @__PURE__ */ new Set(), ctx.labels);
7158
+ }
7159
+ var MARKDOWN_VIEW = () => false;
7160
+ function renderMarkdown(source, ctx) {
7161
+ const root = ctx.doc.createElement("div");
7162
+ root.classList.add("mbe-view-markdown");
7163
+ root.appendChild(renderNodes(parseAst(source, ctx.markdown).children, ctx));
7164
+ makeInert(root);
7165
+ return root;
7166
+ }
7167
+ function renderNodes(nodes, ctx) {
7168
+ const options = ctx.markdown ?? DEFAULT_MARKDOWN;
7169
+ const flow = ctx.doc.createElement("div");
7170
+ flow.className = "mbe-flow";
7171
+ let run = [];
7172
+ for (const node of nodes) {
7173
+ const blocks = lowerIfFits(node, options);
7174
+ if (blocks) {
7175
+ run.push(...blocks);
7176
+ continue;
7177
+ }
7178
+ appendBlocks(flow, run, ctx);
7179
+ run = [];
7180
+ if (node.type === "blockQuote") flow.appendChild(renderQuoteNode(node, ctx));
7181
+ else if (node.type === "list") node.items.forEach((item, i) => flow.appendChild(renderItemNode(node, item, i, ctx)));
7182
+ }
7183
+ appendBlocks(flow, run, ctx);
7184
+ return flow;
7185
+ }
7186
+ function renderQuoteNode(node, ctx) {
7187
+ const alert = ctx.markdown?.callouts === false ? null : calloutOf2(node.children);
7188
+ const children = alert ? [...alert.rest.length > 0 ? [{ type: "paragraph", children: [...alert.rest] }] : [], ...node.children.slice(1)] : node.children;
7189
+ const el = ctx.doc.createElement("blockquote");
7190
+ el.dir = "auto";
7191
+ el.className = classes("mbe-block mbe-quote", ctx.classes.blockquote);
7192
+ if (alert) {
7193
+ el.dataset.callout = alert.type;
7194
+ el.appendChild(calloutIcon(alert.type, ctx));
7195
+ }
7196
+ el.appendChild(renderNodes(children, ctx));
7197
+ return el;
7198
+ }
7199
+ function renderItemNode(list, node, index, ctx) {
7200
+ const listType = node.task ? "task" : list.ordered ? "ordered" : "bullet";
7201
+ const el = ctx.doc.createElement("div");
7202
+ el.dir = "auto";
7203
+ el.className = classes("mbe-block mbe-list-item", ctx.classes[`${listType}List`]);
7204
+ el.dataset.listType = listType;
7205
+ el.dataset.indent = "0";
7206
+ if (index === 0) el.setAttribute(LIST_START_ATTR, "");
7207
+ const marker = ctx.doc.createElement("span");
7208
+ marker.className = "mbe-marker";
7209
+ if (node.task) {
7210
+ const box = ctx.doc.createElement("input");
7211
+ box.className = "mbe-checkbox";
7212
+ box.type = "checkbox";
7213
+ box.checked = node.checked;
7214
+ marker.appendChild(box);
7215
+ } else if (list.ordered) {
7216
+ marker.textContent = `${list.start + index}.`;
7217
+ }
7218
+ const content = ctx.doc.createElement("div");
7219
+ content.className = "mbe-content";
7220
+ content.appendChild(renderNodes(node.children, ctx));
7221
+ el.append(marker, content);
7222
+ return el;
7223
+ }
7224
+ function makeInert(flow) {
6957
7225
  for (const el of Array.from(flow.querySelectorAll(`[${BLOCK_ATTR}], [${CONTENT_ATTR}], [contenteditable], [data-row]`))) {
6958
7226
  el.removeAttribute(BLOCK_ATTR);
6959
7227
  el.removeAttribute(CONTENT_ATTR);
@@ -6966,7 +7234,6 @@ function renderFlow(blocks, ctx) {
6966
7234
  else input.readOnly = true;
6967
7235
  input.tabIndex = -1;
6968
7236
  }
6969
- return flow;
6970
7237
  }
6971
7238
  function fill(doc) {
6972
7239
  const br = doc.createElement("br");
@@ -7068,8 +7335,9 @@ function renderInline(inline3, parent, ctx, decorations, reveal, cell) {
7068
7335
  const href = ctx.resolveUrl(span.link, "link");
7069
7336
  if (href !== null) a.setAttribute("href", href);
7070
7337
  a.dataset.href = span.link;
7338
+ if (span.linkTitle) a.title = span.linkTitle;
7071
7339
  a.className = classes("mbe-link", ctx.classes.link);
7072
- while (i < pieces.length && pieces[i].span.link === span.link) {
7340
+ while (i < pieces.length && sameLink(pieces[i].span, span)) {
7073
7341
  a.appendChild(render2(pieces[i]));
7074
7342
  i++;
7075
7343
  }
@@ -7202,6 +7470,8 @@ var BlockRenderer = class {
7202
7470
  icon;
7203
7471
  /** Code blocks get a copy button. */
7204
7472
  codeCopy = false;
7473
+ /** Source mode: the code block renders as plain text. Changing it needs a forced render. */
7474
+ source = false;
7205
7475
  /** An image failed to load and now shows as unavailable. */
7206
7476
  onImageError;
7207
7477
  /** Collapsible sections shown collapsed, by the ID of their title block. */
@@ -7235,6 +7505,7 @@ var BlockRenderer = class {
7235
7505
  classes: this.classes,
7236
7506
  icon: this.icon,
7237
7507
  codeCopy: this.codeCopy,
7508
+ source: this.source,
7238
7509
  onImageError: this.onImageError,
7239
7510
  loadedImage: (src) => this.loadedImages.get(src)?.shift()
7240
7511
  };
@@ -7395,6 +7666,7 @@ function markSection(el, depth, hidden, collapsed, labels) {
7395
7666
  }
7396
7667
  function updateNeighborMarks(doc, elementFor, written, collapsed, labels) {
7397
7668
  const counters = [];
7669
+ let topOrdered;
7398
7670
  const sections2 = [];
7399
7671
  doc.blocks.forEach((block3, i) => {
7400
7672
  const before = doc.blocks[i - 1];
@@ -7402,13 +7674,18 @@ function updateNeighborMarks(doc, elementFor, written, collapsed, labels) {
7402
7674
  if (block3.type === "detailsEnd") sections2.pop();
7403
7675
  if (el) markSection(el, sections2.length, sections2.includes(true), block3.type === "details" ? collapsed.has(block3.id) : null, labels);
7404
7676
  if (block3.type === "details") sections2.push(collapsed.has(block3.id));
7405
- if (block3.type === "quote") setFlag(el, QUOTE_JOINED_ATTR, before?.type === "quote" && before.callout === block3.callout);
7406
- if (block3.type !== "listItem") {
7677
+ if (quoteKind(block3) !== null) {
7678
+ setFlag(el, QUOTE_JOINED_ATTR, sameQuote(before, block3));
7679
+ setFlag(el, QUOTE_CONTINUED_ATTR, sameQuote(block3, doc.blocks[i + 1]));
7680
+ }
7681
+ if (block3.type !== "listItem" || before?.type !== "listItem" || quoteKind(before) !== quoteKind(block3)) {
7407
7682
  counters.length = 0;
7408
- return;
7683
+ topOrdered = void 0;
7409
7684
  }
7685
+ if (block3.type !== "listItem") return;
7410
7686
  const ordered = block3.listType === "ordered";
7411
- setFlag(el, LIST_START_ATTR, before?.type !== "listItem" || block3.indent === 0 && ordered !== (before.listType === "ordered"));
7687
+ setFlag(el, LIST_START_ATTR, counters.length === 0 || block3.indent === 0 && topOrdered !== void 0 && ordered !== topOrdered);
7688
+ if (block3.indent === 0) topOrdered = ordered;
7412
7689
  counters.length = block3.indent + 1;
7413
7690
  if (!ordered) {
7414
7691
  counters[block3.indent] = void 0;
@@ -7613,11 +7890,13 @@ var BlockHandle = class {
7613
7890
  this.el.hidden = false;
7614
7891
  const offset = attach(this.el, this.editor.root);
7615
7892
  const rect = blockEl.getBoundingClientRect();
7893
+ const icon = blockEl.querySelector(":scope > .mbe-callout-icon");
7894
+ const iconRect = icon?.getBoundingClientRect();
7616
7895
  const lineHeight = parseFloat(doc.defaultView.getComputedStyle(blockEl).lineHeight) || 24;
7617
- const firstLine = Math.min(rect.height, lineHeight);
7896
+ const middle = iconRect?.height ? iconRect.top + iconRect.height / 2 : rect.top + Math.min(rect.height, lineHeight) / 2;
7618
7897
  const size = this.el.offsetHeight || 22;
7619
7898
  this.el.style.left = `${Math.round(rect.left - (this.el.offsetWidth || 20) - 6 - offset.x)}px`;
7620
- this.el.style.top = `${Math.round(rect.top + firstLine / 2 - size / 2 - offset.y)}px`;
7899
+ this.el.style.top = `${Math.round(middle - size / 2 - offset.y)}px`;
7621
7900
  }
7622
7901
  /** True when `node` is the block handle or inside it. */
7623
7902
  contains(node) {
@@ -7678,7 +7957,7 @@ var LinkCard = class {
7678
7957
  };
7679
7958
  const open = button("openLink", (e) => actions.open(this.target, e));
7680
7959
  this.copyButton = button("copyLink", () => this.copy());
7681
- const edit = button("editLink", () => {
7960
+ const edit2 = button("editLink", () => {
7682
7961
  const target = this.target;
7683
7962
  this.hide();
7684
7963
  actions.edit(target);
@@ -7690,7 +7969,7 @@ var LinkCard = class {
7690
7969
  });
7691
7970
  const sep = doc.createElement("span");
7692
7971
  sep.className = "mbe-tool-sep";
7693
- el.append(this.url, sep, open, this.copyButton, edit, remove);
7972
+ el.append(this.url, sep, open, this.copyButton, edit2, remove);
7694
7973
  const root = editor.root;
7695
7974
  const on = (target, type, fn) => {
7696
7975
  target.addEventListener(type, fn);
@@ -8050,7 +8329,7 @@ function sameRevealed(a, b) {
8050
8329
  }
8051
8330
  function viewEntry(block3, forward) {
8052
8331
  const text = inlineText(block3.content);
8053
- if (block3.type === "code") return { blockId: block3.id, offset: forward ? 0 : text.length };
8332
+ if (block3.type === "code" || block3.syntax === "markdown") return { blockId: block3.id, offset: forward ? 0 : text.length };
8054
8333
  if (forward) {
8055
8334
  const firstBreak = text.indexOf("\n");
8056
8335
  return { blockId: block3.id, offset: firstBreak >= 0 && firstBreak < text.length - 1 ? firstBreak + 1 : 0 };
@@ -8153,6 +8432,177 @@ function tokenProperties(tokens) {
8153
8432
  return props;
8154
8433
  }
8155
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
+
8156
8606
  // src/editor.ts
8157
8607
  var SLASH_ITEM_IDS = [
8158
8608
  "text",
@@ -8215,7 +8665,11 @@ var Editor = class {
8215
8665
  source;
8216
8666
  /** The Markdown dialect: options plus the syntax of extensions. */
8217
8667
  markdown;
8218
- 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;
8219
8673
  renderer;
8220
8674
  composing = false;
8221
8675
  /**
@@ -8321,8 +8775,7 @@ var Editor = class {
8321
8775
  const els = this.widgets.filter((w) => w.blockId === blockId).map((w) => w.element);
8322
8776
  return els.length ? els : void 0;
8323
8777
  };
8324
- const views = new Map(this.extensions.flatMap((e) => Object.entries(e.views ?? {})));
8325
- if (views.size > 0) this.renderer.views = views;
8778
+ this.renderer.views = new Map([["markdown", MARKDOWN_VIEW], ...this.extensions.flatMap((e) => Object.entries(e.views ?? {}))]);
8326
8779
  this.renderer.markdown = this.markdown;
8327
8780
  this.renderer.onViewSettled = (ids) => this.viewsSettled(ids);
8328
8781
  const codeDecorators = this.extensions.flatMap((e) => e.codeDecorations ? [e.codeDecorations] : []);
@@ -8420,6 +8873,7 @@ var Editor = class {
8420
8873
  this.listen(root.ownerDocument, "mouseup", () => this.onMouseUp());
8421
8874
  this.listen(root.ownerDocument, "scroll", () => this.onScroll(), true);
8422
8875
  this.listen(root.ownerDocument, "pointerdown", (e) => this.onDocumentPointerDown(e), true);
8876
+ if (options.mode === "source") this.enterSource();
8423
8877
  this.paint(true, true);
8424
8878
  this.afterRender();
8425
8879
  for (const ext of this.extensions) {
@@ -8432,6 +8886,7 @@ var Editor = class {
8432
8886
  // Content
8433
8887
  /** The document as Markdown. Blocks that were not edited are written exactly as they were loaded. */
8434
8888
  getMarkdown() {
8889
+ if (this.modeValue === "source") return sourceText(this.current.doc);
8435
8890
  return serializeMarkdown(this.current.doc, { ...this.markdown, source: this.source });
8436
8891
  }
8437
8892
  /**
@@ -8442,6 +8897,15 @@ var Editor = class {
8442
8897
  if (this.destroyed) return;
8443
8898
  if (options.history === "keep") this.history.record(this.current, "other");
8444
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
+ }
8445
8909
  const loaded = loadMarkdown(markdown, this.markdown);
8446
8910
  this.source = loaded.source;
8447
8911
  this.blockSel = null;
@@ -8457,6 +8921,7 @@ var Editor = class {
8457
8921
  }
8458
8922
  /** True when the document holds only empty paragraphs. */
8459
8923
  get isEmpty() {
8924
+ if (this.modeValue === "source") return sourceText(this.current.doc) === "";
8460
8925
  return this.current.doc.blocks.every((b) => b.type === "paragraph" && inlineLength(b.content) === 0);
8461
8926
  }
8462
8927
  // -------------------------------------------------------------------------
@@ -8469,6 +8934,10 @@ var Editor = class {
8469
8934
  get isComposing() {
8470
8935
  return this.composing;
8471
8936
  }
8937
+ /** `'rich'` or `'source'`: the mode the editor shows now. */
8938
+ get mode() {
8939
+ return this.pendingMode ?? this.modeValue;
8940
+ }
8472
8941
  get isEditable() {
8473
8942
  return !this.readOnly && !this.destroyed;
8474
8943
  }
@@ -8478,6 +8947,7 @@ var Editor = class {
8478
8947
  }
8479
8948
  /** True if `name` applies at the selection: a mark on the selected text, or the type of the block with the caret. */
8480
8949
  isActive(name, attrs) {
8950
+ if (this.modeValue === "source") return false;
8481
8951
  const s = this.current;
8482
8952
  switch (name) {
8483
8953
  case "bold":
@@ -8495,13 +8965,14 @@ var Editor = class {
8495
8965
  }
8496
8966
  }
8497
8967
  const block3 = getBlock(s.doc, s.selection.focus.blockId);
8498
- if (blockName(block3) !== name) return false;
8968
+ if (blockName(block3) !== name && !(name === "blockquote" && quoteKind(block3))) return false;
8499
8969
  if (!attrs) return true;
8500
8970
  const actual = this.getAttributes(name);
8501
8971
  return Object.entries(attrs).every(([k, v]) => actual[k] === v);
8502
8972
  }
8503
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. */
8504
8974
  getAttributes(name) {
8975
+ if (this.modeValue === "source") return {};
8505
8976
  const s = this.current;
8506
8977
  if (name === "link") {
8507
8978
  const link = activeLink(s);
@@ -8512,6 +8983,8 @@ var Editor = class {
8512
8983
  return selected ? { ...selected.image, block: selectedImageBlock(s) !== null } : {};
8513
8984
  }
8514
8985
  const block3 = getBlock(s.doc, s.selection.focus.blockId);
8986
+ const kind = quoteKind(block3);
8987
+ if (name === "blockquote" && kind) return kind === "quote" ? {} : { callout: kind };
8515
8988
  if (blockName(block3) !== name) return {};
8516
8989
  switch (block3.type) {
8517
8990
  case "heading":
@@ -8588,6 +9061,7 @@ var Editor = class {
8588
9061
  const widget = new WidgetImpl(el, blockId, options.render, (w) => {
8589
9062
  this.widgets = this.widgets.filter((x) => x !== w);
8590
9063
  });
9064
+ if (this.modeValue === "source") widget.offset = options.at === "end" ? sourceText(this.current.doc).length : at.offset;
8591
9065
  this.widgets.push(widget);
8592
9066
  this.paint();
8593
9067
  return widget;
@@ -8647,6 +9121,92 @@ var Editor = class {
8647
9121
  this.applyReadOnly();
8648
9122
  }
8649
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 };
8650
9210
  }
8651
9211
  /** Subscribes to an event. Returns a function that unsubscribes. */
8652
9212
  on(type, handler) {
@@ -8798,6 +9358,38 @@ var Editor = class {
8798
9358
  return true;
8799
9359
  }
8800
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
+ }
8801
9393
  for (const name of Object.keys(commands)) {
8802
9394
  const fn = commands[name];
8803
9395
  commands[name] = (...args) => !this.destroyed && fn(...args);
@@ -8805,20 +9397,44 @@ var Editor = class {
8805
9397
  return commands;
8806
9398
  }
8807
9399
  toggleMark(mark) {
9400
+ if (this.modeValue === "source") return false;
8808
9401
  return this.run((s) => toggleMark(s, mark));
8809
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
+ }
8810
9426
  undo() {
8811
9427
  if (this.readOnly) return false;
8812
9428
  const next = this.history.undo(this.current);
8813
9429
  if (!next) return false;
8814
- this.commit(next);
9430
+ this.commit(this.restore(next));
8815
9431
  return true;
8816
9432
  }
8817
9433
  redo() {
8818
9434
  if (this.readOnly) return false;
8819
9435
  const next = this.history.redo(this.current);
8820
9436
  if (!next) return false;
8821
- this.commit(next);
9437
+ this.commit(this.restore(next));
8822
9438
  return true;
8823
9439
  }
8824
9440
  // -------------------------------------------------------------------------
@@ -8905,7 +9521,13 @@ var Editor = class {
8905
9521
  const docChanged = next.doc !== this.state.doc;
8906
9522
  const moved = next.selection !== this.state.selection;
8907
9523
  const hadFocus = this.hasFocus();
8908
- 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
+ }
8909
9531
  this.current = next;
8910
9532
  if (this.blockSel) {
8911
9533
  const range = this.blockRange();
@@ -9367,6 +9989,7 @@ var Editor = class {
9367
9989
  }
9368
9990
  this.refreshSelection();
9369
9991
  if ((type === "insertText" || type === "insertReplacementText") && selectedImageBlock(this.state)) return;
9992
+ if (this.modeValue === "source" && this.onSourceInput(type)) return;
9370
9993
  switch (type) {
9371
9994
  case "insertText": {
9372
9995
  const text = e.data ?? "";
@@ -9411,7 +10034,9 @@ var Editor = class {
9411
10034
  if (range && !isCollapsed(range) && range.anchor.blockId === range.focus.blockId) {
9412
10035
  this.run((s) => deleteSelection({ ...s, selection: range }));
9413
10036
  } else {
9414
- 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
+ );
9415
10040
  }
9416
10041
  return;
9417
10042
  }
@@ -9434,6 +10059,23 @@ var Editor = class {
9434
10059
  return;
9435
10060
  }
9436
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
+ }
9437
10079
  typeText(text) {
9438
10080
  this.run((s) => insertText(s, text), "typing");
9439
10081
  this.afterTyping(text);
@@ -9452,6 +10094,10 @@ var Editor = class {
9452
10094
  }
9453
10095
  /** Markdown shortcuts and suggestion menus that typing `text` triggers. */
9454
10096
  afterTyping(text) {
10097
+ if (this.modeValue === "source") {
10098
+ this.shortcut = null;
10099
+ return;
10100
+ }
9455
10101
  const typed = this.state;
9456
10102
  if (text === " " || text === "-") this.run((s) => applyBlockInputRules(s, this.markdown));
9457
10103
  if (text.length === 1 && "*_`~".includes(text)) this.run((s) => applyInlineInputRules(s));
@@ -9512,6 +10158,7 @@ var Editor = class {
9512
10158
  this.redecoratePending = false;
9513
10159
  this.afterRender();
9514
10160
  if (composed) this.typedForSuggestion();
10161
+ if (this.pendingMode) this.setMode(this.pendingMode);
9515
10162
  }
9516
10163
  onInput(e) {
9517
10164
  if (this.fromControl(e)) return;
@@ -9693,7 +10340,7 @@ var Editor = class {
9693
10340
  const { selection } = this.state;
9694
10341
  if (isCollapsed(selection) && selection.focus.offset === 0) {
9695
10342
  e.preventDefault();
9696
- this.run(deleteBackward);
10343
+ if (this.modeValue !== "source") this.run(deleteBackward);
9697
10344
  return;
9698
10345
  }
9699
10346
  }
@@ -9707,7 +10354,7 @@ var Editor = class {
9707
10354
  return;
9708
10355
  }
9709
10356
  }
9710
- if (e.key.startsWith("Arrow") && !mod2 && !e.shiftKey && !e.altKey) {
10357
+ if (e.key.startsWith("Arrow") && !mod2 && !e.shiftKey && !e.altKey && this.modeValue === "rich") {
9711
10358
  this.refreshSelection();
9712
10359
  const into = this.blockPast(e.key);
9713
10360
  if (into) {
@@ -9810,7 +10457,7 @@ var Editor = class {
9810
10457
  return;
9811
10458
  }
9812
10459
  this.dropBlockSelection();
9813
- 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;
9814
10461
  const imageEl = e.button === 0 && !e.shiftKey && !this.readOnly ? target.closest?.(".mbe-image") : null;
9815
10462
  const image = imageEl && this.root.contains(imageEl) ? this.imageTarget(imageEl) : null;
9816
10463
  if (image) {
@@ -9824,15 +10471,15 @@ var Editor = class {
9824
10471
  this.revealView(view);
9825
10472
  return;
9826
10473
  }
9827
- 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)) {
9828
10475
  e.preventDefault();
9829
10476
  return;
9830
10477
  }
9831
- const title = e.button === 0 && !this.readOnly ? target.closest?.(".mbe-callout-title") : null;
9832
- const titleBlock = title?.parentElement?.getAttribute(BLOCK_ATTR);
9833
- if (title && titleBlock && title.parentElement.parentElement === this.root) {
10478
+ const icon = e.button === 0 && !this.readOnly ? target.closest?.(".mbe-callout-icon") : null;
10479
+ const iconBlock = icon?.parentElement?.getAttribute(BLOCK_ATTR);
10480
+ if (icon && iconBlock && icon.parentElement.parentElement === this.root) {
9834
10481
  e.preventDefault();
9835
- this.openBlockMenu(titleBlock, title.getBoundingClientRect());
10482
+ this.openBlockMenu(iconBlock, icon.getBoundingClientRect());
9836
10483
  return;
9837
10484
  }
9838
10485
  if (e.button === 0) this.pointerDown = true;
@@ -9957,6 +10604,15 @@ var Editor = class {
9957
10604
  // Clipboard
9958
10605
  onCopy(e, cut) {
9959
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
+ }
9960
10616
  const range = this.blockRange();
9961
10617
  if (range) {
9962
10618
  if (!e.clipboardData) return;
@@ -9982,9 +10638,14 @@ var Editor = class {
9982
10638
  const data = e.clipboardData;
9983
10639
  if (!data) return;
9984
10640
  const text = data.getData("text/plain");
9985
- 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;
9986
10643
  const plainOnly = this.plainPasteNext;
9987
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
+ }
9988
10649
  const range = this.blockRange();
9989
10650
  if (range) {
9990
10651
  const fragment2 = this.pastedBlocks(text, html, plainOnly);
@@ -10023,6 +10684,11 @@ var Editor = class {
10023
10684
  for (const ext of this.extensions) if (ext.handleDrop?.({ editor: this, event: e, position })) return;
10024
10685
  const text = e.dataTransfer?.getData("text/plain");
10025
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
+ }
10026
10692
  const fragment = parseMarkdown(text, this.markdown).blocks;
10027
10693
  this.focus();
10028
10694
  this.run((s) => insertFragment(s, fragment, { at: position }));
@@ -10264,8 +10930,9 @@ var Editor = class {
10264
10930
  })));
10265
10931
  sections2.push({ title: this.labels.tableSection, items });
10266
10932
  }
10267
- if (block3.type === "quote" && block3.callout) {
10268
- const current = block3.callout;
10933
+ const kind = quoteKind(block3);
10934
+ if (kind && kind !== "quote") {
10935
+ const current = kind;
10269
10936
  const items = CALLOUT_TYPES.map((type) => {
10270
10937
  const name = calloutName(type);
10271
10938
  return {
@@ -10344,13 +11011,14 @@ var Editor = class {
10344
11011
  * or Markdown shortcuts.
10345
11012
  */
10346
11013
  hasBlockMenu(blockId) {
11014
+ if (this.modeValue === "source") return false;
10347
11015
  const block3 = this.state.doc.blocks.find((b) => b.id === blockId);
10348
- return block3?.type === "table" || block3?.type === "code" || block3?.type === "quote" && !!block3.callout || !!block3 && isImageBlock(block3);
11016
+ return block3?.type === "table" || block3?.type === "code" || isCallout(block3) || !!block3 && isImageBlock(block3);
10349
11017
  }
10350
11018
  /**
10351
11019
  * @internal
10352
11020
  * The block whose block menu `blockId` belongs to, or null when it has none:
10353
- * the first block of a callout, so the handle sits by its title; otherwise
11021
+ * the first block of a callout, so the handle sits by its icon; otherwise
10354
11022
  * the block itself.
10355
11023
  */
10356
11024
  blockMenuOwner(blockId) {
@@ -10384,7 +11052,7 @@ var Editor = class {
10384
11052
  /** True if the blocks `a` and `b` are in the same callout. */
10385
11053
  inSameCallout(a, b) {
10386
11054
  const block3 = getBlock(this.state.doc, b);
10387
- const run = block3.type === "quote" && block3.callout ? quoteRun(this.state, b) : null;
11055
+ const run = isCallout(block3) ? quoteRun(this.state, b) : null;
10388
11056
  if (!run) return false;
10389
11057
  const i = blockIndex(this.state.doc, a);
10390
11058
  return i >= run.start && i <= run.end;
@@ -10412,6 +11080,7 @@ var Editor = class {
10412
11080
  */
10413
11081
  openLinkPopover() {
10414
11082
  if (this.readOnly) return false;
11083
+ if (this.modeValue === "source") return false;
10415
11084
  const block3 = getBlock(this.state.doc, this.state.selection.focus.blockId);
10416
11085
  if (isPlainTextBlock(block3)) return false;
10417
11086
  if (isCollapsed(this.state.selection) && !activeLink(this.state)) return false;
@@ -10677,6 +11346,10 @@ var Editor = class {
10677
11346
  this.cleanup.push(() => target.removeEventListener(type, fn, capture));
10678
11347
  }
10679
11348
  };
11349
+ function isCallout(block3) {
11350
+ const kind = quoteKind(block3);
11351
+ return kind !== null && kind !== "quote";
11352
+ }
10680
11353
  function blockName(block3) {
10681
11354
  switch (block3.type) {
10682
11355
  case "listItem":
@@ -10727,6 +11400,16 @@ function taskName(box, fallback) {
10727
11400
  const text = box.closest("[data-block-id]")?.querySelector(".mbe-content")?.textContent?.trim();
10728
11401
  return text || fallback;
10729
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
+ }
10730
11413
 
10731
11414
  // src/extensions/math.ts
10732
11415
  var DOLLAR = 36;
@@ -10736,11 +11419,16 @@ function isWhitespace(ch) {
10736
11419
  function isDigit(ch) {
10737
11420
  return ch !== void 0 && ch >= "0" && ch <= "9";
10738
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
+ }
10739
11427
  var inline = {
10740
11428
  name: "math",
10741
11429
  triggers: "$",
10742
11430
  match(text, pos) {
10743
- if (text.charCodeAt(pos - 1) === DOLLAR) return -1;
11431
+ if (text.charCodeAt(pos - 1) === DOLLAR && !escaped(text, pos - 1)) return -1;
10744
11432
  let openEnd = pos;
10745
11433
  while (text.charCodeAt(openEnd) === DOLLAR) openEnd++;
10746
11434
  const size = openEnd - pos;
@@ -10895,60 +11583,117 @@ function textDecorator(options) {
10895
11583
  }
10896
11584
 
10897
11585
  // src/extensions/tags.ts
10898
- var reWordChar = /[\p{L}\p{M}\p{N}_]/u;
10899
- var reTagChar = /[\p{L}\p{M}\p{N}_\-\p{Extended_Pictographic}\p{Emoji_Modifier}‍️]/u;
10900
- var reTagStart = /[\p{L}\p{N}_\p{Extended_Pictographic}]/u;
10901
- 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
+ );
10902
11595
  function charAt2(text, i) {
10903
11596
  return String.fromCodePoint(text.codePointAt(i));
10904
11597
  }
10905
- function charBefore2(text, i) {
10906
- if (i <= 0) return void 0;
10907
- const c = text.charCodeAt(i - 1);
10908
- 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;
10909
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);
10910
11606
  function segmentEnd(text, i, to) {
10911
- if (i >= to || !reTagStart.test(charAt2(text, i))) return i;
10912
11607
  let j = i;
10913
- 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
+ }
10914
11615
  const ch = charAt2(text, j);
10915
- 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;
10916
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
+ }
10917
11647
  }
10918
11648
  return j;
10919
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
+ }
10920
11660
  function* scanTags(text, from = 0, to = text.length) {
10921
- for (let i = text.indexOf("#", from); i >= 0 && i < to; i = text.indexOf("#", i + 1)) {
10922
- const prev = charBefore2(text, i);
10923
- 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
+ }
10924
11672
  let end = segmentEnd(text, i + 1, to);
10925
- if (end === i + 1) continue;
11673
+ if (end < 0) {
11674
+ i++;
11675
+ continue;
11676
+ }
10926
11677
  while (text[end] === "/") {
10927
11678
  const next = segmentEnd(text, end + 1, to);
10928
- if (next === end + 1) break;
11679
+ if (next < 0) break;
10929
11680
  end = next;
10930
11681
  }
10931
- if (!reTagNeeds.test(text.slice(i + 1, end))) continue;
10932
11682
  yield { from: i, to: end };
10933
- i = end - 1;
11683
+ i = end;
10934
11684
  }
10935
11685
  }
10936
- var reMentionChar = /[\p{L}\p{M}\p{N}_.\-]/u;
10937
- 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]/;
10938
11688
  function* scanMentions(text, from = 0, to = text.length) {
10939
11689
  for (let i = text.indexOf("@", from); i >= 0 && i < to; i = text.indexOf("@", i + 1)) {
10940
- const prev = charBefore2(text, i);
10941
- if (prev !== void 0 && (reWordChar.test(prev) || /[.+\-@]/.test(prev))) continue;
11690
+ if (i > from && reUsernameChar.test(text[i - 1])) continue;
10942
11691
  let end = i + 1;
10943
- if (end >= to || !reMentionStart.test(charAt2(text, end))) continue;
10944
- while (end < to) {
10945
- const ch = charAt2(text, end);
10946
- if (!reMentionChar.test(ch) || end + ch.length > to) break;
10947
- end += ch.length;
10948
- }
10949
- while (end > i + 1 && (text[end - 1] === "." || text[end - 1] === "-")) end--;
10950
- yield { from: i, to: end };
10951
- 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;
10952
11697
  }
10953
11698
  }
10954
11699
  function decorate2(scan, cls, attributes) {
@@ -11066,6 +11811,7 @@ export {
11066
11811
  isPlainTextBlock,
11067
11812
  isTextBlock,
11068
11813
  isTextless,
11814
+ keepQuoteStart,
11069
11815
  linkAt,
11070
11816
  listItem,
11071
11817
  loadMarkdown,
@@ -11080,11 +11826,14 @@ export {
11080
11826
  parseMarkdown,
11081
11827
  plain,
11082
11828
  quote,
11829
+ quoteKind,
11083
11830
  rangeHasMark,
11084
11831
  rawBlock,
11085
11832
  sameCell,
11833
+ sameLink,
11086
11834
  sameMarks,
11087
11835
  samePosition,
11836
+ sameQuote,
11088
11837
  scanMentions,
11089
11838
  scanTags,
11090
11839
  serializeInline,
@@ -11101,8 +11850,10 @@ export {
11101
11850
  textDecorator,
11102
11851
  toPlain,
11103
11852
  tokensAt,
11853
+ unquote,
11104
11854
  withContainerContent,
11105
- withContent
11855
+ withContent,
11856
+ withQuote
11106
11857
  };
11107
11858
  /*! Icons from Lucide (lucide-static 1.55.0), https://lucide.dev
11108
11859
  * ISC License. Copyright (c) 2026 Lucide Icons and Contributors.