svelte-rtf-editor 1.9.0 → 1.11.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.
@@ -35,8 +35,13 @@ const HIGHLIGHT_COLORS = {
35
35
  const B64_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
36
36
  /** 1 px at 96 dpi = 15 twips. */
37
37
  const TWIPS_PER_PX = 15;
38
- /** A paragraph made up of nothing but pictures is rendered as a <figure>. */
39
- const IMAGE_ONLY_PARAGRAPH = /^(?:<img\b[^>]*>\s*)+$/;
38
+ /** The widest a picture is shown, in px: 22 inches, the largest page Word has. */
39
+ const MAX_PICTURE_PX = 31680 / TWIPS_PER_PX;
40
+ /**
41
+ * A paragraph made up of one picture and nothing else is rendered as a <figure>. Two pictures in
42
+ * a paragraph stay a paragraph: a figure is written back as its picture and its caption.
43
+ */
44
+ const IMAGE_ONLY_PARAGRAPH = /^<img\b[^>]*>$/;
40
45
  /** Nibble value of each hex digit's char code; -1 for anything else. */
41
46
  const HEX_NIBBLE = (() => {
42
47
  const table = new Int8Array(128).fill(-1);
@@ -57,6 +62,8 @@ const LIST_MARKER = /^\s*(?:\u2022|(\d+)\.)\s*$/;
57
62
  * arrives as a middle dot or as the font's private-use character.
58
63
  */
59
64
  const SYMBOL_BULLET = /^\s*[\u00b7\uf0b7]\s*$/;
65
+ /** U+2028, the line separator, and U+2029, the paragraph separator. */
66
+ const LINE_SEPARATOR = /[\u2028\u2029]/;
60
67
  /** Text a browser shows as nothing but space. */
61
68
  const ONLY_SPACES = /^[ \t\r\n\f]*$/;
62
69
  /** The rule the writer sends for <hr>: a centered line of this many em dashes. */
@@ -126,10 +133,9 @@ function hexToBase64(hex) {
126
133
  * formats a browser cannot display (metafiles, device-dependent bitmaps).
127
134
  *
128
135
  * Only hexadecimal picture data is read. RTF also allows \binN, where the next
129
- * N bytes are raw binary — rare outside of Word's own output, and it cannot
130
- * survive readRtfFile() reading the document as text anyway. Such a picture is
131
- * skipped rather than mis-decoded: \bin is not a recognised control word here,
132
- * so its bytes fall through the tokenizer and the hex filter discards them.
136
+ * N bytes are raw binary: rare outside of Word's own output. Such a picture is
137
+ * skipped rather than mis-decoded: parseTree steps over the bytes, so nothing
138
+ * of it is left here.
133
139
  */
134
140
  function renderPicture(group) {
135
141
  let mime = '';
@@ -176,15 +182,25 @@ function renderPicture(group) {
176
182
  const hex = hexParts.join('').replace(/[^0-9a-fA-F]/g, '');
177
183
  if (hex.length < 8)
178
184
  return '';
185
+ // The bytes say what the picture is, where they say it: a PNG written as \jpegblip is a PNG.
186
+ const signature = hex.slice(0, 8).toLowerCase();
187
+ if (signature === '89504e47')
188
+ mime = 'image/png';
189
+ else if (signature.startsWith('ffd8ff'))
190
+ mime = 'image/jpeg';
179
191
  const base64 = hexToBase64(hex);
180
192
  if (!base64)
181
193
  return '';
182
- const widthPx = wgoal
183
- ? Math.round(wgoal / TWIPS_PER_PX)
184
- : Math.round((picw * scaleX) / 100);
185
- const heightPx = hgoal
186
- ? Math.round(hgoal / TWIPS_PER_PX)
187
- : Math.round((pich * scaleY) / 100);
194
+ // \picwgoal is the size the picture was placed at and \picscalex a percentage of it: Word
195
+ // writes a picture someone dragged to half size as \picscalex50, with the goal unchanged.
196
+ if (scaleX <= 0)
197
+ scaleX = 100;
198
+ if (scaleY <= 0)
199
+ scaleY = 100;
200
+ // (No wider than the largest page there is, 22 inches: a damaged \picwgoal gave a width of
201
+ // billions of pixels.)
202
+ const widthPx = Math.min(MAX_PICTURE_PX, Math.round(((wgoal ? wgoal / TWIPS_PER_PX : picw) * scaleX) / 100));
203
+ const heightPx = Math.round(((hgoal ? hgoal / TWIPS_PER_PX : pich) * scaleY) / 100);
188
204
  const styles = [];
189
205
  if (widthPx > 0)
190
206
  styles.push(`width:${widthPx}px`);
@@ -214,18 +230,60 @@ function cp1252Char(byte) {
214
230
  const code = WINDOWS_1252_C1[byte - 0x80] ?? byte;
215
231
  return code ? String.fromCharCode(code) : '';
216
232
  }
217
- function tokenize(rtf) {
218
- const tokens = [];
233
+ /**
234
+ * The deepest group the tree holds. Thousands of nested groups (damaged or hostile input) are
235
+ * nothing a real document has: those nest a few dozen deep at most. Groups below this depth are
236
+ * folded into the one at it: their text is kept, and their formatting carries on to the end of
237
+ * that group.
238
+ */
239
+ const MAX_GROUP_DEPTH = 500;
240
+ /**
241
+ * The most pieces (groups, control words, runs of text) a document is read into. Each costs
242
+ * memory, and a file well inside the size limit can be made of nothing but braces: 36 MB of them
243
+ * ran a process out of 4 GB. A report has thousands of pieces, a long Word document some hundreds
244
+ * of thousands; picture data is one for each line of the file it takes up.
245
+ */
246
+ const MAX_NODES = 5_000_000;
247
+ /** C0 control characters other than tab, and DEL: no reader shows them, and NUL ends a string for some. */
248
+ const CONTROL_CHARACTER = /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/;
249
+ const CONTROL_CHARACTERS = /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g;
250
+ /** RTF text as a tree of groups, control words and text. */
251
+ function parseTree(rtf) {
252
+ const root = { type: 'group', children: [] };
253
+ const stack = [root];
254
+ let current = root;
255
+ /** Groups opened past MAX_GROUP_DEPTH and not closed yet. */
256
+ let folded = 0;
257
+ let count = 0;
258
+ const add = (node) => {
259
+ if (++count > MAX_NODES) {
260
+ throw new RangeError('This document is too complex to show: it has more than 5 million parts');
261
+ }
262
+ current.children.push(node);
263
+ };
219
264
  let i = 0;
220
265
  const len = rtf.length;
221
266
  while (i < len) {
222
267
  const ch = rtf[i];
223
268
  if (ch === '{') {
224
- tokens.push({ type: 'open' });
269
+ if (stack.length > MAX_GROUP_DEPTH) {
270
+ folded++;
271
+ }
272
+ else {
273
+ const group = { type: 'group', children: [] };
274
+ add(group);
275
+ stack.push(group);
276
+ current = group;
277
+ }
225
278
  i++;
226
279
  }
227
280
  else if (ch === '}') {
228
- tokens.push({ type: 'close' });
281
+ if (folded > 0)
282
+ folded--;
283
+ else if (stack.length > 1) {
284
+ stack.pop();
285
+ current = stack[stack.length - 1];
286
+ }
229
287
  i++;
230
288
  }
231
289
  else if (ch === '\\') {
@@ -243,33 +301,41 @@ function tokenize(rtf) {
243
301
  // which became a NUL in the HTML.)
244
302
  if (hi >= 0 && lo >= 0) {
245
303
  i += 2;
246
- tokens.push({ type: 'text', value: cp1252Char((hi << 4) | lo), hex: true });
304
+ const byte = (hi << 4) | lo;
305
+ // A control character written as an escape is no more text than one written
306
+ // as itself: a tab is a tab, the rest are dropped.
307
+ // (Dropped as an empty piece, so that it still counts as the one character
308
+ // that stands in for the Unicode escape before it.)
309
+ if (byte === 9)
310
+ add({ type: 'control', word: 'tab', param: null });
311
+ else
312
+ add({ type: 'text', value: byte >= 0x20 && byte !== 0x7f ? cp1252Char(byte) : '', hex: true });
247
313
  }
248
314
  }
249
315
  // Special escapes
250
316
  else if (next === '\\' || next === '{' || next === '}') {
251
- tokens.push({ type: 'text', value: next });
317
+ add({ type: 'text', value: next });
252
318
  i++;
253
319
  }
254
320
  // Line breaks as control
255
321
  else if (next === '\n' || next === '\r') {
256
- tokens.push({ type: 'control', word: 'par', param: null });
322
+ add({ type: 'control', word: 'par', param: null });
257
323
  i++;
258
324
  if (i < len && rtf[i] === '\n')
259
325
  i++;
260
326
  }
261
327
  // Tilde = non-breaking space
262
328
  else if (next === '~') {
263
- tokens.push({ type: 'text', value: '\u00A0' });
329
+ add({ type: 'text', value: '\u00A0' });
264
330
  i++;
265
331
  }
266
332
  // Hyphen shortcuts
267
333
  else if (next === '-') {
268
- tokens.push({ type: 'text', value: '\u00AD' }); // soft hyphen
334
+ add({ type: 'text', value: '\u00AD' }); // soft hyphen
269
335
  i++;
270
336
  }
271
337
  else if (next === '_') {
272
- tokens.push({ type: 'text', value: '\u2011' }); // non-breaking hyphen
338
+ add({ type: 'text', value: '\u2011' }); // non-breaking hyphen
273
339
  i++;
274
340
  }
275
341
  // Control word or control symbol
@@ -298,11 +364,19 @@ function tokenize(rtf) {
298
364
  // Consume optional trailing space delimiter
299
365
  if (i < len && rtf[i] === ' ')
300
366
  i++;
301
- tokens.push({ type: 'control', word, param });
367
+ // \binN: the next N bytes are raw picture data, not RTF. They are stepped over
368
+ // whole: read as RTF, a brace among them closed the group, and with enough of
369
+ // them the document, and everything after was gone. (readRtfFile reads a file
370
+ // one character to the byte, so N characters is N bytes.)
371
+ if (word === 'bin' && param != null && param > 0) {
372
+ i += param;
373
+ continue;
374
+ }
375
+ add({ type: 'control', word, param });
302
376
  }
303
377
  // Control symbol (single non-alpha char)
304
378
  else {
305
- tokens.push({ type: 'control', word: next, param: null });
379
+ add({ type: 'control', word: next, param: null });
306
380
  i++;
307
381
  }
308
382
  }
@@ -310,6 +384,11 @@ function tokenize(rtf) {
310
384
  // Skip bare newlines (they're not meaningful in RTF)
311
385
  i++;
312
386
  }
387
+ else if (ch === '\t') {
388
+ // A tab character is a tab, the same as \tab: TextEdit writes every tab this way.
389
+ add({ type: 'control', word: 'tab', param: null });
390
+ i++;
391
+ }
313
392
  else {
314
393
  // Plain text — slice up to the next special char. Slicing rather than
315
394
  // appending char-by-char keeps embedded picture data (which arrives as
@@ -317,52 +396,15 @@ function tokenize(rtf) {
317
396
  const start = i;
318
397
  while (i < len) {
319
398
  const c = rtf[i];
320
- if (c === '\\' || c === '{' || c === '}' || c === '\r' || c === '\n')
399
+ if (c === '\\' || c === '{' || c === '}' || c === '\r' || c === '\n' || c === '\t')
321
400
  break;
322
401
  i++;
323
402
  }
324
- if (i > start) {
325
- tokens.push({ type: 'text', value: rtf.substring(start, i) });
326
- }
327
- }
328
- }
329
- return tokens;
330
- }
331
- // ── AST Builder ──
332
- /**
333
- * The deepest group the tree holds. The renderer walks groups recursively, and thousands of
334
- * nested groups (damaged or hostile input) would overflow the stack; real documents nest a few
335
- * dozen deep at most. Groups below this depth are folded into the one at it: their text is kept,
336
- * and their formatting carries on to the end of that group.
337
- */
338
- const MAX_GROUP_DEPTH = 500;
339
- function buildTree(tokens) {
340
- const root = { type: 'group', children: [] };
341
- const stack = [root];
342
- /** Groups opened past MAX_GROUP_DEPTH and not closed yet. */
343
- let folded = 0;
344
- for (const tok of tokens) {
345
- const current = stack[stack.length - 1];
346
- if (tok.type === 'open') {
347
- if (stack.length > MAX_GROUP_DEPTH) {
348
- folded++;
349
- continue;
350
- }
351
- const group = { type: 'group', children: [] };
352
- current.children.push(group);
353
- stack.push(group);
354
- }
355
- else if (tok.type === 'close') {
356
- if (folded > 0)
357
- folded--;
358
- else if (stack.length > 1)
359
- stack.pop();
360
- }
361
- else if (tok.type === 'control') {
362
- current.children.push({ type: 'control', word: tok.word, param: tok.param ?? null });
363
- }
364
- else if (tok.type === 'text') {
365
- current.children.push(tok.hex ? { type: 'text', value: tok.value, hex: true } : { type: 'text', value: tok.value });
403
+ let value = rtf.substring(start, i);
404
+ if (CONTROL_CHARACTER.test(value))
405
+ value = value.replace(CONTROL_CHARACTERS, '');
406
+ if (value)
407
+ add({ type: 'text', value });
366
408
  }
367
409
  }
368
410
  return root;
@@ -414,22 +456,73 @@ function parseColorTable(group) {
414
456
  }
415
457
  // ── Font table parser ──
416
458
  /**
417
- * The numbers of the fonts that are monospace: named like one (Courier New, Consolas), or declared
418
- * \fmodern or fixed-pitch (\fprq1). Reads both shapes a font table comes in: one group per font
459
+ * What each byte of the Symbol font shows, from 0x20 to 0xFF: Greek letters where the Latin ones
460
+ * are, and mathematical signs. Text set in Symbol is stored as those bytes, so "5 mg" with its m
461
+ * in Symbol is 5 micrograms. The table is the one macOS reads Symbol text with; 0 is a byte the font has
462
+ * nothing for.
463
+ */
464
+ const SYMBOL_FONT = [
465
+ 0x0020, 0x0021, 0x2200, 0x0023, 0x2203, 0x0025, 0x0026, 0x220d, 0x0028, 0x0029, 0x2217, 0x002b, 0x002c, 0x2212, 0x002e, 0x002f,
466
+ 0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037, 0x0038, 0x0039, 0x003a, 0x003b, 0x003c, 0x003d, 0x003e, 0x003f,
467
+ 0x2245, 0x0391, 0x0392, 0x03a7, 0x0394, 0x0395, 0x03a6, 0x0393, 0x0397, 0x0399, 0x03d1, 0x039a, 0x039b, 0x039c, 0x039d, 0x039f,
468
+ 0x03a0, 0x0398, 0x03a1, 0x03a3, 0x03a4, 0x03a5, 0x03c2, 0x03a9, 0x039e, 0x03a8, 0x0396, 0x005b, 0x2234, 0x005d, 0x22a5, 0x005f,
469
+ 0x203e, 0x03b1, 0x03b2, 0x03c7, 0x03b4, 0x03b5, 0x03c6, 0x03b3, 0x03b7, 0x03b9, 0x03d5, 0x03ba, 0x03bb, 0x03bc, 0x03bd, 0x03bf,
470
+ 0x03c0, 0x03b8, 0x03c1, 0x03c3, 0x03c4, 0x03c5, 0x03d6, 0x03c9, 0x03be, 0x03c8, 0x03b6, 0x007b, 0x007c, 0x007d, 0x223c, 0,
471
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
472
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
473
+ 0x20ac, 0x03d2, 0x2032, 0x2264, 0x2044, 0x221e, 0x0192, 0x2663, 0x2666, 0x2665, 0x2660, 0x2194, 0x2190, 0x2191, 0x2192, 0x2193,
474
+ 0x00b0, 0x00b1, 0x2033, 0x2265, 0x00d7, 0x221d, 0x2202, 0x2022, 0x00f7, 0x2260, 0x2261, 0x2248, 0x2026, 0x23d0, 0x23af, 0x21b5,
475
+ 0x2135, 0x2111, 0x211c, 0x2118, 0x2297, 0x2295, 0x2205, 0x2229, 0x222a, 0x2283, 0x2287, 0x2284, 0x2282, 0x2286, 0x2208, 0x2209,
476
+ 0x2220, 0x2207, 0x00ae, 0x00a9, 0x2122, 0x220f, 0x221a, 0x22c5, 0x00ac, 0x2227, 0x2228, 0x21d4, 0x21d0, 0x21d1, 0x21d2, 0x21d3,
477
+ 0x25ca, 0x3008, 0x00ae, 0x00a9, 0x2122, 0x2211, 0x239b, 0x239c, 0x239d, 0x23a1, 0x23a2, 0x23a3, 0x23a7, 0x23a8, 0x23a9, 0x23aa,
478
+ 0, 0x3009, 0x222b, 0x2320, 0x23ae, 0x2321, 0x239e, 0x239f, 0x23a0, 0x23a4, 0x23a5, 0x23a6, 0x23ab, 0x23ac, 0x23ad, 0
479
+ ];
480
+ /** A font named Symbol, or Symbol MT. */
481
+ function isSymbolFontName(name) {
482
+ return /^symbol(?: ?mt)?$/i.test(name.trim());
483
+ }
484
+ /** Text set in the Symbol font as the characters it shows. */
485
+ function symbolText(text) {
486
+ let out = '';
487
+ for (let i = 0; i < text.length; i++) {
488
+ let code = text.charCodeAt(i);
489
+ // Word writes a Symbol character as U+F000 plus its byte.
490
+ if (code >= 0xf020 && code <= 0xf0ff)
491
+ code -= 0xf000;
492
+ const shown = code >= 0x20 && code <= 0xff ? SYMBOL_FONT[code - 0x20] : 0;
493
+ out += shown ? String.fromCharCode(shown) : text[i];
494
+ }
495
+ return out;
496
+ }
497
+ /**
498
+ * The numbers of the fonts that are monospace, and of the ones that are Symbol. A font is
499
+ * monospace when it is named like one (Courier New, Consolas), or declared \fmodern or
500
+ * fixed-pitch (\fprq1). It is Symbol when it is named Symbol and declared in the symbol
501
+ * character set (\fcharset2), which is how Word declares it: only then are its bytes places in
502
+ * that font. TextEdit declares its Symbol font in the Mac character set (\fcharset77), where a
503
+ * byte is an ordinary character, and Apple's reader maps neither that nor a Symbol with no
504
+ * character set. Reads both shapes a font table comes in: one group per font
419
505
  * ({\f1\fmodern Courier New;}), and TextEdit's run of entries with no groups
420
506
  * (\f0\fswiss Helvetica;\f1\fmodern Courier;).
421
507
  */
422
- function monospaceFonts(group) {
508
+ function readFontTable(group) {
423
509
  const mono = new Set();
510
+ const symbol = new Set();
424
511
  let num = null;
425
512
  let name = '';
426
513
  let fixed = false;
514
+ let symbolSet = false;
427
515
  const finish = () => {
428
- if (num != null && (fixed || isMonospaceFontName(name)))
429
- mono.add(num);
516
+ if (num != null) {
517
+ if (fixed || isMonospaceFontName(name))
518
+ mono.add(num);
519
+ if (symbolSet && isSymbolFontName(name))
520
+ symbol.add(num);
521
+ }
430
522
  num = null;
431
523
  name = '';
432
524
  fixed = false;
525
+ symbolSet = false;
433
526
  };
434
527
  const read = (nodes) => {
435
528
  for (const node of nodes) {
@@ -442,6 +535,9 @@ function monospaceFonts(group) {
442
535
  else if (node.word === 'fmodern' || (node.word === 'fprq' && node.param === 1)) {
443
536
  fixed = true;
444
537
  }
538
+ else if (node.word === 'fcharset') {
539
+ symbolSet = node.param === 2;
540
+ }
445
541
  }
446
542
  else if (node.type === 'text') {
447
543
  // A name ends at its ';'.
@@ -461,7 +557,7 @@ function monospaceFonts(group) {
461
557
  }
462
558
  read(group.children.filter((n) => n.type !== 'group'));
463
559
  finish();
464
- return mono;
560
+ return { mono, symbol };
465
561
  }
466
562
  // ── Links ──
467
563
  /** The longest field instruction looked at for a link's address. */
@@ -482,6 +578,9 @@ function fieldInstruction(group) {
482
578
  else if (node.type === 'control') {
483
579
  if (node.word === 'u')
484
580
  return null;
581
+ // A tab between the instruction's words is a space between them.
582
+ if (node.word === 'tab')
583
+ text += ' ';
485
584
  }
486
585
  else {
487
586
  text += node.value;
@@ -491,16 +590,18 @@ function fieldInstruction(group) {
491
590
  }
492
591
  return text;
493
592
  }
593
+ /** The instruction of a {\field …} group as text, or null when it has none that can be read. */
594
+ function fieldText(field) {
595
+ const instruction = field.children.find((n) => n.type === 'group' && n.children.some((c) => c.type === 'control' && c.word === 'fldinst'));
596
+ return instruction ? fieldInstruction(instruction) : null;
597
+ }
494
598
  /**
495
599
  * The address a {\field …} group links to, or '' when it is not a link, or not one that may be
496
600
  * followed. Only what the writer itself would write is accepted (linkTarget): an absolute web,
497
601
  * mail or phone address. A javascript: or file: address, or a link to a bookmark, stays text.
498
602
  */
499
603
  function fieldLink(field) {
500
- const instruction = field.children.find((n) => n.type === 'group' && n.children.some((c) => c.type === 'control' && c.word === 'fldinst'));
501
- if (!instruction)
502
- return '';
503
- const text = fieldInstruction(instruction);
604
+ const text = fieldText(field);
504
605
  if (text == null)
505
606
  return '';
506
607
  const m = text.match(/^\s*HYPERLINK\s+(?:"([^"]*)"|([^\s"\\]\S*))/i);
@@ -508,6 +609,37 @@ function fieldLink(field) {
508
609
  return '';
509
610
  return linkTarget(m[1] ?? m[2] ?? '') ?? '';
510
611
  }
612
+ /**
613
+ * The character of a symbol field, {\field{\*\fldinst SYMBOL 176 \\f "Symbol"}}, which is how Word
614
+ * stores a character put in with Insert Symbol: its number, and the font it is a character of.
615
+ * '' when the field is not one, or its font is one whose characters are not known here
616
+ * (Wingdings): the field's own result is shown then, as for any other field.
617
+ */
618
+ function fieldSymbol(field) {
619
+ const text = fieldText(field);
620
+ if (text == null)
621
+ return '';
622
+ const m = text.match(/^\s*SYMBOL\s+(0x[0-9a-f]+|\d+)(?![0-9a-z])([\s\S]*)$/i);
623
+ if (!m)
624
+ return '';
625
+ const code = Number(m[1]);
626
+ const font = /\\f\s*"([^"]*)"/i.exec(m[2])?.[1] ?? /\\f\s+([^\s"\\]+)/i.exec(m[2])?.[1];
627
+ if (font != null && isSymbolFontName(font)) {
628
+ const byte = code >= 0xf020 && code <= 0xf0ff ? code - 0xf000 : code;
629
+ const shown = byte >= 0x20 && byte <= 0xff ? SYMBOL_FONT[byte - 0x20] : 0;
630
+ return shown ? String.fromCharCode(shown) : '';
631
+ }
632
+ // Another font: what the number shows depends on that font.
633
+ if (font != null)
634
+ return '';
635
+ // No font: the number is the character's own. A \\u switch says Unicode; without it a
636
+ // number below 256 is a byte of Windows-1252.
637
+ if (code < 0x20 || code > 0x10ffff || (code >= 0xd800 && code <= 0xdfff))
638
+ return '';
639
+ if (code < 256 && !/\\u(?![a-z])/i.test(m[2]))
640
+ return cp1252Char(code);
641
+ return String.fromCodePoint(code);
642
+ }
511
643
  // ── Body size ──
512
644
  /** Groups whose content is not document text. */
513
645
  const destinationWords = new Set([
@@ -517,7 +649,12 @@ const destinationWords = new Set([
517
649
  'nonshppict',
518
650
  // {\nonesttables \par} is for readers that do not know nested tables; \nestrow is read here
519
651
  'nonesttables',
520
- 'object', 'fldinst', 'xmlnstbl', 'listtable', 'listoverridetable',
652
+ // (\object is handled where groups are read: its data is skipped and its \result shown)
653
+ 'objdata', 'objclass', 'objname', 'fldinst', 'xmlnstbl',
654
+ // An index entry and a contents entry: text that is shown in the index, not where it is marked
655
+ 'xe', 'tc', 'tcn',
656
+ // The drawing a shape is shown as where shapes are not read; the shape itself is read
657
+ 'shprslt', 'listtable', 'listoverridetable',
521
658
  'rsidtbl', 'generator', 'datafield', 'themedata', 'colorschememapping',
522
659
  'latentstyles', 'datastore', 'mmathPr', 'author', 'operator',
523
660
  'title', 'subject', 'doccomm', 'company', 'category', 'keywords'
@@ -563,7 +700,19 @@ function figureIndentStyle(block) {
563
700
  * a non-breaking space or an em space there is text someone put there, and is kept.
564
701
  */
565
702
  function trimSpaces(html) {
566
- return html.replace(/^[ \t\r\n\f]+|[ \t\r\n\f]+$/g, '');
703
+ // Two loops, not a regular expression: /[ \t]+$/ starts again at every space of a long run
704
+ // that does not reach the end, and 200,000 spaces in a paragraph took 23 seconds.
705
+ let start = 0;
706
+ let end = html.length;
707
+ while (start < end && isSpace(html.charCodeAt(start)))
708
+ start++;
709
+ while (end > start && isSpace(html.charCodeAt(end - 1)))
710
+ end--;
711
+ return start === 0 && end === html.length ? html : html.slice(start, end);
712
+ }
713
+ /** Space, tab, line feed, form feed, carriage return. */
714
+ function isSpace(code) {
715
+ return code === 32 || (code >= 9 && code <= 13 && code !== 11);
567
716
  }
568
717
  function escapeText(text) {
569
718
  return text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
@@ -599,19 +748,45 @@ export function rtfToHtml(rtfString, options = {}) {
599
748
  if (maxBytes > 0 && rtfString.length > maxBytes) {
600
749
  throw new RangeError(`This document is too large to show: ${overLimit(rtfString.length, maxBytes)}`);
601
750
  }
602
- const tokens = tokenize(rtfString);
603
- const tree = buildTree(tokens);
751
+ const tree = parseTree(rtfString);
604
752
  let colorTable = [''];
605
753
  let monoFonts = new Set();
754
+ let symbolFonts = new Set();
606
755
  let defaultFont = 0;
607
- const blocks = [];
756
+ /** Where finished paragraphs and tables go: the document, or the footnote or text box being read. */
757
+ let blocks = [];
608
758
  // The paragraph being read
609
759
  let runs = [];
760
+ /** Nothing but text has been read into the paragraph so far. */
761
+ let onlyText = true;
762
+ /**
763
+ * The alignment in force where the paragraph's last piece was read. A paragraph whose
764
+ * alignment was set in a group that closes before its \par ({\qc Title}\par, or a cell
765
+ * written {\pard\intbl\qr 1.0\par}\cell) is still that paragraph's: Apple's reader shows it
766
+ * so, and so did this one while alignment was not kept with the group.
767
+ */
768
+ let contentAlign = 'left';
610
769
  let marker = null;
611
770
  let paragraphHasListMarker = false;
612
771
  let paragraphIsCaption = false;
613
- // Paragraph alignment (reset by \pard, affects cells and paragraphs)
614
- let currentAlign = 'left';
772
+ /**
773
+ * Text boxes met while a paragraph or a table was being read. A box is not part of the line
774
+ * it is anchored in: its text goes after that paragraph, or after that table.
775
+ */
776
+ let paragraphAsides = [];
777
+ let tableAsides = [];
778
+ /** Each footnote's paragraphs, in the order the notes were met. They go at the end. */
779
+ const notes = [];
780
+ /** How many footnotes have been given a number. */
781
+ let noteCount = 0;
782
+ /** The number written where the text refers to a note, until the note itself takes it. */
783
+ let noteMark = 0;
784
+ /** Inside a footnote: its number, or 0 until it has one. Outside: -1. */
785
+ let noteNumber = -1;
786
+ /** Reading a footnote or text box that sits in hidden or deleted text: none of it is shown. */
787
+ let unshown = false;
788
+ /** Where in the stack of formatting states the footnote or text box being read begins. */
789
+ let stateBase = 0;
615
790
  // Table state
616
791
  let tableRows = [];
617
792
  let currentRowCells = [];
@@ -621,18 +796,34 @@ export function rtfToHtml(rtfString, options = {}) {
621
796
  let pendingDef = newCellDef();
622
797
  /** The side a \clbrdrX just named, until a border type (\brdrs...) confirms or \brdrnone clears it. */
623
798
  let pendingSide = null;
624
- /** The sides of the cell being defined that have a real border. */
625
- let cellBorders = { b: false, other: false };
799
+ /**
800
+ * The sides of the cell being defined that have a real border, and whether the bottom one is
801
+ * the bare \brdrs the writer marks a header cell with: no width, no color.
802
+ */
803
+ let cellBorders = { b: false, other: false, bare: false };
804
+ /** The side whose border type was read last, which a \brdrw or \brdrcf after it belongs to. */
805
+ let borderSide = null;
626
806
  let inTableCell = false;
627
807
  /** \par seen in a table cell since its last text: line breaks owed if more text follows. */
628
808
  let cellBreaks = 0;
809
+ /** \lastrow seen in the definition of the row being read: its \row ends the table. */
810
+ let lastRow = false;
629
811
  /** \nestcell seen: a tab is owed if more text follows on the line. */
630
812
  let nestTabPending = false;
631
813
  function newCellDef() {
632
814
  return { right: 0, header: false, vmgf: false, vmrg: false, hmgf: false, hmrg: false };
633
815
  }
816
+ // The document is the first group. A byte-order mark or blank lines before it (a file saved
817
+ // by a tool that adds them) do not make it something else: with those the color and font
818
+ // tables were not found, and every color and code font was lost.
819
+ const firstGroupAt = tree.children.findIndex((n) => n.type === 'group');
820
+ const rootGroup = firstGroupAt >= 0 &&
821
+ tree.children
822
+ .slice(0, firstGroupAt)
823
+ .every((n) => (n.type === 'text' ? /^[\s\uFEFF\u00EF\u00BB\u00BF]*$/.test(n.value) : n.type === 'control' && n.word === 'tab'))
824
+ ? tree.children[firstGroupAt]
825
+ : tree;
634
826
  // First pass: extract color table and font table from the root group
635
- const rootGroup = tree.children[0]?.type === 'group' ? tree.children[0] : tree;
636
827
  for (let i = 0; i < rootGroup.children.length; i++) {
637
828
  const child = rootGroup.children[i];
638
829
  if (child.type === 'group') {
@@ -641,7 +832,7 @@ export function rtfToHtml(rtfString, options = {}) {
641
832
  colorTable = parseColorTable(child);
642
833
  }
643
834
  else if (firstControl?.word === 'fonttbl') {
644
- monoFonts = monospaceFonts(child);
835
+ ({ mono: monoFonts, symbol: symbolFonts } = readFontTable(child));
645
836
  }
646
837
  }
647
838
  else if (child.type === 'control' && child.word === 'deff' && child.param != null) {
@@ -671,6 +862,9 @@ export function rtfToHtml(rtfString, options = {}) {
671
862
  fontIndex: defaultFont,
672
863
  ucSkip: 1,
673
864
  inList: false,
865
+ hidden: false,
866
+ deleted: false,
867
+ align: 'left',
674
868
  link: '',
675
869
  leftIndent: 0,
676
870
  rightIndent: 0,
@@ -786,6 +980,22 @@ export function rtfToHtml(rtfString, options = {}) {
786
980
  // ── Collecting a paragraph ──
787
981
  /** Half of a surrogate pair read from \uN, waiting for the \uN that completes the character. */
788
982
  let pendingHighSurrogate = 0;
983
+ /** A piece of the paragraph that is not text: a line break, a tab, a picture. */
984
+ function pushHtml(kind, html, state) {
985
+ runs.push({ type: 'html', kind, html, fmt: formatOf(state) });
986
+ onlyText = false;
987
+ }
988
+ /** An empty paragraph to read into. */
989
+ function newRuns() {
990
+ runs = [];
991
+ onlyText = true;
992
+ contentAlign = 'left';
993
+ marker = null;
994
+ }
995
+ /** The alignment of the paragraph, or the cell, that ends here: see contentAlign. */
996
+ function alignHere(state) {
997
+ return state.align !== 'left' || runs.length === 0 ? state.align : contentAlign;
998
+ }
789
999
  function pushText(text, state) {
790
1000
  if (!text)
791
1001
  return;
@@ -816,6 +1026,7 @@ export function rtfToHtml(rtfString, options = {}) {
816
1026
  }
817
1027
  /** What is owed before the next piece of a paragraph: see cellBreaks and nestTabPending. */
818
1028
  function beforeContent(state) {
1029
+ contentAlign = state.align;
819
1030
  if (pendingHighSurrogate) {
820
1031
  // A lone half of a pair is no character.
821
1032
  pendingHighSurrogate = 0;
@@ -827,7 +1038,7 @@ export function rtfToHtml(rtfString, options = {}) {
827
1038
  if (inTableCell) {
828
1039
  // A paragraph mark inside a cell: the cell's text goes on, on a new line.
829
1040
  for (let k = 0; k < count; k++)
830
- runs.push({ type: 'html', kind: 'br', html: '<br>', fmt: formatOf(state) });
1041
+ pushHtml('br', '<br>', state);
831
1042
  }
832
1043
  else {
833
1044
  // \pard has left the table without a \cell: what was read is a paragraph.
@@ -837,18 +1048,69 @@ export function rtfToHtml(rtfString, options = {}) {
837
1048
  }
838
1049
  if (nestTabPending) {
839
1050
  nestTabPending = false;
840
- runs.push({ type: 'html', kind: 'tab', html: TAB_HTML, fmt: formatOf(state) });
1051
+ pushHtml('tab', TAB_HTML, state);
841
1052
  }
842
1053
  }
1054
+ /**
1055
+ * Whether what is being read is shown at all. Hidden text (\v) is not, in Word or anywhere:
1056
+ * it holds notes and field codes. Nor is text a tracked change deleted (\deleted), which is
1057
+ * still in the file beside what replaced it, so "malignant" struck out and "benign" put in
1058
+ * read "malignantbenign".
1059
+ */
1060
+ function shown(state) {
1061
+ return !unshown && !state.hidden && !state.deleted;
1062
+ }
843
1063
  function appendText(text, state) {
844
- if (!text)
1064
+ if (!text || !shown(state))
845
1065
  return;
846
1066
  beforeContent(state);
847
1067
  pushText(text, state);
848
1068
  }
849
1069
  function appendHtml(kind, html, state) {
1070
+ if (!shown(state))
1071
+ return;
850
1072
  beforeContent(state);
851
- runs.push({ type: 'html', kind, html, fmt: formatOf(state) });
1073
+ pushHtml(kind, html, state);
1074
+ }
1075
+ /** \par, where it ends a paragraph and where, in a table cell, it starts a new line. */
1076
+ function paragraphMark(state) {
1077
+ if (inTableCell) {
1078
+ cellBreaks++;
1079
+ }
1080
+ else {
1081
+ // Paragraph marks from a cell that \pard has since left end paragraphs too.
1082
+ for (; cellBreaks > 0; cellBreaks--)
1083
+ flushParagraph();
1084
+ flushParagraph();
1085
+ }
1086
+ }
1087
+ /**
1088
+ * Text as the file has it. In a Symbol font each character is the sign that font shows for
1089
+ * it. U+2028 is a line break (TextEdit writes Shift-Return that way; a browser shows nothing
1090
+ * for the character itself, and the two lines ran together) and U+2029 a paragraph mark.
1091
+ */
1092
+ function appendChars(text, state, bytes = true) {
1093
+ if (!text || !shown(state))
1094
+ return;
1095
+ if (bytes && symbolFonts.has(state.fontIndex))
1096
+ text = symbolText(text);
1097
+ if (!LINE_SEPARATOR.test(text)) {
1098
+ appendText(text, state);
1099
+ return;
1100
+ }
1101
+ let from = 0;
1102
+ for (let i = 0; i < text.length; i++) {
1103
+ const code = text.charCodeAt(i);
1104
+ if (code !== 0x2028 && code !== 0x2029)
1105
+ continue;
1106
+ appendText(text.slice(from, i), state);
1107
+ if (code === 0x2028)
1108
+ appendHtml('br', '<br>', state);
1109
+ else
1110
+ paragraphMark(state);
1111
+ from = i + 1;
1112
+ }
1113
+ appendText(text.slice(from), state);
852
1114
  }
853
1115
  /** The text of the line being read, back to the last line break, if text is all it holds. */
854
1116
  function lineText() {
@@ -864,17 +1126,19 @@ export function rtfToHtml(rtfString, options = {}) {
864
1126
  return text;
865
1127
  }
866
1128
  function appendTab(state) {
1129
+ if (!shown(state))
1130
+ return;
867
1131
  beforeContent(state);
868
1132
  // A real tab, in the shape the editor's Tab key inserts, so it shows as
869
- // one and is written back as \tab (an em space came back as 膕).
1133
+ // one and is written back as \tab (an em space came back as a \u escape for U+2003).
870
1134
  // After a list marker ("\bullet\tab", "1.\tab") the gap stays an em
871
1135
  // space where the line is read as a plain one: a full tab there is too wide.
872
1136
  const lead = lineText();
873
1137
  // Only a marker that opens the paragraph can make it a list item.
874
- const opensParagraph = marker === null && runs.every((r) => r.type === 'text');
1138
+ const opensParagraph = marker === null && onlyText;
875
1139
  const listed = lead != null ? lead.match(LIST_MARKER) : null;
876
1140
  if (listed) {
877
- runs.push({ type: 'html', kind: 'gap', html: '&emsp;', fmt: formatOf(state) });
1141
+ pushHtml('gap', '&emsp;', state);
878
1142
  // (A number too long to be an item's number is text, and so is one written with a
879
1143
  // leading zero, "01.": a list would show it as "1.".)
880
1144
  if (opensParagraph && (!listed[1] || (listed[1].length <= MAX_LIST_NUMBER_DIGITS && !/^0\d/.test(listed[1])))) {
@@ -884,7 +1148,7 @@ export function rtfToHtml(rtfString, options = {}) {
884
1148
  }
885
1149
  return;
886
1150
  }
887
- runs.push({ type: 'html', kind: 'tab', html: TAB_HTML, fmt: formatOf(state) });
1151
+ pushHtml('tab', TAB_HTML, state);
888
1152
  // Word's bullet, inside {\listtext …} or {\pntext …}.
889
1153
  if (opensParagraph && lead != null && state.inList && SYMBOL_BULLET.test(lead)) {
890
1154
  marker = { kind: 'ul', number: 0, end: runs.length };
@@ -958,13 +1222,16 @@ export function rtfToHtml(rtfString, options = {}) {
958
1222
  }
959
1223
  // A vertical merge: the cell marked \clvmgf takes in each \clvmrg cell under it, row
960
1224
  // after row. A \clvmrg cell with nothing above it to join stays an ordinary cell.
1225
+ // Each row's cells by the column they start in, so the cell under another is looked up,
1226
+ // not searched for: a search per merged cell took a second for a row of 40,000.
1227
+ const byStart = placedRows.map((row) => new Map(row.map((c) => [c.start, c])));
961
1228
  for (let r = 0; r < placedRows.length; r++) {
962
1229
  for (const cell of placedRows[r]) {
963
1230
  if (!cell.def.vmgf || cell.merged)
964
1231
  continue;
965
1232
  for (let below = r + 1; below < placedRows.length; below++) {
966
- const under = placedRows[below].find((c) => c.start === cell.start && c.def.vmrg && !c.merged);
967
- if (!under)
1233
+ const under = byStart[below].get(cell.start);
1234
+ if (!under || !under.def.vmrg || under.merged)
968
1235
  break;
969
1236
  under.merged = true;
970
1237
  cell.rowspan++;
@@ -1000,6 +1267,9 @@ export function rtfToHtml(rtfString, options = {}) {
1000
1267
  }
1001
1268
  html += '</table>';
1002
1269
  blocks.push({ kind: 'table', html });
1270
+ for (const aside of tableAsides)
1271
+ blocks.push(aside);
1272
+ tableAsides = [];
1003
1273
  }
1004
1274
  function flushParagraph() {
1005
1275
  const state = currentState();
@@ -1013,7 +1283,7 @@ export function rtfToHtml(rtfString, options = {}) {
1013
1283
  blocks.push({
1014
1284
  kind: 'paragraph',
1015
1285
  runs,
1016
- align: currentAlign,
1286
+ align: alignHere(state),
1017
1287
  left: state.leftIndent,
1018
1288
  right: state.rightIndent,
1019
1289
  first: state.firstLineIndent,
@@ -1022,12 +1292,39 @@ export function rtfToHtml(rtfString, options = {}) {
1022
1292
  inTable: inTableCell
1023
1293
  });
1024
1294
  }
1025
- runs = [];
1026
- marker = null;
1295
+ newRuns();
1027
1296
  paragraphHasListMarker = false;
1028
1297
  paragraphIsCaption = false;
1029
- currentAlign = 'left';
1030
1298
  nestTabPending = false;
1299
+ for (const aside of paragraphAsides)
1300
+ blocks.push(aside);
1301
+ paragraphAsides = [];
1302
+ }
1303
+ /** What is still being read when the document, a footnote or a text box ends. */
1304
+ function finishContent() {
1305
+ if (pendingHighSurrogate) {
1306
+ pendingHighSurrogate = 0;
1307
+ pushText('\uFFFD', currentState());
1308
+ }
1309
+ // A row the file ends in the middle of, with cells and no \row, is still a row.
1310
+ if (currentRowCells.length > 0) {
1311
+ tableRows.push({ cells: currentRowCells, defs: currentRowDefs.length > 0 ? currentRowDefs : lastRowDefs });
1312
+ currentRowCells = [];
1313
+ inTableCell = false;
1314
+ }
1315
+ flushTable(); // flush any trailing table rows
1316
+ // Only flush if there's actually pending content — the final \par in most RTF
1317
+ // files already flushed the last paragraph, so an unconditional call here
1318
+ // would push a spurious empty paragraph that becomes a trailing <p><br></p>.
1319
+ if (runs.length > 0) {
1320
+ flushParagraph();
1321
+ }
1322
+ for (const aside of tableAsides)
1323
+ blocks.push(aside);
1324
+ for (const aside of paragraphAsides)
1325
+ blocks.push(aside);
1326
+ tableAsides = [];
1327
+ paragraphAsides = [];
1031
1328
  }
1032
1329
  let pendingUnicodeSkip = 0;
1033
1330
  const frames = [{ nodes: rootGroup.children, index: 0, scoped: false }];
@@ -1035,23 +1332,157 @@ export function rtfToHtml(rtfString, options = {}) {
1035
1332
  stateStack.push(state);
1036
1333
  frames.push({ nodes: group.children, index: 0, scoped: true });
1037
1334
  };
1335
+ const firstControl = (group) => group.children.find((n) => n.type === 'control');
1336
+ /**
1337
+ * A group whose text is not part of the line it sits in: a footnote, a text box. It is read
1338
+ * as a small document of its own, with its own paragraphs and tables, and what was being read
1339
+ * around it is put back as it was afterwards. Read in place, a footnote's paragraph mark
1340
+ * split the sentence it was in, and its \pard took a table cell out of its table.
1341
+ */
1342
+ function aside(group, done, note = false) {
1343
+ let restore = () => { };
1344
+ return {
1345
+ nodes: group.children,
1346
+ index: 0,
1347
+ scoped: true,
1348
+ enter() {
1349
+ const saved = {
1350
+ blocks, runs, onlyText, marker, paragraphHasListMarker, paragraphIsCaption, paragraphAsides,
1351
+ tableAsides, tableRows, currentRowCells, currentRowDefs, lastRowDefs, pendingDef, pendingSide,
1352
+ cellBorders, borderSide, inTableCell, cellBreaks, contentAlign, lastRow, nestTabPending,
1353
+ pendingHighSurrogate, pendingUnicodeSkip, noteNumber, unshown, stateBase
1354
+ };
1355
+ restore = () => {
1356
+ ({
1357
+ blocks, runs, onlyText, marker, paragraphHasListMarker, paragraphIsCaption, paragraphAsides,
1358
+ tableAsides, tableRows, currentRowCells, currentRowDefs, lastRowDefs, pendingDef, pendingSide,
1359
+ cellBorders, borderSide, inTableCell, cellBreaks, contentAlign, lastRow, nestTabPending,
1360
+ pendingHighSurrogate, pendingUnicodeSkip, noteNumber, unshown, stateBase
1361
+ } = saved);
1362
+ };
1363
+ blocks = [];
1364
+ newRuns();
1365
+ paragraphHasListMarker = false;
1366
+ paragraphIsCaption = false;
1367
+ paragraphAsides = [];
1368
+ tableAsides = [];
1369
+ tableRows = [];
1370
+ currentRowCells = [];
1371
+ currentRowDefs = [];
1372
+ lastRowDefs = [];
1373
+ pendingDef = newCellDef();
1374
+ pendingSide = null;
1375
+ cellBorders = { b: false, other: false, bare: false };
1376
+ borderSide = null;
1377
+ inTableCell = false;
1378
+ cellBreaks = 0;
1379
+ lastRow = false;
1380
+ nestTabPending = false;
1381
+ pendingHighSurrogate = 0;
1382
+ pendingUnicodeSkip = 0;
1383
+ if (note) {
1384
+ noteNumber = noteMark;
1385
+ noteMark = 0;
1386
+ }
1387
+ // Its own formatting from the start: Word opens every one with \pard\plain. What
1388
+ // stays is whether the text around it is shown at all: a note in hidden or
1389
+ // deleted text is not, whatever \plain inside it resets.
1390
+ const outer = currentState();
1391
+ unshown = !shown(outer);
1392
+ stateBase = stateStack.length;
1393
+ stateStack.push({ ...defaultState(), ucSkip: outer.ucSkip });
1394
+ },
1395
+ exit() {
1396
+ finishContent();
1397
+ const read = unshown ? [] : blocks;
1398
+ restore();
1399
+ done(read);
1400
+ }
1401
+ };
1402
+ }
1403
+ /** A text box's paragraphs, kept until the paragraph or the table it is anchored in is done. */
1404
+ const keepAside = (read) => {
1405
+ const target = inTableCell || currentRowCells.length > 0 ? tableAsides : paragraphAsides;
1406
+ for (const block of read)
1407
+ target.push(block);
1408
+ };
1409
+ /**
1410
+ * A drawing, {\shp{\*\shpinst …}}: a text box, a picture with text wrapped around it. The
1411
+ * pictures in it are shown where it is anchored and the text of its boxes is read after the
1412
+ * paragraph; the rest of a drawing (lines, fills, positions) is not shown.
1413
+ */
1414
+ function readShape(shape) {
1415
+ const boxes = [];
1416
+ const pending = [shape];
1417
+ while (pending.length > 0) {
1418
+ const node = pending.pop();
1419
+ if (node.type !== 'group')
1420
+ continue;
1421
+ const word = node.children.find((n) => n.type === 'control' && n.word !== '*')?.word;
1422
+ if (word === 'shptxt') {
1423
+ boxes.push(node);
1424
+ continue;
1425
+ }
1426
+ if (word === 'sp') {
1427
+ // A property of the shape. The one named pib holds its picture.
1428
+ const groups = node.children.filter((n) => n.type === 'group');
1429
+ const name = groups.find((g) => firstControl(g)?.word === 'sn');
1430
+ const value = groups.find((g) => firstControl(g)?.word === 'sv');
1431
+ const isPicture = name?.children.some((n) => n.type === 'text' && n.value.trim() === 'pib');
1432
+ const picture = isPicture
1433
+ ? value?.children.find((n) => n.type === 'group' && firstControl(n)?.word === 'pict')
1434
+ : undefined;
1435
+ if (picture) {
1436
+ const img = renderPicture(picture);
1437
+ if (img)
1438
+ appendHtml('img', img, currentState());
1439
+ }
1440
+ continue;
1441
+ }
1442
+ for (let i = node.children.length - 1; i >= 0; i--)
1443
+ pending.push(node.children[i]);
1444
+ }
1445
+ // The last one first: the frame pushed last is read first.
1446
+ for (let i = boxes.length - 1; i >= 0; i--)
1447
+ frames.push(aside(boxes[i], keepAside));
1448
+ }
1038
1449
  while (frames.length > 0) {
1039
1450
  const frame = frames[frames.length - 1];
1451
+ if (frame.enter) {
1452
+ const enter = frame.enter;
1453
+ frame.enter = undefined;
1454
+ enter();
1455
+ }
1040
1456
  if (frame.index >= frame.nodes.length) {
1041
1457
  frames.pop();
1458
+ frame.exit?.();
1042
1459
  if (frame.scoped)
1043
1460
  stateStack.pop();
1044
1461
  continue;
1045
1462
  }
1046
1463
  const node = frame.nodes[frame.index++];
1047
1464
  if (node.type === 'group') {
1048
- const firstCtrl = node.children.find((n) => n.type === 'control');
1465
+ const firstCtrl = firstControl(node);
1049
1466
  if (firstCtrl?.word === 'pict') {
1050
1467
  const img = renderPicture(node);
1051
1468
  if (img)
1052
1469
  appendHtml('img', img, currentState());
1053
1470
  continue;
1054
1471
  }
1472
+ if (firstCtrl?.word === 'footnote') {
1473
+ // A footnote or an endnote. Its text goes to the end of the document; the number
1474
+ // that refers to it (\chftn) stays where it is in the text.
1475
+ frames.push(aside(node, (read) => notes.push(read), true));
1476
+ continue;
1477
+ }
1478
+ if (firstCtrl?.word === 'object') {
1479
+ // An embedded object: a spreadsheet, an equation. Its data is not read; what it
1480
+ // carries to be shown in its place, {\result …}, is.
1481
+ const result = node.children.find((n) => n.type === 'group' && firstControl(n)?.word === 'result');
1482
+ if (result)
1483
+ enterGroup(result, cloneState());
1484
+ continue;
1485
+ }
1055
1486
  if (firstCtrl && destinationWords.has(firstCtrl.word)) {
1056
1487
  continue;
1057
1488
  }
@@ -1064,6 +1495,9 @@ export function rtfToHtml(rtfString, options = {}) {
1064
1495
  if (dest?.word === 'shppict') {
1065
1496
  enterGroup(node, cloneState());
1066
1497
  }
1498
+ else if (dest?.word === 'shpinst') {
1499
+ readShape(node);
1500
+ }
1067
1501
  else if (dest?.word === 'inkcap') {
1068
1502
  // Marks the paragraph that follows as a picture caption.
1069
1503
  paragraphIsCaption = true;
@@ -1080,6 +1514,13 @@ export function rtfToHtml(rtfString, options = {}) {
1080
1514
  // {\field{\*\fldinst HYPERLINK "…"}{\fldrslt text}}: the text is a link, if the
1081
1515
  // address is one the writer would write.
1082
1516
  if (firstCtrl?.word === 'field') {
1517
+ // A character put in with Insert Symbol: the field says which, and that is
1518
+ // shown in place of the field's own result.
1519
+ const symbol = fieldSymbol(node);
1520
+ if (symbol) {
1521
+ appendText(symbol, currentState());
1522
+ continue;
1523
+ }
1083
1524
  const href = fieldLink(node);
1084
1525
  if (href)
1085
1526
  state.link = href;
@@ -1117,8 +1558,9 @@ export function rtfToHtml(rtfString, options = {}) {
1117
1558
  state.sub = false;
1118
1559
  break;
1119
1560
  case 'fs':
1561
+ // (Up to Word's limit of 1638 pt; a damaged file can say anything.)
1120
1562
  if (p != null)
1121
- state.fontSize = p;
1563
+ state.fontSize = Math.min(Math.max(p, 0), 3276);
1122
1564
  break;
1123
1565
  case 'cf':
1124
1566
  if (p != null)
@@ -1134,17 +1576,25 @@ export function rtfToHtml(rtfString, options = {}) {
1134
1576
  if (p != null)
1135
1577
  state.fontIndex = p;
1136
1578
  break;
1579
+ // Alignment is the paragraph's and holds, like an indent, until \pard: Word and
1580
+ // TextEdit state it once for a run of centered paragraphs, not once for each.
1137
1581
  case 'ql':
1138
- currentAlign = 'left';
1582
+ state.align = 'left';
1139
1583
  break;
1140
1584
  case 'qr':
1141
- currentAlign = 'right';
1585
+ state.align = 'right';
1142
1586
  break;
1143
1587
  case 'qc':
1144
- currentAlign = 'center';
1588
+ state.align = 'center';
1145
1589
  break;
1146
1590
  case 'qj':
1147
- currentAlign = 'justify';
1591
+ state.align = 'justify';
1592
+ break;
1593
+ case 'v':
1594
+ state.hidden = p !== 0;
1595
+ break;
1596
+ case 'deleted':
1597
+ state.deleted = p !== 0;
1148
1598
  break;
1149
1599
  case 'li':
1150
1600
  state.leftIndent = p ?? 0;
@@ -1158,15 +1608,7 @@ export function rtfToHtml(rtfString, options = {}) {
1158
1608
  case 'par':
1159
1609
  case 'sect':
1160
1610
  // \sect ends a section, and with it the paragraph: "A\sect B" is two lines.
1161
- if (inTableCell) {
1162
- cellBreaks++;
1163
- }
1164
- else {
1165
- // Paragraph marks from a cell that \pard has since left end paragraphs too.
1166
- for (; cellBreaks > 0; cellBreaks--)
1167
- flushParagraph();
1168
- flushParagraph();
1169
- }
1611
+ paragraphMark(state);
1170
1612
  break;
1171
1613
  case 'trowd':
1172
1614
  // A row's definition, not its start: Word writes the definition before the
@@ -1174,7 +1616,12 @@ export function rtfToHtml(rtfString, options = {}) {
1174
1616
  currentRowDefs = [];
1175
1617
  pendingDef = newCellDef();
1176
1618
  pendingSide = null;
1177
- cellBorders = { b: false, other: false };
1619
+ borderSide = null;
1620
+ cellBorders = { b: false, other: false, bare: false };
1621
+ lastRow = false;
1622
+ break;
1623
+ case 'lastrow':
1624
+ lastRow = true;
1178
1625
  break;
1179
1626
  case 'trgaph':
1180
1627
  case 'trkeep':
@@ -1186,13 +1633,24 @@ export function rtfToHtml(rtfString, options = {}) {
1186
1633
  case 'clbrdrl':
1187
1634
  case 'clbrdrt':
1188
1635
  pendingSide = 'other';
1636
+ borderSide = null;
1189
1637
  break;
1190
1638
  case 'clbrdrb':
1191
1639
  pendingSide = 'b';
1640
+ borderSide = null;
1192
1641
  break;
1193
1642
  case 'brdrnone':
1194
1643
  case 'brdrnil':
1195
1644
  pendingSide = null;
1645
+ borderSide = null;
1646
+ break;
1647
+ case 'brdrw':
1648
+ case 'brdrcf':
1649
+ // A width or a color: a line someone drew under the cell (a signature line,
1650
+ // the rule that closes a table), which Word and TextEdit never write
1651
+ // without one. The writer's header mark is the bare \clbrdrb\brdrs.
1652
+ if (borderSide === 'b')
1653
+ cellBorders.bare = false;
1196
1654
  break;
1197
1655
  // Every border style RTF names: any of them makes the side a border.
1198
1656
  case 'brdrs':
@@ -1222,8 +1680,12 @@ export function rtfToHtml(rtfString, options = {}) {
1222
1680
  case 'brdrengrave':
1223
1681
  case 'brdroutset':
1224
1682
  case 'brdrinset':
1225
- if (pendingSide)
1683
+ if (pendingSide) {
1226
1684
  cellBorders[pendingSide] = true;
1685
+ if (pendingSide === 'b')
1686
+ cellBorders.bare = w === 'brdrs';
1687
+ }
1688
+ borderSide = pendingSide;
1227
1689
  pendingSide = null;
1228
1690
  break;
1229
1691
  case 'clvmgf':
@@ -1241,12 +1703,13 @@ export function rtfToHtml(rtfString, options = {}) {
1241
1703
  case 'cellx':
1242
1704
  if (p != null) {
1243
1705
  pendingDef.right = p;
1244
- pendingDef.header = cellBorders.b && !cellBorders.other;
1706
+ pendingDef.header = cellBorders.b && cellBorders.bare && !cellBorders.other;
1245
1707
  currentRowDefs.push(pendingDef);
1246
1708
  }
1247
1709
  pendingDef = newCellDef();
1248
1710
  pendingSide = null;
1249
- cellBorders = { b: false, other: false };
1711
+ borderSide = null;
1712
+ cellBorders = { b: false, other: false, bare: false };
1250
1713
  break;
1251
1714
  case 'intbl':
1252
1715
  inTableCell = true;
@@ -1256,10 +1719,14 @@ export function rtfToHtml(rtfString, options = {}) {
1256
1719
  pendingHighSurrogate = 0;
1257
1720
  pushText('\ufffd', state);
1258
1721
  }
1259
- currentRowCells.push({ html: trimSpaces(renderRuns(runs)), align: currentAlign });
1260
- runs = [];
1261
- marker = null;
1262
- currentAlign = 'left';
1722
+ currentRowCells.push({
1723
+ html: trimSpaces(renderRuns(runs)),
1724
+ // The alignment of the cell's last paragraph, also where that paragraph
1725
+ // was ended inside a group ({\pard\intbl\qr 1.0\par}\cell, as this writer
1726
+ // wrote cells up to 1.9.0).
1727
+ align: alignHere(state)
1728
+ });
1729
+ newRuns();
1263
1730
  // The paragraph mark that ends a cell's last paragraph adds no line.
1264
1731
  cellBreaks = 0;
1265
1732
  nestTabPending = false;
@@ -1277,9 +1744,8 @@ export function rtfToHtml(rtfString, options = {}) {
1277
1744
  // Text after the row's last \cell is a cell that was not closed, not the
1278
1745
  // start of the paragraph after the table.
1279
1746
  if (trimSpaces(renderRuns(runs))) {
1280
- currentRowCells.push({ html: trimSpaces(renderRuns(runs)), align: currentAlign });
1281
- runs = [];
1282
- marker = null;
1747
+ currentRowCells.push({ html: trimSpaces(renderRuns(runs)), align: alignHere(state) });
1748
+ newRuns();
1283
1749
  }
1284
1750
  // A row with no definition of its own repeats the one before it.
1285
1751
  const defs = currentRowDefs.length > 0 ? currentRowDefs : lastRowDefs;
@@ -1291,15 +1757,27 @@ export function rtfToHtml(rtfString, options = {}) {
1291
1757
  inTableCell = false;
1292
1758
  cellBreaks = 0;
1293
1759
  nestTabPending = false;
1294
- // The cell's indents end with the table, in whichever group set them:
1295
- // \row may sit in a group of its own ({\row}).
1296
- stateStack.forEach(resetIndents);
1760
+ // The cell's indents and alignment end with the row, in whichever group
1761
+ // set them: \row may sit in a group of its own ({\row}). Not in the text a
1762
+ // footnote or text box is anchored in, though: a table in a note left the
1763
+ // paragraph around the note uncentered.
1764
+ for (let k = stateBase; k < stateStack.length; k++) {
1765
+ resetIndents(stateStack[k]);
1766
+ stateStack[k].align = 'left';
1767
+ }
1768
+ // \lastrow: the table ends here. Without this, a table that follows with
1769
+ // no paragraph between was read as more rows of the same one, and where
1770
+ // their columns differed the cells came out merged.
1771
+ if (lastRow) {
1772
+ lastRow = false;
1773
+ flushTable();
1774
+ }
1297
1775
  break;
1298
1776
  }
1299
1777
  case 'pard':
1300
1778
  // \pard resets the paragraph, not the characters: bold, italic, underline
1301
1779
  // and strikethrough carry on until \plain or their own \b0. Word relies on it.
1302
- currentAlign = 'left';
1780
+ state.align = 'left';
1303
1781
  resetIndents(state);
1304
1782
  // Being in a table is a paragraph property too. Without this, one \intbl with
1305
1783
  // no \row made a single cell of the rest of the document. The marker group
@@ -1310,8 +1788,26 @@ export function rtfToHtml(rtfString, options = {}) {
1310
1788
  inTableCell = false;
1311
1789
  break;
1312
1790
  case 'line':
1791
+ case 'column':
1792
+ // (\column: the text goes on in the next column, which on a screen with one
1793
+ // column is the next line.)
1313
1794
  appendHtml('br', '<br>', state);
1314
1795
  break;
1796
+ case 'chftn':
1797
+ // The number of a footnote: where the text refers to it, and again at the
1798
+ // start of the note itself.
1799
+ if (!shown(state))
1800
+ break;
1801
+ if (noteNumber < 0) {
1802
+ noteMark = ++noteCount;
1803
+ appendText(String(noteMark), state);
1804
+ }
1805
+ else {
1806
+ if (noteNumber === 0)
1807
+ noteNumber = ++noteCount;
1808
+ appendText(String(noteNumber), state);
1809
+ }
1810
+ break;
1315
1811
  case 'tab':
1316
1812
  appendTab(state);
1317
1813
  break;
@@ -1327,6 +1823,8 @@ export function rtfToHtml(rtfString, options = {}) {
1327
1823
  const code = p < 0 ? p + 65536 : p;
1328
1824
  if (code <= 0 || code > 0x10ffff)
1329
1825
  break; // no character: a NUL, or out of range
1826
+ if (!shown(state))
1827
+ break;
1330
1828
  if (code >= 0xd800 && code <= 0xdbff) {
1331
1829
  // The first half of a pair: one character with the \u that follows.
1332
1830
  if (pendingHighSurrogate)
@@ -1338,8 +1836,15 @@ export function rtfToHtml(rtfString, options = {}) {
1338
1836
  pendingHighSurrogate = 0;
1339
1837
  appendText(high ? String.fromCharCode(high, code) : '\ufffd', state);
1340
1838
  }
1839
+ else if (code < 0x20 || code === 0x7f) {
1840
+ // A control character: a tab is a tab, the rest are not text.
1841
+ if (code === 9)
1842
+ appendTab(state);
1843
+ }
1341
1844
  else {
1342
- appendText(String.fromCodePoint(code), state);
1845
+ // A Unicode character is itself in any font. Only Word's U+F0xx,
1846
+ // its way of writing a byte of a symbol font, is a place in Symbol.
1847
+ appendChars(String.fromCodePoint(code), state, code >= 0xf020 && code <= 0xf0ff);
1343
1848
  }
1344
1849
  }
1345
1850
  break;
@@ -1360,6 +1865,8 @@ export function rtfToHtml(rtfString, options = {}) {
1360
1865
  state.colorIndex = 0;
1361
1866
  state.highlightIndex = 0;
1362
1867
  state.fontIndex = defaultFont;
1868
+ state.hidden = false;
1869
+ state.deleted = false;
1363
1870
  break;
1364
1871
  case 'page':
1365
1872
  // A page break. On screen it is a rule; the writer sends it back as \page.
@@ -1378,6 +1885,9 @@ export function rtfToHtml(rtfString, options = {}) {
1378
1885
  case 'enspace':
1379
1886
  appendHtml('gap', '&emsp;', state);
1380
1887
  break;
1888
+ case 'qmspace':
1889
+ appendText('\u2005', state); // a quarter of an em
1890
+ break;
1381
1891
  case 'emdash':
1382
1892
  appendText('\u2014', state);
1383
1893
  break;
@@ -1413,28 +1923,17 @@ export function rtfToHtml(rtfString, options = {}) {
1413
1923
  }
1414
1924
  const skipCount = Math.min(pendingUnicodeSkip, node.value.length);
1415
1925
  pendingUnicodeSkip -= skipCount;
1416
- appendText(node.value.slice(skipCount), state);
1926
+ appendChars(node.value.slice(skipCount), state);
1417
1927
  continue;
1418
1928
  }
1419
- appendText(node.value, state);
1929
+ appendChars(node.value, state);
1420
1930
  }
1421
1931
  }
1422
- if (pendingHighSurrogate) {
1423
- pendingHighSurrogate = 0;
1424
- pushText('\ufffd', currentState());
1425
- }
1426
- // A row the file ends in the middle of, with cells and no \row, is still a row.
1427
- if (currentRowCells.length > 0) {
1428
- tableRows.push({ cells: currentRowCells, defs: currentRowDefs.length > 0 ? currentRowDefs : lastRowDefs });
1429
- currentRowCells = [];
1430
- inTableCell = false;
1431
- }
1432
- flushTable(); // flush any trailing table rows
1433
- // Only flush if there's actually pending content — the final \par in most RTF
1434
- // files already flushed the last paragraph, so an unconditional call here
1435
- // would push a spurious empty paragraph that becomes a trailing <p><br></p>.
1436
- if (runs.length > 0) {
1437
- flushParagraph();
1932
+ finishContent();
1933
+ // Footnotes, after everything else: each begins with the number the text refers to it by.
1934
+ for (const note of notes) {
1935
+ for (const block of note)
1936
+ blocks.push(block);
1438
1937
  }
1439
1938
  // ── Building the HTML ──
1440
1939
  /** Each block as an ordinary paragraph's content: what it is unless it turns out to be more. */
@@ -1505,11 +2004,10 @@ export function rtfToHtml(rtfString, options = {}) {
1505
2004
  return { tag: 'pre' };
1506
2005
  if (size === bodySize)
1507
2006
  return null;
1508
- const allBold = visible.every((r) => r.fmt.bold);
1509
- // At the default 12 pt, size alone makes a heading, as it always has. At
1510
- // another screen size, ordinary 12 pt text can be a step above the body,
1511
- // so a heading must also be bold, as every heading the writer emits is.
1512
- if (bodySize !== 24 && !allBold)
2007
+ // A heading is larger than the body and bold throughout, as every heading the writer
2008
+ // emits is. Size alone does not make one: a report set in 14 pt throughout, read on a
2009
+ // 12 pt screen, came back as nothing but headings, and was saved all bold.
2010
+ if (!visible.every((r) => r.fmt.bold))
1513
2011
  return null;
1514
2012
  // Compared in half-points, rounded the way the writer rounds them, so
1515
2013
  // a heading written at any body size is read back as the same level.
@@ -1564,7 +2062,9 @@ export function rtfToHtml(rtfString, options = {}) {
1564
2062
  // The rule the writer sends for <hr>: a centered line of em dashes, and nothing else.
1565
2063
  if (align === 'center' &&
1566
2064
  block.runs.every((r) => r.type === 'text' && !r.fmt.bold && !r.fmt.italic && !r.fmt.underline && !r.fmt.strike && !r.fmt.link) &&
1567
- block.runs.map((r) => (r.type === 'text' ? r.text : '')).join('') === RULE_DASHES) {
2065
+ // (Spaces around the dashes do not show: a space written between two blocks lands in
2066
+ // front of them, and the rule was then a line of dashes until the next save.)
2067
+ trimSpaces(block.runs.map((r) => (r.type === 'text' ? r.text : '')).join('')) === RULE_DASHES) {
1568
2068
  rendered.push('<hr>');
1569
2069
  continue;
1570
2070
  }
@@ -1572,7 +2072,10 @@ export function rtfToHtml(rtfString, options = {}) {
1572
2072
  if (block.caption) {
1573
2073
  const last = rendered.length - 1;
1574
2074
  if (last >= 0 && rendered[last].startsWith('<figure') && !rendered[last].includes('<figcaption')) {
1575
- rendered[last] = rendered[last].replace('</figure>', `<figcaption>${stripWrappingEm(trimmed)}</figcaption></figure>`);
2075
+ // The caption is given by a function: as a replacement string, a "$&" or a "$`"
2076
+ // in the caption's own text would be read as the match or as the figure before it.
2077
+ const caption = `<figcaption>${stripWrappingEm(trimmed)}</figcaption></figure>`;
2078
+ rendered[last] = rendered[last].replace('</figure>', () => caption);
1576
2079
  continue;
1577
2080
  }
1578
2081
  }
@@ -1615,7 +2118,11 @@ export function rtfToHtml(rtfString, options = {}) {
1615
2118
  }
1616
2119
  /** Captions are written as italic text; <figcaption> supplies its own styling. */
1617
2120
  function stripWrappingEm(html) {
1618
- return html.replace(/^<em>([\s\S]*)<\/em>$/, '$1');
2121
+ // Only when the italics are one piece: "<em>a</em> b <em>c</em>" starts and ends the same way.
2122
+ if (!html.startsWith('<em>') || !html.endsWith('</em>'))
2123
+ return html;
2124
+ const inner = html.slice(4, -5);
2125
+ return inner.includes('</em>') ? html : inner;
1619
2126
  }
1620
2127
  export function readRtfFile(file, options = {}) {
1621
2128
  return new Promise((resolve, reject) => {