svelte-rtf-editor 1.8.3 → 1.10.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.
- package/README.md +212 -26
- package/dist/RtfViewer.svelte +69 -7
- package/dist/RtfViewer.svelte.d.ts +2 -1
- package/dist/components/ImageOverlay.svelte +11 -3
- package/dist/components/ImageOverlay.svelte.d.ts +2 -0
- package/dist/components/InkEditor.svelte +705 -35
- package/dist/components/InkEditor.svelte.d.ts +14 -3
- package/dist/components/Modal.svelte +57 -3
- package/dist/components/Toolbar.svelte +44 -1
- package/dist/components/Toolbar.svelte.d.ts +5 -0
- package/dist/components/ToolbarButton.svelte +8 -2
- package/dist/components/ToolbarButton.svelte.d.ts +4 -0
- package/dist/images.d.ts +60 -7
- package/dist/images.js +268 -59
- package/dist/index.d.ts +2 -1
- package/dist/index.js +2 -1
- package/dist/rtf-parser.d.ts +16 -3
- package/dist/rtf-parser.js +1682 -534
- package/dist/rtf-writer.d.ts +40 -9
- package/dist/rtf-writer.js +1175 -359
- package/dist/sanitize.d.ts +77 -0
- package/dist/sanitize.js +755 -0
- package/dist/table-model.d.ts +49 -0
- package/dist/table-model.js +203 -0
- package/dist/utils.js +689 -87
- package/package.json +16 -12
package/dist/rtf-parser.js
CHANGED
|
@@ -4,13 +4,14 @@
|
|
|
4
4
|
* Parses RTF control words and groups into an HTML string.
|
|
5
5
|
* Supports: bold, italic, underline, strikethrough, super/subscript,
|
|
6
6
|
* font size, foreground color (\cf), highlight background color (\highlight),
|
|
7
|
-
* color table, font table, paragraphs
|
|
8
|
-
*
|
|
9
|
-
*
|
|
7
|
+
* color table, font table (monospace text reads as code), paragraphs with their
|
|
8
|
+
* alignment and indents, headings, bullet/numbered lists, hyperlinks, tables with
|
|
9
|
+
* merged cells, embedded pictures (\pict PNG/JPEG blips, with captions),
|
|
10
|
+
* Unicode characters, Windows-1252 hex escapes, and nested groups.
|
|
10
11
|
*
|
|
11
12
|
* \cb (character background) is silently ignored on import.
|
|
12
13
|
*/
|
|
13
|
-
import { HEADING_SCALE, normalizeFontSize } from './rtf-writer.js';
|
|
14
|
+
import { HEADING_SCALE, PRE_SCALE, LINK_COLOR, isMonospaceFontName, linkTarget, normalizeFontSize } from './rtf-writer.js';
|
|
14
15
|
// ── Highlight palette (RTF \highlight 1-16) ──
|
|
15
16
|
const HIGHLIGHT_COLORS = {
|
|
16
17
|
1: '#000000', // Black
|
|
@@ -34,8 +35,13 @@ const HIGHLIGHT_COLORS = {
|
|
|
34
35
|
const B64_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
|
|
35
36
|
/** 1 px at 96 dpi = 15 twips. */
|
|
36
37
|
const TWIPS_PER_PX = 15;
|
|
37
|
-
/**
|
|
38
|
-
const
|
|
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[^>]*>$/;
|
|
39
45
|
/** Nibble value of each hex digit's char code; -1 for anything else. */
|
|
40
46
|
const HEX_NIBBLE = (() => {
|
|
41
47
|
const table = new Int8Array(128).fill(-1);
|
|
@@ -49,8 +55,49 @@ const HEX_NIBBLE = (() => {
|
|
|
49
55
|
})();
|
|
50
56
|
/** A tab as the editor's Tab key inserts it (Chromium's own shape for a typed tab). */
|
|
51
57
|
const TAB_HTML = '<span style="white-space:pre">\t</span>';
|
|
52
|
-
/**
|
|
53
|
-
const LIST_MARKER =
|
|
58
|
+
/** Text so far holding only a list marker: a bullet, or a number and a period. */
|
|
59
|
+
const LIST_MARKER = /^\s*(?:\u2022|(\d+)\.)\s*$/;
|
|
60
|
+
/**
|
|
61
|
+
* The bullet Word writes inside {\listtext …} and {\pntext …}: byte B7 of the Symbol font, which
|
|
62
|
+
* arrives as a middle dot or as the font's private-use character.
|
|
63
|
+
*/
|
|
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]/;
|
|
67
|
+
/** Text a browser shows as nothing but space. */
|
|
68
|
+
const ONLY_SPACES = /^[ \t\r\n\f]*$/;
|
|
69
|
+
/** The rule the writer sends for <hr>: a centered line of this many em dashes. */
|
|
70
|
+
const RULE_DASHES = '\u2014'.repeat(20);
|
|
71
|
+
/** A hanging indent of this many twips is the one the writer gives a list item (\fi-360). */
|
|
72
|
+
const LIST_HANG = 360;
|
|
73
|
+
/** The longest number a numbered list item is read with. */
|
|
74
|
+
const MAX_LIST_NUMBER_DIGITS = 9;
|
|
75
|
+
/** Each level of a list is indented this much further (\li720). */
|
|
76
|
+
const LIST_STEP = 720;
|
|
77
|
+
/**
|
|
78
|
+
* The largest RTF string rtfToHtml reads unless told otherwise: 50 MB. A document is parsed in
|
|
79
|
+
* one go on the main thread, and a picture is decoded from two characters per byte, so the size
|
|
80
|
+
* of what is handed in is the only bound on how long the page stops responding.
|
|
81
|
+
*/
|
|
82
|
+
export const DEFAULT_MAX_RTF_BYTES = 50 * 1024 * 1024;
|
|
83
|
+
/** A byte count as people read it: "52.4 MB", rounded up when asked. */
|
|
84
|
+
function megabytes(n, roundUp = false) {
|
|
85
|
+
const tenths = (n / (1024 * 1024)) * 10;
|
|
86
|
+
return `${((roundUp ? Math.ceil(tenths) : Math.round(tenths)) / 10).toFixed(1)} MB`;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* "52.4 MB, and the limit is 50.0 MB". A size just over the limit is rounded up, so it does not
|
|
90
|
+
* read as "50.0 MB, and the limit is 50.0 MB".
|
|
91
|
+
*/
|
|
92
|
+
function overLimit(size, limit) {
|
|
93
|
+
let shown = megabytes(size);
|
|
94
|
+
if (shown === megabytes(limit))
|
|
95
|
+
shown = megabytes(size, true);
|
|
96
|
+
// Still the same at a tenth of a megabyte (a limit of its own, just under the size): bytes.
|
|
97
|
+
if (shown === megabytes(limit))
|
|
98
|
+
return `${size} bytes, and the limit is ${limit} bytes`;
|
|
99
|
+
return `${shown}, and the limit is ${megabytes(limit)}`;
|
|
100
|
+
}
|
|
54
101
|
/** Hex picture data → base64, without depending on btoa/Buffer. */
|
|
55
102
|
function hexToBase64(hex) {
|
|
56
103
|
const byteCount = hex.length >> 1;
|
|
@@ -86,10 +133,9 @@ function hexToBase64(hex) {
|
|
|
86
133
|
* formats a browser cannot display (metafiles, device-dependent bitmaps).
|
|
87
134
|
*
|
|
88
135
|
* Only hexadecimal picture data is read. RTF also allows \binN, where the next
|
|
89
|
-
* N bytes are raw binary
|
|
90
|
-
*
|
|
91
|
-
*
|
|
92
|
-
* 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.
|
|
93
139
|
*/
|
|
94
140
|
function renderPicture(group) {
|
|
95
141
|
let mime = '';
|
|
@@ -136,15 +182,25 @@ function renderPicture(group) {
|
|
|
136
182
|
const hex = hexParts.join('').replace(/[^0-9a-fA-F]/g, '');
|
|
137
183
|
if (hex.length < 8)
|
|
138
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';
|
|
139
191
|
const base64 = hexToBase64(hex);
|
|
140
192
|
if (!base64)
|
|
141
193
|
return '';
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
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);
|
|
148
204
|
const styles = [];
|
|
149
205
|
if (widthPx > 0)
|
|
150
206
|
styles.push(`width:${widthPx}px`);
|
|
@@ -166,18 +222,68 @@ const WINDOWS_1252_C1 = [
|
|
|
166
222
|
0x90, 0x2018, 0x2019, 0x201c, 0x201d, 0x2022, 0x2013, 0x2014,
|
|
167
223
|
0x02dc, 0x2122, 0x0161, 0x203a, 0x0153, 0x9d, 0x017e, 0x0178
|
|
168
224
|
];
|
|
169
|
-
|
|
170
|
-
|
|
225
|
+
/**
|
|
226
|
+
* The character a \'xx byte stands for. A NUL is no character and decodes to nothing: it would
|
|
227
|
+
* end the text where a browser or a receiving system reads it.
|
|
228
|
+
*/
|
|
229
|
+
function cp1252Char(byte) {
|
|
230
|
+
const code = WINDOWS_1252_C1[byte - 0x80] ?? byte;
|
|
231
|
+
return code ? String.fromCharCode(code) : '';
|
|
232
|
+
}
|
|
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
|
+
};
|
|
171
264
|
let i = 0;
|
|
172
265
|
const len = rtf.length;
|
|
173
266
|
while (i < len) {
|
|
174
267
|
const ch = rtf[i];
|
|
175
268
|
if (ch === '{') {
|
|
176
|
-
|
|
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
|
+
}
|
|
177
278
|
i++;
|
|
178
279
|
}
|
|
179
280
|
else if (ch === '}') {
|
|
180
|
-
|
|
281
|
+
if (folded > 0)
|
|
282
|
+
folded--;
|
|
283
|
+
else if (stack.length > 1) {
|
|
284
|
+
stack.pop();
|
|
285
|
+
current = stack[stack.length - 1];
|
|
286
|
+
}
|
|
181
287
|
i++;
|
|
182
288
|
}
|
|
183
289
|
else if (ch === '\\') {
|
|
@@ -185,41 +291,51 @@ function tokenize(rtf) {
|
|
|
185
291
|
if (i >= len)
|
|
186
292
|
break;
|
|
187
293
|
const next = rtf[i];
|
|
188
|
-
// Hex escape \'xx
|
|
189
|
-
// what follows it is read as usual, rather than turned into a NUL or a control character.
|
|
294
|
+
// Hex escape \'xx: one byte of Windows-1252.
|
|
190
295
|
if (next === "'") {
|
|
191
296
|
i++;
|
|
192
|
-
const
|
|
193
|
-
|
|
297
|
+
const hi = HEX_NIBBLE[rtf.charCodeAt(i)] ?? -1;
|
|
298
|
+
const lo = HEX_NIBBLE[rtf.charCodeAt(i + 1)] ?? -1;
|
|
299
|
+
// A \' with no two hex digits after it is damage, not a character: it is
|
|
300
|
+
// dropped, and what follows is read as it stands. (parseInt on it gave NaN,
|
|
301
|
+
// which became a NUL in the HTML.)
|
|
302
|
+
if (hi >= 0 && lo >= 0) {
|
|
194
303
|
i += 2;
|
|
195
|
-
const
|
|
196
|
-
|
|
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 });
|
|
197
313
|
}
|
|
198
314
|
}
|
|
199
315
|
// Special escapes
|
|
200
316
|
else if (next === '\\' || next === '{' || next === '}') {
|
|
201
|
-
|
|
317
|
+
add({ type: 'text', value: next });
|
|
202
318
|
i++;
|
|
203
319
|
}
|
|
204
320
|
// Line breaks as control
|
|
205
321
|
else if (next === '\n' || next === '\r') {
|
|
206
|
-
|
|
322
|
+
add({ type: 'control', word: 'par', param: null });
|
|
207
323
|
i++;
|
|
208
324
|
if (i < len && rtf[i] === '\n')
|
|
209
325
|
i++;
|
|
210
326
|
}
|
|
211
327
|
// Tilde = non-breaking space
|
|
212
328
|
else if (next === '~') {
|
|
213
|
-
|
|
329
|
+
add({ type: 'text', value: '\u00A0' });
|
|
214
330
|
i++;
|
|
215
331
|
}
|
|
216
332
|
// Hyphen shortcuts
|
|
217
333
|
else if (next === '-') {
|
|
218
|
-
|
|
334
|
+
add({ type: 'text', value: '\u00AD' }); // soft hyphen
|
|
219
335
|
i++;
|
|
220
336
|
}
|
|
221
337
|
else if (next === '_') {
|
|
222
|
-
|
|
338
|
+
add({ type: 'text', value: '\u2011' }); // non-breaking hyphen
|
|
223
339
|
i++;
|
|
224
340
|
}
|
|
225
341
|
// Control word or control symbol
|
|
@@ -241,16 +357,26 @@ function tokenize(rtf) {
|
|
|
241
357
|
numStr += rtf[i];
|
|
242
358
|
i++;
|
|
243
359
|
}
|
|
244
|
-
|
|
360
|
+
// A lone "-" is no number.
|
|
361
|
+
const value = parseInt(numStr, 10);
|
|
362
|
+
param = Number.isFinite(value) ? value : null;
|
|
245
363
|
}
|
|
246
364
|
// Consume optional trailing space delimiter
|
|
247
365
|
if (i < len && rtf[i] === ' ')
|
|
248
366
|
i++;
|
|
249
|
-
|
|
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 });
|
|
250
376
|
}
|
|
251
377
|
// Control symbol (single non-alpha char)
|
|
252
378
|
else {
|
|
253
|
-
|
|
379
|
+
add({ type: 'control', word: next, param: null });
|
|
254
380
|
i++;
|
|
255
381
|
}
|
|
256
382
|
}
|
|
@@ -258,6 +384,11 @@ function tokenize(rtf) {
|
|
|
258
384
|
// Skip bare newlines (they're not meaningful in RTF)
|
|
259
385
|
i++;
|
|
260
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
|
+
}
|
|
261
392
|
else {
|
|
262
393
|
// Plain text — slice up to the next special char. Slicing rather than
|
|
263
394
|
// appending char-by-char keeps embedded picture data (which arrives as
|
|
@@ -265,57 +396,24 @@ function tokenize(rtf) {
|
|
|
265
396
|
const start = i;
|
|
266
397
|
while (i < len) {
|
|
267
398
|
const c = rtf[i];
|
|
268
|
-
if (c === '\\' || c === '{' || c === '}' || c === '\r' || c === '\n')
|
|
399
|
+
if (c === '\\' || c === '{' || c === '}' || c === '\r' || c === '\n' || c === '\t')
|
|
269
400
|
break;
|
|
270
401
|
i++;
|
|
271
402
|
}
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
return tokens;
|
|
278
|
-
}
|
|
279
|
-
// ── AST Builder ──
|
|
280
|
-
/**
|
|
281
|
-
* The deepest group the tree holds. The renderer walks groups recursively, and thousands of
|
|
282
|
-
* nested groups (damaged or hostile input) would overflow the stack; real documents nest a few
|
|
283
|
-
* dozen deep at most. Groups below this depth are folded into the one at it: their text is kept,
|
|
284
|
-
* and their formatting carries on to the end of that group.
|
|
285
|
-
*/
|
|
286
|
-
const MAX_GROUP_DEPTH = 500;
|
|
287
|
-
function buildTree(tokens) {
|
|
288
|
-
const root = { type: 'group', children: [] };
|
|
289
|
-
const stack = [root];
|
|
290
|
-
/** Groups opened past MAX_GROUP_DEPTH and not closed yet. */
|
|
291
|
-
let folded = 0;
|
|
292
|
-
for (const tok of tokens) {
|
|
293
|
-
const current = stack[stack.length - 1];
|
|
294
|
-
if (tok.type === 'open') {
|
|
295
|
-
if (stack.length > MAX_GROUP_DEPTH) {
|
|
296
|
-
folded++;
|
|
297
|
-
continue;
|
|
298
|
-
}
|
|
299
|
-
const group = { type: 'group', children: [] };
|
|
300
|
-
current.children.push(group);
|
|
301
|
-
stack.push(group);
|
|
302
|
-
}
|
|
303
|
-
else if (tok.type === 'close') {
|
|
304
|
-
if (folded > 0)
|
|
305
|
-
folded--;
|
|
306
|
-
else if (stack.length > 1)
|
|
307
|
-
stack.pop();
|
|
308
|
-
}
|
|
309
|
-
else if (tok.type === 'control') {
|
|
310
|
-
current.children.push({ type: 'control', word: tok.word, param: tok.param ?? null });
|
|
311
|
-
}
|
|
312
|
-
else if (tok.type === 'text') {
|
|
313
|
-
current.children.push({ 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 });
|
|
314
408
|
}
|
|
315
409
|
}
|
|
316
410
|
return root;
|
|
317
411
|
}
|
|
318
412
|
// ── Color table parser ──
|
|
413
|
+
/** A color component as a reader may use it: a damaged table can hold \red999 or \green-5. */
|
|
414
|
+
function colorComponent(value) {
|
|
415
|
+
return Math.min(255, Math.max(0, value ?? 0));
|
|
416
|
+
}
|
|
319
417
|
function parseColorTable(group) {
|
|
320
418
|
const colors = ['']; // index 0 = auto/default
|
|
321
419
|
let r = 0, g = 0, b = 0;
|
|
@@ -329,18 +427,16 @@ function parseColorTable(group) {
|
|
|
329
427
|
}
|
|
330
428
|
for (const node of group.children) {
|
|
331
429
|
if (node.type === 'control') {
|
|
332
|
-
// A component outside 0 to 255 is damaged: it is held to the nearest end of the range.
|
|
333
|
-
const value = Math.min(255, Math.max(0, node.param ?? 0));
|
|
334
430
|
if (node.word === 'red') {
|
|
335
|
-
r =
|
|
431
|
+
r = colorComponent(node.param);
|
|
336
432
|
hasComponents = true;
|
|
337
433
|
}
|
|
338
434
|
else if (node.word === 'green') {
|
|
339
|
-
g =
|
|
435
|
+
g = colorComponent(node.param);
|
|
340
436
|
hasComponents = true;
|
|
341
437
|
}
|
|
342
438
|
else if (node.word === 'blue') {
|
|
343
|
-
b =
|
|
439
|
+
b = colorComponent(node.param);
|
|
344
440
|
hasComponents = true;
|
|
345
441
|
}
|
|
346
442
|
}
|
|
@@ -359,27 +455,190 @@ function parseColorTable(group) {
|
|
|
359
455
|
return colors;
|
|
360
456
|
}
|
|
361
457
|
// ── Font table parser ──
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
458
|
+
/**
|
|
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
|
|
505
|
+
* ({\f1\fmodern Courier New;}), and TextEdit's run of entries with no groups
|
|
506
|
+
* (\f0\fswiss Helvetica;\f1\fmodern Courier;).
|
|
507
|
+
*/
|
|
508
|
+
function readFontTable(group) {
|
|
509
|
+
const mono = new Set();
|
|
510
|
+
const symbol = new Set();
|
|
511
|
+
let num = null;
|
|
512
|
+
let name = '';
|
|
513
|
+
let fixed = false;
|
|
514
|
+
let symbolSet = false;
|
|
515
|
+
const finish = () => {
|
|
516
|
+
if (num != null) {
|
|
517
|
+
if (fixed || isMonospaceFontName(name))
|
|
518
|
+
mono.add(num);
|
|
519
|
+
if (symbolSet && isSymbolFontName(name))
|
|
520
|
+
symbol.add(num);
|
|
521
|
+
}
|
|
522
|
+
num = null;
|
|
523
|
+
name = '';
|
|
524
|
+
fixed = false;
|
|
525
|
+
symbolSet = false;
|
|
526
|
+
};
|
|
527
|
+
const read = (nodes) => {
|
|
528
|
+
for (const node of nodes) {
|
|
529
|
+
if (node.type === 'control') {
|
|
530
|
+
if (node.word === 'f' && node.param != null) {
|
|
531
|
+
if (num != null)
|
|
532
|
+
finish();
|
|
533
|
+
num = node.param;
|
|
534
|
+
}
|
|
535
|
+
else if (node.word === 'fmodern' || (node.word === 'fprq' && node.param === 1)) {
|
|
536
|
+
fixed = true;
|
|
371
537
|
}
|
|
372
|
-
if (node.
|
|
373
|
-
|
|
538
|
+
else if (node.word === 'fcharset') {
|
|
539
|
+
symbolSet = node.param === 2;
|
|
374
540
|
}
|
|
375
541
|
}
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
542
|
+
else if (node.type === 'text') {
|
|
543
|
+
// A name ends at its ';'.
|
|
544
|
+
const parts = node.value.split(';');
|
|
545
|
+
name += parts[0];
|
|
546
|
+
if (parts.length > 1)
|
|
547
|
+
finish();
|
|
548
|
+
}
|
|
549
|
+
// A group inside an entry ({\*\panose …}, {\*\falt …}) is not part of the name.
|
|
550
|
+
}
|
|
551
|
+
};
|
|
552
|
+
for (const child of group.children) {
|
|
553
|
+
if (child.type === 'group') {
|
|
554
|
+
read(child.children);
|
|
555
|
+
finish();
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
read(group.children.filter((n) => n.type !== 'group'));
|
|
559
|
+
finish();
|
|
560
|
+
return { mono, symbol };
|
|
561
|
+
}
|
|
562
|
+
// ── Links ──
|
|
563
|
+
/** The longest field instruction looked at for a link's address. */
|
|
564
|
+
const MAX_FIELD_INSTRUCTION = 8192;
|
|
565
|
+
/**
|
|
566
|
+
* The text of a field's instruction group, {\*\fldinst HYPERLINK "…"}, or null when it holds a
|
|
567
|
+
* \u escape: the address would then be the fallback character's, not the one meant.
|
|
568
|
+
*/
|
|
569
|
+
function fieldInstruction(group) {
|
|
570
|
+
let text = '';
|
|
571
|
+
const pending = [...group.children].reverse();
|
|
572
|
+
while (pending.length > 0) {
|
|
573
|
+
const node = pending.pop();
|
|
574
|
+
if (node.type === 'group') {
|
|
575
|
+
for (let i = node.children.length - 1; i >= 0; i--)
|
|
576
|
+
pending.push(node.children[i]);
|
|
577
|
+
}
|
|
578
|
+
else if (node.type === 'control') {
|
|
579
|
+
if (node.word === 'u')
|
|
580
|
+
return null;
|
|
581
|
+
// A tab between the instruction's words is a space between them.
|
|
582
|
+
if (node.word === 'tab')
|
|
583
|
+
text += ' ';
|
|
584
|
+
}
|
|
585
|
+
else {
|
|
586
|
+
text += node.value;
|
|
587
|
+
if (text.length > MAX_FIELD_INSTRUCTION)
|
|
588
|
+
return null;
|
|
380
589
|
}
|
|
381
590
|
}
|
|
382
|
-
return
|
|
591
|
+
return text;
|
|
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
|
+
}
|
|
598
|
+
/**
|
|
599
|
+
* The address a {\field …} group links to, or '' when it is not a link, or not one that may be
|
|
600
|
+
* followed. Only what the writer itself would write is accepted (linkTarget): an absolute web,
|
|
601
|
+
* mail or phone address. A javascript: or file: address, or a link to a bookmark, stays text.
|
|
602
|
+
*/
|
|
603
|
+
function fieldLink(field) {
|
|
604
|
+
const text = fieldText(field);
|
|
605
|
+
if (text == null)
|
|
606
|
+
return '';
|
|
607
|
+
const m = text.match(/^\s*HYPERLINK\s+(?:"([^"]*)"|([^\s"\\]\S*))/i);
|
|
608
|
+
if (!m)
|
|
609
|
+
return '';
|
|
610
|
+
return linkTarget(m[1] ?? m[2] ?? '') ?? '';
|
|
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);
|
|
383
642
|
}
|
|
384
643
|
// ── Body size ──
|
|
385
644
|
/** Groups whose content is not document text. */
|
|
@@ -388,7 +647,14 @@ const destinationWords = new Set([
|
|
|
388
647
|
'headerl', 'headerr', 'headerf', 'footerl', 'footerr', 'footerf',
|
|
389
648
|
// \nonshppict duplicates the picture already carried by \*\shppict
|
|
390
649
|
'nonshppict',
|
|
391
|
-
|
|
650
|
+
// {\nonesttables \par} is for readers that do not know nested tables; \nestrow is read here
|
|
651
|
+
'nonesttables',
|
|
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',
|
|
392
658
|
'rsidtbl', 'generator', 'datafield', 'themedata', 'colorschememapping',
|
|
393
659
|
'latentstyles', 'datastore', 'mmathPr', 'author', 'operator',
|
|
394
660
|
'title', 'subject', 'doccomm', 'company', 'category', 'keywords'
|
|
@@ -402,69 +668,162 @@ function resetIndents(state) {
|
|
|
402
668
|
state.rightIndent = 0;
|
|
403
669
|
state.firstLineIndent = 0;
|
|
404
670
|
}
|
|
671
|
+
/**
|
|
672
|
+
* A paragraph's indents as CSS, in points (20 twips), which the writer reads back as the same
|
|
673
|
+
* \li, \ri and \fi: "margin-left:36pt;text-indent:-36pt". A first line may not start left of
|
|
674
|
+
* the page margin, where a browser would clip it.
|
|
675
|
+
*/
|
|
676
|
+
function indentStyle(block) {
|
|
677
|
+
const left = Math.max(0, block.left);
|
|
678
|
+
const first = Math.max(-left, block.first);
|
|
679
|
+
const parts = [];
|
|
680
|
+
if (left > 0)
|
|
681
|
+
parts.push(`margin-left:${twipsToPt(left)}`);
|
|
682
|
+
if (block.right > 0)
|
|
683
|
+
parts.push(`margin-right:${twipsToPt(block.right)}`);
|
|
684
|
+
if (first !== 0)
|
|
685
|
+
parts.push(`text-indent:${twipsToPt(first)}`);
|
|
686
|
+
return parts.join(';');
|
|
687
|
+
}
|
|
688
|
+
/**
|
|
689
|
+
* The indent of a picture's paragraph: where its one line starts, as a left margin. A figure
|
|
690
|
+
* is written back with a left indent only, and a first-line indent on it would be passed on to
|
|
691
|
+
* its caption.
|
|
692
|
+
*/
|
|
693
|
+
function figureIndentStyle(block) {
|
|
694
|
+
const left = Math.max(0, block.left);
|
|
695
|
+
const start = left + Math.max(-left, block.first);
|
|
696
|
+
return start > 0 ? `margin-left:${twipsToPt(start)}` : '';
|
|
697
|
+
}
|
|
698
|
+
/**
|
|
699
|
+
* A paragraph's HTML without the spaces at its ends, which a browser does not show. Only those:
|
|
700
|
+
* a non-breaking space or an em space there is text someone put there, and is kept.
|
|
701
|
+
*/
|
|
702
|
+
function trimSpaces(html) {
|
|
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);
|
|
716
|
+
}
|
|
717
|
+
function escapeText(text) {
|
|
718
|
+
return text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
719
|
+
}
|
|
720
|
+
/** Text as an attribute value in double quotes. */
|
|
721
|
+
function escapeAttribute(text) {
|
|
722
|
+
return escapeText(text).replace(/"/g, '"');
|
|
723
|
+
}
|
|
724
|
+
function sameFormat(a, b) {
|
|
725
|
+
return (a.bold === b.bold &&
|
|
726
|
+
a.italic === b.italic &&
|
|
727
|
+
a.underline === b.underline &&
|
|
728
|
+
a.strike === b.strike &&
|
|
729
|
+
a.super_ === b.super_ &&
|
|
730
|
+
a.sub === b.sub &&
|
|
731
|
+
a.fontSize === b.fontSize &&
|
|
732
|
+
sameFormatButSize(a, b));
|
|
733
|
+
}
|
|
734
|
+
function sameFormatButSize(a, b) {
|
|
735
|
+
return (a.bold === b.bold &&
|
|
736
|
+
a.italic === b.italic &&
|
|
737
|
+
a.underline === b.underline &&
|
|
738
|
+
a.strike === b.strike &&
|
|
739
|
+
a.super_ === b.super_ &&
|
|
740
|
+
a.sub === b.sub &&
|
|
741
|
+
a.color === b.color &&
|
|
742
|
+
a.background === b.background &&
|
|
743
|
+
a.mono === b.mono &&
|
|
744
|
+
a.link === b.link);
|
|
745
|
+
}
|
|
405
746
|
export function rtfToHtml(rtfString, options = {}) {
|
|
406
|
-
const
|
|
407
|
-
|
|
747
|
+
const maxBytes = options.maxBytes ?? DEFAULT_MAX_RTF_BYTES;
|
|
748
|
+
if (maxBytes > 0 && rtfString.length > maxBytes) {
|
|
749
|
+
throw new RangeError(`This document is too large to show: ${overLimit(rtfString.length, maxBytes)}`);
|
|
750
|
+
}
|
|
751
|
+
const tree = parseTree(rtfString);
|
|
408
752
|
let colorTable = [''];
|
|
409
|
-
let
|
|
410
|
-
let
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
let
|
|
418
|
-
let paragraphIsCaption = false;
|
|
419
|
-
/** Append a finished paragraph, keeping the parallel metadata arrays in sync. */
|
|
420
|
-
function pushParagraph(html, align, isCaption = false) {
|
|
421
|
-
paragraphs.push(html);
|
|
422
|
-
paragraphAligns.push(align);
|
|
423
|
-
const inTable = inTableCell || html.startsWith('<table');
|
|
424
|
-
paragraphIndents.push(inTable ? '' : indentStyle());
|
|
425
|
-
paragraphFigureIndents.push(inTable ? '' : figureIndentStyle());
|
|
426
|
-
paragraphCaptions.push(isCaption);
|
|
427
|
-
}
|
|
428
|
-
// Paragraph alignment (reset by \pard, affects cells and paragraphs)
|
|
429
|
-
let currentAlign = 'left';
|
|
753
|
+
let monoFonts = new Set();
|
|
754
|
+
let symbolFonts = new Set();
|
|
755
|
+
let defaultFont = 0;
|
|
756
|
+
/** Where finished paragraphs and tables go: the document, or the footnote or text box being read. */
|
|
757
|
+
let blocks = [];
|
|
758
|
+
// The paragraph being read
|
|
759
|
+
let runs = [];
|
|
760
|
+
/** Nothing but text has been read into the paragraph so far. */
|
|
761
|
+
let onlyText = true;
|
|
430
762
|
/**
|
|
431
|
-
* The
|
|
432
|
-
*
|
|
433
|
-
*
|
|
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.
|
|
434
767
|
*/
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
const parts = [];
|
|
440
|
-
if (left > 0)
|
|
441
|
-
parts.push(`margin-left:${twipsToPt(left)}`);
|
|
442
|
-
if (rightIndent > 0)
|
|
443
|
-
parts.push(`margin-right:${twipsToPt(rightIndent)}`);
|
|
444
|
-
if (first !== 0)
|
|
445
|
-
parts.push(`text-indent:${twipsToPt(first)}`);
|
|
446
|
-
return parts.join(';');
|
|
447
|
-
}
|
|
768
|
+
let contentAlign = 'left';
|
|
769
|
+
let marker = null;
|
|
770
|
+
let paragraphHasListMarker = false;
|
|
771
|
+
let paragraphIsCaption = false;
|
|
448
772
|
/**
|
|
449
|
-
*
|
|
450
|
-
* is
|
|
451
|
-
* its caption.
|
|
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.
|
|
452
775
|
*/
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
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;
|
|
458
790
|
// Table state
|
|
459
791
|
let tableRows = [];
|
|
460
792
|
let currentRowCells = [];
|
|
461
|
-
let
|
|
462
|
-
|
|
463
|
-
let
|
|
793
|
+
let currentRowDefs = [];
|
|
794
|
+
/** The definition of the row before, which a row with no \trowd of its own repeats. */
|
|
795
|
+
let lastRowDefs = [];
|
|
796
|
+
let pendingDef = newCellDef();
|
|
797
|
+
/** The side a \clbrdrX just named, until a border type (\brdrs...) confirms or \brdrnone clears it. */
|
|
798
|
+
let pendingSide = null;
|
|
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;
|
|
464
806
|
let inTableCell = false;
|
|
465
|
-
|
|
807
|
+
/** \par seen in a table cell since its last text: line breaks owed if more text follows. */
|
|
808
|
+
let cellBreaks = 0;
|
|
809
|
+
/** \lastrow seen in the definition of the row being read: its \row ends the table. */
|
|
810
|
+
let lastRow = false;
|
|
811
|
+
/** \nestcell seen: a tab is owed if more text follows on the line. */
|
|
812
|
+
let nestTabPending = false;
|
|
813
|
+
function newCellDef() {
|
|
814
|
+
return { right: 0, header: false, vmgf: false, vmrg: false, hmgf: false, hmrg: false };
|
|
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;
|
|
466
826
|
// First pass: extract color table and font table from the root group
|
|
467
|
-
const rootGroup = tree.children[0]?.type === 'group' ? tree.children[0] : tree;
|
|
468
827
|
for (let i = 0; i < rootGroup.children.length; i++) {
|
|
469
828
|
const child = rootGroup.children[i];
|
|
470
829
|
if (child.type === 'group') {
|
|
@@ -473,13 +832,21 @@ export function rtfToHtml(rtfString, options = {}) {
|
|
|
473
832
|
colorTable = parseColorTable(child);
|
|
474
833
|
}
|
|
475
834
|
else if (firstControl?.word === 'fonttbl') {
|
|
476
|
-
|
|
835
|
+
({ mono: monoFonts, symbol: symbolFonts } = readFontTable(child));
|
|
477
836
|
}
|
|
478
837
|
}
|
|
838
|
+
else if (child.type === 'control' && child.word === 'deff' && child.param != null) {
|
|
839
|
+
defaultFont = child.param;
|
|
840
|
+
}
|
|
479
841
|
}
|
|
842
|
+
// In a document whose own font is monospace, code cannot be told from text by its font.
|
|
843
|
+
const documentIsMono = monoFonts.has(defaultFont);
|
|
844
|
+
const linkColor = `rgb(${LINK_COLOR.r},${LINK_COLOR.g},${LINK_COLOR.b})`;
|
|
480
845
|
// The screen's body size, in half-points. It is given, not guessed from the
|
|
481
846
|
// document: guessing misread short documents and ones set below 12 pt.
|
|
482
847
|
const bodySize = normalizeFontSize(options.fontSize) * 2;
|
|
848
|
+
/** The size the writer sets a code block in, in half-points. */
|
|
849
|
+
const preSize = Math.round(bodySize * PRE_SCALE);
|
|
483
850
|
// State stack for nested groups
|
|
484
851
|
function defaultState() {
|
|
485
852
|
return {
|
|
@@ -492,9 +859,13 @@ export function rtfToHtml(rtfString, options = {}) {
|
|
|
492
859
|
fontSize: 24, // 12pt default
|
|
493
860
|
colorIndex: 0,
|
|
494
861
|
highlightIndex: 0,
|
|
495
|
-
fontIndex:
|
|
862
|
+
fontIndex: defaultFont,
|
|
496
863
|
ucSkip: 1,
|
|
497
864
|
inList: false,
|
|
865
|
+
hidden: false,
|
|
866
|
+
deleted: false,
|
|
867
|
+
align: 'left',
|
|
868
|
+
link: '',
|
|
498
869
|
leftIndent: 0,
|
|
499
870
|
rightIndent: 0,
|
|
500
871
|
firstLineIndent: 0,
|
|
@@ -507,410 +878,1178 @@ export function rtfToHtml(rtfString, options = {}) {
|
|
|
507
878
|
function cloneState() {
|
|
508
879
|
return { ...currentState() };
|
|
509
880
|
}
|
|
510
|
-
function
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
881
|
+
function formatOf(state) {
|
|
882
|
+
let color = state.colorIndex > 0 && state.colorIndex < colorTable.length ? colorTable[state.colorIndex] : '';
|
|
883
|
+
// Black is the color text has anyway, and a link's own color is the <a>'s to give.
|
|
884
|
+
if (color === 'rgb(0,0,0)' || (state.link && color === linkColor))
|
|
885
|
+
color = '';
|
|
886
|
+
return {
|
|
887
|
+
bold: state.bold,
|
|
888
|
+
italic: state.italic,
|
|
889
|
+
// A link is underlined as a link; the writer adds that underline itself.
|
|
890
|
+
underline: state.underline && !state.link,
|
|
891
|
+
strike: state.strike,
|
|
892
|
+
super_: state.super_,
|
|
893
|
+
sub: state.sub,
|
|
894
|
+
fontSize: state.fontSize || bodySize,
|
|
895
|
+
color,
|
|
896
|
+
background: (state.highlightIndex > 0 && HIGHLIGHT_COLORS[state.highlightIndex]) || '',
|
|
897
|
+
// A list marker is set in whatever font the list uses (Word's second-level "o" is in
|
|
898
|
+
// Courier New): it is not code.
|
|
899
|
+
mono: !documentIsMono && !state.inList && monoFonts.has(state.fontIndex),
|
|
900
|
+
link: state.link
|
|
901
|
+
};
|
|
529
902
|
}
|
|
530
|
-
|
|
903
|
+
// ── Writing a paragraph's pieces as HTML ──
|
|
904
|
+
function renderText(text, fmt, opts) {
|
|
531
905
|
if (!text)
|
|
532
906
|
return '';
|
|
533
907
|
// A size on spaces alone is not shown and would be read as the
|
|
534
908
|
// paragraph's size, so it is dropped. Underline, strikethrough and
|
|
535
909
|
// highlight are kept: an underlined blank is a signature line.
|
|
536
|
-
const onlySpaces =
|
|
537
|
-
let result = text
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
.
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
if (
|
|
544
|
-
|
|
545
|
-
}
|
|
546
|
-
if (
|
|
910
|
+
const onlySpaces = ONLY_SPACES.test(text);
|
|
911
|
+
let result = escapeText(text);
|
|
912
|
+
const styles = [];
|
|
913
|
+
if (fmt.color)
|
|
914
|
+
styles.push(`color:${fmt.color}`);
|
|
915
|
+
if (fmt.background)
|
|
916
|
+
styles.push(`background-color:${fmt.background}`);
|
|
917
|
+
if (!onlySpaces && fmt.fontSize !== bodySize && fmt.fontSize !== opts.dropSize) {
|
|
918
|
+
styles.push(`font-size:${fmt.fontSize / 2}pt`);
|
|
919
|
+
}
|
|
920
|
+
if (styles.length > 0)
|
|
921
|
+
result = `<span style="${styles.join(';')}">${result}</span>`;
|
|
922
|
+
if (fmt.mono && !opts.pre)
|
|
923
|
+
result = `<code>${result}</code>`;
|
|
924
|
+
if (fmt.bold && !opts.dropBold)
|
|
547
925
|
result = `<strong>${result}</strong>`;
|
|
548
|
-
if (
|
|
926
|
+
if (fmt.italic)
|
|
549
927
|
result = `<em>${result}</em>`;
|
|
550
|
-
if (
|
|
928
|
+
if (fmt.underline)
|
|
551
929
|
result = `<u>${result}</u>`;
|
|
552
|
-
if (
|
|
930
|
+
if (fmt.strike)
|
|
553
931
|
result = `<s>${result}</s>`;
|
|
554
|
-
if (
|
|
932
|
+
if (fmt.super_)
|
|
555
933
|
result = `<sup>${result}</sup>`;
|
|
556
|
-
if (
|
|
934
|
+
if (fmt.sub)
|
|
557
935
|
result = `<sub>${result}</sub>`;
|
|
558
936
|
return result;
|
|
559
937
|
}
|
|
560
|
-
|
|
938
|
+
function renderRun(run, opts) {
|
|
939
|
+
if (run.type === 'text')
|
|
940
|
+
return renderText(run.text, run.fmt, opts);
|
|
941
|
+
if (opts.pre && run.kind === 'br')
|
|
942
|
+
return '\n';
|
|
943
|
+
if (opts.pre && run.kind === 'tab')
|
|
944
|
+
return '\t';
|
|
945
|
+
return run.html;
|
|
946
|
+
}
|
|
947
|
+
/** The opening tag of a link. The address has been through linkTarget; a web page opens in a tab of its own. */
|
|
948
|
+
function linkOpen(href) {
|
|
949
|
+
const newTab = /^https?:/i.test(href) ? ' target="_blank" rel="noopener noreferrer"' : '';
|
|
950
|
+
return `<a href="${escapeAttribute(href)}"${newTab}>`;
|
|
951
|
+
}
|
|
952
|
+
function renderRuns(list, opts = {}) {
|
|
953
|
+
// A line break that ends the paragraph (\line\par) leaves an empty last line. A browser
|
|
954
|
+
// shows nothing for a <br> at the end of a block, so that one is written twice; the
|
|
955
|
+
// writer, which drops a closing <br>, then sends the one \line back.
|
|
956
|
+
let closing = -1;
|
|
957
|
+
if (!opts.pre) {
|
|
958
|
+
let k = list.length - 1;
|
|
959
|
+
while (k >= 0 && list[k].type === 'text' && ONLY_SPACES.test(list[k].text))
|
|
960
|
+
k--;
|
|
961
|
+
if (k >= 0 && list[k].type === 'html' && list[k].kind === 'br')
|
|
962
|
+
closing = k;
|
|
963
|
+
}
|
|
964
|
+
const render = (i) => renderRun(list[i], opts) + (i === closing ? '<br>' : '');
|
|
965
|
+
let out = '';
|
|
966
|
+
for (let i = 0; i < list.length;) {
|
|
967
|
+
const link = list[i].fmt.link;
|
|
968
|
+
if (!link) {
|
|
969
|
+
out += render(i++);
|
|
970
|
+
continue;
|
|
971
|
+
}
|
|
972
|
+
// Every piece in a row that carries the same address is one link.
|
|
973
|
+
let inner = '';
|
|
974
|
+
while (i < list.length && list[i].fmt.link === link)
|
|
975
|
+
inner += render(i++);
|
|
976
|
+
out += `${linkOpen(link)}${inner}</a>`;
|
|
977
|
+
}
|
|
978
|
+
return out;
|
|
979
|
+
}
|
|
980
|
+
// ── Collecting a paragraph ──
|
|
981
|
+
/** Half of a surrogate pair read from \uN, waiting for the \uN that completes the character. */
|
|
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
|
+
}
|
|
999
|
+
function pushText(text, state) {
|
|
1000
|
+
if (!text)
|
|
1001
|
+
return;
|
|
1002
|
+
const fmt = formatOf(state);
|
|
1003
|
+
const last = runs[runs.length - 1];
|
|
1004
|
+
if (last && last.type === 'text') {
|
|
1005
|
+
// Text in the same formatting as the text before it is one piece: "caf" and the
|
|
1006
|
+
// \'e9 after it, or the two \u halves of an emoji, are not two elements.
|
|
1007
|
+
if (sameFormat(last.fmt, fmt)) {
|
|
1008
|
+
last.text += text;
|
|
1009
|
+
return;
|
|
1010
|
+
}
|
|
1011
|
+
// A size does not show on spaces, so spaces go with the text beside them
|
|
1012
|
+
// whatever size they were set in.
|
|
1013
|
+
if (sameFormatButSize(last.fmt, fmt)) {
|
|
1014
|
+
if (ONLY_SPACES.test(text)) {
|
|
1015
|
+
last.text += text;
|
|
1016
|
+
return;
|
|
1017
|
+
}
|
|
1018
|
+
if (ONLY_SPACES.test(last.text)) {
|
|
1019
|
+
last.text += text;
|
|
1020
|
+
last.fmt = fmt;
|
|
1021
|
+
return;
|
|
1022
|
+
}
|
|
1023
|
+
}
|
|
1024
|
+
}
|
|
1025
|
+
runs.push({ type: 'text', text, fmt });
|
|
1026
|
+
}
|
|
1027
|
+
/** What is owed before the next piece of a paragraph: see cellBreaks and nestTabPending. */
|
|
1028
|
+
function beforeContent(state) {
|
|
1029
|
+
contentAlign = state.align;
|
|
1030
|
+
if (pendingHighSurrogate) {
|
|
1031
|
+
// A lone half of a pair is no character.
|
|
1032
|
+
pendingHighSurrogate = 0;
|
|
1033
|
+
pushText('\ufffd', state);
|
|
1034
|
+
}
|
|
1035
|
+
if (cellBreaks > 0) {
|
|
1036
|
+
const count = cellBreaks;
|
|
1037
|
+
cellBreaks = 0;
|
|
1038
|
+
if (inTableCell) {
|
|
1039
|
+
// A paragraph mark inside a cell: the cell's text goes on, on a new line.
|
|
1040
|
+
for (let k = 0; k < count; k++)
|
|
1041
|
+
pushHtml('br', '<br>', state);
|
|
1042
|
+
}
|
|
1043
|
+
else {
|
|
1044
|
+
// \pard has left the table without a \cell: what was read is a paragraph.
|
|
1045
|
+
for (let k = 0; k < count; k++)
|
|
1046
|
+
flushParagraph();
|
|
1047
|
+
}
|
|
1048
|
+
}
|
|
1049
|
+
if (nestTabPending) {
|
|
1050
|
+
nestTabPending = false;
|
|
1051
|
+
pushHtml('tab', TAB_HTML, state);
|
|
1052
|
+
}
|
|
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
|
+
}
|
|
1063
|
+
function appendText(text, state) {
|
|
1064
|
+
if (!text || !shown(state))
|
|
1065
|
+
return;
|
|
1066
|
+
beforeContent(state);
|
|
1067
|
+
pushText(text, state);
|
|
1068
|
+
}
|
|
1069
|
+
function appendHtml(kind, html, state) {
|
|
1070
|
+
if (!shown(state))
|
|
1071
|
+
return;
|
|
1072
|
+
beforeContent(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);
|
|
1114
|
+
}
|
|
1115
|
+
/** The text of the line being read, back to the last line break, if text is all it holds. */
|
|
1116
|
+
function lineText() {
|
|
1117
|
+
let text = '';
|
|
1118
|
+
for (let i = runs.length - 1; i >= 0; i--) {
|
|
1119
|
+
const run = runs[i];
|
|
1120
|
+
if (run.type === 'html' && run.kind === 'br')
|
|
1121
|
+
break;
|
|
1122
|
+
if (run.type !== 'text')
|
|
1123
|
+
return null;
|
|
1124
|
+
text = run.text + text;
|
|
1125
|
+
}
|
|
1126
|
+
return text;
|
|
1127
|
+
}
|
|
1128
|
+
function appendTab(state) {
|
|
1129
|
+
if (!shown(state))
|
|
1130
|
+
return;
|
|
1131
|
+
beforeContent(state);
|
|
1132
|
+
// A real tab, in the shape the editor's Tab key inserts, so it shows as
|
|
1133
|
+
// one and is written back as \tab (an em space came back as a \u escape for U+2003).
|
|
1134
|
+
// After a list marker ("\bullet\tab", "1.\tab") the gap stays an em
|
|
1135
|
+
// space where the line is read as a plain one: a full tab there is too wide.
|
|
1136
|
+
const lead = lineText();
|
|
1137
|
+
// Only a marker that opens the paragraph can make it a list item.
|
|
1138
|
+
const opensParagraph = marker === null && onlyText;
|
|
1139
|
+
const listed = lead != null ? lead.match(LIST_MARKER) : null;
|
|
1140
|
+
if (listed) {
|
|
1141
|
+
pushHtml('gap', ' ', state);
|
|
1142
|
+
// (A number too long to be an item's number is text, and so is one written with a
|
|
1143
|
+
// leading zero, "01.": a list would show it as "1.".)
|
|
1144
|
+
if (opensParagraph && (!listed[1] || (listed[1].length <= MAX_LIST_NUMBER_DIGITS && !/^0\d/.test(listed[1])))) {
|
|
1145
|
+
marker = listed[1]
|
|
1146
|
+
? { kind: 'ol', number: Number(listed[1]), end: runs.length }
|
|
1147
|
+
: { kind: 'ul', number: 0, end: runs.length };
|
|
1148
|
+
}
|
|
1149
|
+
return;
|
|
1150
|
+
}
|
|
1151
|
+
pushHtml('tab', TAB_HTML, state);
|
|
1152
|
+
// Word's bullet, inside {\listtext …} or {\pntext …}.
|
|
1153
|
+
if (opensParagraph && lead != null && state.inList && SYMBOL_BULLET.test(lead)) {
|
|
1154
|
+
marker = { kind: 'ul', number: 0, end: runs.length };
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
1157
|
+
// ── Tables ──
|
|
1158
|
+
/** Column edges closer than this, in twips (2 px), are the same edge. */
|
|
1159
|
+
const EDGE_TOLERANCE = 30;
|
|
561
1160
|
function flushTable() {
|
|
562
1161
|
if (tableRows.length === 0)
|
|
563
1162
|
return;
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
const
|
|
568
|
-
const total = row.cellRights[row.cellRights.length - 1] || 1;
|
|
1163
|
+
const rows = tableRows;
|
|
1164
|
+
tableRows = [];
|
|
1165
|
+
const placedRows = rows.map((row) => {
|
|
1166
|
+
const placed = [];
|
|
569
1167
|
let prevRight = 0;
|
|
1168
|
+
let step = 0;
|
|
570
1169
|
for (let ci = 0; ci < row.cells.length; ci++) {
|
|
571
|
-
const
|
|
572
|
-
const
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
1170
|
+
const def = row.defs[ci] ?? { ...newCellDef(), right: prevRight + (step || 1440) };
|
|
1171
|
+
const cell = row.cells[ci];
|
|
1172
|
+
const last = placed[placed.length - 1];
|
|
1173
|
+
if (def.hmrg && last) {
|
|
1174
|
+
last.right = Math.max(last.right, def.right);
|
|
1175
|
+
if (cell.html)
|
|
1176
|
+
last.html += (last.html ? ' ' : '') + cell.html;
|
|
1177
|
+
}
|
|
1178
|
+
else {
|
|
1179
|
+
placed.push({
|
|
1180
|
+
html: cell.html, align: cell.align, def,
|
|
1181
|
+
left: prevRight, right: Math.max(def.right, prevRight),
|
|
1182
|
+
start: 0, end: 0, rowspan: 1, merged: false
|
|
1183
|
+
});
|
|
1184
|
+
}
|
|
1185
|
+
step = Math.max(1, def.right - prevRight);
|
|
1186
|
+
prevRight = Math.max(def.right, prevRight);
|
|
1187
|
+
}
|
|
1188
|
+
return placed;
|
|
1189
|
+
});
|
|
1190
|
+
// One set of columns for the table: every edge any row has. A cell that crosses edges
|
|
1191
|
+
// of other rows spans those columns.
|
|
1192
|
+
const allEdges = placedRows.flatMap((row) => row.map((c) => c.right)).sort((a, b) => a - b);
|
|
1193
|
+
const edges = [];
|
|
1194
|
+
for (const e of allEdges) {
|
|
1195
|
+
if (edges.length === 0 || e - edges[edges.length - 1] > EDGE_TOLERANCE)
|
|
1196
|
+
edges.push(e);
|
|
1197
|
+
}
|
|
1198
|
+
// The column whose edge is nearest, the earlier one on a tie. A binary search over the
|
|
1199
|
+
// sorted edges: a scan of every edge for every cell froze the page on a row of 100,000
|
|
1200
|
+
// cells (14 s for 2 MB).
|
|
1201
|
+
const columnOf = (right) => {
|
|
1202
|
+
let lo = 0;
|
|
1203
|
+
let hi = edges.length - 1;
|
|
1204
|
+
while (lo < hi) {
|
|
1205
|
+
const mid = (lo + hi) >> 1;
|
|
1206
|
+
if (edges[mid] < right)
|
|
1207
|
+
lo = mid + 1;
|
|
1208
|
+
else
|
|
1209
|
+
hi = mid;
|
|
1210
|
+
}
|
|
1211
|
+
if (lo > 0 && Math.abs(edges[lo - 1] - right) <= Math.abs(edges[lo] - right))
|
|
1212
|
+
return lo - 1;
|
|
1213
|
+
return lo;
|
|
1214
|
+
};
|
|
1215
|
+
for (const row of placedRows) {
|
|
1216
|
+
let start = 0;
|
|
1217
|
+
for (const cell of row) {
|
|
1218
|
+
cell.start = start;
|
|
1219
|
+
cell.end = Math.max(start, columnOf(cell.right));
|
|
1220
|
+
start = cell.end + 1;
|
|
1221
|
+
}
|
|
1222
|
+
}
|
|
1223
|
+
// A vertical merge: the cell marked \clvmgf takes in each \clvmrg cell under it, row
|
|
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])));
|
|
1228
|
+
for (let r = 0; r < placedRows.length; r++) {
|
|
1229
|
+
for (const cell of placedRows[r]) {
|
|
1230
|
+
if (!cell.def.vmgf || cell.merged)
|
|
1231
|
+
continue;
|
|
1232
|
+
for (let below = r + 1; below < placedRows.length; below++) {
|
|
1233
|
+
const under = byStart[below].get(cell.start);
|
|
1234
|
+
if (!under || !under.def.vmrg || under.merged)
|
|
1235
|
+
break;
|
|
1236
|
+
under.merged = true;
|
|
1237
|
+
cell.rowspan++;
|
|
1238
|
+
// A merged cell is empty; if a damaged file has text there, it is kept.
|
|
1239
|
+
if (under.html)
|
|
1240
|
+
cell.html += (cell.html ? '<br>' : '') + under.html;
|
|
1241
|
+
}
|
|
1242
|
+
}
|
|
1243
|
+
}
|
|
1244
|
+
const total = edges[edges.length - 1] || 1;
|
|
1245
|
+
// A cell's width is the difference of where it ends and where it starts, each as a
|
|
1246
|
+
// share of the table rounded to a hundredth of a percent. Written that way the widths
|
|
1247
|
+
// of a row add up exactly, and the writer puts every column edge back where it was;
|
|
1248
|
+
// each width rounded by itself moved an edge a few twips on every save.
|
|
1249
|
+
const shareAt = (edge) => Math.round((edge / total) * 10000) / 100;
|
|
1250
|
+
let html = '<table style="border-collapse:collapse;width:100%;margin:4px 0">';
|
|
1251
|
+
for (const row of placedRows) {
|
|
1252
|
+
html += '<tr>';
|
|
1253
|
+
for (const cell of row) {
|
|
1254
|
+
if (cell.merged)
|
|
1255
|
+
continue;
|
|
1256
|
+
const tag = cell.def.header ? 'th' : 'td';
|
|
1257
|
+
const pct = (shareAt(cell.right) - shareAt(cell.left)).toFixed(2).replace(/0$/, '');
|
|
1258
|
+
const alignStyle = cell.align !== 'left' ? `;text-align:${cell.align}` : '';
|
|
1259
|
+
const style = cell.def.header
|
|
1260
|
+
? `border-bottom:1px solid;padding:2px 6px;text-align:${cell.align};width:${pct}%`
|
|
578
1261
|
: `padding:2px 6px;width:${pct}%${alignStyle}`;
|
|
579
|
-
|
|
1262
|
+
const colspan = cell.end > cell.start ? ` colspan="${cell.end - cell.start + 1}"` : '';
|
|
1263
|
+
const rowspan = cell.rowspan > 1 ? ` rowspan="${cell.rowspan}"` : '';
|
|
1264
|
+
html += `<${tag}${colspan}${rowspan} style="${style}">${cell.html}</${tag}>`;
|
|
580
1265
|
}
|
|
581
1266
|
html += '</tr>';
|
|
582
1267
|
}
|
|
583
1268
|
html += '</table>';
|
|
584
|
-
|
|
585
|
-
|
|
1269
|
+
blocks.push({ kind: 'table', html });
|
|
1270
|
+
for (const aside of tableAsides)
|
|
1271
|
+
blocks.push(aside);
|
|
1272
|
+
tableAsides = [];
|
|
586
1273
|
}
|
|
587
1274
|
function flushParagraph() {
|
|
1275
|
+
const state = currentState();
|
|
1276
|
+
if (pendingHighSurrogate) {
|
|
1277
|
+
pendingHighSurrogate = 0;
|
|
1278
|
+
pushText('\ufffd', state);
|
|
1279
|
+
}
|
|
588
1280
|
flushTable();
|
|
589
|
-
|
|
590
|
-
if (
|
|
591
|
-
|
|
1281
|
+
// A paragraph that held a list marker and nothing else is no line of its own.
|
|
1282
|
+
if (!paragraphHasListMarker || trimSpaces(renderRuns(runs))) {
|
|
1283
|
+
blocks.push({
|
|
1284
|
+
kind: 'paragraph',
|
|
1285
|
+
runs,
|
|
1286
|
+
align: alignHere(state),
|
|
1287
|
+
left: state.leftIndent,
|
|
1288
|
+
right: state.rightIndent,
|
|
1289
|
+
first: state.firstLineIndent,
|
|
1290
|
+
caption: paragraphIsCaption,
|
|
1291
|
+
marker,
|
|
1292
|
+
inTable: inTableCell
|
|
1293
|
+
});
|
|
592
1294
|
}
|
|
593
|
-
|
|
594
|
-
paragraphHasText = false;
|
|
1295
|
+
newRuns();
|
|
595
1296
|
paragraphHasListMarker = false;
|
|
596
1297
|
paragraphIsCaption = false;
|
|
597
|
-
|
|
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 = [];
|
|
598
1328
|
}
|
|
599
1329
|
let pendingUnicodeSkip = 0;
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
1330
|
+
const frames = [{ nodes: rootGroup.children, index: 0, scoped: false }];
|
|
1331
|
+
const enterGroup = (group, state) => {
|
|
1332
|
+
stateStack.push(state);
|
|
1333
|
+
frames.push({ nodes: group.children, index: 0, scoped: true });
|
|
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);
|
|
604
1424
|
continue;
|
|
605
1425
|
}
|
|
606
|
-
if (
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
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());
|
|
612
1439
|
}
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
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
|
+
}
|
|
1449
|
+
while (frames.length > 0) {
|
|
1450
|
+
const frame = frames[frames.length - 1];
|
|
1451
|
+
if (frame.enter) {
|
|
1452
|
+
const enter = frame.enter;
|
|
1453
|
+
frame.enter = undefined;
|
|
1454
|
+
enter();
|
|
1455
|
+
}
|
|
1456
|
+
if (frame.index >= frame.nodes.length) {
|
|
1457
|
+
frames.pop();
|
|
1458
|
+
frame.exit?.();
|
|
1459
|
+
if (frame.scoped)
|
|
1460
|
+
stateStack.pop();
|
|
1461
|
+
continue;
|
|
1462
|
+
}
|
|
1463
|
+
const node = frame.nodes[frame.index++];
|
|
1464
|
+
if (node.type === 'group') {
|
|
1465
|
+
const firstCtrl = firstControl(node);
|
|
1466
|
+
if (firstCtrl?.word === 'pict') {
|
|
1467
|
+
const img = renderPicture(node);
|
|
1468
|
+
if (img)
|
|
1469
|
+
appendHtml('img', img, currentState());
|
|
1470
|
+
continue;
|
|
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
|
+
}
|
|
1486
|
+
if (firstCtrl && destinationWords.has(firstCtrl.word)) {
|
|
1487
|
+
continue;
|
|
1488
|
+
}
|
|
1489
|
+
const hasStarDest = node.children.length >= 2 &&
|
|
1490
|
+
node.children[0].type === 'control' && node.children[0].word === '*';
|
|
1491
|
+
if (hasStarDest) {
|
|
1492
|
+
const dest = node.children.find((n) => n.type === 'control' && n.word !== '*');
|
|
1493
|
+
// Word wraps pictures in {\*\shppict{\pict …}} — descend into it
|
|
1494
|
+
// rather than dropping the picture with the rest of the ignorables.
|
|
1495
|
+
if (dest?.word === 'shppict') {
|
|
1496
|
+
enterGroup(node, cloneState());
|
|
1497
|
+
}
|
|
1498
|
+
else if (dest?.word === 'shpinst') {
|
|
1499
|
+
readShape(node);
|
|
621
1500
|
}
|
|
622
|
-
if (
|
|
1501
|
+
else if (dest?.word === 'inkcap') {
|
|
1502
|
+
// Marks the paragraph that follows as a picture caption.
|
|
1503
|
+
paragraphIsCaption = true;
|
|
1504
|
+
}
|
|
1505
|
+
else if (dest?.word === 'nesttableprops') {
|
|
1506
|
+
// Word ends each row of a table inside a cell with this group, which holds
|
|
1507
|
+
// the row's definition and its \nestrow.
|
|
1508
|
+
nestTabPending = false;
|
|
1509
|
+
cellBreaks++;
|
|
1510
|
+
}
|
|
1511
|
+
continue;
|
|
1512
|
+
}
|
|
1513
|
+
const state = cloneState();
|
|
1514
|
+
// {\field{\*\fldinst HYPERLINK "…"}{\fldrslt text}}: the text is a link, if the
|
|
1515
|
+
// address is one the writer would write.
|
|
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());
|
|
623
1522
|
continue;
|
|
624
1523
|
}
|
|
625
|
-
const
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
1524
|
+
const href = fieldLink(node);
|
|
1525
|
+
if (href)
|
|
1526
|
+
state.link = href;
|
|
1527
|
+
}
|
|
1528
|
+
enterGroup(node, state);
|
|
1529
|
+
}
|
|
1530
|
+
else if (node.type === 'control') {
|
|
1531
|
+
const state = currentState();
|
|
1532
|
+
const w = node.word;
|
|
1533
|
+
const p = node.param;
|
|
1534
|
+
switch (w) {
|
|
1535
|
+
case 'b':
|
|
1536
|
+
state.bold = p !== 0;
|
|
1537
|
+
break;
|
|
1538
|
+
case 'i':
|
|
1539
|
+
state.italic = p !== 0;
|
|
1540
|
+
break;
|
|
1541
|
+
case 'ul':
|
|
1542
|
+
case 'ulnone':
|
|
1543
|
+
state.underline = w === 'ul' && p !== 0;
|
|
1544
|
+
break;
|
|
1545
|
+
case 'strike':
|
|
1546
|
+
state.strike = p !== 0;
|
|
1547
|
+
break;
|
|
1548
|
+
case 'super':
|
|
1549
|
+
state.super_ = true;
|
|
1550
|
+
state.sub = false;
|
|
1551
|
+
break;
|
|
1552
|
+
case 'sub':
|
|
1553
|
+
state.sub = true;
|
|
1554
|
+
state.super_ = false;
|
|
1555
|
+
break;
|
|
1556
|
+
case 'nosupersub':
|
|
1557
|
+
state.super_ = false;
|
|
1558
|
+
state.sub = false;
|
|
1559
|
+
break;
|
|
1560
|
+
case 'fs':
|
|
1561
|
+
// (Up to Word's limit of 1638 pt; a damaged file can say anything.)
|
|
1562
|
+
if (p != null)
|
|
1563
|
+
state.fontSize = Math.min(Math.max(p, 0), 3276);
|
|
1564
|
+
break;
|
|
1565
|
+
case 'cf':
|
|
1566
|
+
if (p != null)
|
|
1567
|
+
state.colorIndex = p;
|
|
1568
|
+
break;
|
|
1569
|
+
case 'cb':
|
|
1570
|
+
break; // \cb not rendered on import
|
|
1571
|
+
case 'highlight':
|
|
1572
|
+
if (p != null)
|
|
1573
|
+
state.highlightIndex = p;
|
|
1574
|
+
break;
|
|
1575
|
+
case 'f':
|
|
1576
|
+
if (p != null)
|
|
1577
|
+
state.fontIndex = p;
|
|
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.
|
|
1581
|
+
case 'ql':
|
|
1582
|
+
state.align = 'left';
|
|
1583
|
+
break;
|
|
1584
|
+
case 'qr':
|
|
1585
|
+
state.align = 'right';
|
|
1586
|
+
break;
|
|
1587
|
+
case 'qc':
|
|
1588
|
+
state.align = 'center';
|
|
1589
|
+
break;
|
|
1590
|
+
case 'qj':
|
|
1591
|
+
state.align = 'justify';
|
|
1592
|
+
break;
|
|
1593
|
+
case 'v':
|
|
1594
|
+
state.hidden = p !== 0;
|
|
1595
|
+
break;
|
|
1596
|
+
case 'deleted':
|
|
1597
|
+
state.deleted = p !== 0;
|
|
1598
|
+
break;
|
|
1599
|
+
case 'li':
|
|
1600
|
+
state.leftIndent = p ?? 0;
|
|
1601
|
+
break;
|
|
1602
|
+
case 'ri':
|
|
1603
|
+
state.rightIndent = p ?? 0;
|
|
1604
|
+
break;
|
|
1605
|
+
case 'fi':
|
|
1606
|
+
state.firstLineIndent = p ?? 0;
|
|
1607
|
+
break;
|
|
1608
|
+
case 'par':
|
|
1609
|
+
case 'sect':
|
|
1610
|
+
// \sect ends a section, and with it the paragraph: "A\sect B" is two lines.
|
|
1611
|
+
paragraphMark(state);
|
|
1612
|
+
break;
|
|
1613
|
+
case 'trowd':
|
|
1614
|
+
// A row's definition, not its start: Word writes the definition before the
|
|
1615
|
+
// cells and again before \row, so the cells read so far are kept.
|
|
1616
|
+
currentRowDefs = [];
|
|
1617
|
+
pendingDef = newCellDef();
|
|
1618
|
+
pendingSide = null;
|
|
1619
|
+
borderSide = null;
|
|
1620
|
+
cellBorders = { b: false, other: false, bare: false };
|
|
1621
|
+
lastRow = false;
|
|
1622
|
+
break;
|
|
1623
|
+
case 'lastrow':
|
|
1624
|
+
lastRow = true;
|
|
1625
|
+
break;
|
|
1626
|
+
case 'trgaph':
|
|
1627
|
+
case 'trkeep':
|
|
1628
|
+
case 'trleft':
|
|
1629
|
+
case 'trhdr':
|
|
1630
|
+
pendingSide = null;
|
|
1631
|
+
break; // table formatting, ignored
|
|
1632
|
+
case 'clbrdrr':
|
|
1633
|
+
case 'clbrdrl':
|
|
1634
|
+
case 'clbrdrt':
|
|
1635
|
+
pendingSide = 'other';
|
|
1636
|
+
borderSide = null;
|
|
1637
|
+
break;
|
|
1638
|
+
case 'clbrdrb':
|
|
1639
|
+
pendingSide = 'b';
|
|
1640
|
+
borderSide = null;
|
|
1641
|
+
break;
|
|
1642
|
+
case 'brdrnone':
|
|
1643
|
+
case 'brdrnil':
|
|
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;
|
|
1654
|
+
break;
|
|
1655
|
+
// Every border style RTF names: any of them makes the side a border.
|
|
1656
|
+
case 'brdrs':
|
|
1657
|
+
case 'brdrdb':
|
|
1658
|
+
case 'brdrth':
|
|
1659
|
+
case 'brdrsh':
|
|
1660
|
+
case 'brdrdot':
|
|
1661
|
+
case 'brdrdash':
|
|
1662
|
+
case 'brdrhair':
|
|
1663
|
+
case 'brdrdashsm':
|
|
1664
|
+
case 'brdrdashd':
|
|
1665
|
+
case 'brdrdashdd':
|
|
1666
|
+
case 'brdrdashdotstr':
|
|
1667
|
+
case 'brdrtriple':
|
|
1668
|
+
case 'brdrtnthsg':
|
|
1669
|
+
case 'brdrthtnsg':
|
|
1670
|
+
case 'brdrtnthtnsg':
|
|
1671
|
+
case 'brdrtnthmg':
|
|
1672
|
+
case 'brdrthtnmg':
|
|
1673
|
+
case 'brdrtnthtnmg':
|
|
1674
|
+
case 'brdrtnthlg':
|
|
1675
|
+
case 'brdrthtnlg':
|
|
1676
|
+
case 'brdrtnthtnlg':
|
|
1677
|
+
case 'brdrwavy':
|
|
1678
|
+
case 'brdrwavydb':
|
|
1679
|
+
case 'brdremboss':
|
|
1680
|
+
case 'brdrengrave':
|
|
1681
|
+
case 'brdroutset':
|
|
1682
|
+
case 'brdrinset':
|
|
1683
|
+
if (pendingSide) {
|
|
1684
|
+
cellBorders[pendingSide] = true;
|
|
1685
|
+
if (pendingSide === 'b')
|
|
1686
|
+
cellBorders.bare = w === 'brdrs';
|
|
1687
|
+
}
|
|
1688
|
+
borderSide = pendingSide;
|
|
1689
|
+
pendingSide = null;
|
|
1690
|
+
break;
|
|
1691
|
+
case 'clvmgf':
|
|
1692
|
+
pendingDef.vmgf = true;
|
|
1693
|
+
break;
|
|
1694
|
+
case 'clvmrg':
|
|
1695
|
+
pendingDef.vmrg = true;
|
|
1696
|
+
break;
|
|
1697
|
+
case 'clmgf':
|
|
1698
|
+
pendingDef.hmgf = true;
|
|
1699
|
+
break;
|
|
1700
|
+
case 'clmrg':
|
|
1701
|
+
pendingDef.hmrg = true;
|
|
1702
|
+
break;
|
|
1703
|
+
case 'cellx':
|
|
1704
|
+
if (p != null) {
|
|
1705
|
+
pendingDef.right = p;
|
|
1706
|
+
pendingDef.header = cellBorders.b && cellBorders.bare && !cellBorders.other;
|
|
1707
|
+
currentRowDefs.push(pendingDef);
|
|
635
1708
|
}
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
1709
|
+
pendingDef = newCellDef();
|
|
1710
|
+
pendingSide = null;
|
|
1711
|
+
borderSide = null;
|
|
1712
|
+
cellBorders = { b: false, other: false, bare: false };
|
|
1713
|
+
break;
|
|
1714
|
+
case 'intbl':
|
|
1715
|
+
inTableCell = true;
|
|
1716
|
+
break;
|
|
1717
|
+
case 'cell':
|
|
1718
|
+
if (pendingHighSurrogate) {
|
|
1719
|
+
pendingHighSurrogate = 0;
|
|
1720
|
+
pushText('\ufffd', state);
|
|
639
1721
|
}
|
|
640
|
-
|
|
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();
|
|
1730
|
+
// The paragraph mark that ends a cell's last paragraph adds no line.
|
|
1731
|
+
cellBreaks = 0;
|
|
1732
|
+
nestTabPending = false;
|
|
1733
|
+
break;
|
|
1734
|
+
case 'nestcell':
|
|
1735
|
+
// A table inside a cell is read as lines of text in that cell: its cells a
|
|
1736
|
+
// tab apart, each of its rows a line. The writer sends one the same way.
|
|
1737
|
+
nestTabPending = true;
|
|
1738
|
+
break;
|
|
1739
|
+
case 'nestrow':
|
|
1740
|
+
nestTabPending = false;
|
|
1741
|
+
cellBreaks++;
|
|
1742
|
+
break;
|
|
1743
|
+
case 'row': {
|
|
1744
|
+
// Text after the row's last \cell is a cell that was not closed, not the
|
|
1745
|
+
// start of the paragraph after the table.
|
|
1746
|
+
if (trimSpaces(renderRuns(runs))) {
|
|
1747
|
+
currentRowCells.push({ html: trimSpaces(renderRuns(runs)), align: alignHere(state) });
|
|
1748
|
+
newRuns();
|
|
1749
|
+
}
|
|
1750
|
+
// A row with no definition of its own repeats the one before it.
|
|
1751
|
+
const defs = currentRowDefs.length > 0 ? currentRowDefs : lastRowDefs;
|
|
1752
|
+
tableRows.push({ cells: currentRowCells, defs });
|
|
1753
|
+
lastRowDefs = defs;
|
|
1754
|
+
currentRowCells = [];
|
|
1755
|
+
currentRowDefs = [];
|
|
1756
|
+
pendingDef = newCellDef();
|
|
1757
|
+
inTableCell = false;
|
|
1758
|
+
cellBreaks = 0;
|
|
1759
|
+
nestTabPending = false;
|
|
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
|
+
}
|
|
1775
|
+
break;
|
|
641
1776
|
}
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
break;
|
|
654
|
-
case 'i':
|
|
655
|
-
state.italic = p !== 0;
|
|
656
|
-
break;
|
|
657
|
-
case 'ul':
|
|
658
|
-
case 'ulnone':
|
|
659
|
-
state.underline = w === 'ul' && p !== 0;
|
|
660
|
-
break;
|
|
661
|
-
case 'strike':
|
|
662
|
-
state.strike = p !== 0;
|
|
663
|
-
break;
|
|
664
|
-
case 'super':
|
|
665
|
-
state.super_ = true;
|
|
666
|
-
state.sub = false;
|
|
667
|
-
break;
|
|
668
|
-
case 'sub':
|
|
669
|
-
state.sub = true;
|
|
670
|
-
state.super_ = false;
|
|
671
|
-
break;
|
|
672
|
-
case 'nosupersub':
|
|
673
|
-
state.super_ = false;
|
|
674
|
-
state.sub = false;
|
|
675
|
-
break;
|
|
676
|
-
case 'fs':
|
|
677
|
-
if (p != null)
|
|
678
|
-
state.fontSize = p;
|
|
679
|
-
break;
|
|
680
|
-
case 'cf':
|
|
681
|
-
if (p != null)
|
|
682
|
-
state.colorIndex = p;
|
|
683
|
-
break;
|
|
684
|
-
case 'cb':
|
|
685
|
-
break; // \cb not rendered on import
|
|
686
|
-
case 'highlight':
|
|
687
|
-
if (p != null)
|
|
688
|
-
state.highlightIndex = p;
|
|
689
|
-
break;
|
|
690
|
-
case 'f':
|
|
691
|
-
if (p != null)
|
|
692
|
-
state.fontIndex = p;
|
|
693
|
-
break;
|
|
694
|
-
case 'ql':
|
|
695
|
-
currentAlign = 'left';
|
|
696
|
-
break;
|
|
697
|
-
case 'qr':
|
|
698
|
-
currentAlign = 'right';
|
|
699
|
-
break;
|
|
700
|
-
case 'qc':
|
|
701
|
-
currentAlign = 'center';
|
|
702
|
-
break;
|
|
703
|
-
case 'qj':
|
|
704
|
-
currentAlign = 'justify';
|
|
705
|
-
break;
|
|
706
|
-
case 'li':
|
|
707
|
-
state.leftIndent = p ?? 0;
|
|
708
|
-
break;
|
|
709
|
-
case 'ri':
|
|
710
|
-
state.rightIndent = p ?? 0;
|
|
711
|
-
break;
|
|
712
|
-
case 'fi':
|
|
713
|
-
state.firstLineIndent = p ?? 0;
|
|
714
|
-
break;
|
|
715
|
-
case 'par':
|
|
716
|
-
if (!inTableCell)
|
|
717
|
-
flushParagraph();
|
|
718
|
-
break;
|
|
719
|
-
case 'trowd':
|
|
720
|
-
currentRowCells = [];
|
|
721
|
-
currentRowIsHeader = false;
|
|
722
|
-
currentRowCellRights = [];
|
|
723
|
-
pendingBottomBorder = false;
|
|
724
|
-
break;
|
|
725
|
-
case 'trgaph':
|
|
726
|
-
case 'trkeep':
|
|
727
|
-
case 'trleft':
|
|
728
|
-
case 'trhdr':
|
|
729
|
-
case 'clbrdrr':
|
|
730
|
-
case 'clbrdrl':
|
|
731
|
-
case 'clbrdrt':
|
|
732
|
-
pendingBottomBorder = false;
|
|
733
|
-
break; // table formatting, ignored
|
|
734
|
-
case 'clbrdrb':
|
|
735
|
-
pendingBottomBorder = true;
|
|
736
|
-
break;
|
|
737
|
-
case 'brdrnone':
|
|
738
|
-
case 'brdrnil':
|
|
739
|
-
pendingBottomBorder = false;
|
|
740
|
-
break;
|
|
741
|
-
case 'brdrs':
|
|
742
|
-
case 'brdrdb':
|
|
743
|
-
case 'brdrth':
|
|
744
|
-
case 'brdrdot':
|
|
745
|
-
case 'brdrdash':
|
|
746
|
-
if (pendingBottomBorder)
|
|
747
|
-
currentRowIsHeader = true;
|
|
748
|
-
pendingBottomBorder = false;
|
|
749
|
-
break;
|
|
750
|
-
case 'cellx':
|
|
751
|
-
if (p != null)
|
|
752
|
-
currentRowCellRights.push(p);
|
|
753
|
-
break;
|
|
754
|
-
case 'intbl':
|
|
755
|
-
inTableCell = true;
|
|
756
|
-
break;
|
|
757
|
-
case 'cell':
|
|
758
|
-
currentRowCells.push(currentParagraph.trim());
|
|
759
|
-
currentRowCellAligns.push(currentAlign);
|
|
760
|
-
currentParagraph = '';
|
|
761
|
-
paragraphHasText = false;
|
|
762
|
-
currentAlign = 'left';
|
|
763
|
-
break;
|
|
764
|
-
case 'row':
|
|
765
|
-
tableRows.push({ cells: currentRowCells, isHeader: currentRowIsHeader, cellRights: currentRowCellRights, cellAligns: currentRowCellAligns });
|
|
766
|
-
currentRowCells = [];
|
|
767
|
-
currentRowIsHeader = false;
|
|
768
|
-
currentRowCellRights = [];
|
|
769
|
-
currentRowCellAligns = [];
|
|
1777
|
+
case 'pard':
|
|
1778
|
+
// \pard resets the paragraph, not the characters: bold, italic, underline
|
|
1779
|
+
// and strikethrough carry on until \plain or their own \b0. Word relies on it.
|
|
1780
|
+
state.align = 'left';
|
|
1781
|
+
resetIndents(state);
|
|
1782
|
+
// Being in a table is a paragraph property too. Without this, one \intbl with
|
|
1783
|
+
// no \row made a single cell of the rest of the document. The marker group
|
|
1784
|
+
// of a list item ({\listtext\pard …}) resets only itself. Between a row's
|
|
1785
|
+
// first \cell and its \row the table goes on whatever \pard says: a writer
|
|
1786
|
+
// that leaves \intbl out there still means the next cell.
|
|
1787
|
+
if (!state.inList && currentRowCells.length === 0)
|
|
770
1788
|
inTableCell = false;
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
break;
|
|
783
|
-
case 'line':
|
|
784
|
-
currentParagraph += '<br>';
|
|
785
|
-
paragraphHasText = true;
|
|
786
|
-
break;
|
|
787
|
-
case 'tab':
|
|
788
|
-
// A real tab, in the shape the editor's Tab key inserts, so it shows as
|
|
789
|
-
// one and is written back as \tab (an em space came back as \u8195).
|
|
790
|
-
// After a list marker ("\bullet\tab", "1.\tab") the gap stays an em
|
|
791
|
-
// space: lists are read as plain lines, and a full tab there is too wide.
|
|
792
|
-
currentParagraph += LIST_MARKER.test(currentParagraph) ? ' ' : TAB_HTML;
|
|
793
|
-
paragraphHasText = true;
|
|
794
|
-
break;
|
|
795
|
-
case 'pntext':
|
|
796
|
-
case 'listtext':
|
|
797
|
-
state.inList = true;
|
|
798
|
-
paragraphHasListMarker = true;
|
|
799
|
-
break;
|
|
800
|
-
case 'u': {
|
|
801
|
-
if (p != null) {
|
|
802
|
-
let codePoint = p;
|
|
803
|
-
if (codePoint < 0)
|
|
804
|
-
codePoint += 65536;
|
|
805
|
-
currentParagraph += wrapText(String.fromCodePoint(codePoint), state);
|
|
806
|
-
paragraphHasText = true;
|
|
807
|
-
pendingUnicodeSkip = state.ucSkip ?? 1;
|
|
808
|
-
}
|
|
1789
|
+
break;
|
|
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.)
|
|
1794
|
+
appendHtml('br', '<br>', state);
|
|
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))
|
|
809
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);
|
|
810
1809
|
}
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
1810
|
+
break;
|
|
1811
|
+
case 'tab':
|
|
1812
|
+
appendTab(state);
|
|
1813
|
+
break;
|
|
1814
|
+
case 'pntext':
|
|
1815
|
+
case 'listtext':
|
|
1816
|
+
state.inList = true;
|
|
1817
|
+
paragraphHasListMarker = true;
|
|
1818
|
+
break;
|
|
1819
|
+
case 'u': {
|
|
1820
|
+
if (p != null) {
|
|
1821
|
+
pendingUnicodeSkip = state.ucSkip ?? 1;
|
|
1822
|
+
// \uN is a signed 16-bit number; some writers give the code point itself.
|
|
1823
|
+
const code = p < 0 ? p + 65536 : p;
|
|
1824
|
+
if (code <= 0 || code > 0x10ffff)
|
|
1825
|
+
break; // no character: a NUL, or out of range
|
|
1826
|
+
if (!shown(state))
|
|
1827
|
+
break;
|
|
1828
|
+
if (code >= 0xd800 && code <= 0xdbff) {
|
|
1829
|
+
// The first half of a pair: one character with the \u that follows.
|
|
1830
|
+
if (pendingHighSurrogate)
|
|
1831
|
+
appendText('\ufffd', state);
|
|
1832
|
+
pendingHighSurrogate = code;
|
|
814
1833
|
}
|
|
1834
|
+
else if (code >= 0xdc00 && code <= 0xdfff) {
|
|
1835
|
+
const high = pendingHighSurrogate;
|
|
1836
|
+
pendingHighSurrogate = 0;
|
|
1837
|
+
appendText(high ? String.fromCharCode(high, code) : '\ufffd', state);
|
|
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
|
+
}
|
|
1844
|
+
else {
|
|
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);
|
|
1848
|
+
}
|
|
1849
|
+
}
|
|
1850
|
+
break;
|
|
1851
|
+
}
|
|
1852
|
+
case 'uc':
|
|
1853
|
+
if (p != null) {
|
|
1854
|
+
state.ucSkip = Math.max(0, p);
|
|
1855
|
+
}
|
|
1856
|
+
break;
|
|
1857
|
+
case 'plain':
|
|
1858
|
+
state.bold = false;
|
|
1859
|
+
state.italic = false;
|
|
1860
|
+
state.underline = false;
|
|
1861
|
+
state.strike = false;
|
|
1862
|
+
state.super_ = false;
|
|
1863
|
+
state.sub = false;
|
|
1864
|
+
state.fontSize = 24;
|
|
1865
|
+
state.colorIndex = 0;
|
|
1866
|
+
state.highlightIndex = 0;
|
|
1867
|
+
state.fontIndex = defaultFont;
|
|
1868
|
+
state.hidden = false;
|
|
1869
|
+
state.deleted = false;
|
|
1870
|
+
break;
|
|
1871
|
+
case 'page':
|
|
1872
|
+
// A page break. On screen it is a rule; the writer sends it back as \page.
|
|
1873
|
+
if (inTableCell) {
|
|
1874
|
+
cellBreaks++;
|
|
815
1875
|
break;
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
state.italic = false;
|
|
819
|
-
state.underline = false;
|
|
820
|
-
state.strike = false;
|
|
821
|
-
state.super_ = false;
|
|
822
|
-
state.sub = false;
|
|
823
|
-
state.fontSize = 24;
|
|
824
|
-
state.colorIndex = 0;
|
|
825
|
-
state.highlightIndex = 0;
|
|
826
|
-
state.fontIndex = 0;
|
|
827
|
-
break;
|
|
828
|
-
case 'page':
|
|
1876
|
+
}
|
|
1877
|
+
for (; cellBreaks > 0; cellBreaks--)
|
|
829
1878
|
flushParagraph();
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
default:
|
|
866
|
-
break;
|
|
867
|
-
}
|
|
1879
|
+
if (runs.length > 0)
|
|
1880
|
+
flushParagraph();
|
|
1881
|
+
flushTable();
|
|
1882
|
+
blocks.push({ kind: 'rule', pageBreak: true });
|
|
1883
|
+
break;
|
|
1884
|
+
case 'emspace':
|
|
1885
|
+
case 'enspace':
|
|
1886
|
+
appendHtml('gap', ' ', state);
|
|
1887
|
+
break;
|
|
1888
|
+
case 'qmspace':
|
|
1889
|
+
appendText('\u2005', state); // a quarter of an em
|
|
1890
|
+
break;
|
|
1891
|
+
case 'emdash':
|
|
1892
|
+
appendText('\u2014', state);
|
|
1893
|
+
break;
|
|
1894
|
+
case 'endash':
|
|
1895
|
+
appendText('\u2013', state);
|
|
1896
|
+
break;
|
|
1897
|
+
case 'lquote':
|
|
1898
|
+
appendText('\u2018', state);
|
|
1899
|
+
break;
|
|
1900
|
+
case 'rquote':
|
|
1901
|
+
appendText('\u2019', state);
|
|
1902
|
+
break;
|
|
1903
|
+
case 'ldblquote':
|
|
1904
|
+
appendText('\u201C', state);
|
|
1905
|
+
break;
|
|
1906
|
+
case 'rdblquote':
|
|
1907
|
+
appendText('\u201D', state);
|
|
1908
|
+
break;
|
|
1909
|
+
case 'bullet':
|
|
1910
|
+
appendText('\u2022', state);
|
|
1911
|
+
break;
|
|
1912
|
+
default:
|
|
1913
|
+
break;
|
|
868
1914
|
}
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
pendingUnicodeSkip
|
|
876
|
-
const remainder = node.value.slice(skipCount);
|
|
877
|
-
if (remainder) {
|
|
878
|
-
currentParagraph += wrapText(remainder, state);
|
|
879
|
-
if (/[^\s]/.test(remainder))
|
|
880
|
-
paragraphHasText = true;
|
|
881
|
-
}
|
|
1915
|
+
}
|
|
1916
|
+
else {
|
|
1917
|
+
const state = currentState();
|
|
1918
|
+
if (pendingUnicodeSkip > 0) {
|
|
1919
|
+
// The characters after \uN that stand in for it where Unicode is not read.
|
|
1920
|
+
if (node.hex) {
|
|
1921
|
+
pendingUnicodeSkip--;
|
|
882
1922
|
continue;
|
|
883
1923
|
}
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
1924
|
+
const skipCount = Math.min(pendingUnicodeSkip, node.value.length);
|
|
1925
|
+
pendingUnicodeSkip -= skipCount;
|
|
1926
|
+
appendChars(node.value.slice(skipCount), state);
|
|
1927
|
+
continue;
|
|
1928
|
+
}
|
|
1929
|
+
appendChars(node.value, state);
|
|
1930
|
+
}
|
|
1931
|
+
}
|
|
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);
|
|
1937
|
+
}
|
|
1938
|
+
// ── Building the HTML ──
|
|
1939
|
+
/** Each block as an ordinary paragraph's content: what it is unless it turns out to be more. */
|
|
1940
|
+
const plain = blocks.map((b) => (b.kind === 'paragraph' ? trimSpaces(renderRuns(b.runs)) : b.kind === 'table' ? b.html : '<hr>'));
|
|
1941
|
+
const items = blocks.map((b) => {
|
|
1942
|
+
if (b.kind !== 'paragraph' || !b.marker || b.inTable || b.caption)
|
|
1943
|
+
return null;
|
|
1944
|
+
if (b.first !== -LIST_HANG || b.left < LIST_HANG || b.right !== 0 || b.align !== 'left')
|
|
1945
|
+
return null;
|
|
1946
|
+
return {
|
|
1947
|
+
kind: b.marker.kind,
|
|
1948
|
+
number: b.marker.number,
|
|
1949
|
+
left: b.left,
|
|
1950
|
+
html: trimSpaces(renderRuns(b.runs.slice(b.marker.end)))
|
|
1951
|
+
};
|
|
1952
|
+
});
|
|
1953
|
+
/** Consecutive list items as nested <ul> and <ol>, one string per list at the top level. */
|
|
1954
|
+
function renderLists(list) {
|
|
1955
|
+
const out = [];
|
|
1956
|
+
let html = '';
|
|
1957
|
+
const open = [];
|
|
1958
|
+
const closeList = () => {
|
|
1959
|
+
const done = open.pop();
|
|
1960
|
+
html += `</li></${done.kind}>`;
|
|
1961
|
+
if (open.length === 0) {
|
|
1962
|
+
out.push(html);
|
|
1963
|
+
html = '';
|
|
1964
|
+
}
|
|
1965
|
+
};
|
|
1966
|
+
for (const item of list) {
|
|
1967
|
+
// A smaller indent ends the lists nested deeper than it.
|
|
1968
|
+
while (open.length > 0 && item.left < open[open.length - 1].left)
|
|
1969
|
+
closeList();
|
|
1970
|
+
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;
|
|
1974
|
+
}
|
|
1975
|
+
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)
|
|
1979
|
+
closeList();
|
|
1980
|
+
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 });
|
|
887
1987
|
}
|
|
1988
|
+
html += item.html || '<br>';
|
|
888
1989
|
}
|
|
1990
|
+
while (open.length > 0)
|
|
1991
|
+
closeList();
|
|
1992
|
+
return out;
|
|
889
1993
|
}
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
1994
|
+
/** Whether a paragraph is a heading or a code block, from the formatting of all its text. */
|
|
1995
|
+
function classify(b) {
|
|
1996
|
+
const visible = b.runs.filter((r) => r.type === 'text' && !ONLY_SPACES.test(r.text));
|
|
1997
|
+
if (visible.length === 0 || b.runs.some((r) => r.type === 'html' && r.kind === 'img'))
|
|
1998
|
+
return null;
|
|
1999
|
+
// The size must be the whole paragraph's: one large word does not make a heading.
|
|
2000
|
+
const size = visible[0].fmt.fontSize;
|
|
2001
|
+
if (visible.some((r) => r.fmt.fontSize !== size))
|
|
2002
|
+
return null;
|
|
2003
|
+
if (size === preSize && visible.every((r) => r.fmt.mono))
|
|
2004
|
+
return { tag: 'pre' };
|
|
2005
|
+
if (size === bodySize)
|
|
2006
|
+
return null;
|
|
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))
|
|
2011
|
+
return null;
|
|
2012
|
+
// Compared in half-points, rounded the way the writer rounds them, so
|
|
2013
|
+
// a heading written at any body size is read back as the same level.
|
|
2014
|
+
for (const tag of ['h1', 'h2', 'h3']) {
|
|
2015
|
+
const nominal = Math.round(bodySize * HEADING_SCALE[tag]);
|
|
2016
|
+
// The heading's own size and bold are the element's: only a size that differs
|
|
2017
|
+
// from it is kept inside.
|
|
2018
|
+
if (size >= nominal)
|
|
2019
|
+
return { tag, options: { dropSize: nominal, dropBold: true } };
|
|
2020
|
+
}
|
|
2021
|
+
return null;
|
|
897
2022
|
}
|
|
898
|
-
// Build final HTML from paragraphs (collapse repeated empty lines)
|
|
899
2023
|
const rendered = [];
|
|
900
|
-
|
|
901
|
-
const isListLine = (
|
|
902
|
-
for (let i = 0; i <
|
|
903
|
-
const
|
|
904
|
-
const
|
|
2024
|
+
// A typed line that starts with a dash or a bullet; a rebuilt list item is not one.
|
|
2025
|
+
const isListLine = (i) => i >= 0 && i < plain.length && !items[i] && /^[-\u2022]/.test(plain[i].replace(/^ +/g, ''));
|
|
2026
|
+
for (let i = 0; i < blocks.length; i++) {
|
|
2027
|
+
const block = blocks[i];
|
|
2028
|
+
const trimmed = plain[i];
|
|
2029
|
+
if (block.kind === 'rule') {
|
|
2030
|
+
rendered.push(block.pageBreak ? '<hr style="break-after:page">' : '<hr>');
|
|
2031
|
+
continue;
|
|
2032
|
+
}
|
|
2033
|
+
if (block.kind === 'table') {
|
|
2034
|
+
rendered.push(trimmed);
|
|
2035
|
+
continue;
|
|
2036
|
+
}
|
|
2037
|
+
if (items[i]) {
|
|
2038
|
+
const list = [];
|
|
2039
|
+
for (; i < blocks.length && items[i]; i++)
|
|
2040
|
+
list.push(items[i]);
|
|
2041
|
+
i--;
|
|
2042
|
+
rendered.push(...renderLists(list));
|
|
2043
|
+
continue;
|
|
2044
|
+
}
|
|
2045
|
+
const align = block.align;
|
|
905
2046
|
// The paragraph's style attribute: its alignment, then its indents.
|
|
906
|
-
const blockStyle = [align !== 'left' ? `text-align:${align}` : '',
|
|
2047
|
+
const blockStyle = [align !== 'left' ? `text-align:${align}` : '', block.inTable ? '' : indentStyle(block)]
|
|
907
2048
|
.filter(Boolean)
|
|
908
2049
|
.join(';');
|
|
909
2050
|
const styleAttr = blockStyle ? ` style="${blockStyle}"` : '';
|
|
910
|
-
const prev = i > 0 ? trimmedParagraphs[i - 1] : '';
|
|
911
|
-
const next = i + 1 < trimmedParagraphs.length ? trimmedParagraphs[i + 1] : '';
|
|
912
2051
|
if (!trimmed) {
|
|
913
|
-
if (isListLine(
|
|
2052
|
+
if (isListLine(i - 1) && isListLine(i + 1)) {
|
|
914
2053
|
continue;
|
|
915
2054
|
}
|
|
916
2055
|
const last = rendered[rendered.length - 1];
|
|
@@ -920,70 +2059,79 @@ export function rtfToHtml(rtfString, options = {}) {
|
|
|
920
2059
|
rendered.push('<p><br></p>');
|
|
921
2060
|
continue;
|
|
922
2061
|
}
|
|
923
|
-
|
|
2062
|
+
// The rule the writer sends for <hr>: a centered line of em dashes, and nothing else.
|
|
2063
|
+
if (align === 'center' &&
|
|
2064
|
+
block.runs.every((r) => r.type === 'text' && !r.fmt.bold && !r.fmt.italic && !r.fmt.underline && !r.fmt.strike && !r.fmt.link) &&
|
|
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) {
|
|
924
2068
|
rendered.push('<hr>');
|
|
925
2069
|
continue;
|
|
926
2070
|
}
|
|
927
|
-
if (trimmed.startsWith('<table')) {
|
|
928
|
-
rendered.push(trimmed);
|
|
929
|
-
continue;
|
|
930
|
-
}
|
|
931
2071
|
// A paragraph tagged by {\*\inkcap} is the description of the figure above it.
|
|
932
|
-
if (
|
|
2072
|
+
if (block.caption) {
|
|
933
2073
|
const last = rendered.length - 1;
|
|
934
2074
|
if (last >= 0 && rendered[last].startsWith('<figure') && !rendered[last].includes('<figcaption')) {
|
|
935
|
-
|
|
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);
|
|
936
2079
|
continue;
|
|
937
2080
|
}
|
|
938
2081
|
}
|
|
939
2082
|
// A paragraph holding nothing but pictures becomes a figure, so it can carry
|
|
940
2083
|
// a caption and be aligned/resized as a unit in the editor.
|
|
941
2084
|
if (IMAGE_ONLY_PARAGRAPH.test(trimmed)) {
|
|
942
|
-
const figureStyle = [align !== 'left' ? `text-align:${align}` : '',
|
|
2085
|
+
const figureStyle = [align !== 'left' ? `text-align:${align}` : '', block.inTable ? '' : figureIndentStyle(block)]
|
|
943
2086
|
.filter(Boolean)
|
|
944
2087
|
.join(';');
|
|
945
2088
|
rendered.push(`<figure${figureStyle ? ` style="${figureStyle}"` : ''}>${trimmed}</figure>`);
|
|
946
2089
|
continue;
|
|
947
2090
|
}
|
|
948
|
-
const
|
|
949
|
-
if (
|
|
950
|
-
//
|
|
951
|
-
|
|
952
|
-
const
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
if
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
rendered.push(`<h3${styleAttr}>${stripSizeSpan(trimmed)}</h3>`);
|
|
968
|
-
continue;
|
|
2091
|
+
const kind = classify(block);
|
|
2092
|
+
if (kind?.tag === 'pre') {
|
|
2093
|
+
// A code block keeps its spaces, and is written back with a left indent only.
|
|
2094
|
+
const left = block.inTable ? 0 : Math.max(0, block.left);
|
|
2095
|
+
const preStyle = left > 0 ? ` style="margin-left:${twipsToPt(left)}"` : '';
|
|
2096
|
+
rendered.push(`<pre${preStyle}>${renderRuns(block.runs, { pre: true, dropSize: preSize })}</pre>`);
|
|
2097
|
+
continue;
|
|
2098
|
+
}
|
|
2099
|
+
if (kind) {
|
|
2100
|
+
// A heading is bold throughout, on screen and when it is written again, so its
|
|
2101
|
+
// pieces are joined as if they all were: what differed only in bold is one piece.
|
|
2102
|
+
const bold = [];
|
|
2103
|
+
for (const run of block.runs) {
|
|
2104
|
+
const fmt = { ...run.fmt, bold: true };
|
|
2105
|
+
const last = bold[bold.length - 1];
|
|
2106
|
+
if (run.type === 'text' && last?.type === 'text' && sameFormat(last.fmt, fmt))
|
|
2107
|
+
last.text += run.text;
|
|
2108
|
+
else
|
|
2109
|
+
bold.push({ ...run, fmt });
|
|
969
2110
|
}
|
|
2111
|
+
rendered.push(`<${kind.tag}${styleAttr}>${trimSpaces(renderRuns(bold, kind.options))}</${kind.tag}>`);
|
|
2112
|
+
continue;
|
|
970
2113
|
}
|
|
971
2114
|
rendered.push(`<p${styleAttr}>${trimmed}</p>`);
|
|
972
2115
|
}
|
|
973
2116
|
const output = rendered.join('\n');
|
|
974
|
-
// fontTable is parsed (for future font rendering) but not yet used in output
|
|
975
|
-
void fontTable;
|
|
976
2117
|
return output || '<p></p>';
|
|
977
2118
|
}
|
|
978
|
-
function stripSizeSpan(html) {
|
|
979
|
-
return html.replace(/^<span style="[^"]*font-size:[^"]*">([\s\S]*)<\/span>$/, '$1');
|
|
980
|
-
}
|
|
981
2119
|
/** Captions are written as italic text; <figcaption> supplies its own styling. */
|
|
982
2120
|
function stripWrappingEm(html) {
|
|
983
|
-
|
|
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;
|
|
984
2126
|
}
|
|
985
2127
|
export function readRtfFile(file, options = {}) {
|
|
986
2128
|
return new Promise((resolve, reject) => {
|
|
2129
|
+
const maxBytes = options.maxBytes ?? DEFAULT_MAX_RTF_BYTES;
|
|
2130
|
+
// Refused before it is read: reading is what takes the memory.
|
|
2131
|
+
if (maxBytes > 0 && file.size > maxBytes) {
|
|
2132
|
+
reject(new Error(`This file is too large to import: ${overLimit(file.size, maxBytes)}`));
|
|
2133
|
+
return;
|
|
2134
|
+
}
|
|
987
2135
|
const reader = new FileReader();
|
|
988
2136
|
reader.onload = () => {
|
|
989
2137
|
try {
|