svelte-rtf-editor 1.6.0 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -9,6 +9,9 @@
9
9
  onblock?: (tag: string) => void;
10
10
  oninsertlink?: () => void;
11
11
  oninsertimage?: () => void;
12
+ /** The Copy format brush is in hand: the button shows as pressed. */
13
+ copyingFormat?: boolean;
14
+ oncopyformat?: () => void;
12
15
  }
13
16
 
14
17
  let {
@@ -17,7 +20,9 @@
17
20
  onexec,
18
21
  onblock,
19
22
  oninsertlink,
20
- oninsertimage
23
+ oninsertimage,
24
+ copyingFormat = false,
25
+ oncopyformat
21
26
  }: Props = $props();
22
27
 
23
28
  function exec(cmd: string, value: string | null = null) {
@@ -96,6 +101,42 @@
96
101
 
97
102
  <div class="toolbar-divider"></div>
98
103
 
104
+ <!-- Indent -->
105
+ <div class="toolbar-group">
106
+ <ToolbarButton title="Decrease indent (Ctrl+[)" onclick={() => exec('outdent')}>
107
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="3" y1="5" x2="21" y2="5"/><line x1="11" y1="10" x2="21" y2="10"/><line x1="11" y1="14" x2="21" y2="14"/><line x1="3" y1="19" x2="21" y2="19"/><polyline points="7 9 4 12 7 15"/></svg>
108
+ </ToolbarButton>
109
+ <ToolbarButton title="Increase indent (Ctrl+])" onclick={() => exec('indent')}>
110
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="3" y1="5" x2="21" y2="5"/><line x1="11" y1="10" x2="21" y2="10"/><line x1="11" y1="14" x2="21" y2="14"/><line x1="3" y1="19" x2="21" y2="19"/><polyline points="4 9 7 12 4 15"/></svg>
111
+ </ToolbarButton>
112
+ <ToolbarButton title="Decrease hanging indent" onclick={() => exec('hangingOutdent')}>
113
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="3" y1="5" x2="21" y2="5"/><line x1="11" y1="10" x2="21" y2="10"/><line x1="11" y1="14" x2="21" y2="14"/><line x1="11" y1="19" x2="21" y2="19"/><polyline points="7 11.5 4 14.5 7 17.5"/></svg>
114
+ </ToolbarButton>
115
+ <ToolbarButton title="Increase hanging indent" onclick={() => exec('hangingIndent')}>
116
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="3" y1="5" x2="21" y2="5"/><line x1="11" y1="10" x2="21" y2="10"/><line x1="11" y1="14" x2="21" y2="14"/><line x1="11" y1="19" x2="21" y2="19"/><polyline points="4 11.5 7 14.5 4 17.5"/></svg>
117
+ </ToolbarButton>
118
+ <ToolbarButton title="Hang at caret" onclick={() => exec('hangAtCaret')}>
119
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="3" y1="5" x2="7" y2="5"/><line x1="14" y1="5" x2="21" y2="5"/><line x1="10.5" y1="2" x2="10.5" y2="8" stroke="var(--accent, currentColor)"/><line x1="10.5" y1="11" x2="21" y2="11"/><line x1="10.5" y1="15" x2="21" y2="15"/><line x1="10.5" y1="19" x2="21" y2="19"/></svg>
120
+ </ToolbarButton>
121
+ <ToolbarButton title="Decrease right indent" onclick={() => exec('rightOutdent')}>
122
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="3" y1="5" x2="21" y2="5"/><line x1="3" y1="10" x2="13" y2="10"/><line x1="3" y1="14" x2="13" y2="14"/><line x1="3" y1="19" x2="21" y2="19"/><polyline points="17 9 20 12 17 15"/></svg>
123
+ </ToolbarButton>
124
+ <ToolbarButton title="Increase right indent" onclick={() => exec('rightIndent')}>
125
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="3" y1="5" x2="21" y2="5"/><line x1="3" y1="10" x2="13" y2="10"/><line x1="3" y1="14" x2="13" y2="14"/><line x1="3" y1="19" x2="21" y2="19"/><polyline points="20 9 17 12 20 15"/></svg>
126
+ </ToolbarButton>
127
+ </div>
128
+
129
+ <div class="toolbar-divider"></div>
130
+
131
+ <!-- Copy format -->
132
+ <div class="toolbar-group">
133
+ <ToolbarButton active={copyingFormat} title="Copy format" onclick={oncopyformat}>
134
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="14" height="6" rx="1.5"/><path d="M17 6h3v5h-9v3"/><rect x="9.5" y="14" width="3" height="7" rx="1"/></svg>
135
+ </ToolbarButton>
136
+ </div>
137
+
138
+ <div class="toolbar-divider"></div>
139
+
99
140
  <!-- Insert -->
100
141
  <div class="toolbar-group">
101
142
  <ToolbarButton title="Insert link (Ctrl+K)" onclick={oninsertlink}>
@@ -5,6 +5,9 @@ interface Props {
5
5
  onblock?: (tag: string) => void;
6
6
  oninsertlink?: () => void;
7
7
  oninsertimage?: () => void;
8
+ /** The Copy format brush is in hand: the button shows as pressed. */
9
+ copyingFormat?: boolean;
10
+ oncopyformat?: () => void;
8
11
  }
9
12
  declare const Toolbar: import("svelte").Component<Props, {}, "">;
10
13
  type Toolbar = ReturnType<typeof Toolbar>;
@@ -154,6 +154,18 @@ function renderPicture(group) {
154
154
  return `<img src="data:${mime};base64,${base64}"${style} alt="">`;
155
155
  }
156
156
  // ── Tokenizer ──
157
+ /**
158
+ * What \'80 to \'9f stand for in Windows-1252, the code page RTF's \ansi text is written in:
159
+ * curly quotes, dashes, the euro sign and the like, where Latin-1 has invisible control
160
+ * characters. \'92 is the apostrophe in "It's" as TextEdit and many Windows programs write it.
161
+ * The five bytes Windows-1252 leaves undefined (0x81, 0x8D, 0x8F, 0x90, 0x9D) keep their own value.
162
+ */
163
+ const WINDOWS_1252_C1 = [
164
+ 0x20ac, 0x81, 0x201a, 0x0192, 0x201e, 0x2026, 0x2020, 0x2021,
165
+ 0x02c6, 0x2030, 0x0160, 0x2039, 0x0152, 0x8d, 0x017d, 0x8f,
166
+ 0x90, 0x2018, 0x2019, 0x201c, 0x201d, 0x2022, 0x2013, 0x2014,
167
+ 0x02dc, 0x2122, 0x0161, 0x203a, 0x0153, 0x9d, 0x017e, 0x0178
168
+ ];
157
169
  function tokenize(rtf) {
158
170
  const tokens = [];
159
171
  let i = 0;
@@ -179,7 +191,7 @@ function tokenize(rtf) {
179
191
  const hex = rtf.substring(i, i + 2);
180
192
  i += 2;
181
193
  const code = parseInt(hex, 16);
182
- tokens.push({ type: 'text', value: String.fromCharCode(code) });
194
+ tokens.push({ type: 'text', value: String.fromCharCode(WINDOWS_1252_C1[code - 0x80] ?? code) });
183
195
  }
184
196
  // Special escapes
185
197
  else if (next === '\\' || next === '{' || next === '}') {
@@ -361,6 +373,15 @@ const destinationWords = new Set([
361
373
  'latentstyles', 'datastore', 'mmathPr', 'author', 'operator',
362
374
  'title', 'subject', 'doccomm', 'company', 'category', 'keywords'
363
375
  ]);
376
+ /** Twips as a CSS length in points (20 twips), which the writer reads back as the same twips. */
377
+ function twipsToPt(twips) {
378
+ return `${Math.round(twips * 5) / 100}pt`;
379
+ }
380
+ function resetIndents(state) {
381
+ state.leftIndent = 0;
382
+ state.rightIndent = 0;
383
+ state.firstLineIndent = 0;
384
+ }
364
385
  export function rtfToHtml(rtfString, options = {}) {
365
386
  const tokens = tokenize(rtfString);
366
387
  const tree = buildTree(tokens);
@@ -369,6 +390,8 @@ export function rtfToHtml(rtfString, options = {}) {
369
390
  let currentParagraph = '';
370
391
  const paragraphs = [];
371
392
  const paragraphAligns = [];
393
+ const paragraphIndents = [];
394
+ const paragraphFigureIndents = [];
372
395
  const paragraphCaptions = [];
373
396
  let paragraphHasText = false;
374
397
  let paragraphHasListMarker = false;
@@ -377,10 +400,41 @@ export function rtfToHtml(rtfString, options = {}) {
377
400
  function pushParagraph(html, align, isCaption = false) {
378
401
  paragraphs.push(html);
379
402
  paragraphAligns.push(align);
403
+ const inTable = inTableCell || html.startsWith('<table');
404
+ paragraphIndents.push(inTable ? '' : indentStyle());
405
+ paragraphFigureIndents.push(inTable ? '' : figureIndentStyle());
380
406
  paragraphCaptions.push(isCaption);
381
407
  }
382
408
  // Paragraph alignment (reset by \pard, affects cells and paragraphs)
383
409
  let currentAlign = 'left';
410
+ /**
411
+ * The current indents as CSS, in points (20 twips), which the writer reads back as the same
412
+ * \li, \ri and \fi: "margin-left:36pt;text-indent:-36pt". A first line may not start left of
413
+ * the page margin, where a browser would clip it.
414
+ */
415
+ function indentStyle() {
416
+ const { leftIndent, rightIndent, firstLineIndent } = currentState();
417
+ const left = Math.max(0, leftIndent);
418
+ const first = Math.max(-left, firstLineIndent);
419
+ const parts = [];
420
+ if (left > 0)
421
+ parts.push(`margin-left:${twipsToPt(left)}`);
422
+ if (rightIndent > 0)
423
+ parts.push(`margin-right:${twipsToPt(rightIndent)}`);
424
+ if (first !== 0)
425
+ parts.push(`text-indent:${twipsToPt(first)}`);
426
+ return parts.join(';');
427
+ }
428
+ /**
429
+ * The indent of a picture's paragraph: where its one line starts, as a left margin. A figure
430
+ * is written back with a left indent only, and a first-line indent on it would be passed on to
431
+ * its caption.
432
+ */
433
+ function figureIndentStyle() {
434
+ const { leftIndent, firstLineIndent } = currentState();
435
+ const start = Math.max(0, leftIndent) + Math.max(-Math.max(0, leftIndent), firstLineIndent);
436
+ return start > 0 ? `margin-left:${twipsToPt(start)}` : '';
437
+ }
384
438
  // Table state
385
439
  let tableRows = [];
386
440
  let currentRowCells = [];
@@ -421,6 +475,9 @@ export function rtfToHtml(rtfString, options = {}) {
421
475
  fontIndex: 0,
422
476
  ucSkip: 1,
423
477
  inList: false,
478
+ leftIndent: 0,
479
+ rightIndent: 0,
480
+ firstLineIndent: 0,
424
481
  };
425
482
  }
426
483
  const stateStack = [defaultState()];
@@ -626,6 +683,15 @@ export function rtfToHtml(rtfString, options = {}) {
626
683
  case 'qj':
627
684
  currentAlign = 'justify';
628
685
  break;
686
+ case 'li':
687
+ state.leftIndent = p ?? 0;
688
+ break;
689
+ case 'ri':
690
+ state.rightIndent = p ?? 0;
691
+ break;
692
+ case 'fi':
693
+ state.firstLineIndent = p ?? 0;
694
+ break;
629
695
  case 'par':
630
696
  if (!inTableCell)
631
697
  flushParagraph();
@@ -682,6 +748,9 @@ export function rtfToHtml(rtfString, options = {}) {
682
748
  currentRowCellRights = [];
683
749
  currentRowCellAligns = [];
684
750
  inTableCell = false;
751
+ // The cell's indents end with the table, in whichever group set them:
752
+ // \row may sit in a group of its own ({\row}).
753
+ stateStack.forEach(resetIndents);
685
754
  break;
686
755
  case 'pard':
687
756
  state.bold = false;
@@ -689,6 +758,7 @@ export function rtfToHtml(rtfString, options = {}) {
689
758
  state.underline = false;
690
759
  state.strike = false;
691
760
  currentAlign = 'left';
761
+ resetIndents(state);
692
762
  break;
693
763
  case 'line':
694
764
  currentParagraph += '<br>';
@@ -812,6 +882,11 @@ export function rtfToHtml(rtfString, options = {}) {
812
882
  for (let i = 0; i < trimmedParagraphs.length; i++) {
813
883
  const trimmed = trimmedParagraphs[i];
814
884
  const align = paragraphAligns[i] ?? 'left';
885
+ // The paragraph's style attribute: its alignment, then its indents.
886
+ const blockStyle = [align !== 'left' ? `text-align:${align}` : '', paragraphIndents[i] ?? '']
887
+ .filter(Boolean)
888
+ .join(';');
889
+ const styleAttr = blockStyle ? ` style="${blockStyle}"` : '';
815
890
  const prev = i > 0 ? trimmedParagraphs[i - 1] : '';
816
891
  const next = i + 1 < trimmedParagraphs.length ? trimmedParagraphs[i + 1] : '';
817
892
  if (!trimmed) {
@@ -844,8 +919,10 @@ export function rtfToHtml(rtfString, options = {}) {
844
919
  // A paragraph holding nothing but pictures becomes a figure, so it can carry
845
920
  // a caption and be aligned/resized as a unit in the editor.
846
921
  if (IMAGE_ONLY_PARAGRAPH.test(trimmed)) {
847
- const alignAttr = align !== 'left' ? ` style="text-align:${align}"` : '';
848
- rendered.push(`<figure${alignAttr}>${trimmed}</figure>`);
922
+ const figureStyle = [align !== 'left' ? `text-align:${align}` : '', paragraphFigureIndents[i] ?? '']
923
+ .filter(Boolean)
924
+ .join(';');
925
+ rendered.push(`<figure${figureStyle ? ` style="${figureStyle}"` : ''}>${trimmed}</figure>`);
849
926
  continue;
850
927
  }
851
928
  const sizeMatch = trimmed.match(/font-size:\s*([\d.]+)pt/);
@@ -853,27 +930,25 @@ export function rtfToHtml(rtfString, options = {}) {
853
930
  // Compared in half-points, rounded the way the writer rounds them, so
854
931
  // a heading written at any body size is read back as the same level.
855
932
  const halfPoints = Math.round(parseFloat(sizeMatch[1]) * 2);
856
- const alignAttr = align !== 'left' ? ` style="text-align:${align}"` : '';
857
933
  const atLeast = (scale) => halfPoints >= Math.round(bodySize * scale);
858
934
  // At the default 12 pt, size alone makes a heading, as it always has. At
859
935
  // another screen size, ordinary 12 pt text can be a step above the body,
860
936
  // so a heading must also be bold, as every heading the writer emits is.
861
937
  const looksLikeHeading = bodySize === 24 || /^<strong>/.test(trimmed);
862
938
  if (looksLikeHeading && atLeast(HEADING_SCALE.h1)) {
863
- rendered.push(`<h1${alignAttr}>${stripSizeSpan(trimmed)}</h1>`);
939
+ rendered.push(`<h1${styleAttr}>${stripSizeSpan(trimmed)}</h1>`);
864
940
  continue;
865
941
  }
866
942
  if (looksLikeHeading && atLeast(HEADING_SCALE.h2)) {
867
- rendered.push(`<h2${alignAttr}>${stripSizeSpan(trimmed)}</h2>`);
943
+ rendered.push(`<h2${styleAttr}>${stripSizeSpan(trimmed)}</h2>`);
868
944
  continue;
869
945
  }
870
946
  if (looksLikeHeading && atLeast(HEADING_SCALE.h3)) {
871
- rendered.push(`<h3${alignAttr}>${stripSizeSpan(trimmed)}</h3>`);
947
+ rendered.push(`<h3${styleAttr}>${stripSizeSpan(trimmed)}</h3>`);
872
948
  continue;
873
949
  }
874
950
  }
875
- const pStyle = align !== 'left' ? ` style="text-align:${align}"` : '';
876
- rendered.push(`<p${pStyle}>${trimmed}</p>`);
951
+ rendered.push(`<p${styleAttr}>${trimmed}</p>`);
877
952
  }
878
953
  const output = rendered.join('\n');
879
954
  // fontTable is parsed (for future font rendering) but not yet used in output
@@ -287,9 +287,10 @@ function imageBody(el) {
287
287
  const label = el.getAttribute('alt') || el.getAttribute('src') || 'image';
288
288
  return `\\i [Image: ${escapeRtf(label)}]\\i0 `;
289
289
  }
290
- /** \ql / \qc / \qr for a figure's text-align. */
290
+ /** \ql / \qc / \qr / \qj for a block's text-align. */
291
291
  function alignControl(el) {
292
- const align = (el.style?.textAlign || '').toLowerCase();
292
+ // Firefox's Center writes <p align="center">, not a style.
293
+ const align = (el.style?.textAlign || el.getAttribute?.('align') || '').toLowerCase();
293
294
  if (align === 'center')
294
295
  return '\\qc';
295
296
  if (align === 'right')
@@ -381,6 +382,27 @@ export function estimateRtfBytes(editorEl) {
381
382
  // A tab that shows is written as "\tab " (5) and counted as 1; counting every tab that way
382
383
  // can only overestimate.
383
384
  total += ((editorEl.textContent || '').match(/\t/g)?.length ?? 0) * 4;
385
+ // A block's alignment (\qc, 3) and left indent (\liN, up to 7) are written per paragraph,
386
+ // for every block inside an indented one too: count 12 for each block that could carry them.
387
+ // A paragraph's own right indent (\\riN) and first-line indent (\\fi-N) are up to 8 more each.
388
+ for (const block of Array.from(editorEl.querySelectorAll('p, div, li, h1, h2, h3, h4, h5, h6, pre, blockquote'))) {
389
+ if (block.closest('[style*="margin"], [style*="text-align"], [align]'))
390
+ total += 12;
391
+ if (block.style?.marginRight)
392
+ total += 8;
393
+ if (block.style?.textIndent)
394
+ total += 8;
395
+ }
396
+ // Each paragraph's formatting, worked out once: a blank line looks at the one before it.
397
+ const formatCache = new Map();
398
+ const ownFormat = (el) => {
399
+ let format = formatCache.get(el);
400
+ if (format === undefined) {
401
+ format = `${alignOf(el)}${paragraphControls(el, leftMarginTwips(el))}`;
402
+ formatCache.set(el, format);
403
+ }
404
+ return format;
405
+ };
384
406
  for (const el of Array.from(editorEl.querySelectorAll('*'))) {
385
407
  const tag = el.tagName.toLowerCase();
386
408
  total += BLOCK_OVERHEAD_BYTES[tag] ?? 0;
@@ -396,6 +418,15 @@ export function estimateRtfBytes(editorEl) {
396
418
  // writes one paragraph per item, so the item is counted, not the list.
397
419
  if (CELL_PARAGRAPH_TAGS.has(tag) && el.closest('td, th'))
398
420
  total += 6;
421
+ // A paragraph's own formatting costs its controls, and a blank line after one restates
422
+ // \pard (5); counting both on every such paragraph can only overestimate. The indent of
423
+ // the blocks around it is counted above.
424
+ if ((tag === 'p' || tag === 'div') && !el.closest('td, th')) {
425
+ const para = ownFormat(el);
426
+ const prev = el.previousElementSibling;
427
+ if (para || (prev && formatCache.get(prev)))
428
+ total += para.length + 6;
429
+ }
399
430
  // Every cell in a row with a header cell carries \clbrdrb\brdrs.
400
431
  if (tag === 'td' && el.parentElement?.querySelector(':scope > th'))
401
432
  total += 14;
@@ -527,7 +558,8 @@ export function htmlToRtf(editorEl, options = {}) {
527
558
  size: bodySize,
528
559
  color: 0,
529
560
  script: null,
530
- mono: false
561
+ mono: false,
562
+ indent: 0
531
563
  });
532
564
  const rtf = '{\\rtf1\\ansi\\ansicpg1252\\deff0' +
533
565
  fontTable +
@@ -570,6 +602,8 @@ function walkChildren(parent, ctx) {
570
602
  const tabsShow = ctx.inPre || showsTabs(node);
571
603
  if (!tabsShow && COLLAPSIBLE_WHITESPACE.test(text) && besideBlock(node))
572
604
  continue;
605
+ if (!ctx.inPre)
606
+ rtf += restateAfterBlock(node, ctx);
573
607
  if (ctx.inPre) {
574
608
  // Split before escaping — escapeRtf collapses newlines, so the
575
609
  // line structure a <pre> block depends on has to become \line
@@ -585,21 +619,24 @@ function walkChildren(parent, ctx) {
585
619
  continue;
586
620
  const el = node;
587
621
  const tag = el.tagName.toLowerCase();
622
+ // A picture directly under the root writes its own paragraph.
623
+ if (!isBlock(el) && !(tag === 'img' && el.parentNode === ctx.root))
624
+ rtf += restateAfterBlock(el, ctx);
588
625
  switch (tag) {
589
626
  // Heading sizes keep their ratio to the body (HEADING_SCALE).
590
627
  case 'h1': {
591
628
  const size = scaled(ctx, HEADING_SCALE.h1);
592
- rtf += `\\pard${inCell(ctx)}\\f0\\fs${size}\\b ${walkChildren(el, { ...ctx, bold: true, size })}${ctx.bold ? '' : '\\b0'}\\fs${ctx.size}\\par `;
629
+ rtf += `\\pard${inCell(ctx)}${headingLayout(el, ctx)}\\f0\\fs${size}\\b ${walkChildren(el, { ...ctx, bold: true, size })}${ctx.bold ? '' : '\\b0'}\\fs${ctx.size}\\par `;
593
630
  break;
594
631
  }
595
632
  case 'h2': {
596
633
  const size = scaled(ctx, HEADING_SCALE.h2);
597
- rtf += `\\pard${inCell(ctx)}\\f0\\fs${size}\\b ${walkChildren(el, { ...ctx, bold: true, size })}${ctx.bold ? '' : '\\b0'}\\fs${ctx.size}\\par `;
634
+ rtf += `\\pard${inCell(ctx)}${headingLayout(el, ctx)}\\f0\\fs${size}\\b ${walkChildren(el, { ...ctx, bold: true, size })}${ctx.bold ? '' : '\\b0'}\\fs${ctx.size}\\par `;
598
635
  break;
599
636
  }
600
637
  case 'h3': {
601
638
  const size = scaled(ctx, HEADING_SCALE.h3);
602
- rtf += `\\pard${inCell(ctx)}\\f0\\fs${size}\\b ${walkChildren(el, { ...ctx, bold: true, size })}${ctx.bold ? '' : '\\b0'}\\fs${ctx.size}\\par `;
639
+ rtf += `\\pard${inCell(ctx)}${headingLayout(el, ctx)}\\f0\\fs${size}\\b ${walkChildren(el, { ...ctx, bold: true, size })}${ctx.bold ? '' : '\\b0'}\\fs${ctx.size}\\par `;
603
640
  break;
604
641
  }
605
642
  case 'p':
@@ -613,9 +650,11 @@ function walkChildren(parent, ctx) {
613
650
  // the two lines run together.
614
651
  const afterLooseText = followsInlineContent(el);
615
652
  if (ctx.inTableCell) {
653
+ // Alignment or an indent needs a paragraph of its own, even as the cell's first.
654
+ const layout = paragraphLayout(el, ctx);
616
655
  const restate = afterLooseText
617
- ? '\\par \\pard\\intbl '
618
- : el.previousElementSibling ? '\\pard\\intbl ' : '';
656
+ ? `\\par \\pard\\intbl${layout} `
657
+ : el.previousElementSibling || layout ? `\\pard\\intbl${layout} ` : '';
619
658
  if (isBlankLine(el)) {
620
659
  rtf += `${restate}\\par `;
621
660
  break;
@@ -627,17 +666,38 @@ function walkChildren(parent, ctx) {
627
666
  : `${restate}${inner}\\par `;
628
667
  break;
629
668
  }
669
+ // A <div> that holds blocks (pasted content wraps paragraphs in one) is not a
670
+ // paragraph itself: each block inside writes its own \\pard, which would drop the
671
+ // div's indent, and the div's own \\par would add a blank line. Its left margin is
672
+ // carried into the blocks instead, and loose text in it gets a paragraph.
673
+ if (tag === 'div' && Array.from(el.children).some(isBlock)) {
674
+ const indent = ctx.indent + leftMarginTwips(el);
675
+ const colorIdx = colorIndexOf(el, ctx);
676
+ const inner = { ...ctx, indent, color: colorIdx ?? ctx.color };
677
+ const lead = startsWithInline(el) ? `\\pard${liControl(indent)} ` : '';
678
+ const tail = endsWithInline(el) ? '\\par ' : '';
679
+ const colorPrefix = colorIdx != null ? `\\cf${colorIdx} ` : '';
680
+ const colorSuffix = colorIdx != null ? `\\cf${ctx.color} ` : '';
681
+ rtf += `${afterLooseText ? '\\par ' : ''}${lead}${colorPrefix}${walkChildren(el, inner)}${colorSuffix}${tail}`;
682
+ break;
683
+ }
684
+ // The paragraph's alignment, indents, spacing, keep-with-next and tab stops, if it
685
+ // sets any.
686
+ const para = paragraphFormat(el, ctx);
630
687
  // A <p> with no children or only a single <br> is a blank line —
631
688
  // emit a bare \par rather than \pard \line\par, which adds an extra line.
689
+ // A bare \par keeps the formatting of the paragraph before it, so a blank line after a
690
+ // formatted paragraph, or with formatting of its own, restates \pard.
632
691
  if (isBlankLine(el)) {
633
- rtf += afterLooseText ? '\\par \\par ' : '\\par ';
692
+ const reset = para || followsFormattedParagraph(el, ctx) ? `\\pard${para} ` : '';
693
+ rtf += `${afterLooseText ? '\\par ' : ''}${reset}\\par `;
634
694
  break;
635
695
  }
636
696
  const colorIdx = colorIndexOf(el, ctx);
637
697
  const inlineRtf = walkChildren(el, colorIdx != null ? { ...ctx, color: colorIdx } : ctx);
638
698
  const colorPrefix = colorIdx != null ? `\\cf${colorIdx} ` : '';
639
699
  const colorSuffix = colorIdx != null ? `\\cf${ctx.color} ` : '';
640
- rtf += `${afterLooseText ? '\\par ' : ''}\\pard ${colorPrefix}${inlineRtf}${colorSuffix}\\par `;
700
+ rtf += `${afterLooseText ? '\\par ' : ''}\\pard${para} ${colorPrefix}${inlineRtf}${colorSuffix}\\par `;
641
701
  break;
642
702
  }
643
703
  case 'table': {
@@ -677,12 +737,25 @@ function walkChildren(parent, ctx) {
677
737
  }
678
738
  break;
679
739
  }
680
- case 'blockquote':
681
- rtf += `\\pard${inCell(ctx)}\\li720\\i ${walkChildren(el, { ...ctx, italic: true })}${ctx.italic ? '' : '\\i0'}\\par `;
740
+ case 'blockquote': {
741
+ // The browser's Indent wraps the lines in a blockquote with a left margin and
742
+ // border: none (Chromium, WebKit, Gmail): that is an indent, not a quotation, so it
743
+ // is not italic. A quotation is indented half an inch, plus any margin of its own.
744
+ // Either way the blocks inside carry the indent, and loose text gets a paragraph.
745
+ const quote = !isIndentBlockquote(el);
746
+ const indent = ctx.indent + leftMarginTwips(el) + (quote ? 720 : 0);
747
+ const inner = { ...ctx, indent, italic: ctx.italic || quote };
748
+ const lead = startsWithInline(el) ? `\\pard${inCell(ctx)}${liControl(indent)}` : '';
749
+ const tail = endsWithInline(el) ? '\\par ' : '';
750
+ const content = walkChildren(el, inner);
751
+ const italicOn = quote && !ctx.italic;
752
+ const italicOff = italicOn ? (tail ? '\\i0' : '\\i0 ') : '';
753
+ rtf += `${lead}${italicOn ? '\\i ' : lead ? ' ' : ''}${content}${italicOff}${tail}`;
682
754
  break;
755
+ }
683
756
  case 'pre': {
684
757
  const size = scaled(ctx, PRE_SCALE);
685
- rtf += `\\pard${inCell(ctx)}\\f1\\fs${size} ${walkChildren(el, { ...ctx, inPre: true, size })}\\f0\\fs${ctx.size}\\par `;
758
+ rtf += `\\pard${inCell(ctx)}${liControl(ctx.indent + leftMarginTwips(el))}\\f1\\fs${size} ${walkChildren(el, { ...ctx, inPre: true, size })}\\f0\\fs${ctx.size}\\par `;
686
759
  break;
687
760
  }
688
761
  case 'hr':
@@ -690,16 +763,18 @@ function walkChildren(parent, ctx) {
690
763
  break;
691
764
  case 'ul': {
692
765
  const items = el.querySelectorAll(':scope > li');
693
- items.forEach((li) => {
694
- rtf += `\\pard${inCell(ctx)}\\li720\\fi-360\\bullet\\tab ${walkChildren(li, ctx)}\\par `;
766
+ const li = liControl(ctx.indent + leftMarginTwips(el) + 720);
767
+ items.forEach((item) => {
768
+ rtf += `\\pard${inCell(ctx)}${li}\\fi-360\\bullet\\tab ${walkChildren(item, ctx)}\\par `;
695
769
  });
696
770
  break;
697
771
  }
698
772
  case 'ol': {
699
773
  let counter = 1;
700
774
  const items = el.querySelectorAll(':scope > li');
701
- items.forEach((li) => {
702
- rtf += `\\pard${inCell(ctx)}\\li720\\fi-360 ${counter}.\\tab ${walkChildren(li, ctx)}\\par `;
775
+ const li = liControl(ctx.indent + leftMarginTwips(el) + 720);
776
+ items.forEach((item) => {
777
+ rtf += `\\pard${inCell(ctx)}${li}\\fi-360 ${counter}.\\tab ${walkChildren(item, ctx)}\\par `;
703
778
  counter++;
704
779
  });
705
780
  break;
@@ -764,7 +839,7 @@ function walkChildren(parent, ctx) {
764
839
  case 'figure': {
765
840
  const img = el.querySelector('img');
766
841
  const caption = (el.querySelector('figcaption')?.textContent || '').trim();
767
- const align = alignControl(el);
842
+ const align = `${alignControl(el)}${liControl(ctx.indent + leftMarginTwips(el))}`;
768
843
  if (img)
769
844
  rtf += `\\pard${inCell(ctx)}${align} ${imageBody(img)}\\par `;
770
845
  else
@@ -851,6 +926,29 @@ function followsInlineContent(el) {
851
926
  return true;
852
927
  return prev.nodeType === Node.ELEMENT_NODE && !isBlock(prev);
853
928
  }
929
+ /** Blocks whose last paragraph always carries an indent or alignment of its own. */
930
+ const FORMATTED_BLOCK_TAGS = new Set(['ul', 'ol', 'blockquote', 'figure', 'hr']);
931
+ /**
932
+ * Loose text or an inline element right after a block has no paragraph of its own, and would
933
+ * keep that block's alignment and indent (a centered line's \qc, a list's \li). Start a plain
934
+ * one, at the indent of the blocks around it. After a block with no formatting of its own,
935
+ * nothing is written, as before.
936
+ */
937
+ function restateAfterBlock(node, ctx) {
938
+ let prev = node.previousSibling;
939
+ while (prev && prev.nodeType === Node.TEXT_NODE && COLLAPSIBLE_WHITESPACE.test(prev.textContent || '')) {
940
+ prev = prev.previousSibling;
941
+ }
942
+ if (!isBlock(prev))
943
+ return '';
944
+ const block = prev;
945
+ const tag = block.tagName.toLowerCase();
946
+ const formatted = FORMATTED_BLOCK_TAGS.has(tag) ||
947
+ (['p', 'div'].includes(tag) && (ctx.inTableCell ? paragraphLayout(block, ctx) : paragraphFormat(block, ctx)) !== '') ||
948
+ (['h1', 'h2', 'h3'].includes(tag) && headingLayout(block, ctx) !== '') ||
949
+ (tag === 'pre' && ctx.indent + leftMarginTwips(block) > 0);
950
+ return formatted ? `\\pard${inCell(ctx)}${liControl(ctx.indent)} ` : '';
951
+ }
854
952
  /**
855
953
  * The cell's own \par ends its last paragraph, so that paragraph's mark is dropped. Only a
856
954
  * real control word: "\par " preceded by an odd run of backslashes is escaped text.
@@ -863,6 +961,138 @@ function withoutTrailingPar(content) {
863
961
  slashes++;
864
962
  return slashes % 2 === 0 ? content.slice(0, -5) : content;
865
963
  }
964
+ // ── Paragraph formatting ──
965
+ const TWIPS_PER_UNIT = { in: 1440, pt: 20, cm: 1440 / 2.54, mm: 144 / 2.54, px: TWIPS_PER_PX };
966
+ /**
967
+ * A CSS length in whole twips, or null when it cannot be read: a unit other than in, pt, cm, mm or
968
+ * px, a percentage, a keyword, or a negative value where one is not allowed.
969
+ */
970
+ function lengthTwips(value, allowNegative = false) {
971
+ const m = (value ?? '').trim().toLowerCase().match(/^(-?\d+(?:\.\d+)?|-?\.\d+)(in|pt|cm|mm|px)$/);
972
+ if (!m)
973
+ return null;
974
+ const twips = Math.round(parseFloat(m[1]) * TWIPS_PER_UNIT[m[2]]);
975
+ if (twips < 0 && !allowNegative)
976
+ return null;
977
+ return twips;
978
+ }
979
+ /**
980
+ * An element's own left margin in twips, from its inline style: what the browser's Indent sets
981
+ * (Firefox puts margin-left on the paragraph; Chromium and WebKit on a wrapping blockquote).
982
+ * Units a reader cannot pin to a length (%, em) count as none.
983
+ */
984
+ function leftMarginTwips(el) {
985
+ return lengthTwips(el.style?.marginLeft) ?? 0;
986
+ }
987
+ /**
988
+ * The indent shape Chromium, WebKit and Gmail write: a blockquote with border: none, where a
989
+ * quotation keeps its border. The editor's Indent reads it the same way.
990
+ */
991
+ function isIndentBlockquote(el) {
992
+ return el.style?.borderLeftStyle === 'none';
993
+ }
994
+ /** \liN for a left indent in twips, or nothing when there is none. */
995
+ function liControl(twips) {
996
+ return twips > 0 ? `\\li${twips}` : '';
997
+ }
998
+ /** \qc, \qr or \qj; left is the default and is not written. */
999
+ function alignOf(el) {
1000
+ const align = alignControl(el);
1001
+ return align === '\\ql' ? '' : align;
1002
+ }
1003
+ /**
1004
+ * A heading's, or a paragraph's inside a table cell: its alignment, and \liN for the indent of
1005
+ * the blocks around it plus its own margin.
1006
+ */
1007
+ function paragraphLayout(el, ctx) {
1008
+ return `${alignOf(el)}${liControl(ctx.indent + leftMarginTwips(el))}`;
1009
+ }
1010
+ /**
1011
+ * A heading's layout: its alignment and left indent, and outside a table cell its right and
1012
+ * first-line indents too, so a heading read from RTF with a hanging number goes back as it came.
1013
+ */
1014
+ function headingLayout(el, ctx) {
1015
+ return `${paragraphLayout(el, ctx)}${ctx.inTableCell ? '' : edgeIndents(el)}`;
1016
+ }
1017
+ /** \\riN for margin-right and \\fiN for text-indent, or nothing where the element sets none. */
1018
+ function edgeIndents(el) {
1019
+ const ri = lengthTwips(el.style?.marginRight);
1020
+ const fi = lengthTwips(el.style?.textIndent, true);
1021
+ return `${ri ? `\\ri${ri}` : ''}${fi ? `\\fi${fi}` : ''}`;
1022
+ }
1023
+ /**
1024
+ * A <p> or <div>'s formatting outside a table cell: its alignment, then paragraphControls with the
1025
+ * indent of the blocks around it plus its own margin.
1026
+ */
1027
+ function paragraphFormat(el, ctx) {
1028
+ return `${alignOf(el)}${paragraphControls(el, ctx.indent + leftMarginTwips(el))}`;
1029
+ }
1030
+ /**
1031
+ * The RTF paragraph controls for a <p> or <div>'s own formatting, or '' when it sets none:
1032
+ *
1033
+ * | HTML | RTF |
1034
+ * |--------------------------------------------------|-------------------|
1035
+ * | data-rtf-tab-stops="1.75in" (comma-separated) | \tx2520 |
1036
+ * | margin-left: 1.75in (the left indent, given) | \li2520 |
1037
+ * | margin-right: 0.5in | \ri720 |
1038
+ * | text-indent: -1.75in | \fi-2520 |
1039
+ * | margin-top: 5pt / margin-bottom: 5pt | \sb100 / \sa100 |
1040
+ * | break-after: avoid, or page-break-after: avoid | \keepn |
1041
+ *
1042
+ * CSS has no absolute tab stop, hence the data- attribute. A value that cannot be read writes
1043
+ * nothing, and so does zero, which is what \pard already sets. Not written inside a table cell,
1044
+ * where the cell declares its own paragraph.
1045
+ */
1046
+ function paragraphControls(el, leftTwips) {
1047
+ let out = '';
1048
+ const stops = (el.getAttribute('data-rtf-tab-stops') ?? '')
1049
+ .split(',')
1050
+ .map((v) => lengthTwips(v))
1051
+ .filter((t) => t != null && t > 0);
1052
+ for (const t of Array.from(new Set(stops)).sort((a, b) => a - b))
1053
+ out += `\\tx${t}`;
1054
+ out += liControl(leftTwips);
1055
+ const style = el.style;
1056
+ if (!style)
1057
+ return out;
1058
+ out += edgeIndents(el);
1059
+ const sb = lengthTwips(style.marginTop);
1060
+ if (sb)
1061
+ out += `\\sb${sb}`;
1062
+ const sa = lengthTwips(style.marginBottom);
1063
+ if (sa)
1064
+ out += `\\sa${sa}`;
1065
+ const keep = (prop) => style.getPropertyValue(prop).trim() === 'avoid';
1066
+ if (keep('break-after') || keep('page-break-after'))
1067
+ out += '\\keepn';
1068
+ return out;
1069
+ }
1070
+ /** Whether the nearest element before this one is a <p> or <div> with formatting of its own. */
1071
+ function followsFormattedParagraph(el, ctx) {
1072
+ const prev = el.previousElementSibling;
1073
+ if (!prev)
1074
+ return false;
1075
+ const tag = prev.tagName.toLowerCase();
1076
+ return (tag === 'p' || tag === 'div') && paragraphFormat(prev, ctx) !== '';
1077
+ }
1078
+ /** Whether a container's first (or last) content is loose text or an inline element, not a block. */
1079
+ function startsWithInline(el) {
1080
+ return edgeIsInline(el, 'first');
1081
+ }
1082
+ function endsWithInline(el) {
1083
+ return edgeIsInline(el, 'last');
1084
+ }
1085
+ function edgeIsInline(el, edge) {
1086
+ const nodes = Array.from(el.childNodes);
1087
+ if (edge === 'last')
1088
+ nodes.reverse();
1089
+ for (const n of nodes) {
1090
+ if (n.nodeType === Node.TEXT_NODE && COLLAPSIBLE_WHITESPACE.test(n.textContent || ''))
1091
+ continue;
1092
+ return !isBlock(n);
1093
+ }
1094
+ return false;
1095
+ }
866
1096
  /** \intbl for a paragraph a block writes inside a table cell, so it stays in the cell. */
867
1097
  function inCell(ctx) {
868
1098
  return ctx.inTableCell ? '\\intbl' : '';