svelte-rtf-editor 1.12.0 → 1.15.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.
@@ -11,7 +11,22 @@
11
11
  *
12
12
  * \cb (character background) is silently ignored on import.
13
13
  */
14
- import { HEADING_SCALE, PRE_SCALE, LINK_COLOR, isMonospaceFontName, linkTarget, normalizeFontSize } from './rtf-writer.js';
14
+ import { HEADING_SCALE, PRE_SCALE, LINK_COLOR, DEFAULT_FONT_FAMILY, fontChoices, fontKey, isMonospaceFontName, linkTarget, normalizeFontSize, hardToReadOnWhite, LEAST_LINES } from './rtf-writer.js';
15
+ import { LEAST_MARKER_GAP, MOST_MARKER_GAP, letterReadings, listTypeAttribute } from './list-markers.js';
16
+ /** The lines RTF names that CSS has too; any other is a plain line. */
17
+ const BORDER_LINE_CSS = new Map(Object.entries({ brdrdb: 'double', brdrdot: 'dotted', brdrdash: 'dashed', brdrdashsm: 'dashed', brdrdashd: 'dashed', brdrdashdd: 'dashed' }));
18
+ /**
19
+ * A cell's borders as CSS, which the writer reads back as the same: "border:1px solid;" where
20
+ * all four are one, else each side that has one. A width is given in px, 15 twips each, as
21
+ * the writer counts them.
22
+ */
23
+ function bordersStyle(borders) {
24
+ const css = (b) => b ? `${Math.round((Math.max(1, Math.min(b.twips, 75)) / 15) * 100) / 100}px ${b.line}${b.color ? ` ${b.color}` : ''}` : '';
25
+ const sides = [css(borders.t), css(borders.r), css(borders.b), css(borders.l)];
26
+ if (sides[0] && sides.every((side) => side === sides[0]))
27
+ return `border:${sides[0]};`;
28
+ return ['top', 'right', 'bottom', 'left'].map((name, i) => (sides[i] ? `border-${name}:${sides[i]};` : '')).join('');
29
+ }
15
30
  // ── Highlight palette (RTF \highlight 1-16) ──
16
31
  const HIGHLIGHT_COLORS = {
17
32
  1: '#000000', // Black
@@ -57,6 +72,8 @@ const HEX_NIBBLE = (() => {
57
72
  const TAB_HTML = '<span style="white-space:pre">\t</span>';
58
73
  /** Text so far holding only a list marker: a bullet, or a number and a period. */
59
74
  const LIST_MARKER = /^\s*(?:\u2022|(\d+)\.)\s*$/;
75
+ /** The same for an item numbered in letters or Roman numerals: "C.", "iv.". */
76
+ const LETTER_MARKER = /^\s*([A-Z]{1,15}|[a-z]{1,15})\.\s*$/;
60
77
  /**
61
78
  * The bullet Word writes inside {\listtext …} and {\pntext …}: byte B7 of the Symbol font, which
62
79
  * arrives as a middle dot or as the font's private-use character.
@@ -70,6 +87,14 @@ const ONLY_SPACES = /^[ \t\r\n\f]*$/;
70
87
  const RULE_DASHES = '\u2014'.repeat(20);
71
88
  /** A hanging indent of this many twips is the one the writer gives a list item (\fi-360). */
72
89
  const LIST_HANG = 360;
90
+ /**
91
+ * Whether a paragraph hangs as a list item does: its first line out by a gap a list can have
92
+ * (see markerGapTwips), and no further than the page. A list hung by any such gap is read as a
93
+ * list with that gap, which is written back the same.
94
+ */
95
+ function hangsAsItem(first, left) {
96
+ return -first >= LEAST_MARKER_GAP && -first <= MOST_MARKER_GAP && left >= -first;
97
+ }
73
98
  /** The longest number a numbered list item is read with. */
74
99
  const MAX_LIST_NUMBER_DIGITS = 9;
75
100
  /** Each level of a list is indented this much further (\li720). */
@@ -209,6 +234,42 @@ function renderPicture(group) {
209
234
  const style = styles.length ? ` style="${styles.join(';')}"` : '';
210
235
  return `<img src="data:${mime};base64,${base64}"${style} alt="">`;
211
236
  }
237
+ /**
238
+ * The pictures of an RTF document, in the order they are in it: each as the data address a
239
+ * browser shows (PNG or JPEG), or null for one it cannot show (a metafile).
240
+ *
241
+ * Word copies a picture to the clipboard twice: in its HTML as the address of a file on the
242
+ * writer's own disk, which no page may open, and in its RTF as the picture itself. So the
243
+ * pictures of a paste are read from here (see pastePictures). The second copy Word writes of
244
+ * each for older readers (\nonshppict, and a shape's \shprslt) is not counted.
245
+ */
246
+ export function rtfPictures(rtf) {
247
+ let tree;
248
+ try {
249
+ tree = parseTree(rtf);
250
+ }
251
+ catch {
252
+ return [];
253
+ }
254
+ const pictures = [];
255
+ const todo = [tree];
256
+ while (todo.length > 0) {
257
+ const group = todo.pop();
258
+ const first = group.children.find((n) => n.type === 'control' && n.word !== '*');
259
+ if (first?.word === 'nonshppict' || first?.word === 'shprslt')
260
+ continue;
261
+ if (first?.word === 'pict') {
262
+ pictures.push(/ src="([^"]+)"/.exec(renderPicture(group))?.[1] ?? null);
263
+ continue;
264
+ }
265
+ for (let i = group.children.length - 1; i >= 0; i--) {
266
+ const child = group.children[i];
267
+ if (child.type === 'group')
268
+ todo.push(child);
269
+ }
270
+ }
271
+ return pictures;
272
+ }
212
273
  // ── Tokenizer ──
213
274
  /**
214
275
  * What \'80 to \'9f stand for in Windows-1252, the code page RTF's \ansi text is written in:
@@ -508,6 +569,7 @@ function symbolText(text) {
508
569
  function readFontTable(group) {
509
570
  const mono = new Set();
510
571
  const symbol = new Set();
572
+ const names = new Map();
511
573
  let num = null;
512
574
  let name = '';
513
575
  let fixed = false;
@@ -518,6 +580,7 @@ function readFontTable(group) {
518
580
  mono.add(num);
519
581
  if (symbolSet && isSymbolFontName(name))
520
582
  symbol.add(num);
583
+ names.set(num, name.trim());
521
584
  }
522
585
  num = null;
523
586
  name = '';
@@ -557,7 +620,20 @@ function readFontTable(group) {
557
620
  }
558
621
  read(group.children.filter((n) => n.type !== 'group'));
559
622
  finish();
560
- return { mono, symbol };
623
+ return { mono, symbol, names };
624
+ }
625
+ /**
626
+ * A font name as programs that name each cut of a font write it, brought back to the family:
627
+ * TextEdit's "Helvetica-Bold", "TimesNewRomanPS-ItalicMT" and "ArialMT" are Helvetica, Times New
628
+ * Roman and Arial. Without spaces or capitals, to be compared with a name taken the same way.
629
+ */
630
+ function looseFontKey(name) {
631
+ return name
632
+ .toLowerCase()
633
+ .replace(/-(regular|roman|book|light|medium|semibold|demibold|bold|heavy|black|italic|oblique|bolditalic|boldoblique)[a-z]*$/, '')
634
+ .replace(/(ps)?mt$/, '')
635
+ .replace(/ps$/, '')
636
+ .replace(/[\s_-]/g, '');
561
637
  }
562
638
  // ── Links ──
563
639
  /** The longest field instruction looked at for a link's address. */
@@ -667,6 +743,49 @@ function resetIndents(state) {
667
743
  state.leftIndent = 0;
668
744
  state.rightIndent = 0;
669
745
  state.firstLineIndent = 0;
746
+ state.spaceBefore = 0;
747
+ state.spaceAfter = 0;
748
+ state.lineSpacing = 0;
749
+ state.lineMultiple = false;
750
+ }
751
+ /** The most space before or after a paragraph that is read: a page's height. More is a mistake in the file. */
752
+ const MOST_SPACE_TWIPS = 15840;
753
+ /**
754
+ * A paragraph's spacing as CSS, which the writer reads back as the same \sb, \sa and \sl:
755
+ * "margin-top:6pt;margin-bottom:6pt;line-height:1.5". A height the lines have at least (\sl
756
+ * above zero with no \slmult1) is not a thing CSS has, and is left to the screen.
757
+ */
758
+ function spacingStyle(block, part = 'all') {
759
+ const parts = [];
760
+ const space = (twips) => twipsToPt(Math.min(twips, MOST_SPACE_TWIPS));
761
+ if (part !== 'after' && block.before > 0)
762
+ parts.push(`margin-top:${space(block.before)}`);
763
+ if (part !== 'before' && block.after > 0)
764
+ parts.push(`margin-bottom:${space(block.after)}`);
765
+ if (part === 'all') {
766
+ // Lines closer than LEAST_LINES of their text are printed over each other, and are
767
+ // not read: "\sl-20" put two lines of a diagnosis on top of each other, and the
768
+ // paragraph after them on both. (A half-point is ten twips.)
769
+ const tallest = block.runs.reduce((most, run) => Math.max(most, run.fmt.fontSize || 0), 0);
770
+ if (block.lineMultiple && block.line >= LEAST_LINES * 240 && block.line <= 2400)
771
+ parts.push(`line-height:${Math.round((block.line / 240) * 100) / 100}`);
772
+ else if (!block.lineMultiple && block.line < 0 && block.line >= -MOST_SPACE_TWIPS && -block.line >= LEAST_LINES * tallest * 10)
773
+ parts.push(`line-height:${twipsToPt(-block.line)}`);
774
+ }
775
+ return parts.join(';');
776
+ }
777
+ /** A style added to the element an HTML string opens with: `<figure>` or `<figure style="…">`. */
778
+ function withStyle(html, style) {
779
+ if (!style)
780
+ return html;
781
+ const open = html.match(/^<[a-z0-9]+( style="([^"]*)")?/);
782
+ if (!open)
783
+ return html;
784
+ const tag = open[0].slice(0, open[0].length - (open[1]?.length ?? 0));
785
+ // (What it sets replaces what the element had of the same name.)
786
+ const named = new Set(style.split(';').map((declaration) => declaration.split(':')[0]));
787
+ const kept = (open[2] ?? '').split(';').filter((declaration) => declaration && !named.has(declaration.split(':')[0]));
788
+ return `${tag} style="${[...kept, style].join(';')}"${html.slice(open[0].length)}`;
670
789
  }
671
790
  /**
672
791
  * A paragraph's indents as CSS, in points (20 twips), which the writer reads back as the same
@@ -741,6 +860,7 @@ function sameFormatButSize(a, b) {
741
860
  a.color === b.color &&
742
861
  a.background === b.background &&
743
862
  a.mono === b.mono &&
863
+ a.font === b.font &&
744
864
  a.link === b.link);
745
865
  }
746
866
  export function rtfToHtml(rtfString, options = {}) {
@@ -752,6 +872,7 @@ export function rtfToHtml(rtfString, options = {}) {
752
872
  let colorTable = [''];
753
873
  let monoFonts = new Set();
754
874
  let symbolFonts = new Set();
875
+ let fontNames = new Map();
755
876
  let defaultFont = 0;
756
877
  /** Where finished paragraphs and tables go: the document, or the footnote or text box being read. */
757
878
  let blocks = [];
@@ -793,6 +914,9 @@ export function rtfToHtml(rtfString, options = {}) {
793
914
  let currentRowDefs = [];
794
915
  /** The definition of the row before, which a row with no \trowd of its own repeats. */
795
916
  let lastRowDefs = [];
917
+ /** The row's \trgaph, and the row before's, which a row with no \trowd of its own repeats. */
918
+ let rowGaph = null;
919
+ let lastRowGaph = null;
796
920
  let pendingDef = newCellDef();
797
921
  /** The side a \clbrdrX just named, until a border type (\brdrs...) confirms or \brdrnone clears it. */
798
922
  let pendingSide = null;
@@ -803,15 +927,21 @@ export function rtfToHtml(rtfString, options = {}) {
803
927
  let cellBorders = { b: false, other: false, bare: false };
804
928
  /** The side whose border type was read last, which a \brdrw or \brdrcf after it belongs to. */
805
929
  let borderSide = null;
930
+ /** {\*\inkth} was read in the cell being read: it is a header cell. */
931
+ let cellMarkedHeader = false;
932
+ /** How much of the cell had been read when {\*\inkcap} marked what follows as a caption. */
933
+ let captionAt = null;
806
934
  let inTableCell = false;
807
935
  /** \par seen in a table cell since its last text: line breaks owed if more text follows. */
808
936
  let cellBreaks = 0;
937
+ /** The spacing of the paragraph each of those paragraph marks ended; null for a line that is no paragraph's (a row of a table in the cell). */
938
+ let cellBreakSpacing = [];
809
939
  /** \lastrow seen in the definition of the row being read: its \row ends the table. */
810
940
  let lastRow = false;
811
941
  /** \nestcell seen: a tab is owed if more text follows on the line. */
812
942
  let nestTabPending = false;
813
943
  function newCellDef() {
814
- return { right: 0, header: false, vmgf: false, vmrg: false, hmgf: false, hmrg: false };
944
+ return { right: 0, header: false, vmgf: false, vmrg: false, hmgf: false, hmrg: false, shade: '', borders: {}, edge: null, drawn: null };
815
945
  }
816
946
  // The document is the first group. A byte-order mark or blank lines before it (a file saved
817
947
  // by a tool that adds them) do not make it something else: with those the color and font
@@ -832,7 +962,7 @@ export function rtfToHtml(rtfString, options = {}) {
832
962
  colorTable = parseColorTable(child);
833
963
  }
834
964
  else if (firstControl?.word === 'fonttbl') {
835
- ({ mono: monoFonts, symbol: symbolFonts } = readFontTable(child));
965
+ ({ mono: monoFonts, symbol: symbolFonts, names: fontNames } = readFontTable(child));
836
966
  }
837
967
  }
838
968
  else if (child.type === 'control' && child.word === 'deff' && child.param != null) {
@@ -841,6 +971,27 @@ export function rtfToHtml(rtfString, options = {}) {
841
971
  }
842
972
  // In a document whose own font is monospace, code cannot be told from text by its font.
843
973
  const documentIsMono = monoFonts.has(defaultFont);
974
+ // The fonts the application offers. Text in any other font, and text in the font the screen
975
+ // shows the document in, carries no font.
976
+ const offered = fontChoices(options.fonts);
977
+ const screenFont = fontKey(options.fontFamily) || fontKey(DEFAULT_FONT_FAMILY);
978
+ const fontCss = new Map();
979
+ /** The font with this number in the font table, as CSS, if it is one text is shown in. */
980
+ function fontOf(index) {
981
+ if (offered.length === 0)
982
+ return '';
983
+ let css = fontCss.get(index);
984
+ if (css === undefined) {
985
+ const name = fontNames.get(index) ?? '';
986
+ const key = fontKey(name);
987
+ const loose = looseFontKey(name);
988
+ const isScreenFont = key === screenFont || loose === looseFontKey(screenFont);
989
+ const choice = offered.find((font) => font.key === key) ?? offered.find((font) => looseFontKey(font.key) === loose);
990
+ css = !key || isScreenFont || !choice ? '' : choice.css;
991
+ fontCss.set(index, css);
992
+ }
993
+ return css;
994
+ }
844
995
  const linkColor = `rgb(${LINK_COLOR.r},${LINK_COLOR.g},${LINK_COLOR.b})`;
845
996
  // The screen's body size, in half-points. It is given, not guessed from the
846
997
  // document: guessing misread short documents and ones set below 12 pt.
@@ -859,6 +1010,8 @@ export function rtfToHtml(rtfString, options = {}) {
859
1010
  fontSize: 24, // 12pt default
860
1011
  colorIndex: 0,
861
1012
  highlightIndex: 0,
1013
+ backIndex: 0,
1014
+ paragraphBackIndex: 0,
862
1015
  fontIndex: defaultFont,
863
1016
  ucSkip: 1,
864
1017
  inList: false,
@@ -869,6 +1022,10 @@ export function rtfToHtml(rtfString, options = {}) {
869
1022
  leftIndent: 0,
870
1023
  rightIndent: 0,
871
1024
  firstLineIndent: 0,
1025
+ spaceBefore: 0,
1026
+ spaceAfter: 0,
1027
+ lineSpacing: 0,
1028
+ lineMultiple: false,
872
1029
  };
873
1030
  }
874
1031
  const stateStack = [defaultState()];
@@ -878,8 +1035,26 @@ export function rtfToHtml(rtfString, options = {}) {
878
1035
  function cloneState() {
879
1036
  return { ...currentState() };
880
1037
  }
1038
+ /** A color of the table as the background it is: none for the automatic color, and none for white, which the page is. */
1039
+ function shadeAt(index) {
1040
+ const color = index > 0 && index < colorTable.length ? colorTable[index] : '';
1041
+ return color === 'rgb(255,255,255)' ? '' : color;
1042
+ }
1043
+ /**
1044
+ * Shading is not shown: every word is on the white of the page. A color given to words so
1045
+ * that they could be read on their shading (the white header of a table whose header row is
1046
+ * dark, a white title on a shaded bar) cannot be read without it, and the cell or the line
1047
+ * looked empty. Such words are shown in the page's own color. A color that can be read on
1048
+ * white stays, shaded or not.
1049
+ */
1050
+ function readsOnWhite(color) {
1051
+ const parts = color.match(/^rgb\((\d+),(\d+),(\d+)\)$/);
1052
+ return !parts || !hardToReadOnWhite({ r: +parts[1], g: +parts[2], b: +parts[3] });
1053
+ }
881
1054
  function formatOf(state) {
882
1055
  let color = state.colorIndex > 0 && state.colorIndex < colorTable.length ? colorTable[state.colorIndex] : '';
1056
+ if (color && (shadeAt(state.backIndex) || shadeAt(state.paragraphBackIndex)) && !readsOnWhite(color))
1057
+ color = '';
883
1058
  // Black is the color text has anyway, and a link's own color is the <a>'s to give.
884
1059
  if (color === 'rgb(0,0,0)' || (state.link && color === linkColor))
885
1060
  color = '';
@@ -897,6 +1072,8 @@ export function rtfToHtml(rtfString, options = {}) {
897
1072
  // A list marker is set in whatever font the list uses (Word's second-level "o" is in
898
1073
  // Courier New): it is not code.
899
1074
  mono: !documentIsMono && !state.inList && monoFonts.has(state.fontIndex),
1075
+ // (Not a list marker's, as above: Word sets its bullets in Symbol and Wingdings.)
1076
+ font: state.inList ? '' : fontOf(state.fontIndex),
900
1077
  link: state.link
901
1078
  };
902
1079
  }
@@ -910,13 +1087,17 @@ export function rtfToHtml(rtfString, options = {}) {
910
1087
  const onlySpaces = ONLY_SPACES.test(text);
911
1088
  let result = escapeText(text);
912
1089
  const styles = [];
913
- if (fmt.color)
1090
+ // (A highlight is shown, and its words are read on it.)
1091
+ if (fmt.color && (!opts.onWhite || fmt.background || readsOnWhite(fmt.color)))
914
1092
  styles.push(`color:${fmt.color}`);
915
1093
  if (fmt.background)
916
1094
  styles.push(`background-color:${fmt.background}`);
917
1095
  if (!onlySpaces && fmt.fontSize !== bodySize && fmt.fontSize !== opts.dropSize) {
918
1096
  styles.push(`font-size:${fmt.fontSize / 2}pt`);
919
1097
  }
1098
+ // (Code is in the code font: a font named for it would be the one it is shown in.)
1099
+ if (!onlySpaces && fmt.font && !fmt.mono && !opts.pre)
1100
+ styles.push(`font-family:${escapeAttribute(fmt.font)}`);
920
1101
  if (styles.length > 0)
921
1102
  result = `<span style="${styles.join(';')}">${result}</span>`;
922
1103
  if (fmt.mono && !opts.pre)
@@ -988,6 +1169,7 @@ export function rtfToHtml(rtfString, options = {}) {
988
1169
  /** An empty paragraph to read into. */
989
1170
  function newRuns() {
990
1171
  runs = [];
1172
+ captionAt = null;
991
1173
  onlyText = true;
992
1174
  contentAlign = 'left';
993
1175
  marker = null;
@@ -1034,11 +1216,15 @@ export function rtfToHtml(rtfString, options = {}) {
1034
1216
  }
1035
1217
  if (cellBreaks > 0) {
1036
1218
  const count = cellBreaks;
1219
+ const spacings = cellBreakSpacing;
1037
1220
  cellBreaks = 0;
1221
+ cellBreakSpacing = [];
1038
1222
  if (inTableCell) {
1039
1223
  // A paragraph mark inside a cell: the cell's text goes on, on a new line.
1040
- for (let k = 0; k < count; k++)
1224
+ for (let k = 0; k < count; k++) {
1041
1225
  pushHtml('br', '<br>', state);
1226
+ runs[runs.length - 1].spacing = spacings[k] ?? null;
1227
+ }
1042
1228
  }
1043
1229
  else {
1044
1230
  // \pard has left the table without a \cell: what was read is a paragraph.
@@ -1072,15 +1258,43 @@ export function rtfToHtml(rtfString, options = {}) {
1072
1258
  beforeContent(state);
1073
1259
  pushHtml(kind, html, state);
1074
1260
  }
1261
+ /** The spacing the paragraph being read has. */
1262
+ function spacingHere(state) {
1263
+ return { before: state.spaceBefore, after: state.spaceAfter, line: state.lineSpacing, lineMultiple: state.lineMultiple };
1264
+ }
1265
+ /**
1266
+ * What a table cell holds, as HTML. Its paragraphs are lines of the cell, a <br> apart; where
1267
+ * one of them is spaced (\sa, \sb, \sl, as Word writes a cell's paragraphs), each is a
1268
+ * paragraph of its own with its spacing. `last` is the spacing of the last one.
1269
+ */
1270
+ function cellHtml(last) {
1271
+ const paragraphs = [];
1272
+ let from = 0;
1273
+ runs.forEach((run, i) => {
1274
+ if (run.type !== 'html' || !run.spacing)
1275
+ return;
1276
+ paragraphs.push({ runs: runs.slice(from, i), spacing: run.spacing });
1277
+ from = i + 1;
1278
+ });
1279
+ paragraphs.push({ runs: runs.slice(from), spacing: last });
1280
+ const styles = paragraphs.map((paragraph) => spacingStyle({ ...paragraph.spacing, runs: paragraph.runs }));
1281
+ if (styles.every((style) => !style))
1282
+ return trimSpaces(renderRuns(runs));
1283
+ return paragraphs
1284
+ .map((paragraph, k) => `<p${styles[k] ? ` style="${styles[k]}"` : ''}>${trimSpaces(renderRuns(paragraph.runs)) || '<br>'}</p>`)
1285
+ .join('');
1286
+ }
1075
1287
  /** \par, where it ends a paragraph and where, in a table cell, it starts a new line. */
1076
1288
  function paragraphMark(state) {
1077
1289
  if (inTableCell) {
1078
1290
  cellBreaks++;
1291
+ cellBreakSpacing.push(spacingHere(state));
1079
1292
  }
1080
1293
  else {
1081
1294
  // Paragraph marks from a cell that \pard has since left end paragraphs too.
1082
1295
  for (; cellBreaks > 0; cellBreaks--)
1083
1296
  flushParagraph();
1297
+ cellBreakSpacing = [];
1084
1298
  flushParagraph();
1085
1299
  }
1086
1300
  }
@@ -1112,7 +1326,31 @@ export function rtfToHtml(rtfString, options = {}) {
1112
1326
  }
1113
1327
  appendText(text.slice(from), state);
1114
1328
  }
1115
- /** The text of the line being read, back to the last line break, if text is all it holds. */
1329
+ /**
1330
+ * The cell being read as the figure it is, where it holds one picture and then the caption
1331
+ * the writer marked ({\*\inkcap}): pictures side by side are a row of such cells, each
1332
+ * picture with its own caption. Null for any other cell, which is read as its lines.
1333
+ */
1334
+ function cellFigure() {
1335
+ if (captionAt == null || captionAt < 1)
1336
+ return null;
1337
+ const before = runs.slice(0, captionAt).filter((run) => !(run.type === 'text' && ONLY_SPACES.test(run.text)));
1338
+ if (before.length !== 1 || before[0].type !== 'html' || before[0].kind !== 'img')
1339
+ return null;
1340
+ let from = captionAt;
1341
+ while (from < runs.length && runs[from].type === 'html' && runs[from].kind === 'br')
1342
+ from++;
1343
+ const caption = stripWrappingEm(trimSpaces(renderRuns(runs.slice(from))));
1344
+ if (!caption)
1345
+ return null;
1346
+ return `<figure>${trimSpaces(renderRuns(before))}<figcaption>${caption}</figcaption></figure>`;
1347
+ }
1348
+ /** The cell being read, with the colors left out that cannot be read on white; undefined where it has none. */
1349
+ function cellOnWhite() {
1350
+ if (!runs.some((run) => run.fmt.color && !run.fmt.background && !readsOnWhite(run.fmt.color)))
1351
+ return undefined;
1352
+ return trimSpaces(renderRuns(runs, { onWhite: true }));
1353
+ }
1116
1354
  function lineText() {
1117
1355
  let text = '';
1118
1356
  for (let i = runs.length - 1; i >= 0; i--) {
@@ -1148,6 +1386,19 @@ export function rtfToHtml(rtfString, options = {}) {
1148
1386
  }
1149
1387
  return;
1150
1388
  }
1389
+ // "C." or "iv.", which is a marker only on a paragraph set as the writer sets a list
1390
+ // item: on any other line it is what someone typed ("A.", a tab, the specimen), and
1391
+ // the tab after it stays a tab.
1392
+ const lettered = opensParagraph && lead != null ? lead.match(LETTER_MARKER) : null;
1393
+ if (lettered &&
1394
+ hangsAsItem(state.firstLineIndent, state.leftIndent) &&
1395
+ state.rightIndent === 0 &&
1396
+ (state.align || 'left') === 'left' &&
1397
+ letterReadings(lettered[1]).length > 0) {
1398
+ pushHtml('gap', '&emsp;', state);
1399
+ marker = { kind: 'ol', number: 0, letters: lettered[1], end: runs.length };
1400
+ return;
1401
+ }
1151
1402
  pushHtml('tab', TAB_HTML, state);
1152
1403
  // Word's bullet, inside {\listtext …} or {\pntext …}.
1153
1404
  if (opensParagraph && lead != null && state.inList && SYMBOL_BULLET.test(lead)) {
@@ -1169,15 +1420,17 @@ export function rtfToHtml(rtfString, options = {}) {
1169
1420
  for (let ci = 0; ci < row.cells.length; ci++) {
1170
1421
  const def = row.defs[ci] ?? { ...newCellDef(), right: prevRight + (step || 1440) };
1171
1422
  const cell = row.cells[ci];
1423
+ // The words of a shaded cell, as they can be read without the shading.
1424
+ const cellHtml = def.shade && cell.onWhite !== undefined ? cell.onWhite : cell.html;
1172
1425
  const last = placed[placed.length - 1];
1173
1426
  if (def.hmrg && last) {
1174
1427
  last.right = Math.max(last.right, def.right);
1175
- if (cell.html)
1176
- last.html += (last.html ? ' ' : '') + cell.html;
1428
+ if (cellHtml)
1429
+ last.html += (last.html ? ' ' : '') + cellHtml;
1177
1430
  }
1178
1431
  else {
1179
1432
  placed.push({
1180
- html: cell.html, align: cell.align, def,
1433
+ html: cellHtml, align: cell.align, header: def.header || cell.header === true, def,
1181
1434
  left: prevRight, right: Math.max(def.right, prevRight),
1182
1435
  start: 0, end: 0, rowspan: 1, merged: false
1183
1436
  });
@@ -1241,6 +1494,26 @@ export function rtfToHtml(rtfString, options = {}) {
1241
1494
  }
1242
1495
  }
1243
1496
  }
1497
+ // Pictures side by side with a set gap: one row, a picture in each cell and an empty
1498
+ // cell between each two, written with no space inside a cell (\trgaph0) and nothing
1499
+ // drawn or shaded. It is read at its own widths, as it was written, and not stretched
1500
+ // across the page: what was set is the distance between the pictures. (See
1501
+ // picture-rows.ts.) A table that only looks like one, with borders, shading, or the
1502
+ // space a reader puts inside its cells, is read as the table it is.
1503
+ const plain = rows.length === 1 && rows[0].gaph === 0 && rows[0].defs.every((def) => !def.shade && Object.keys(def.borders).length === 0);
1504
+ const only = plain && placedRows.length === 1 ? placedRows[0] : null;
1505
+ const onePicture = (html) => /^<(figure|img)\b/.test(html) && html.split('<img').length === 2;
1506
+ if (only &&
1507
+ only.length >= 3 &&
1508
+ only.length % 2 === 1 &&
1509
+ only.every((cell, i) => !cell.merged && !cell.header && cell.rowspan === 1 && cell.end === cell.start && cell.right > cell.left && (i % 2 === 0 ? onePicture(cell.html) : cell.html === ''))) {
1510
+ const cells = only.map((cell) => `<td style="padding:0;width:${(cell.right - cell.left) / 20}pt">${cell.html}</td>`).join('');
1511
+ blocks.push({ kind: 'table', html: `<table style="border-collapse:collapse;margin:4px 0"><tr>${cells}</tr></table>` });
1512
+ for (const aside of tableAsides)
1513
+ blocks.push(aside);
1514
+ tableAsides = [];
1515
+ return;
1516
+ }
1244
1517
  const total = edges[edges.length - 1] || 1;
1245
1518
  // A cell's width is the difference of where it ends and where it starts, each as a
1246
1519
  // share of the table rounded to a hundredth of a percent. Written that way the widths
@@ -1253,12 +1526,15 @@ export function rtfToHtml(rtfString, options = {}) {
1253
1526
  for (const cell of row) {
1254
1527
  if (cell.merged)
1255
1528
  continue;
1256
- const tag = cell.def.header ? 'th' : 'td';
1529
+ const tag = cell.header ? 'th' : 'td';
1257
1530
  const pct = (shareAt(cell.right) - shareAt(cell.left)).toFixed(2).replace(/0$/, '');
1258
1531
  const alignStyle = cell.align !== 'left' ? `;text-align:${cell.align}` : '';
1532
+ // (A header cell says how it is aligned, left too: a browser centers one that does not.)
1259
1533
  const style = cell.def.header
1260
1534
  ? `border-bottom:1px solid;padding:2px 6px;text-align:${cell.align};width:${pct}%`
1261
- : `padding:2px 6px;width:${pct}%${alignStyle}`;
1535
+ : cell.header
1536
+ ? `${bordersStyle(cell.def.borders)}padding:2px 6px;text-align:${cell.align};width:${pct}%`
1537
+ : `${bordersStyle(cell.def.borders)}padding:2px 6px;width:${pct}%${alignStyle}`;
1262
1538
  const colspan = cell.end > cell.start ? ` colspan="${cell.end - cell.start + 1}"` : '';
1263
1539
  const rowspan = cell.rowspan > 1 ? ` rowspan="${cell.rowspan}"` : '';
1264
1540
  html += `<${tag}${colspan}${rowspan} style="${style}">${cell.html}</${tag}>`;
@@ -1287,6 +1563,10 @@ export function rtfToHtml(rtfString, options = {}) {
1287
1563
  left: state.leftIndent,
1288
1564
  right: state.rightIndent,
1289
1565
  first: state.firstLineIndent,
1566
+ before: state.spaceBefore,
1567
+ after: state.spaceAfter,
1568
+ line: state.lineSpacing,
1569
+ lineMultiple: state.lineMultiple,
1290
1570
  caption: paragraphIsCaption,
1291
1571
  marker,
1292
1572
  inTable: inTableCell
@@ -1349,14 +1629,14 @@ export function rtfToHtml(rtfString, options = {}) {
1349
1629
  const saved = {
1350
1630
  blocks, runs, onlyText, marker, paragraphHasListMarker, paragraphIsCaption, paragraphAsides,
1351
1631
  tableAsides, tableRows, currentRowCells, currentRowDefs, lastRowDefs, pendingDef, pendingSide,
1352
- cellBorders, borderSide, inTableCell, cellBreaks, contentAlign, lastRow, nestTabPending,
1632
+ cellBorders, borderSide, cellMarkedHeader, captionAt, inTableCell, cellBreaks, cellBreakSpacing, contentAlign, lastRow, nestTabPending,
1353
1633
  pendingHighSurrogate, pendingUnicodeSkip, noteNumber, unshown, stateBase
1354
1634
  };
1355
1635
  restore = () => {
1356
1636
  ({
1357
1637
  blocks, runs, onlyText, marker, paragraphHasListMarker, paragraphIsCaption, paragraphAsides,
1358
1638
  tableAsides, tableRows, currentRowCells, currentRowDefs, lastRowDefs, pendingDef, pendingSide,
1359
- cellBorders, borderSide, inTableCell, cellBreaks, contentAlign, lastRow, nestTabPending,
1639
+ cellBorders, borderSide, cellMarkedHeader, captionAt, inTableCell, cellBreaks, cellBreakSpacing, contentAlign, lastRow, nestTabPending,
1360
1640
  pendingHighSurrogate, pendingUnicodeSkip, noteNumber, unshown, stateBase
1361
1641
  } = saved);
1362
1642
  };
@@ -1374,8 +1654,10 @@ export function rtfToHtml(rtfString, options = {}) {
1374
1654
  pendingSide = null;
1375
1655
  cellBorders = { b: false, other: false, bare: false };
1376
1656
  borderSide = null;
1657
+ cellMarkedHeader = false;
1377
1658
  inTableCell = false;
1378
1659
  cellBreaks = 0;
1660
+ cellBreakSpacing = [];
1379
1661
  lastRow = false;
1380
1662
  nestTabPending = false;
1381
1663
  pendingHighSurrogate = 0;
@@ -1501,12 +1783,18 @@ export function rtfToHtml(rtfString, options = {}) {
1501
1783
  else if (dest?.word === 'inkcap') {
1502
1784
  // Marks the paragraph that follows as a picture caption.
1503
1785
  paragraphIsCaption = true;
1786
+ captionAt = runs.length;
1787
+ }
1788
+ else if (dest?.word === 'inkth') {
1789
+ // Marks the cell it is in as a header cell.
1790
+ cellMarkedHeader = true;
1504
1791
  }
1505
1792
  else if (dest?.word === 'nesttableprops') {
1506
1793
  // Word ends each row of a table inside a cell with this group, which holds
1507
1794
  // the row's definition and its \nestrow.
1508
1795
  nestTabPending = false;
1509
1796
  cellBreaks++;
1797
+ cellBreakSpacing.push(null);
1510
1798
  }
1511
1799
  continue;
1512
1800
  }
@@ -1567,7 +1855,15 @@ export function rtfToHtml(rtfString, options = {}) {
1567
1855
  state.colorIndex = p;
1568
1856
  break;
1569
1857
  case 'cb':
1570
- break; // \cb not rendered on import
1858
+ case 'chcbpat':
1859
+ state.backIndex = p ?? 0;
1860
+ break;
1861
+ case 'cbpat':
1862
+ state.paragraphBackIndex = p ?? 0;
1863
+ break;
1864
+ case 'clcbpat':
1865
+ pendingDef.shade = shadeAt(p ?? 0);
1866
+ break;
1571
1867
  case 'highlight':
1572
1868
  if (p != null)
1573
1869
  state.highlightIndex = p;
@@ -1605,6 +1901,18 @@ export function rtfToHtml(rtfString, options = {}) {
1605
1901
  case 'fi':
1606
1902
  state.firstLineIndent = p ?? 0;
1607
1903
  break;
1904
+ case 'sb':
1905
+ state.spaceBefore = Math.max(0, p ?? 0);
1906
+ break;
1907
+ case 'sa':
1908
+ state.spaceAfter = Math.max(0, p ?? 0);
1909
+ break;
1910
+ case 'sl':
1911
+ state.lineSpacing = p ?? 0;
1912
+ break;
1913
+ case 'slmult':
1914
+ state.lineMultiple = p === 1;
1915
+ break;
1608
1916
  case 'par':
1609
1917
  case 'sect':
1610
1918
  // \sect ends a section, and with it the paragraph: "A\sect B" is two lines.
@@ -1614,6 +1922,7 @@ export function rtfToHtml(rtfString, options = {}) {
1614
1922
  // A row's definition, not its start: Word writes the definition before the
1615
1923
  // cells and again before \row, so the cells read so far are kept.
1616
1924
  currentRowDefs = [];
1925
+ rowGaph = null;
1617
1926
  pendingDef = newCellDef();
1618
1927
  pendingSide = null;
1619
1928
  borderSide = null;
@@ -1624,25 +1933,37 @@ export function rtfToHtml(rtfString, options = {}) {
1624
1933
  lastRow = true;
1625
1934
  break;
1626
1935
  case 'trgaph':
1936
+ rowGaph = p ?? null;
1937
+ pendingSide = null;
1938
+ pendingDef.edge = null;
1939
+ break;
1627
1940
  case 'trkeep':
1628
1941
  case 'trleft':
1629
1942
  case 'trhdr':
1630
1943
  pendingSide = null;
1944
+ pendingDef.edge = null;
1631
1945
  break; // table formatting, ignored
1632
1946
  case 'clbrdrr':
1633
1947
  case 'clbrdrl':
1634
1948
  case 'clbrdrt':
1635
1949
  pendingSide = 'other';
1636
1950
  borderSide = null;
1951
+ pendingDef.edge = w === 'clbrdrr' ? 'r' : w === 'clbrdrl' ? 'l' : 't';
1952
+ pendingDef.drawn = null;
1637
1953
  break;
1638
1954
  case 'clbrdrb':
1639
1955
  pendingSide = 'b';
1640
1956
  borderSide = null;
1957
+ pendingDef.edge = 'b';
1958
+ pendingDef.drawn = null;
1641
1959
  break;
1642
1960
  case 'brdrnone':
1643
1961
  case 'brdrnil':
1962
+ case 'brdrtbl':
1644
1963
  pendingSide = null;
1645
1964
  borderSide = null;
1965
+ pendingDef.edge = null;
1966
+ pendingDef.drawn = null;
1646
1967
  break;
1647
1968
  case 'brdrw':
1648
1969
  case 'brdrcf':
@@ -1651,6 +1972,20 @@ export function rtfToHtml(rtfString, options = {}) {
1651
1972
  // without one. The writer's header mark is the bare \clbrdrb\brdrs.
1652
1973
  if (borderSide === 'b')
1653
1974
  cellBorders.bare = false;
1975
+ if (pendingDef.drawn && p != null) {
1976
+ const border = pendingDef.borders[pendingDef.drawn];
1977
+ if (w === 'brdrw') {
1978
+ // (No width is no line: Word writes \brdrw0 for a border that is off.)
1979
+ if (p > 0)
1980
+ border.twips = p;
1981
+ else
1982
+ delete pendingDef.borders[pendingDef.drawn];
1983
+ }
1984
+ else {
1985
+ const color = p > 0 && p < colorTable.length ? colorTable[p] : '';
1986
+ border.color = color === 'rgb(0,0,0)' ? '' : color;
1987
+ }
1988
+ }
1654
1989
  break;
1655
1990
  // Every border style RTF names: any of them makes the side a border.
1656
1991
  case 'brdrs':
@@ -1687,6 +2022,11 @@ export function rtfToHtml(rtfString, options = {}) {
1687
2022
  }
1688
2023
  borderSide = pendingSide;
1689
2024
  pendingSide = null;
2025
+ if (pendingDef.edge) {
2026
+ pendingDef.borders[pendingDef.edge] = { line: BORDER_LINE_CSS.get(w) ?? 'solid', twips: 15, color: '' };
2027
+ pendingDef.drawn = pendingDef.edge;
2028
+ pendingDef.edge = null;
2029
+ }
1690
2030
  break;
1691
2031
  case 'clvmgf':
1692
2032
  pendingDef.vmgf = true;
@@ -1719,16 +2059,23 @@ export function rtfToHtml(rtfString, options = {}) {
1719
2059
  pendingHighSurrogate = 0;
1720
2060
  pushText('\ufffd', state);
1721
2061
  }
2062
+ // (A caption in a cell is the cell's; it is not the paragraph's after the table.)
2063
+ paragraphIsCaption = false;
2064
+ const figure = cellFigure();
1722
2065
  currentRowCells.push({
1723
- html: trimSpaces(renderRuns(runs)),
2066
+ html: figure ?? cellHtml(spacingHere(state)),
2067
+ onWhite: figure ? undefined : cellOnWhite(),
1724
2068
  // The alignment of the cell's last paragraph, also where that paragraph
1725
2069
  // was ended inside a group ({\pard\intbl\qr 1.0\par}\cell, as this writer
1726
2070
  // wrote cells up to 1.9.0).
1727
- align: alignHere(state)
2071
+ align: alignHere(state),
2072
+ header: cellMarkedHeader
1728
2073
  });
2074
+ cellMarkedHeader = false;
1729
2075
  newRuns();
1730
2076
  // The paragraph mark that ends a cell's last paragraph adds no line.
1731
2077
  cellBreaks = 0;
2078
+ cellBreakSpacing = [];
1732
2079
  nestTabPending = false;
1733
2080
  break;
1734
2081
  case 'nestcell':
@@ -1739,23 +2086,27 @@ export function rtfToHtml(rtfString, options = {}) {
1739
2086
  case 'nestrow':
1740
2087
  nestTabPending = false;
1741
2088
  cellBreaks++;
2089
+ cellBreakSpacing.push(null);
1742
2090
  break;
1743
2091
  case 'row': {
1744
2092
  // Text after the row's last \cell is a cell that was not closed, not the
1745
2093
  // start of the paragraph after the table.
1746
2094
  if (trimSpaces(renderRuns(runs))) {
1747
- currentRowCells.push({ html: trimSpaces(renderRuns(runs)), align: alignHere(state) });
2095
+ currentRowCells.push({ html: trimSpaces(renderRuns(runs)), onWhite: cellOnWhite(), align: alignHere(state) });
1748
2096
  newRuns();
1749
2097
  }
1750
2098
  // A row with no definition of its own repeats the one before it.
1751
2099
  const defs = currentRowDefs.length > 0 ? currentRowDefs : lastRowDefs;
1752
- tableRows.push({ cells: currentRowCells, defs });
2100
+ const gaph = currentRowDefs.length > 0 ? rowGaph : lastRowGaph;
2101
+ tableRows.push({ cells: currentRowCells, defs, gaph });
1753
2102
  lastRowDefs = defs;
2103
+ lastRowGaph = gaph;
1754
2104
  currentRowCells = [];
1755
2105
  currentRowDefs = [];
1756
2106
  pendingDef = newCellDef();
1757
2107
  inTableCell = false;
1758
2108
  cellBreaks = 0;
2109
+ cellBreakSpacing = [];
1759
2110
  nestTabPending = false;
1760
2111
  // The cell's indents and alignment end with the row, in whichever group
1761
2112
  // set them: \row may sit in a group of its own ({\row}). Not in the text a
@@ -1778,6 +2129,7 @@ export function rtfToHtml(rtfString, options = {}) {
1778
2129
  // \pard resets the paragraph, not the characters: bold, italic, underline
1779
2130
  // and strikethrough carry on until \plain or their own \b0. Word relies on it.
1780
2131
  state.align = 'left';
2132
+ state.paragraphBackIndex = 0;
1781
2133
  resetIndents(state);
1782
2134
  // Being in a table is a paragraph property too. Without this, one \intbl with
1783
2135
  // no \row made a single cell of the rest of the document. The marker group
@@ -1864,6 +2216,7 @@ export function rtfToHtml(rtfString, options = {}) {
1864
2216
  state.fontSize = 24;
1865
2217
  state.colorIndex = 0;
1866
2218
  state.highlightIndex = 0;
2219
+ state.backIndex = 0;
1867
2220
  state.fontIndex = defaultFont;
1868
2221
  state.hidden = false;
1869
2222
  state.deleted = false;
@@ -1872,10 +2225,12 @@ export function rtfToHtml(rtfString, options = {}) {
1872
2225
  // A page break. On screen it is a rule; the writer sends it back as \page.
1873
2226
  if (inTableCell) {
1874
2227
  cellBreaks++;
2228
+ cellBreakSpacing.push(null);
1875
2229
  break;
1876
2230
  }
1877
2231
  for (; cellBreaks > 0; cellBreaks--)
1878
2232
  flushParagraph();
2233
+ cellBreakSpacing = [];
1879
2234
  if (runs.length > 0)
1880
2235
  flushParagraph();
1881
2236
  flushTable();
@@ -1941,20 +2296,81 @@ export function rtfToHtml(rtfString, options = {}) {
1941
2296
  const items = blocks.map((b) => {
1942
2297
  if (b.kind !== 'paragraph' || !b.marker || b.inTable || b.caption)
1943
2298
  return null;
1944
- if (b.first !== -LIST_HANG || b.left < LIST_HANG || b.right !== 0 || b.align !== 'left')
2299
+ if (!hangsAsItem(b.first, b.left) || b.right !== 0 || b.align !== 'left')
1945
2300
  return null;
1946
2301
  return {
1947
2302
  kind: b.marker.kind,
1948
2303
  number: b.marker.number,
2304
+ letters: b.marker.letters,
1949
2305
  left: b.left,
1950
- html: trimSpaces(renderRuns(b.runs.slice(b.marker.end)))
2306
+ hang: -b.first,
2307
+ html: trimSpaces(renderRuns(b.runs.slice(b.marker.end))),
2308
+ spacing: spacingStyle(b)
1951
2309
  };
1952
2310
  });
2311
+ /** Where an item's marker stands, in twips: its text's indent less its hang. */
2312
+ const markAt = (item) => item.left - item.hang;
1953
2313
  /** Consecutive list items as nested <ul> and <ol>, one string per list at the top level. */
1954
2314
  function renderLists(list) {
1955
2315
  const out = [];
1956
2316
  let html = '';
2317
+ // (A level is where its markers stand, as Word has it: lists with other gaps after the
2318
+ // marker are at one level where their markers are at one place.)
1957
2319
  const open = [];
2320
+ /**
2321
+ * The number an item has and the way its list counts. Letters can be read two ways: "C"
2322
+ * is the third letter and the Roman 100. It is the one that goes on with the list the
2323
+ * item is in; where it opens a list, the one the next item at its level goes on with
2324
+ * ("D." or "CI."); and with neither to go by, a Roman numeral for "I" and for several
2325
+ * letters, a letter for any other.
2326
+ */
2327
+ /**
2328
+ * For each item, the next one at its level in the same run of items: the one after it
2329
+ * with the same indent, with none of a smaller indent between; -1 where there is none.
2330
+ * Found for all of them in one pass from the end. (Looked for from each item in turn,
2331
+ * a list in which every item is one level deeper than the last was read through once
2332
+ * for each of its items: a second for 20,000 of them, four for 40,000.)
2333
+ */
2334
+ const nextAtLevel = new Array(list.length).fill(-1);
2335
+ {
2336
+ /** The items after this one that one before it may still go on to: the nearest at each indent, the smallest indent first. */
2337
+ const ahead = [];
2338
+ for (let i = list.length - 1; i >= 0; i--) {
2339
+ const mark = markAt(list[i]);
2340
+ while (ahead.length > 0 && ahead[ahead.length - 1].mark > mark)
2341
+ ahead.pop();
2342
+ const same = ahead[ahead.length - 1];
2343
+ if (same && same.mark === mark) {
2344
+ nextAtLevel[i] = same.at;
2345
+ same.at = i;
2346
+ }
2347
+ else {
2348
+ ahead.push({ mark, at: i });
2349
+ }
2350
+ }
2351
+ }
2352
+ const readingOf = (at, top) => {
2353
+ const item = list[at];
2354
+ if (!item.letters)
2355
+ return { style: 'decimal', number: item.number };
2356
+ const readings = letterReadings(item.letters);
2357
+ if (top && top.kind === 'ol' && markAt(item) === top.at) {
2358
+ const goesOn = readings.find((r) => r.style === top.style && r.number === top.next);
2359
+ if (goesOn)
2360
+ return goesOn;
2361
+ }
2362
+ if (readings.length === 1)
2363
+ return readings[0];
2364
+ const next = nextAtLevel[at];
2365
+ if (next !== -1) {
2366
+ const after = list[next].letters ? letterReadings(list[next].letters) : [];
2367
+ const led = readings.find((r) => after.some((a) => a.style === r.style && a.number === r.number + 1));
2368
+ if (led)
2369
+ return led;
2370
+ }
2371
+ const roman = item.letters.length > 1 || /^[Ii]$/.test(item.letters);
2372
+ return readings.find((r) => r.style.endsWith(roman ? 'roman' : 'alpha')) ?? readings[0];
2373
+ };
1958
2374
  const closeList = () => {
1959
2375
  const done = open.pop();
1960
2376
  html += `</li></${done.kind}>`;
@@ -1963,27 +2379,31 @@ export function rtfToHtml(rtfString, options = {}) {
1963
2379
  html = '';
1964
2380
  }
1965
2381
  };
1966
- for (const item of list) {
2382
+ for (const [at, item] of list.entries()) {
1967
2383
  // A smaller indent ends the lists nested deeper than it.
1968
- while (open.length > 0 && item.left < open[open.length - 1].left)
2384
+ while (open.length > 0 && markAt(item) < open[open.length - 1].at)
1969
2385
  closeList();
1970
2386
  const top = open[open.length - 1];
1971
- if (top && item.left === top.left && item.kind === top.kind && (item.kind === 'ul' || item.number === top.next)) {
1972
- html += '</li><li>';
1973
- top.next = item.number + 1;
2387
+ const { style, number } = readingOf(at, top);
2388
+ if (top && markAt(item) === top.at && item.hang === top.hang && item.kind === top.kind && (item.kind === 'ul' || (number === top.next && style === top.style))) {
2389
+ html += `</li><li${item.spacing ? ` style="${item.spacing}"` : ''}>`;
2390
+ top.next = number + 1;
1974
2391
  }
1975
2392
  else {
1976
- // A change from bullets to numbers, or a number out of sequence, is a new list
1977
- // in the same place.
1978
- if (top && item.left === top.left)
2393
+ // A change from bullets to numbers, a number out of sequence or another gap after
2394
+ // the marker is a new list in the same place.
2395
+ if (top && markAt(item) === top.at)
1979
2396
  closeList();
1980
2397
  const parent = open[open.length - 1];
1981
- // What the indent adds to the half inch a list level has by itself.
1982
- const margin = item.left - (parent ? parent.left : 0) - LIST_STEP;
1983
- const style = margin !== 0 ? ` style="margin-left:${twipsToPt(margin)}"` : '';
1984
- const start = item.kind === 'ol' && item.number !== 1 ? ` start="${item.number}"` : '';
1985
- html += `<${item.kind}${start}${style}><li>`;
1986
- open.push({ kind: item.kind, left: item.left, next: item.number + 1 });
2398
+ // What the indent adds to the half inch a list level has by itself: the marker
2399
+ // stands a quarter inch into the level, and the text the list's gap after it.
2400
+ const margin = item.left - item.hang - (parent ? parent.left : 0) - (LIST_STEP - LIST_HANG);
2401
+ const start = item.kind === 'ol' && number !== 1 ? ` start="${number}"` : '';
2402
+ const type = item.kind === 'ol' && style !== 'decimal' ? ` type="${listTypeAttribute(style)}"` : '';
2403
+ // (A gap other than the quarter inch is the list's padding: see markerGapTwips.)
2404
+ const listStyle = [margin !== 0 ? `margin-left:${twipsToPt(margin)}` : '', item.hang !== LIST_HANG ? `padding-left:${twipsToPt(item.hang)}` : ''].filter(Boolean).join(';');
2405
+ html += `<${item.kind}${type}${start}${listStyle ? ` style="${listStyle}"` : ''}><li${item.spacing ? ` style="${item.spacing}"` : ''}>`;
2406
+ open.push({ kind: item.kind, left: item.left, at: markAt(item), hang: item.hang, next: number + 1, style });
1987
2407
  }
1988
2408
  html += item.html || '<br>';
1989
2409
  }
@@ -2043,8 +2463,8 @@ export function rtfToHtml(rtfString, options = {}) {
2043
2463
  continue;
2044
2464
  }
2045
2465
  const align = block.align;
2046
- // The paragraph's style attribute: its alignment, then its indents.
2047
- const blockStyle = [align !== 'left' ? `text-align:${align}` : '', block.inTable ? '' : indentStyle(block)]
2466
+ // The paragraph's style attribute: its alignment, then its indents and its spacing.
2467
+ const blockStyle = [align !== 'left' ? `text-align:${align}` : '', block.inTable ? '' : indentStyle(block), block.inTable ? '' : spacingStyle(block)]
2048
2468
  .filter(Boolean)
2049
2469
  .join(';');
2050
2470
  const styleAttr = blockStyle ? ` style="${blockStyle}"` : '';
@@ -2075,14 +2495,15 @@ export function rtfToHtml(rtfString, options = {}) {
2075
2495
  // The caption is given by a function: as a replacement string, a "$&" or a "$`"
2076
2496
  // in the caption's own text would be read as the match or as the figure before it.
2077
2497
  const caption = `<figcaption>${stripWrappingEm(trimmed)}</figcaption></figure>`;
2078
- rendered[last] = rendered[last].replace('</figure>', () => caption);
2498
+ // (The space after a picture is written after its caption.)
2499
+ rendered[last] = withStyle(rendered[last].replace('</figure>', () => caption), block.inTable ? '' : spacingStyle(block, 'after'));
2079
2500
  continue;
2080
2501
  }
2081
2502
  }
2082
2503
  // A paragraph holding nothing but pictures becomes a figure, so it can carry
2083
2504
  // a caption and be aligned/resized as a unit in the editor.
2084
2505
  if (IMAGE_ONLY_PARAGRAPH.test(trimmed)) {
2085
- const figureStyle = [align !== 'left' ? `text-align:${align}` : '', block.inTable ? '' : figureIndentStyle(block)]
2506
+ const figureStyle = [align !== 'left' ? `text-align:${align}` : '', block.inTable ? '' : figureIndentStyle(block), block.inTable ? '' : spacingStyle(block, 'before'), block.inTable ? '' : spacingStyle(block, 'after')]
2086
2507
  .filter(Boolean)
2087
2508
  .join(';');
2088
2509
  rendered.push(`<figure${figureStyle ? ` style="${figureStyle}"` : ''}>${trimmed}</figure>`);