@richscripts/richtexteditor 2.6.0 → 2.6.2

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.
@@ -23370,1269 +23370,1285 @@ function RTE_Plugin_Dictation() {
23370
23370
  }
23371
23371
  }
23372
23372
 
23373
- if (!window.RTE_DefaultConfig) window.RTE_DefaultConfig = {};
23374
-
23375
- // 2026-06-09 Document import — the natural pair to Export-to-Word/Markdown/PDF.
23376
- // Opens a local file and loads it into the editor. Library-free for the common
23377
- // formats: Markdown (.md/.markdown via the core fromMarkdown engine), HTML
23378
- // (.html/.htm), plain text (.txt), and Word's HTML-based format (.doc, which
23379
- // Word saves as MSO-flavored HTML) — Word junk (mso-* styles, o:/w: tags,
23380
- // conditional comments) is stripped the same way paste-from-Word is.
23381
- //
23382
- // .docx IS parsed library-free: it is a ZIP of XML, and the ZIP central
23383
- // directory is read directly while DecompressionStream("deflate-raw") handles
23384
- // the inflate. No dependency, no server round-trip.
23385
- // (This comment used to say .docx was not parseable library-free. That was true
23386
- // when it was written and stopped being true when the ZIP reader landed below;
23387
- // it then misled a reader into reporting the feature as missing. Kept explicit
23388
- // so it does not happen again.)
23389
- //
23390
- // 2026-07-28 fidelity pass — what a naive converter silently loses, and what
23391
- // this now preserves:
23392
- // - HYPERLINK URLS. w:hyperlink carries only an r:id; the address lives in
23393
- // word/_rels/document.xml.rels. Without resolving it every link imports as
23394
- // plain text with the URL discarded.
23395
- // - IMAGES. w:drawing -> a:blip r:embed -> word/media/*, inlined as data URIs
23396
- // (set config.documentImportImages = false to skip, for image-heavy files).
23397
- // - ORDERED vs BULLET lists and NESTING. document.xml stores every list the
23398
- // same way; only word/numbering.xml says which is which, so a naive reader
23399
- // turns numbered lists into bullets. w:ilvl gives real nesting, placed
23400
- // inside the parent <li> so the markup is valid.
23401
- // - Paragraph alignment (w:jc).
23402
- // Supply config.documentImportResolver(file) to override any type (e.g. to run
23403
- // a server-side converter for formats this does not cover).
23404
- //
23405
- // API:
23406
- // editor.openImportDialog(options?) -> file picker, then import
23407
- // editor.importFile(file, options?) -> import a File object (Promise)
23408
- // editor.htmlFromImportText(text, kind) -> convert text to HTML (kind: md|html|txt|doc)
23409
- // Command: exec_command "importdocument" opens the picker. Slash: "/import".
23410
- // Config:
23411
- // config.documentImport = false // disable
23412
- // config.documentImportMode = "replace" | "insert" // default "replace"
23413
- // config.documentImportAccept = ".md,.markdown,.html,.htm,.txt,.doc,.docx"
23414
- // config.documentImportResolver = function(file){ return htmlOrPromise; }
23415
- RTE_DefaultConfig.plugin_documentimport = RTE_Plugin_DocumentImport;
23416
- if (typeof RTE_DefaultConfig.documentImport === "undefined") RTE_DefaultConfig.documentImport = true;
23417
-
23418
- function RTE_Plugin_DocumentImport() {
23419
- var obj = this;
23420
- var config, editor;
23421
-
23422
- obj.PluginName = "DocumentImport";
23423
-
23424
- obj.InitConfig = function (argconfig) { config = argconfig; };
23425
-
23426
- obj.InitEditor = function (argeditor) {
23427
- editor = argeditor;
23428
- if (config.documentImport === false) return;
23429
-
23430
- editor.htmlFromImportText = function (text, kind) { return toHtml(String(text == null ? "" : text), kind); };
23431
- editor.importFile = function (file, options) { return importFile(file, options || {}); };
23432
- editor.openImportDialog = function (options) { return openPicker(options || {}); };
23433
-
23434
- editor.attachEvent("exec_command_importdocument", function (state) {
23435
- state.returnValue = true;
23436
- state.stopBubble = true;
23437
- openPicker({});
23438
- });
23439
-
23440
- if (editor.slashCommands && typeof editor.slashCommands.register === "function") {
23441
- try {
23442
- editor.slashCommands.register({
23443
- id: "import-document",
23444
- title: "Import document",
23445
- description: "Open a Markdown, HTML, text, or Word (.doc) file into the editor",
23446
- keywords: ["import", "open", "file", "word", "markdown", "upload"],
23447
- action: function () { openPicker({}); }
23448
- });
23449
- } catch (e) {}
23450
- }
23451
- };
23452
-
23453
- function kindFromName(name) {
23454
- var n = String(name || "").toLowerCase();
23455
- if (/\.(md|markdown|mdown|mkd)$/.test(n)) return "md";
23456
- if (/\.html?$/.test(n)) return "html";
23457
- if (/\.doc$/.test(n)) return "doc";
23458
- if (/\.docx$/.test(n)) return "docx";
23459
- if (/\.txt$/.test(n)) return "txt";
23460
- return "txt";
23461
- }
23462
-
23463
- function esc(s) {
23464
- return String(s == null ? "" : s).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
23465
- }
23466
-
23467
- // A Word text box and a SmartArt graphic are BOXES on the page. Importing
23468
- // them as bare <div>s keeps the words but loses the thing that made them
23469
- // read as separate from the body text, so the import looks lossier than it
23470
- // is. Styled inline rather than by class because this is saved content: it
23471
- // has to survive wherever the host renders it, with no stylesheet of ours
23472
- // loaded. (Found by check-css-contract.mjs -- the classes were emitted with
23473
- // no rule anywhere.)
23474
- var TEXTBOX_STYLE = "border:1px solid #b9c2cf;border-radius:4px;padding:10px 14px;margin:12px 0;background:#fbfcfe";
23475
- var SMARTART_STYLE = "border:1px solid #b9c2cf;border-radius:4px;padding:10px 14px 10px 6px;margin:12px 0;background:#f7faff";
23476
-
23477
- // Strip Word/MSO debris from .doc HTML (same intent as paste-from-Word).
23478
- function cleanWordHtml(html) {
23479
- var h = String(html || "");
23480
- // body only, drop head/xml/style islands and conditional comments
23481
- var bodyMatch = /<body[^>]*>([\s\S]*?)<\/body>/i.exec(h);
23482
- if (bodyMatch) h = bodyMatch[1];
23483
- h = h.replace(/<!--\[if[\s\S]*?\[endif\]-->/gi, "");
23484
- h = h.replace(/<!--[\s\S]*?-->/g, "");
23485
- h = h.replace(/<\/?(o:p|o:|w:|xml|style|meta|link|title|head)[^>]*>/gi, "");
23486
- h = h.replace(/<\\?\?xml[^>]*>/gi, "");
23487
- // strip mso-* declarations + empty style/class/lang attrs
23488
- h = h.replace(/\sstyle="[^"]*"/gi, function (m) {
23489
- var cleaned = m.replace(/mso-[^;"]*;?/gi, "").replace(/style="\s*;*\s*"/i, "");
23490
- return /style="\s*"/.test(cleaned) || cleaned === ' style=""' ? "" : cleaned;
23491
- });
23492
- h = h.replace(/\sclass="Mso[^"]*"/gi, "");
23493
- h = h.replace(/\s(lang|xmlns(:\w+)?)="[^"]*"/gi, "");
23494
- return h;
23495
- }
23496
-
23497
- function toHtml(text, kind) {
23498
- switch (kind) {
23499
- case "md":
23500
- if (editor && typeof editor.fromMarkdown === "function") return editor.fromMarkdown(text, { apply: false });
23501
- return "<p>" + esc(text).replace(/\n{2,}/g, "</p><p>").replace(/\n/g, "<br>") + "</p>";
23502
- case "html":
23503
- return text;
23504
- case "doc":
23505
- return cleanWordHtml(text);
23506
- case "txt":
23507
- default:
23508
- var paras = String(text).replace(/\r\n?/g, "\n").split(/\n{2,}/);
23509
- return paras.map(function (p) {
23510
- return "<p>" + esc(p).replace(/\n/g, "<br>") + "</p>";
23511
- }).join("");
23512
- }
23513
- }
23514
-
23515
- function applyHtml(html, mode) {
23516
- if (html == null) return false;
23517
- if (mode === "insert") {
23518
- if (typeof editor.insertHTML === "function") { editor.insertHTML(html); return true; }
23519
- }
23520
- if (typeof editor.setHTMLCode === "function") { editor.setHTMLCode(html); return true; }
23521
- return false;
23522
- }
23523
-
23524
- function importFile(file, options) {
23525
- var mode = options.mode || config.documentImportMode || "replace";
23526
- return new Promise(function (resolve) {
23527
- if (!file) { resolve(false); return; }
23528
- var kind = kindFromName(file.name);
23529
-
23530
- // BYOK resolver wins for any type (lets a host handle .docx etc.).
23531
- if (typeof config.documentImportResolver === "function") {
23532
- try {
23533
- var r = config.documentImportResolver(file);
23534
- Promise.resolve(r).then(function (html) {
23535
- if (typeof html === "string") { resolve(applyHtml(html, mode)); }
23536
- else { builtin(); }
23537
- }, function () { builtin(); });
23538
- return;
23539
- } catch (e) { builtin(); return; }
23540
- }
23541
- builtin();
23542
-
23543
- function builtin() {
23544
- if (kind === "docx") {
23545
- // Library-free .docx: unzip word/document.xml (native
23546
- // DecompressionStream) + transform WordprocessingML -> HTML.
23547
- if (!docxSupported()) {
23548
- notify("This browser can't unpack .docx (no DecompressionStream). Save as .doc/.html/.md, or wire config.documentImportResolver.");
23549
- resolve(false);
23550
- return;
23551
- }
23552
- readDocx(file).then(function (html) {
23553
- if (html != null) resolve(applyHtml(html, mode));
23554
- else { notify("Could not read this .docx file."); resolve(false); }
23555
- }, function () { notify("Could not read this .docx file."); resolve(false); });
23556
- return;
23557
- }
23558
- if (typeof FileReader === "undefined") { resolve(false); return; }
23559
- var reader = new FileReader();
23560
- reader.onload = function () {
23561
- var html = toHtml(reader.result, kind);
23562
- resolve(applyHtml(html, mode));
23563
- };
23564
- reader.onerror = function () { resolve(false); };
23565
- reader.readAsText(file);
23566
- }
23567
- });
23568
- }
23569
-
23570
- function openPicker(options) {
23571
- try {
23572
- var input = document.createElement("input");
23573
- input.type = "file";
23574
- input.accept = options.accept || config.documentImportAccept || ".md,.markdown,.html,.htm,.txt,.doc,.docx";
23575
- input.style.position = "fixed";
23576
- input.style.left = "-9999px";
23577
- input.addEventListener("change", function () {
23578
- var f = input.files && input.files[0];
23579
- if (f) importFile(f, options);
23580
- setTimeout(function () { try { document.body.removeChild(input); } catch (e) {} }, 0);
23581
- });
23582
- document.body.appendChild(input);
23583
- input.click();
23584
- return true;
23585
- } catch (e) {
23586
- if (window.console) console.error("documentimport: openPicker failed", e);
23587
- return false;
23588
- }
23589
- }
23590
-
23591
- // ---- library-free .docx (ZIP of XML) ----
23592
- function docxSupported() {
23593
- return typeof DecompressionStream === "function" && typeof DOMParser === "function" &&
23594
- (typeof Response === "function" || typeof Blob === "function");
23595
- }
23596
-
23597
- // Locate an entry via the ZIP central directory (reliable comp sizes/offsets).
23598
- function findZipEntry(bytes, wantName) {
23599
- var dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
23600
- // End Of Central Directory: signature 0x06054b50, scan from the end.
23601
- var eocd = -1;
23602
- for (var i = bytes.length - 22; i >= 0 && i >= bytes.length - 22 - 65536; i--) {
23603
- if (dv.getUint32(i, true) === 0x06054b50) { eocd = i; break; }
23604
- }
23605
- if (eocd < 0) return null;
23606
- var cdOffset = dv.getUint32(eocd + 16, true);
23607
- var cdCount = dv.getUint16(eocd + 10, true);
23608
- var p = cdOffset;
23609
- for (var n = 0; n < cdCount; n++) {
23610
- if (dv.getUint32(p, true) !== 0x02014b50) break;
23611
- var method = dv.getUint16(p + 10, true);
23612
- var compSize = dv.getUint32(p + 20, true);
23613
- var nameLen = dv.getUint16(p + 28, true);
23614
- var extraLen = dv.getUint16(p + 30, true);
23615
- var commentLen = dv.getUint16(p + 32, true);
23616
- var localOff = dv.getUint32(p + 42, true);
23617
- // Normalize separators: the ZIP spec mandates "/", but some Windows
23618
- // tools (.NET ZipFile on older runtimes) emit "\".
23619
- var name = utf8(bytes.subarray(p + 46, p + 46 + nameLen)).replace(/\\/g, "/");
23620
- if (name === wantName) {
23621
- var lh = new DataView(bytes.buffer, bytes.byteOffset + localOff, 30);
23622
- var lNameLen = lh.getUint16(26, true);
23623
- var lExtraLen = lh.getUint16(28, true);
23624
- var dataStart = localOff + 30 + lNameLen + lExtraLen;
23625
- return { method: method, data: bytes.subarray(dataStart, dataStart + compSize) };
23626
- }
23627
- p += 46 + nameLen + extraLen + commentLen;
23628
- }
23629
- return null;
23630
- }
23631
-
23632
- function utf8(u8) {
23633
- try { return new TextDecoder("utf-8").decode(u8); } catch (e) {
23634
- var s = ""; for (var i = 0; i < u8.length; i++) s += String.fromCharCode(u8[i]); return s;
23635
- }
23636
- }
23637
-
23638
- function inflateRaw(u8) {
23639
- // method 0 = stored, 8 = deflate (raw).
23640
- var ds = new DecompressionStream("deflate-raw");
23641
- var blob = new Blob([u8]);
23642
- return new Response(blob.stream().pipeThrough(ds)).arrayBuffer().then(function (ab) {
23643
- return new Uint8Array(ab);
23644
- });
23645
- }
23646
-
23647
- // Every entry whose name matches, decompressed. Needed because a faithful
23648
- // conversion is not just document.xml: the hyperlink URLs live in the rels
23649
- // part, whether a list is bulleted or numbered lives in numbering.xml, and
23650
- // the images live in word/media.
23651
- function listZipEntries(bytes) {
23652
- var dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
23653
- var eocd = -1;
23654
- for (var i = bytes.length - 22; i >= 0 && i >= bytes.length - 22 - 65536; i--) {
23655
- if (dv.getUint32(i, true) === 0x06054b50) { eocd = i; break; }
23656
- }
23657
- if (eocd < 0) return [];
23658
- var cdOffset = dv.getUint32(eocd + 16, true);
23659
- var cdCount = dv.getUint16(eocd + 10, true);
23660
- var p = cdOffset, out = [];
23661
- for (var n = 0; n < cdCount; n++) {
23662
- if (dv.getUint32(p, true) !== 0x02014b50) break;
23663
- var method = dv.getUint16(p + 10, true);
23664
- var compSize = dv.getUint32(p + 20, true);
23665
- var nameLen = dv.getUint16(p + 28, true);
23666
- var extraLen = dv.getUint16(p + 30, true);
23667
- var commentLen = dv.getUint16(p + 32, true);
23668
- var localOff = dv.getUint32(p + 42, true);
23669
- var name = utf8(bytes.subarray(p + 46, p + 46 + nameLen)).replace(/\\/g, "/");
23670
- var lh = new DataView(bytes.buffer, bytes.byteOffset + localOff, 30);
23671
- var dataStart = localOff + 30 + lh.getUint16(26, true) + lh.getUint16(28, true);
23672
- out.push({ name: name, method: method, data: bytes.subarray(dataStart, dataStart + compSize) });
23673
- p += 46 + nameLen + extraLen + commentLen;
23674
- }
23675
- return out;
23676
- }
23677
-
23678
- function entryBytes(entry) {
23679
- return entry.method === 0 ? Promise.resolve(entry.data) : inflateRaw(entry.data);
23680
- }
23681
-
23682
- function mimeForExt(name) {
23683
- var e = (name.split(".").pop() || "").toLowerCase();
23684
- if (e === "png") return "image/png";
23685
- if (e === "jpg" || e === "jpeg") return "image/jpeg";
23686
- if (e === "gif") return "image/gif";
23687
- if (e === "bmp") return "image/bmp";
23688
- if (e === "webp") return "image/webp";
23689
- if (e === "svg") return "image/svg+xml";
23690
- return null; // wmf/emf and friends have no browser-renderable form
23691
- }
23692
-
23693
- function bytesToDataUri(u8, mime) {
23694
- var CHUNK = 0x8000, s = "";
23695
- for (var i = 0; i < u8.length; i += CHUNK) {
23696
- s += String.fromCharCode.apply(null, u8.subarray(i, i + CHUNK));
23697
- }
23698
- return "data:" + mime + ";base64," + btoa(s);
23699
- }
23700
-
23701
- function readDocx(file) {
23702
- var bufPromise = file.arrayBuffer ? file.arrayBuffer() : new Promise(function (res, rej) {
23703
- var r = new FileReader(); r.onload = function () { res(r.result); }; r.onerror = rej; r.readAsArrayBuffer(file);
23704
- });
23705
- return bufPromise.then(function (ab) {
23706
- var bytes = new Uint8Array(ab);
23707
- var entries = listZipEntries(bytes);
23708
- var byName = {};
23709
- for (var i = 0; i < entries.length; i++) byName[entries[i].name] = entries[i];
23710
- if (!byName["word/document.xml"]) return null;
23711
-
23712
- var ctx = { rels: {}, numbering: {}, media: {}, footnotes: {}, endnotes: {}, comments: {}, diagrams: {}, vectorNames: {} };
23713
-
23714
- // Images are opt-in: a document full of photographs would otherwise
23715
- // inline megabytes of base64 into the editor.
23716
- var wantMedia = config.documentImportImages !== false;
23717
-
23718
- var jobs = [entryBytes(byName["word/document.xml"]).then(function (b) { ctx.documentXml = utf8(b); })];
23719
-
23720
- if (byName["word/_rels/document.xml.rels"]) {
23721
- jobs.push(entryBytes(byName["word/_rels/document.xml.rels"]).then(function (b) {
23722
- ctx.rels = parseRels(utf8(b));
23723
- }));
23724
- }
23725
- if (byName["word/numbering.xml"]) {
23726
- jobs.push(entryBytes(byName["word/numbering.xml"]).then(function (b) {
23727
- ctx.numbering = parseNumbering(utf8(b));
23728
- }));
23729
- }
23730
- // Footnotes live in their OWN part; document.xml only carries
23731
- // w:footnoteReference with an id. Skip this and a footnoted contract
23732
- // imports with every citation silently deleted.
23733
- if (byName["word/footnotes.xml"]) {
23734
- jobs.push(entryBytes(byName["word/footnotes.xml"]).then(function (b) {
23735
- ctx.footnotes = parseFootnotes(utf8(b), "footnote");
23736
- }));
23737
- }
23738
- // Comment bodies live in their own part too, keyed by id; the
23739
- // document only marks the commented RANGE.
23740
- // Endnotes are structurally identical to footnotes, in their own part.
23741
- if (byName["word/endnotes.xml"]) {
23742
- jobs.push(entryBytes(byName["word/endnotes.xml"]).then(function (b) {
23743
- ctx.endnotes = parseFootnotes(utf8(b), "endnote");
23744
- }));
23745
- }
23746
- if (byName["word/comments.xml"]) {
23747
- jobs.push(entryBytes(byName["word/comments.xml"]).then(function (b) {
23748
- ctx.comments = parseComments(utf8(b));
23749
- }));
23750
- }
23751
- // SmartArt. The drawing in document.xml holds only relationship ids;
23752
- // every word of the diagram lives in word/diagrams/dataN.xml, in the
23753
- // DrawingML *diagram* namespace. A reader that looks for a:blip finds
23754
- // nothing and drops the whole graphic, so an org chart or a process
23755
- // flow imports as empty space.
23756
- for (var dg = 0; dg < entries.length; dg++) {
23757
- (function (ent) {
23758
- if (!/^word\/diagrams\/data\d*\.xml$/.test(ent.name)) return;
23759
- jobs.push(entryBytes(ent).then(function (b) {
23760
- try { ctx.diagrams[ent.name] = parseDiagram(utf8(b)); } catch (e) {}
23761
- }));
23762
- })(entries[dg]);
23763
- }
23764
- if (wantMedia) {
23765
- for (var n = 0; n < entries.length; n++) {
23766
- (function (ent) {
23767
- if (ent.name.indexOf("word/media/") !== 0) return;
23768
- var mime = mimeForExt(ent.name);
23769
- if (!mime) return;
23770
- jobs.push(entryBytes(ent).then(function (b) {
23771
- try { ctx.media[ent.name] = bytesToDataUri(b, mime); } catch (e) {}
23772
- }));
23773
- })(entries[n]);
23774
- }
23775
- }
23776
-
23777
- return Promise.all(jobs).then(function () { return docxXmlToHtml(ctx.documentXml, ctx); });
23778
- });
23779
- }
23780
-
23781
- // r:id -> target. Without this, every hyperlink in the document survives as
23782
- // plain text with its URL silently discarded.
23783
- function parseRels(xml) {
23784
- var map = {};
23785
- try {
23786
- var d = new DOMParser().parseFromString(xml, "application/xml");
23787
- var rs = d.getElementsByTagName("*");
23788
- for (var i = 0; i < rs.length; i++) {
23789
- if (rs[i].localName !== "Relationship") continue;
23790
- var id = rs[i].getAttribute("Id");
23791
- var target = rs[i].getAttribute("Target");
23792
- var mode = rs[i].getAttribute("TargetMode");
23793
- if (id && target) map[id] = { target: target, external: mode === "External" };
23794
- }
23795
- } catch (e) {}
23796
- return map;
23797
- }
23798
-
23799
- // w:id -> plain text of the footnote body.
23800
- // Word reserves ids 0 and -1 for the separator rules drawn above footnotes;
23801
- // those carry type="separator"/"continuationSeparator" and are not content.
23802
- // tagName is "footnote" or "endnote": the two parts share a schema but NOT
23803
- // an element name, so parsing endnotes.xml with "footnote" silently returns
23804
- // nothing at all.
23805
- function parseFootnotes(xml, tagName) {
23806
- var out = {};
23807
- try {
23808
- var W = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
23809
- var d = new DOMParser().parseFromString(xml, "application/xml");
23810
- var notes = d.getElementsByTagNameNS(W, tagName || "footnote");
23811
- for (var i = 0; i < notes.length; i++) {
23812
- var n = notes[i];
23813
- var type = n.getAttributeNS(W, "type") || n.getAttribute("w:type") || "";
23814
- if (type) continue; // separator, not a real note
23815
- var id = n.getAttributeNS(W, "id") || n.getAttribute("w:id");
23816
- if (id == null) continue;
23817
- // Body text only; the leading footnote-reference mark inside the
23818
- // note is Word's own numbering and would duplicate ours.
23819
- var txt = (n.textContent || "").replace(/\s+/g, " ").trim();
23820
- if (txt) out[String(id)] = txt;
23821
- }
23822
- } catch (e) {}
23823
- return out;
23824
- }
23825
-
23826
- // w:id -> { text, author }
23827
- function parseComments(xml) {
23828
- var out = {};
23829
- try {
23830
- var W = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
23831
- var d = new DOMParser().parseFromString(xml, "application/xml");
23832
- var cs = d.getElementsByTagNameNS(W, "comment");
23833
- for (var i = 0; i < cs.length; i++) {
23834
- var c = cs[i];
23835
- var id = c.getAttributeNS(W, "id") || c.getAttribute("w:id");
23836
- if (id == null) continue;
23837
- out[String(id)] = {
23838
- text: (c.textContent || "").replace(/\s+/g, " ").trim(),
23839
- author: c.getAttributeNS(W, "author") || c.getAttribute("w:author") || ""
23840
- };
23841
- }
23842
- } catch (e) {}
23843
- return out;
23844
- }
23845
-
23846
- // word/diagrams/dataN.xml -> the diagram's text, one entry per node, in
23847
- // document order.
23848
- //
23849
- // SmartArt has no browser equivalent -- it is a laid-out graphic driven by a
23850
- // layout algorithm -- but its CONTENT is ordinary text, and text is what the
23851
- // reader actually needs. An org chart that imports as an outline is usable; an
23852
- // org chart that imports as nothing is a hole in the document.
23853
- //
23854
- // Nodes with presentation-only roles (`dgm:prSet` with no text, and the
23855
- // ptType "pres"/"parTrans"/"sibTrans" connector points) carry no content and
23856
- // would otherwise contribute blank list items.
23857
- function parseDiagram(xml) {
23858
- var out = [];
23859
- try {
23860
- var DGM = "http://schemas.openxmlformats.org/drawingml/2006/diagram";
23861
- var d = new DOMParser().parseFromString(xml, "application/xml");
23862
- var pts = d.getElementsByTagNameNS(DGM, "pt");
23863
- for (var i = 0; i < pts.length; i++) {
23864
- var type = pts[i].getAttribute("type") || "";
23865
- if (type === "pres" || type === "parTrans" || type === "sibTrans") continue;
23866
- var t = pts[i].getElementsByTagNameNS(DGM, "t")[0];
23867
- if (!t) continue;
23868
- var text = (t.textContent || "").replace(/\s+/g, " ").trim();
23869
- if (text) out.push(text);
23870
- }
23871
- } catch (e) {}
23872
- return out;
23873
- }
23874
-
23875
- // numId -> { level -> "bullet" | "decimal" | ... }. Word stores every list
23876
- // the same way in document.xml; only numbering.xml says whether it renders
23877
- // as bullets or numbers, which is why a naive converter turns every ordered
23878
- // list into a <ul>.
23879
- function parseNumbering(xml) {
23880
- var out = {};
23881
- try {
23882
- var W = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
23883
- var d = new DOMParser().parseFromString(xml, "application/xml");
23884
- function val(el) { return el ? (el.getAttributeNS(W, "val") || el.getAttribute("w:val") || "") : ""; }
23885
-
23886
- // abstractNumId -> { ilvl -> numFmt }
23887
- var abstracts = {};
23888
- var aNums = d.getElementsByTagNameNS(W, "abstractNum");
23889
- for (var i = 0; i < aNums.length; i++) {
23890
- var aid = aNums[i].getAttributeNS(W, "abstractNumId") || aNums[i].getAttribute("w:abstractNumId");
23891
- var levels = {};
23892
- var lvls = aNums[i].getElementsByTagNameNS(W, "lvl");
23893
- for (var j = 0; j < lvls.length; j++) {
23894
- var ilvl = lvls[j].getAttributeNS(W, "ilvl") || lvls[j].getAttribute("w:ilvl") || "0";
23895
- var fmt = val(lvls[j].getElementsByTagNameNS(W, "numFmt")[0]);
23896
- levels[ilvl] = fmt || "decimal";
23897
- }
23898
- if (aid != null) abstracts[aid] = levels;
23899
- }
23900
- // num -> abstractNumId
23901
- var nums = d.getElementsByTagNameNS(W, "num");
23902
- for (var k = 0; k < nums.length; k++) {
23903
- var nid = nums[k].getAttributeNS(W, "numId") || nums[k].getAttribute("w:numId");
23904
- var ref = nums[k].getElementsByTagNameNS(W, "abstractNumId")[0];
23905
- var aref = val(ref);
23906
- if (nid != null && abstracts[aref]) out[nid] = abstracts[aref];
23907
- }
23908
- } catch (e) {}
23909
- return out;
23910
- }
23911
-
23912
- // ---------------------------------------------------------------------
23913
- // OMML (Office Math Markup) -> LaTeX.
23914
- //
23915
- // Word does not store equations as text, MathML or an image: it stores an
23916
- // <m:oMath> tree in its OWN namespace, interleaved between the runs of a
23917
- // paragraph. A converter that walks w:r elements never sees it, so every
23918
- // equation in the document disappears without a trace -- and because the
23919
- // surrounding sentence still imports, nothing looks broken.
23920
- //
23921
- // The target is the editor's own inline-math format
23922
- // (<span class="rte-math-inline" data-tex="...">), so imported equations
23923
- // are editable and re-render through whichever renderer the host page
23924
- // loads, exactly like one typed in the math dialog.
23925
- //
23926
- // This covers the constructs Word's equation editor actually produces.
23927
- // Anything unrecognised degrades to its literal text rather than vanishing
23928
- // -- a wrong-looking formula is recoverable, a missing one is not.
23929
- var OMML_NS = "http://schemas.openxmlformats.org/officeDocument/2006/math";
23930
-
23931
- // Word writes operators as Unicode, but a TeX renderer wants command names.
23932
- // Passing "∑" through untouched produces a glyph that KaTeX cannot size or
23933
- // place limits on.
23934
- var MATH_SYMBOLS = {
23935
- "∑": "\\sum", "∏": "\\prod", "∐": "\\coprod",
23936
- "∫": "\\int", "∬": "\\iint", "∭": "\\iiint", "∮": "\\oint",
23937
- "⋃": "\\bigcup", "⋂": "\\bigcap",
23938
- "±": "\\pm", "∓": "\\mp", "×": "\\times", "÷": "\\div",
23939
- "−": "-", "≠": "\\neq", "≤": "\\leq", "≥": "\\geq",
23940
- "≈": "\\approx", "≡": "\\equiv", "∝": "\\propto",
23941
- "∞": "\\infty", "∂": "\\partial", "∇": "\\nabla",
23942
- "√": "\\sqrt", "∠": "\\angle", "⋅": "\\cdot", "…": "\\dots",
23943
- "→": "\\to", "←": "\\leftarrow", "⇒": "\\Rightarrow", "⇔": "\\Leftrightarrow",
23944
- "∈": "\\in", "∉": "\\notin", "⊂": "\\subset", "⊆": "\\subseteq",
23945
- "∪": "\\cup", "∩": "\\cap", "∅": "\\emptyset",
23946
- "∀": "\\forall", "∃": "\\exists", "¬": "\\neg",
23947
- "∧": "\\land", "∨": "\\lor", "∴": "\\therefore",
23948
- "α": "\\alpha", "β": "\\beta", "γ": "\\gamma", "δ": "\\delta",
23949
- "ε": "\\epsilon", "ζ": "\\zeta", "η": "\\eta", "θ": "\\theta",
23950
- "ι": "\\iota", "κ": "\\kappa", "λ": "\\lambda", "μ": "\\mu",
23951
- "ν": "\\nu", "ξ": "\\xi", "π": "\\pi", "ρ": "\\rho",
23952
- "σ": "\\sigma", "τ": "\\tau", "υ": "\\upsilon", "φ": "\\varphi",
23953
- "χ": "\\chi", "ψ": "\\psi", "ω": "\\omega",
23954
- "Γ": "\\Gamma", "Δ": "\\Delta", "Θ": "\\Theta", "Λ": "\\Lambda",
23955
- "Ξ": "\\Xi", "Π": "\\Pi", "Σ": "\\Sigma", "Φ": "\\Phi",
23956
- "Ψ": "\\Psi", "Ω": "\\Omega"
23957
- };
23958
- // Accent character -> TeX accent command (m:acc carries the mark as a chr).
23959
- var MATH_ACCENTS = {
23960
- "̂": "\\hat", "̃": "\\tilde", "̄": "\\bar", "̅": "\\overline",
23961
- "̆": "\\breve", "̇": "\\dot", "̈": "\\ddot", "̊": "\\mathring",
23962
- "̌": "\\check", "→": "\\vec", "⃗": "\\vec", "́": "\\acute", "̀": "\\grave"
23963
- };
23964
-
23965
- function ommlToTex(node) {
23966
- var M = OMML_NS;
23967
- function attrVal(parent, ln) {
23968
- // Properties sit in a child element whose only content is m:val.
23969
- for (var i = 0; i < parent.childNodes.length; i++) {
23970
- var c = parent.childNodes[i];
23971
- if (c.nodeType === 1 && c.localName === ln) {
23972
- return c.getAttributeNS(M, "val") || c.getAttribute("m:val") || "";
23973
- }
23974
- }
23975
- return "";
23976
- }
23977
- function propOf(el, propName, ln) {
23978
- var p = child(el, propName);
23979
- return p ? attrVal(p, ln) : "";
23980
- }
23981
- function child(el, ln) {
23982
- for (var i = 0; i < el.childNodes.length; i++) {
23983
- var c = el.childNodes[i];
23984
- if (c.nodeType === 1 && c.localName === ln && c.namespaceURI === M) return c;
23985
- }
23986
- return null;
23987
- }
23988
- function children(el, ln) {
23989
- var out = [];
23990
- for (var i = 0; i < el.childNodes.length; i++) {
23991
- var c = el.childNodes[i];
23992
- if (c.nodeType === 1 && c.localName === ln && c.namespaceURI === M) out.push(c);
23993
- }
23994
- return out;
23995
- }
23996
- // An argument slot: braces so multi-character content binds correctly.
23997
- // "x+1" without them turns \frac{x+1}{2} into \fracx+12.
23998
- function arg(el) {
23999
- return "{" + (el ? walk(el).trim() : "") + "}";
24000
- }
24001
- // A slot where braces are optional. Emitting them unconditionally is
24002
- // correct but produces "{x}^{2}" and "{{i}^{2}}" -- valid TeX that is
24003
- // unreadable the moment the user opens the equation in the math dialog.
24004
- // A lone letter, digit or command needs none.
24005
- function atom(el) {
24006
- var t = el ? walk(el).trim() : "";
24007
- if (/^[A-Za-z0-9]$/.test(t) || /^\\[A-Za-z]+$/.test(t)) return t;
24008
- return "{" + t + "}";
24009
- }
24010
- function mapText(s) {
24011
- var out = "";
24012
- for (var i = 0; i < s.length; i++) {
24013
- var ch = s.charAt(i);
24014
- var sym = MATH_SYMBOLS[ch];
24015
- if (sym) { out += sym + " "; continue; }
24016
- // TeX metacharacters inside literal math text.
24017
- if ("#$%&_{}".indexOf(ch) >= 0) { out += "\\" + ch; continue; }
24018
- if (ch === "\\") { out += "\\backslash "; continue; }
24019
- out += ch;
24020
- }
24021
- return out;
24022
- }
24023
- function walk(el) {
24024
- var tex = "";
24025
- for (var i = 0; i < el.childNodes.length; i++) {
24026
- var c = el.childNodes[i];
24027
- if (c.nodeType !== 1) continue;
24028
- if (c.namespaceURI !== M) { tex += mapText(c.textContent || ""); continue; }
24029
- tex += convert(c);
24030
- }
24031
- return tex;
24032
- }
24033
- function convert(el) {
24034
- var ln = el.localName;
24035
- switch (ln) {
24036
- case "oMath":
24037
- case "oMathPara":
24038
- case "e":
24039
- case "num":
24040
- case "den":
24041
- case "sub":
24042
- case "sup":
24043
- case "deg":
24044
- case "lim":
24045
- case "fName":
24046
- return walk(el);
24047
- // Properties describe how to render, not what to render; emitting
24048
- // their text would leak stray characters into the formula.
24049
- case "rPr": case "ctrlPr": case "fPr": case "radPr": case "naryPr":
24050
- case "dPr": case "sSupPr": case "sSubPr": case "sSubSupPr": case "accPr":
24051
- case "barPr": case "funcPr": case "mPr": case "limLowPr": case "limUppPr":
24052
- case "groupChrPr": case "mcPr": case "eqArrPr": case "boxPr": case "borderBoxPr":
24053
- case "phantPr": case "sPrePr":
24054
- return "";
24055
- case "r":
24056
- return mapText(el.textContent || "");
24057
- case "t":
24058
- return mapText(el.textContent || "");
24059
- case "f": {
24060
- // A "no bar" fraction is Word's binomial/stacked form.
24061
- var type = propOf(el, "fPr", "type");
24062
- var n = arg(child(el, "num")), d = arg(child(el, "den"));
24063
- if (type === "noBar") return "\\binom" + n + d;
24064
- if (type === "skw" || type === "lin") return n + "/" + d;
24065
- return "\\frac" + n + d;
24066
- }
24067
- case "sSup": return atom(child(el, "e")) + "^" + arg(child(el, "sup"));
24068
- case "sSub": return atom(child(el, "e")) + "_" + arg(child(el, "sub"));
24069
- case "sSubSup": return atom(child(el, "e")) + "_" + arg(child(el, "sub")) + "^" + arg(child(el, "sup"));
24070
- case "sPre": return "{}_" + arg(child(el, "sub")) + "^" + arg(child(el, "sup")) + arg(child(el, "e"));
24071
- case "rad": {
24072
- // degHide means a plain square root; otherwise it is \sqrt[n]{}.
24073
- var hide = propOf(el, "radPr", "degHide");
24074
- var deg = child(el, "deg");
24075
- var body = arg(child(el, "e"));
24076
- if (hide === "1" || hide === "on" || hide === "true" || !deg || !(deg.textContent || "").trim()) return "\\sqrt" + body;
24077
- return "\\sqrt[" + walk(deg) + "]" + body;
24078
- }
24079
- case "nary": {
24080
- // The operator itself is an ATTRIBUTE (m:chr), not text. Miss
24081
- // it and every summation imports as a bare limit pair.
24082
- var chr = propOf(el, "naryPr", "chr") || "∫";
24083
- var op = MATH_SYMBOLS[chr] || mapText(chr);
24084
- var subHide = propOf(el, "naryPr", "subHide");
24085
- var supHide = propOf(el, "naryPr", "supHide");
24086
- var s = op;
24087
- if (subHide !== "1" && subHide !== "on" && child(el, "sub")) s += "_" + arg(child(el, "sub"));
24088
- if (supHide !== "1" && supHide !== "on" && child(el, "sup")) s += "^" + arg(child(el, "sup"));
24089
- // The integrand takes no braces: \sum_{i=1}^{n} i^{2}, not
24090
- // \sum_{i=1}^{n} {i^{2}}.
24091
- var nbody = child(el, "e");
24092
- return s + " " + (nbody ? walk(nbody).trim() : "");
24093
- }
24094
- case "d": {
24095
- // \left/\right so the fences grow with their content.
24096
- var beg = propOf(el, "dPr", "begChr");
24097
- var end = propOf(el, "dPr", "endChr");
24098
- var sep = propOf(el, "dPr", "sepChr") || "|";
24099
- if (beg === "") beg = "(";
24100
- if (end === "") end = ")";
24101
- function fence(ch, side) {
24102
- if (!ch) return side === "l" ? "\\left." : "\\right.";
24103
- if (ch === "{" || ch === "}") return "\\" + ch;
24104
- if (ch === "|") return "|";
24105
- if (ch === "‖") return "\\|";
24106
- // THREE different codepoints render as an angle
24107
- // bracket and are indistinguishable on screen: the
24108
- // mathematical pair (U+27E8/9), the CJK pair
24109
- // (U+3008/9) and the deprecated pair (U+2329/A) that
24110
- // several generators still emit. Comparing against a
24111
- // literal in the source would silently match only one
24112
- // of them, so compare by codepoint.
24113
- var cp = ch.charCodeAt(0);
24114
- if (cp === 0x27E8 || cp === 0x3008 || cp === 0x2329) return "\\langle";
24115
- if (cp === 0x27E9 || cp === 0x3009 || cp === 0x232A) return "\\rangle";
24116
- if (ch === "⌊") return "\\lfloor";
24117
- if (ch === "⌋") return "\\rfloor";
24118
- if (ch === "⌈") return "\\lceil";
24119
- if (ch === "⌉") return "\\rceil";
24120
- return ch;
24121
- }
24122
- var parts = children(el, "e");
24123
- var inner = [];
24124
- for (var q = 0; q < parts.length; q++) inner.push(walk(parts[q]));
24125
- return "\\left" + fence(beg, "l") + inner.join(" " + fence(sep, "m") + " ") + "\\right" + fence(end, "r");
24126
- }
24127
- case "func": {
24128
- // Word stores "sin"/"log" as ordinary text; without
24129
- // \operatorname TeX renders it as s*i*n in italics.
24130
- var name = walk(child(el, "fName")).trim();
24131
- var known = /^(sin|cos|tan|cot|sec|csc|sinh|cosh|tanh|log|ln|lg|exp|lim|max|min|det|dim|gcd|arg|deg|hom|ker|Pr|sup|inf)$/;
24132
- var head = known.test(name) ? "\\" + name : (name ? "\\operatorname{" + name + "}" : "");
24133
- return head + arg(child(el, "e"));
24134
- }
24135
- case "limLow": {
24136
- var base = walk(child(el, "e")).trim();
24137
- if (base === "lim" || base === "\\lim") return "\\lim_" + arg(child(el, "lim"));
24138
- return "\\underset" + arg(child(el, "lim")) + "{" + base + "}";
24139
- }
24140
- case "limUpp":
24141
- return "\\overset" + arg(child(el, "lim")) + arg(child(el, "e"));
24142
- case "acc": {
24143
- var mark = propOf(el, "accPr", "chr") || "̂";
24144
- var cmd = MATH_ACCENTS[mark] || "\\hat";
24145
- return cmd + arg(child(el, "e"));
24146
- }
24147
- case "bar":
24148
- return (propOf(el, "barPr", "pos") === "bot" ? "\\underline" : "\\overline") + arg(child(el, "e"));
24149
- case "groupChr": {
24150
- var g = propOf(el, "groupChrPr", "chr");
24151
- if (g === "⏟") return "\\underbrace" + arg(child(el, "e"));
24152
- return "\\overbrace" + arg(child(el, "e"));
24153
- }
24154
- case "borderBox":
24155
- return "\\boxed" + arg(child(el, "e"));
24156
- case "box":
24157
- case "phant":
24158
- return walk(el);
24159
- case "m": {
24160
- // Matrix: rows are m:mr, cells are m:e inside them.
24161
- var rows = children(el, "mr"), lines = [];
24162
- for (var r = 0; r < rows.length; r++) {
24163
- var cells = children(rows[r], "e"), cs = [];
24164
- for (var cix = 0; cix < cells.length; cix++) cs.push(walk(cells[cix]));
24165
- lines.push(cs.join(" & "));
24166
- }
24167
- return "\\begin{matrix}" + lines.join(" \\\\ ") + "\\end{matrix}";
24168
- }
24169
- case "eqArr": {
24170
- var eqs = children(el, "e"), rowsOut = [];
24171
- for (var e2 = 0; e2 < eqs.length; e2++) rowsOut.push(walk(eqs[e2]));
24172
- return "\\begin{aligned}" + rowsOut.join(" \\\\ ") + "\\end{aligned}";
24173
- }
24174
- default:
24175
- // Unknown construct: keep the content rather than losing it.
24176
- return walk(el);
24177
- }
24178
- }
24179
- try {
24180
- return convert(node).replace(/\s+/g, " ").trim();
24181
- } catch (e) { return (node.textContent || "").trim(); }
24182
- }
24183
-
24184
- function docxXmlToHtml(xml, ctx) {
24185
- ctx = ctx || { rels: {}, numbering: {}, media: {} };
24186
- if (!ctx.diagrams) ctx.diagrams = {};
24187
- var doc = new DOMParser().parseFromString(xml, "application/xml");
24188
- var W = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
24189
- var R = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
24190
-
24191
- function relTarget(el) {
24192
- if (!el) return null;
24193
- var id = el.getAttributeNS(R, "id") || el.getAttribute("r:id") ||
24194
- el.getAttributeNS(R, "embed") || el.getAttribute("r:embed");
24195
- if (!id) return null;
24196
- return ctx.rels[id] || null;
24197
- }
24198
-
24199
- // <w:drawing>/<w:pict> -> <img> from word/media, inlined as a data URI.
24200
- function imageHtml(node) {
24201
- var blips = node.getElementsByTagName("*");
24202
- for (var i = 0; i < blips.length; i++) {
24203
- if (blips[i].localName !== "blip" && blips[i].localName !== "imagedata") continue;
24204
- var rel = relTarget(blips[i]);
24205
- if (!rel) continue;
24206
- // Targets are relative to word/: "media/image1.png".
24207
- var path = rel.target.replace(/^\.\//, "");
24208
- var key = path.indexOf("word/") === 0 ? path : "word/" + path;
24209
- var uri = ctx.media[key];
24210
- if (uri) return '<img src="' + uri + '" alt="">';
24211
- if (rel.external) return '<img src="' + esc(rel.target) + '" alt="">';
24212
- // A vector metafile (WMF/EMF) has no browser-renderable form, so
24213
- // there is no data URI for it. Dropping it silently leaves the
24214
- // reader with no idea a figure was ever there -- and no filename
24215
- // to go looking for in the original.
24216
- if (/\.(wmf|emf|emz|wmz)$/i.test(path)) {
24217
- var fileName = path.split("/").pop();
24218
- queueBlock('<p class="rte-imported-unsupported" data-source="' + esc(fileName) +
24219
- '"><em>[Unsupported image: ' + esc(fileName) +
24220
- " — Windows metafiles have no browser-renderable form]</em></p>");
24221
- return "";
24222
- }
24223
- }
24224
- queueBlock(diagramHtml(node));
24225
- return "";
24226
- }
24227
-
24228
- // SmartArt: the drawing references word/diagrams/dataN.xml through
24229
- // r:dm. Rendered as a labelled list -- the layout cannot be reproduced,
24230
- // but every word of it survives and stays editable.
24231
- function diagramHtml(node) {
24232
- var all = node.getElementsByTagName("*");
24233
- for (var i = 0; i < all.length; i++) {
24234
- if (all[i].localName !== "relIds") continue;
24235
- var id = all[i].getAttributeNS(R, "dm") || all[i].getAttribute("r:dm");
24236
- var rel = id ? ctx.rels[id] : null;
24237
- if (!rel) continue;
24238
- var path = rel.target.replace(/^\.\//, "");
24239
- var key = path.indexOf("word/") === 0 ? path : "word/" + path;
24240
- var nodes = ctx.diagrams[key];
24241
- if (!nodes || !nodes.length) continue;
24242
- var items = "";
24243
- for (var n = 0; n < nodes.length; n++) items += "<li>" + esc(nodes[n]) + "</li>";
24244
- return '<div class="rte-imported-smartart" style="' + SMARTART_STYLE + '"><ul>' + items + "</ul></div>";
24245
- }
24246
- return "";
24247
- }
24248
- function els(parent, ln) { return parent.getElementsByTagNameNS(W, ln); }
24249
- function firstChildEl(parent, ln) {
24250
- for (var i = 0; i < parent.childNodes.length; i++) {
24251
- var c = parent.childNodes[i];
24252
- if (c.nodeType === 1 && c.localName === ln && c.namespaceURI === W) return c;
24253
- }
24254
- return null;
24255
- }
24256
- function runText(r) {
24257
- var t = "", kids = r.childNodes;
24258
- for (var i = 0; i < kids.length; i++) {
24259
- var c = kids[i];
24260
- if (c.nodeType !== 1) continue;
24261
- // Deleted text is stored as w:delText, never w:t — read only w:t
24262
- // and every tracked deletion imports as an empty run.
24263
- if (c.localName === "t" || c.localName === "delText") t += c.textContent || "";
24264
- else if (c.localName === "tab") t += "\t";
24265
- else if (c.localName === "br" || c.localName === "cr") t += "\n";
24266
- }
24267
- return t;
24268
- }
24269
- function runHtml(r) {
24270
- // A run can carry a picture instead of text; without this every
24271
- // image in the document is silently dropped on import.
24272
- var pics = "";
24273
- for (var d = 0; d < r.childNodes.length; d++) {
24274
- var ch = r.childNodes[d];
24275
- if (ch.nodeType === 1 && (ch.localName === "drawing" || ch.localName === "pict")) {
24276
- pics += imageHtml(ch);
24277
- }
24278
- // A run holding a footnote reference has no text of its own.
24279
- if (ch.nodeType === 1 && ch.localName === "footnoteReference") {
24280
- var fid = ch.getAttributeNS(W, "id") || ch.getAttribute("w:id");
24281
- var body = fid != null ? ctx.footnotes[String(fid)] : null;
24282
- if (body) pics += footnoteMarker(body);
24283
- }
24284
- // Endnotes render through the same notes machinery: Word puts
24285
- // both at the end of the document, and the distinction is not
24286
- // one HTML has a separate representation for.
24287
- if (ch.nodeType === 1 && ch.localName === "endnoteReference") {
24288
- var eid = ch.getAttributeNS(W, "id") || ch.getAttribute("w:id");
24289
- var ebody = eid != null ? ctx.endnotes[String(eid)] : null;
24290
- if (ebody) pics += footnoteMarker(ebody);
24291
- }
24292
- // TEXT BOXES. Their content is nested several levels below the
24293
- // run (w:pict > v:shape > v:textbox > w:txbxContent, or the
24294
- // DrawingML mc:AlternateContent equivalent), so a reader that
24295
- // only looks at a run's DIRECT children drops every word inside
24296
- // them -- silently, with no sign anything is missing.
24297
- if (ch.nodeType === 1 && (ch.localName === "pict" || ch.localName === "drawing" ||
24298
- ch.localName === "object" || ch.localName === "AlternateContent")) {
24299
- collectTextBoxes(ch);
24300
- }
24301
- }
24302
- var txt = esc(runText(r));
24303
- if (!txt) return pics;
24304
- txt = txt.replace(/\n/g, "<br>");
24305
- var rpr = firstChildEl(r, "rPr");
24306
- if (rpr) {
24307
- if (firstChildEl(rpr, "b")) txt = "<strong>" + txt + "</strong>";
24308
- if (firstChildEl(rpr, "i")) txt = "<em>" + txt + "</em>";
24309
- if (firstChildEl(rpr, "u")) txt = "<u>" + txt + "</u>";
24310
- if (firstChildEl(rpr, "strike")) txt = "<s>" + txt + "</s>";
24311
- var vert = firstChildEl(rpr, "vertAlign");
24312
- if (vert) {
24313
- var va = vert.getAttributeNS(W, "val") || vert.getAttribute("w:val") || "";
24314
- if (va === "superscript") txt = "<sup>" + txt + "</sup>";
24315
- else if (va === "subscript") txt = "<sub>" + txt + "</sub>";
24316
- }
24317
- // Character colour and size. w:sz is in HALF-points, so 24 = 12pt;
24318
- // forgetting the halving makes every imported document twice the
24319
- // size it should be.
24320
- var css = "";
24321
- var col = firstChildEl(rpr, "color");
24322
- if (col) {
24323
- var cv = col.getAttributeNS(W, "val") || col.getAttribute("w:val") || "";
24324
- if (cv && /^[0-9A-Fa-f]{6}$/.test(cv)) css += "color:#" + cv + ";";
24325
- }
24326
- var hl = firstChildEl(rpr, "highlight");
24327
- if (hl) {
24328
- var hv = hl.getAttributeNS(W, "val") || hl.getAttribute("w:val") || "";
24329
- if (hv && hv !== "none") css += "background-color:" + hv + ";";
24330
- }
24331
- var sz = firstChildEl(rpr, "sz");
24332
- if (sz) {
24333
- var sv = parseInt(sz.getAttributeNS(W, "val") || sz.getAttribute("w:val") || "", 10);
24334
- if (sv > 0) css += "font-size:" + (sv / 2) + "pt;";
24335
- }
24336
- if (css) txt = '<span style="' + css + '">' + txt + "</span>";
24337
- }
24338
- return pics + txt;
24339
- }
24340
-
24341
- // Block-level content discovered while rendering a paragraph: text
24342
- // boxes, SmartArt outlines, and placeholders for images the browser
24343
- // cannot render. None of them may be emitted inline inside the
24344
- // paragraph that referenced them -- a <div> inside a <p> is invalid and
24345
- // browsers silently close the paragraph around it -- so each is
24346
- // buffered here, already wrapped, and flushed straight after.
24347
- var pendingBlocks = [];
24348
- function queueBlock(html) {
24349
- // Dedup on the whole string: an mc:AlternateContent block carries
24350
- // the same graphic twice, once per rendering flavour.
24351
- if (html && pendingBlocks.indexOf(html) < 0) pendingBlocks.push(html);
24352
- }
24353
- function collectTextBoxes(node) {
24354
- var boxes = node.getElementsByTagName("*");
24355
- for (var i = 0; i < boxes.length; i++) {
24356
- if (boxes[i].localName !== "txbxContent") continue;
24357
- var inner = "";
24358
- var kids = boxes[i].childNodes;
24359
- for (var k = 0; k < kids.length; k++) {
24360
- var c = kids[k];
24361
- if (c.nodeType !== 1) continue;
24362
- if (c.localName === "p") {
24363
- var t = paraInner(c);
24364
- if (t) inner += "<p>" + t + "</p>";
24365
- } else if (c.localName === "tbl") {
24366
- inner += tableHtml(c);
24367
- }
24368
- }
24369
- if (inner) queueBlock('<div class="rte-imported-textbox" style="' + TEXTBOX_STYLE + '">' + inner + "</div>");
24370
- }
24371
- }
24372
-
24373
- function flushBlocks() {
24374
- if (!pendingBlocks.length) return "";
24375
- var html = pendingBlocks.join("");
24376
- pendingBlocks = [];
24377
- return html;
24378
- }
24379
-
24380
- // Emit a marker in the shape footnotes.js already understands, and stash
24381
- // the body so the notes section can be built at the end. The plugin
24382
- // renumbers on load, so the number written here is provisional.
24383
- var importedNotes = [];
24384
- // OMML -> the editor's own inline-math span, so an imported equation is
24385
- // editable in the math dialog and renders through whatever renderer the
24386
- // host page loads. The visible text is the TeX itself: that is what a
24387
- // page with no renderer shows, and it is readable rather than blank.
24388
- function mathHtml(node) {
24389
- var tex = ommlToTex(node);
24390
- if (!tex) return "";
24391
- var display = node.localName === "oMathPara";
24392
- return '<span class="rte-math-inline' + (display ? " rte-math-display" : "") +
24393
- '" data-tex="' + esc(tex) + '">' + esc(tex) + "</span>";
24394
- }
24395
-
24396
- function footnoteMarker(text) {
24397
- var id = "fnimp" + (importedNotes.length + 1);
24398
- importedNotes.push({ id: id, text: text });
24399
- var n = importedNotes.length;
24400
- return '<sup class="rte-fn-ref" data-fn-id="' + id + '" data-fn-number="' + n +
24401
- '" id="fnref-' + id + '" contenteditable="false">' + n + "</sup>";
24402
- }
24403
-
24404
- function footnotesSection() {
24405
- if (!importedNotes.length) return "";
24406
- var items = "";
24407
- for (var i = 0; i < importedNotes.length; i++) {
24408
- var f = importedNotes[i];
24409
- items += '<li class="rte-fn-note" data-fn-id="' + f.id + '" data-fn-number="' + (i + 1) +
24410
- '" id="fn-' + f.id + '">' + esc(f.text) +
24411
- '<a class="rte-fn-back" data-fn-id="' + f.id + '" href="#fnref-' + f.id +
24412
- '" contenteditable="false" title="Back to reference">↩</a></li>';
24413
- }
24414
- return '<section class="rte-footnotes"><h2 class="rte-fn-title">Footnotes</h2>' +
24415
- '<ol class="rte-fn-list" data-numbering="decimal">' + items + "</ol></section>";
24416
- }
24417
- // Runs inside a w:ins / w:del wrapper, rendered with the review markup
24418
- // that the DOCX *export* already round-trips (<ins data-author>/<del>).
24419
- function revisionHtml(node, tag) {
24420
- var inner = "";
24421
- for (var i = 0; i < node.childNodes.length; i++) {
24422
- var c = node.childNodes[i];
24423
- if (c.nodeType !== 1) continue;
24424
- if (c.localName === "r") inner += runHtml(c);
24425
- else if (c.localName === "ins") inner += revisionHtml(c, "ins");
24426
- else if (c.localName === "del") inner += revisionHtml(c, "del");
24427
- }
24428
- if (!inner) return "";
24429
- var author = node.getAttributeNS(W, "author") || node.getAttribute("w:author") || "";
24430
- var date = node.getAttributeNS(W, "date") || node.getAttribute("w:date") || "";
24431
- return "<" + tag +
24432
- (author ? ' data-author="' + esc(author) + '"' : "") +
24433
- (date ? ' data-date="' + esc(date) + '"' : "") +
24434
- ">" + inner + "</" + tag + ">";
24435
- }
24436
-
24437
- function paraInner(p) {
24438
- var h = "", kids = p.childNodes;
24439
- // Word marks a commented RANGE with start/end markers around the runs,
24440
- // so the wrapper has to be opened and closed as we walk, not derived
24441
- // from any single element.
24442
- var openComments = [];
24443
- function commentOpen(id) {
24444
- var c = ctx.comments[String(id)];
24445
- if (!c) return "";
24446
- openComments.push(id);
24447
- return '<span data-comment="' + esc(c.text) + '"' +
24448
- (c.author ? ' data-comment-author="' + esc(c.author) + '"' : "") + ">";
24449
- }
24450
- for (var i = 0; i < kids.length; i++) {
24451
- var c = kids[i];
24452
- if (c.nodeType === 1 && c.localName === "commentRangeStart") {
24453
- h += commentOpen(c.getAttributeNS(W, "id") || c.getAttribute("w:id"));
24454
- continue;
24455
- }
24456
- if (c.nodeType === 1 && c.localName === "commentRangeEnd") {
24457
- if (openComments.length) { openComments.pop(); h += "</span>"; }
24458
- continue;
24459
- }
24460
- if (c.nodeType === 1 && (c.localName === "ins" || c.localName === "del") && c.namespaceURI === W) {
24461
- h += revisionHtml(c, c.localName);
24462
- continue;
24463
- }
24464
- // EQUATIONS. OMML is a sibling of the runs, in its own
24465
- // namespace -- a walker that only recognises w:r skips it and
24466
- // the equation is gone. m:oMathPara is the display (own-line)
24467
- // wrapper around one or more m:oMath.
24468
- if (c.nodeType === 1 && c.namespaceURI === OMML_NS &&
24469
- (c.localName === "oMath" || c.localName === "oMathPara")) {
24470
- h += mathHtml(c);
24471
- continue;
24472
- }
24473
- if (c.nodeType === 1 && c.localName === "r" && c.namespaceURI === W) h += runHtml(c);
24474
- else if (c.nodeType === 1 && c.localName === "hyperlink") {
24475
- var inner = "";
24476
- for (var j = 0; j < c.childNodes.length; j++) if (c.childNodes[j].localName === "r") inner += runHtml(c.childNodes[j]);
24477
- // Resolve r:id through the rels part. Previously the run text
24478
- // was emitted bare and the URL was thrown away, so every link
24479
- // in an imported document became plain text.
24480
- var rel = relTarget(c);
24481
- var anchor = c.getAttributeNS(W, "anchor") || c.getAttribute("w:anchor");
24482
- var href = rel ? rel.target : (anchor ? "#" + anchor : null);
24483
- h += href ? ('<a href="' + esc(href) + '">' + (inner || esc(href)) + "</a>") : inner;
24484
- }
24485
- }
24486
- // A comment range left open at the end of the paragraph would leak an
24487
- // unbalanced <span> into the document.
24488
- while (openComments.length) { openComments.pop(); h += "</span>"; }
24489
- return h;
24490
- }
24491
- function paraStyle(p) {
24492
- var ppr = firstChildEl(p, "pPr"); if (!ppr) return {};
24493
- var info = {};
24494
- var ps = firstChildEl(ppr, "pStyle");
24495
- if (ps) { var v = ps.getAttributeNS(W, "val") || ps.getAttribute("w:val") || ""; var m = /heading(\d)/i.exec(v); if (m) info.heading = Math.min(6, parseInt(m[1], 10)); }
24496
- var numPr = firstChildEl(ppr, "numPr");
24497
- if (numPr) {
24498
- info.list = true;
24499
- var ilvl = firstChildEl(numPr, "ilvl");
24500
- var numId = firstChildEl(numPr, "numId");
24501
- info.level = parseInt(ilvl ? (ilvl.getAttributeNS(W, "val") || ilvl.getAttribute("w:val") || "0") : "0", 10) || 0;
24502
- var nid = numId ? (numId.getAttributeNS(W, "val") || numId.getAttribute("w:val") || "") : "";
24503
- var levels = ctx.numbering[nid];
24504
- var fmt = levels ? levels[String(info.level)] : null;
24505
- // Word marks bullets with numFmt="bullet"; anything else is an
24506
- // ordered list. Defaulting to bullet when numbering.xml is absent
24507
- // matches the old behaviour rather than inventing <ol>s.
24508
- info.ordered = !!fmt && fmt !== "bullet" && fmt !== "none";
24509
- }
24510
- var jc = firstChildEl(ppr, "jc");
24511
- if (jc) {
24512
- var a = jc.getAttributeNS(W, "val") || jc.getAttribute("w:val") || "";
24513
- if (a === "center" || a === "right" || a === "both") {
24514
- info.align = (a === "both") ? "justify" : a;
24515
- }
24516
- }
24517
- return info;
24518
- }
24519
- var body = els(doc, "body")[0];
24520
- if (!body) return "";
24521
- var out = [];
24522
- // Stack of open lists so w:ilvl produces real nesting instead of a flat
24523
- // run of <li>s. liOpen tracks whether an <li> is still open at each
24524
- // depth, because a nested list must live INSIDE its parent <li> --
24525
- // <ol><li>a</li><ol>...</ol></ol> is invalid HTML, and shipping invalid
24526
- // markup out of an importer undermines the whole clean-output promise.
24527
- var listStack = [];
24528
- var liOpen = [];
24529
- function closeListsTo(depth) {
24530
- while (listStack.length > depth) {
24531
- var d = listStack.length - 1;
24532
- if (liOpen[d]) { out.push("</li>"); liOpen[d] = false; }
24533
- out.push("</" + listStack.pop() + ">");
24534
- liOpen.pop();
24535
- }
24536
- }
24537
- for (var i = 0; i < body.childNodes.length; i++) {
24538
- var node = body.childNodes[i];
24539
- if (node.nodeType !== 1) continue;
24540
- // A display equation can sit at body level rather than inside a
24541
- // w:p, so the "wordprocessingml namespace only" filter below would
24542
- // drop it.
24543
- if (node.namespaceURI === OMML_NS &&
24544
- (node.localName === "oMathPara" || node.localName === "oMath")) {
24545
- closeListsTo(0);
24546
- var mh = mathHtml(node);
24547
- if (mh) out.push("<p>" + mh + "</p>");
24548
- continue;
24549
- }
24550
- if (node.namespaceURI !== W) continue;
24551
- if (node.localName === "p") {
24552
- var st = paraStyle(node);
24553
- var inner = paraInner(node);
24554
- if (st.list) {
24555
- var want = (st.level || 0) + 1;
24556
- var tag = st.ordered ? "ol" : "ul";
24557
- // Come back up to this depth FIRST. Checking the type before
24558
- // this ran compared against the wrong level, so a bullet
24559
- // following a deeper numbered item silently joined the <ol>.
24560
- if (listStack.length > want) closeListsTo(want);
24561
- // Now at this depth: a different list type means a new list.
24562
- if (listStack.length === want && listStack[want - 1] !== tag) closeListsTo(want - 1);
24563
- // Going deeper leaves the parent <li> open so the sublist
24564
- // nests inside it.
24565
- while (listStack.length < want) {
24566
- out.push("<" + tag + ">");
24567
- listStack.push(tag);
24568
- liOpen.push(false);
24569
- }
24570
- if (liOpen[want - 1]) { out.push("</li>"); liOpen[want - 1] = false; }
24571
- out.push("<li>" + (inner || ""));
24572
- liOpen[want - 1] = true;
24573
- continue;
24574
- }
24575
- closeListsTo(0);
24576
- if (st.heading) out.push("<h" + st.heading + ">" + (inner || "") + "</h" + st.heading + ">");
24577
- else {
24578
- var style = st.align ? ' style="text-align:' + st.align + '"' : "";
24579
- // A paragraph that contained ONLY a text box has no text of
24580
- // its own; emitting an empty <p> before the box adds a blank
24581
- // line that was never in the document.
24582
- var boxes = flushBlocks();
24583
- if (inner || !boxes) out.push("<p" + style + ">" + (inner || "<br>") + "</p>");
24584
- if (boxes) out.push(boxes);
24585
- }
24586
- } else if (node.localName === "tbl") {
24587
- closeListsTo(0);
24588
- out.push(tableHtml(node));
24589
- }
24590
- }
24591
- closeListsTo(0);
24592
- // A text box hanging off the last paragraph, or off a heading/list item,
24593
- // still has to land somewhere.
24594
- var trailing = flushBlocks();
24595
- if (trailing) out.push(trailing);
24596
- // The notes section goes last, after every marker has been collected.
24597
- var notes = footnotesSection();
24598
- if (notes) out.push(notes);
24599
- return out.join("\n");
24600
-
24601
- function tableHtml(tbl) {
24602
- var rows = [], kids = tbl.childNodes;
24603
- for (var i = 0; i < kids.length; i++) {
24604
- var tr = kids[i];
24605
- if (tr.nodeType !== 1 || tr.localName !== "tr") continue;
24606
- var cells = [];
24607
- for (var j = 0; j < tr.childNodes.length; j++) {
24608
- var tc = tr.childNodes[j];
24609
- if (tc.nodeType !== 1 || tc.localName !== "tc") continue;
24610
- var cellHtml = "";
24611
- for (var k = 0; k < tc.childNodes.length; k++) {
24612
- if (tc.childNodes[k].localName === "p") cellHtml += "<p>" + (paraInner(tc.childNodes[k]) || "<br>") + "</p>";
24613
- }
24614
- cells.push("<td>" + cellHtml + "</td>");
24615
- }
24616
- rows.push("<tr>" + cells.join("") + "</tr>");
24617
- }
24618
- return "<table>" + rows.join("") + "</table>";
24619
- }
24620
- }
24621
-
24622
- function notify(msg) {
24623
- try {
24624
- if (editor && typeof editor.createDialog === "function") {
24625
- var d = editor.createDialog((editor.getLangText && editor.getLangText("importtitle")) || "Import document", "rte-dialog-import");
24626
- var w = d.ownerDocument.createElement("div");
24627
- w.style.cssText = "padding:16px;max-width:420px;font:13px -apple-system,Segoe UI,sans-serif;line-height:1.5";
24628
- w.textContent = msg;
24629
- d.appendChild(w);
24630
- return;
24631
- }
24632
- } catch (e) {}
24633
- if (window.console) console.warn("documentimport:", msg);
24634
- }
24635
- }
23373
+ if (!window.RTE_DefaultConfig) window.RTE_DefaultConfig = {};
23374
+
23375
+ // 2026-06-09 Document import — the natural pair to Export-to-Word/Markdown/PDF.
23376
+ // Opens a local file and loads it into the editor. Library-free for the common
23377
+ // formats: Markdown (.md/.markdown via the core fromMarkdown engine), HTML
23378
+ // (.html/.htm), plain text (.txt), and Word's HTML-based format (.doc, which
23379
+ // Word saves as MSO-flavored HTML) — Word junk (mso-* styles, o:/w: tags,
23380
+ // conditional comments) is stripped the same way paste-from-Word is.
23381
+ //
23382
+ // .docx IS parsed library-free: it is a ZIP of XML, and the ZIP central
23383
+ // directory is read directly while DecompressionStream("deflate-raw") handles
23384
+ // the inflate. No dependency, no server round-trip.
23385
+ // (This comment used to say .docx was not parseable library-free. That was true
23386
+ // when it was written and stopped being true when the ZIP reader landed below;
23387
+ // it then misled a reader into reporting the feature as missing. Kept explicit
23388
+ // so it does not happen again.)
23389
+ //
23390
+ // 2026-07-28 fidelity pass — what a naive converter silently loses, and what
23391
+ // this now preserves:
23392
+ // - HYPERLINK URLS. w:hyperlink carries only an r:id; the address lives in
23393
+ // word/_rels/document.xml.rels. Without resolving it every link imports as
23394
+ // plain text with the URL discarded.
23395
+ // - IMAGES. w:drawing -> a:blip r:embed -> word/media/*, inlined as data URIs
23396
+ // (set config.documentImportImages = false to skip, for image-heavy files).
23397
+ // - ORDERED vs BULLET lists and NESTING. document.xml stores every list the
23398
+ // same way; only word/numbering.xml says which is which, so a naive reader
23399
+ // turns numbered lists into bullets. w:ilvl gives real nesting, placed
23400
+ // inside the parent <li> so the markup is valid.
23401
+ // - Paragraph alignment (w:jc).
23402
+ // Supply config.documentImportResolver(file) to override any type (e.g. to run
23403
+ // a server-side converter for formats this does not cover).
23404
+ //
23405
+ // API:
23406
+ // editor.openImportDialog(options?) -> file picker, then import
23407
+ // editor.importFile(file, options?) -> import a File object (Promise)
23408
+ // editor.htmlFromImportText(text, kind) -> convert text to HTML (kind: md|html|txt|doc)
23409
+ // Command: exec_command "importdocument" opens the picker. Slash: "/import".
23410
+ // Config:
23411
+ // config.documentImport = false // disable
23412
+ // config.documentImportMode = "replace" | "insert" // default "replace"
23413
+ // config.documentImportAccept = ".md,.markdown,.html,.htm,.txt,.doc,.docx"
23414
+ // config.documentImportResolver = function(file){ return htmlOrPromise; }
23415
+ RTE_DefaultConfig.plugin_documentimport = RTE_Plugin_DocumentImport;
23416
+ if (typeof RTE_DefaultConfig.documentImport === "undefined") RTE_DefaultConfig.documentImport = true;
23417
+
23418
+ function RTE_Plugin_DocumentImport() {
23419
+ var obj = this;
23420
+ var config, editor;
23421
+
23422
+ obj.PluginName = "DocumentImport";
23423
+
23424
+ obj.InitConfig = function (argconfig) { config = argconfig; };
23425
+
23426
+ obj.InitEditor = function (argeditor) {
23427
+ editor = argeditor;
23428
+ if (config.documentImport === false) return;
23429
+
23430
+ editor.htmlFromImportText = function (text, kind) { return toHtml(String(text == null ? "" : text), kind); };
23431
+ editor.importFile = function (file, options) { return importFile(file, options || {}); };
23432
+ editor.openImportDialog = function (options) { return openPicker(options || {}); };
23433
+
23434
+ editor.attachEvent("exec_command_importdocument", function (state) {
23435
+ state.returnValue = true;
23436
+ state.stopBubble = true;
23437
+ openPicker({});
23438
+ });
23439
+
23440
+ if (editor.slashCommands && typeof editor.slashCommands.register === "function") {
23441
+ try {
23442
+ editor.slashCommands.register({
23443
+ id: "import-document",
23444
+ title: "Import document",
23445
+ description: "Open a Markdown, HTML, text, or Word (.doc) file into the editor",
23446
+ keywords: ["import", "open", "file", "word", "markdown", "upload"],
23447
+ action: function () { openPicker({}); }
23448
+ });
23449
+ } catch (e) {}
23450
+ }
23451
+ };
23452
+
23453
+ function kindFromName(name) {
23454
+ var n = String(name || "").toLowerCase();
23455
+ if (/\.(md|markdown|mdown|mkd)$/.test(n)) return "md";
23456
+ if (/\.html?$/.test(n)) return "html";
23457
+ if (/\.doc$/.test(n)) return "doc";
23458
+ if (/\.docx$/.test(n)) return "docx";
23459
+ if (/\.txt$/.test(n)) return "txt";
23460
+ return "txt";
23461
+ }
23462
+
23463
+ function esc(s) {
23464
+ return String(s == null ? "" : s).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
23465
+ }
23466
+
23467
+ // A Word text box and a SmartArt graphic are BOXES on the page. Importing
23468
+ // them as bare <div>s keeps the words but loses the thing that made them
23469
+ // read as separate from the body text, so the import looks lossier than it
23470
+ // is. Styled inline rather than by class because this is saved content: it
23471
+ // has to survive wherever the host renders it, with no stylesheet of ours
23472
+ // loaded. (Found by check-css-contract.mjs -- the classes were emitted with
23473
+ // no rule anywhere.)
23474
+ var TEXTBOX_STYLE = "border:1px solid #b9c2cf;border-radius:4px;padding:10px 14px;margin:12px 0;background:#fbfcfe";
23475
+ var SMARTART_STYLE = "border:1px solid #b9c2cf;border-radius:4px;padding:10px 14px 10px 6px;margin:12px 0;background:#f7faff";
23476
+
23477
+ // Strip Word/MSO debris from .doc HTML (same intent as paste-from-Word).
23478
+ function cleanWordHtml(html) {
23479
+ var h = String(html || "");
23480
+ // body only, drop head/xml/style islands and conditional comments
23481
+ var bodyMatch = /<body[^>]*>([\s\S]*?)<\/body>/i.exec(h);
23482
+ if (bodyMatch) h = bodyMatch[1];
23483
+ h = h.replace(/<!--\[if[\s\S]*?\[endif\]-->/gi, "");
23484
+ h = h.replace(/<!--[\s\S]*?-->/g, "");
23485
+ h = h.replace(/<\/?(o:p|o:|w:|xml|style|meta|link|title|head)[^>]*>/gi, "");
23486
+ h = h.replace(/<\\?\?xml[^>]*>/gi, "");
23487
+ // strip mso-* declarations + empty style/class/lang attrs
23488
+ h = h.replace(/\sstyle="[^"]*"/gi, function (m) {
23489
+ var cleaned = m.replace(/mso-[^;"]*;?/gi, "").replace(/style="\s*;*\s*"/i, "");
23490
+ return /style="\s*"/.test(cleaned) || cleaned === ' style=""' ? "" : cleaned;
23491
+ });
23492
+ h = h.replace(/\sclass="Mso[^"]*"/gi, "");
23493
+ h = h.replace(/\s(lang|xmlns(:\w+)?)="[^"]*"/gi, "");
23494
+ return h;
23495
+ }
23496
+
23497
+ function toHtml(text, kind) {
23498
+ switch (kind) {
23499
+ case "md":
23500
+ if (editor && typeof editor.fromMarkdown === "function") return editor.fromMarkdown(text, { apply: false });
23501
+ return "<p>" + esc(text).replace(/\n{2,}/g, "</p><p>").replace(/\n/g, "<br>") + "</p>";
23502
+ case "html":
23503
+ return text;
23504
+ case "doc":
23505
+ return cleanWordHtml(text);
23506
+ case "txt":
23507
+ default:
23508
+ var paras = String(text).replace(/\r\n?/g, "\n").split(/\n{2,}/);
23509
+ return paras.map(function (p) {
23510
+ return "<p>" + esc(p).replace(/\n/g, "<br>") + "</p>";
23511
+ }).join("");
23512
+ }
23513
+ }
23514
+
23515
+ function applyHtml(html, mode) {
23516
+ if (html == null) return false;
23517
+ if (mode === "insert") {
23518
+ if (typeof editor.insertHTML === "function") { editor.insertHTML(html); return true; }
23519
+ }
23520
+ if (typeof editor.setHTMLCode === "function") { editor.setHTMLCode(html); return true; }
23521
+ return false;
23522
+ }
23523
+
23524
+ function importFile(file, options) {
23525
+ var mode = options.mode || config.documentImportMode || "replace";
23526
+ return new Promise(function (resolve) {
23527
+ if (!file) { resolve(false); return; }
23528
+ var kind = kindFromName(file.name);
23529
+
23530
+ // BYOK resolver wins for any type (lets a host handle .docx etc.).
23531
+ if (typeof config.documentImportResolver === "function") {
23532
+ try {
23533
+ var r = config.documentImportResolver(file);
23534
+ Promise.resolve(r).then(function (html) {
23535
+ if (typeof html === "string") { resolve(applyHtml(html, mode)); }
23536
+ else { builtin(); }
23537
+ }, function () { builtin(); });
23538
+ return;
23539
+ } catch (e) { builtin(); return; }
23540
+ }
23541
+ builtin();
23542
+
23543
+ function builtin() {
23544
+ if (kind === "docx") {
23545
+ // Library-free .docx: unzip word/document.xml (native
23546
+ // DecompressionStream) + transform WordprocessingML -> HTML.
23547
+ if (!docxSupported()) {
23548
+ notify("This browser can't unpack .docx (no DecompressionStream). Save as .doc/.html/.md, or wire config.documentImportResolver.");
23549
+ resolve(false);
23550
+ return;
23551
+ }
23552
+ readDocx(file).then(function (html) {
23553
+ if (html != null) resolve(applyHtml(html, mode));
23554
+ else { notify("Could not read this .docx file."); resolve(false); }
23555
+ }, function () { notify("Could not read this .docx file."); resolve(false); });
23556
+ return;
23557
+ }
23558
+ if (typeof FileReader === "undefined") { resolve(false); return; }
23559
+ var reader = new FileReader();
23560
+ reader.onload = function () {
23561
+ var html = toHtml(reader.result, kind);
23562
+ resolve(applyHtml(html, mode));
23563
+ };
23564
+ reader.onerror = function () { resolve(false); };
23565
+ reader.readAsText(file);
23566
+ }
23567
+ });
23568
+ }
23569
+
23570
+ function openPicker(options) {
23571
+ try {
23572
+ var input = document.createElement("input");
23573
+ input.type = "file";
23574
+ input.accept = options.accept || config.documentImportAccept || ".md,.markdown,.html,.htm,.txt,.doc,.docx";
23575
+ input.style.position = "fixed";
23576
+ input.style.left = "-9999px";
23577
+ input.addEventListener("change", function () {
23578
+ var f = input.files && input.files[0];
23579
+ if (f) importFile(f, options);
23580
+ setTimeout(function () { try { document.body.removeChild(input); } catch (e) {} }, 0);
23581
+ });
23582
+ document.body.appendChild(input);
23583
+ input.click();
23584
+ return true;
23585
+ } catch (e) {
23586
+ if (window.console) console.error("documentimport: openPicker failed", e);
23587
+ return false;
23588
+ }
23589
+ }
23590
+
23591
+ // ---- library-free .docx (ZIP of XML) ----
23592
+ function docxSupported() {
23593
+ return typeof DecompressionStream === "function" && typeof DOMParser === "function" &&
23594
+ (typeof Response === "function" || typeof Blob === "function");
23595
+ }
23596
+
23597
+ // Locate an entry via the ZIP central directory (reliable comp sizes/offsets).
23598
+ function findZipEntry(bytes, wantName) {
23599
+ var dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
23600
+ // End Of Central Directory: signature 0x06054b50, scan from the end.
23601
+ var eocd = -1;
23602
+ for (var i = bytes.length - 22; i >= 0 && i >= bytes.length - 22 - 65536; i--) {
23603
+ if (dv.getUint32(i, true) === 0x06054b50) { eocd = i; break; }
23604
+ }
23605
+ if (eocd < 0) return null;
23606
+ var cdOffset = dv.getUint32(eocd + 16, true);
23607
+ var cdCount = dv.getUint16(eocd + 10, true);
23608
+ var p = cdOffset;
23609
+ for (var n = 0; n < cdCount; n++) {
23610
+ if (dv.getUint32(p, true) !== 0x02014b50) break;
23611
+ var method = dv.getUint16(p + 10, true);
23612
+ var compSize = dv.getUint32(p + 20, true);
23613
+ var nameLen = dv.getUint16(p + 28, true);
23614
+ var extraLen = dv.getUint16(p + 30, true);
23615
+ var commentLen = dv.getUint16(p + 32, true);
23616
+ var localOff = dv.getUint32(p + 42, true);
23617
+ // Normalize separators: the ZIP spec mandates "/", but some Windows
23618
+ // tools (.NET ZipFile on older runtimes) emit "\".
23619
+ var name = utf8(bytes.subarray(p + 46, p + 46 + nameLen)).replace(/\\/g, "/");
23620
+ if (name === wantName) {
23621
+ var lh = new DataView(bytes.buffer, bytes.byteOffset + localOff, 30);
23622
+ var lNameLen = lh.getUint16(26, true);
23623
+ var lExtraLen = lh.getUint16(28, true);
23624
+ var dataStart = localOff + 30 + lNameLen + lExtraLen;
23625
+ return { method: method, data: bytes.subarray(dataStart, dataStart + compSize) };
23626
+ }
23627
+ p += 46 + nameLen + extraLen + commentLen;
23628
+ }
23629
+ return null;
23630
+ }
23631
+
23632
+ function utf8(u8) {
23633
+ try { return new TextDecoder("utf-8").decode(u8); } catch (e) {
23634
+ var s = ""; for (var i = 0; i < u8.length; i++) s += String.fromCharCode(u8[i]); return s;
23635
+ }
23636
+ }
23637
+
23638
+ function inflateRaw(u8) {
23639
+ // method 0 = stored, 8 = deflate (raw).
23640
+ var ds = new DecompressionStream("deflate-raw");
23641
+ var blob = new Blob([u8]);
23642
+ return new Response(blob.stream().pipeThrough(ds)).arrayBuffer().then(function (ab) {
23643
+ return new Uint8Array(ab);
23644
+ });
23645
+ }
23646
+
23647
+ // Every entry whose name matches, decompressed. Needed because a faithful
23648
+ // conversion is not just document.xml: the hyperlink URLs live in the rels
23649
+ // part, whether a list is bulleted or numbered lives in numbering.xml, and
23650
+ // the images live in word/media.
23651
+ function listZipEntries(bytes) {
23652
+ var dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
23653
+ var eocd = -1;
23654
+ for (var i = bytes.length - 22; i >= 0 && i >= bytes.length - 22 - 65536; i--) {
23655
+ if (dv.getUint32(i, true) === 0x06054b50) { eocd = i; break; }
23656
+ }
23657
+ if (eocd < 0) return [];
23658
+ var cdOffset = dv.getUint32(eocd + 16, true);
23659
+ var cdCount = dv.getUint16(eocd + 10, true);
23660
+ var p = cdOffset, out = [];
23661
+ for (var n = 0; n < cdCount; n++) {
23662
+ if (dv.getUint32(p, true) !== 0x02014b50) break;
23663
+ var method = dv.getUint16(p + 10, true);
23664
+ var compSize = dv.getUint32(p + 20, true);
23665
+ var nameLen = dv.getUint16(p + 28, true);
23666
+ var extraLen = dv.getUint16(p + 30, true);
23667
+ var commentLen = dv.getUint16(p + 32, true);
23668
+ var localOff = dv.getUint32(p + 42, true);
23669
+ var name = utf8(bytes.subarray(p + 46, p + 46 + nameLen)).replace(/\\/g, "/");
23670
+ var lh = new DataView(bytes.buffer, bytes.byteOffset + localOff, 30);
23671
+ var dataStart = localOff + 30 + lh.getUint16(26, true) + lh.getUint16(28, true);
23672
+ out.push({ name: name, method: method, data: bytes.subarray(dataStart, dataStart + compSize) });
23673
+ p += 46 + nameLen + extraLen + commentLen;
23674
+ }
23675
+ return out;
23676
+ }
23677
+
23678
+ function entryBytes(entry) {
23679
+ return entry.method === 0 ? Promise.resolve(entry.data) : inflateRaw(entry.data);
23680
+ }
23681
+
23682
+ function mimeForExt(name) {
23683
+ var e = (name.split(".").pop() || "").toLowerCase();
23684
+ if (e === "png") return "image/png";
23685
+ if (e === "jpg" || e === "jpeg") return "image/jpeg";
23686
+ if (e === "gif") return "image/gif";
23687
+ if (e === "bmp") return "image/bmp";
23688
+ if (e === "webp") return "image/webp";
23689
+ if (e === "svg") return "image/svg+xml";
23690
+ return null; // wmf/emf and friends have no browser-renderable form
23691
+ }
23692
+
23693
+ function bytesToDataUri(u8, mime) {
23694
+ var CHUNK = 0x8000, s = "";
23695
+ for (var i = 0; i < u8.length; i += CHUNK) {
23696
+ s += String.fromCharCode.apply(null, u8.subarray(i, i + CHUNK));
23697
+ }
23698
+ return "data:" + mime + ";base64," + btoa(s);
23699
+ }
23700
+
23701
+ function readDocx(file) {
23702
+ var bufPromise = file.arrayBuffer ? file.arrayBuffer() : new Promise(function (res, rej) {
23703
+ var r = new FileReader(); r.onload = function () { res(r.result); }; r.onerror = rej; r.readAsArrayBuffer(file);
23704
+ });
23705
+ return bufPromise.then(function (ab) {
23706
+ var bytes = new Uint8Array(ab);
23707
+ var entries = listZipEntries(bytes);
23708
+ var byName = {};
23709
+ for (var i = 0; i < entries.length; i++) byName[entries[i].name] = entries[i];
23710
+ if (!byName["word/document.xml"]) return null;
23711
+
23712
+ var ctx = { rels: {}, numbering: {}, media: {}, footnotes: {}, endnotes: {}, comments: {}, diagrams: {}, vectorNames: {} };
23713
+
23714
+ // Images are opt-in: a document full of photographs would otherwise
23715
+ // inline megabytes of base64 into the editor.
23716
+ var wantMedia = config.documentImportImages !== false;
23717
+
23718
+ var jobs = [entryBytes(byName["word/document.xml"]).then(function (b) { ctx.documentXml = utf8(b); })];
23719
+
23720
+ if (byName["word/_rels/document.xml.rels"]) {
23721
+ jobs.push(entryBytes(byName["word/_rels/document.xml.rels"]).then(function (b) {
23722
+ ctx.rels = parseRels(utf8(b));
23723
+ }));
23724
+ }
23725
+ if (byName["word/numbering.xml"]) {
23726
+ jobs.push(entryBytes(byName["word/numbering.xml"]).then(function (b) {
23727
+ ctx.numbering = parseNumbering(utf8(b));
23728
+ }));
23729
+ }
23730
+ // Footnotes live in their OWN part; document.xml only carries
23731
+ // w:footnoteReference with an id. Skip this and a footnoted contract
23732
+ // imports with every citation silently deleted.
23733
+ if (byName["word/footnotes.xml"]) {
23734
+ jobs.push(entryBytes(byName["word/footnotes.xml"]).then(function (b) {
23735
+ ctx.footnotes = parseFootnotes(utf8(b), "footnote");
23736
+ }));
23737
+ }
23738
+ // Comment bodies live in their own part too, keyed by id; the
23739
+ // document only marks the commented RANGE.
23740
+ // Endnotes are structurally identical to footnotes, in their own part.
23741
+ if (byName["word/endnotes.xml"]) {
23742
+ jobs.push(entryBytes(byName["word/endnotes.xml"]).then(function (b) {
23743
+ ctx.endnotes = parseFootnotes(utf8(b), "endnote");
23744
+ }));
23745
+ }
23746
+ if (byName["word/comments.xml"]) {
23747
+ jobs.push(entryBytes(byName["word/comments.xml"]).then(function (b) {
23748
+ ctx.comments = parseComments(utf8(b));
23749
+ }));
23750
+ }
23751
+ // SmartArt. The drawing in document.xml holds only relationship ids;
23752
+ // every word of the diagram lives in word/diagrams/dataN.xml, in the
23753
+ // DrawingML *diagram* namespace. A reader that looks for a:blip finds
23754
+ // nothing and drops the whole graphic, so an org chart or a process
23755
+ // flow imports as empty space.
23756
+ for (var dg = 0; dg < entries.length; dg++) {
23757
+ (function (ent) {
23758
+ if (!/^word\/diagrams\/data\d*\.xml$/.test(ent.name)) return;
23759
+ jobs.push(entryBytes(ent).then(function (b) {
23760
+ try { ctx.diagrams[ent.name] = parseDiagram(utf8(b)); } catch (e) {}
23761
+ }));
23762
+ })(entries[dg]);
23763
+ }
23764
+ if (wantMedia) {
23765
+ for (var n = 0; n < entries.length; n++) {
23766
+ (function (ent) {
23767
+ if (ent.name.indexOf("word/media/") !== 0) return;
23768
+ var mime = mimeForExt(ent.name);
23769
+ if (!mime) return;
23770
+ jobs.push(entryBytes(ent).then(function (b) {
23771
+ try { ctx.media[ent.name] = bytesToDataUri(b, mime); } catch (e) {}
23772
+ }));
23773
+ })(entries[n]);
23774
+ }
23775
+ }
23776
+
23777
+ return Promise.all(jobs).then(function () { return docxXmlToHtml(ctx.documentXml, ctx); });
23778
+ });
23779
+ }
23780
+
23781
+ // r:id -> target. Without this, every hyperlink in the document survives as
23782
+ // plain text with its URL silently discarded.
23783
+ function parseRels(xml) {
23784
+ var map = {};
23785
+ try {
23786
+ var d = new DOMParser().parseFromString(xml, "application/xml");
23787
+ var rs = d.getElementsByTagName("*");
23788
+ for (var i = 0; i < rs.length; i++) {
23789
+ if (rs[i].localName !== "Relationship") continue;
23790
+ var id = rs[i].getAttribute("Id");
23791
+ var target = rs[i].getAttribute("Target");
23792
+ var mode = rs[i].getAttribute("TargetMode");
23793
+ if (id && target) map[id] = { target: target, external: mode === "External" };
23794
+ }
23795
+ } catch (e) {}
23796
+ return map;
23797
+ }
23798
+
23799
+ // w:id -> plain text of the footnote body.
23800
+ // Word reserves ids 0 and -1 for the separator rules drawn above footnotes;
23801
+ // those carry type="separator"/"continuationSeparator" and are not content.
23802
+ // tagName is "footnote" or "endnote": the two parts share a schema but NOT
23803
+ // an element name, so parsing endnotes.xml with "footnote" silently returns
23804
+ // nothing at all.
23805
+ function parseFootnotes(xml, tagName) {
23806
+ var out = {};
23807
+ try {
23808
+ var W = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
23809
+ var d = new DOMParser().parseFromString(xml, "application/xml");
23810
+ var notes = d.getElementsByTagNameNS(W, tagName || "footnote");
23811
+ for (var i = 0; i < notes.length; i++) {
23812
+ var n = notes[i];
23813
+ var type = n.getAttributeNS(W, "type") || n.getAttribute("w:type") || "";
23814
+ if (type) continue; // separator, not a real note
23815
+ var id = n.getAttributeNS(W, "id") || n.getAttribute("w:id");
23816
+ if (id == null) continue;
23817
+ // Body text only; the leading footnote-reference mark inside the
23818
+ // note is Word's own numbering and would duplicate ours.
23819
+ var txt = (n.textContent || "").replace(/\s+/g, " ").trim();
23820
+ if (txt) out[String(id)] = txt;
23821
+ }
23822
+ } catch (e) {}
23823
+ return out;
23824
+ }
23825
+
23826
+ // w:id -> { text, author }
23827
+ function parseComments(xml) {
23828
+ var out = {};
23829
+ try {
23830
+ var W = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
23831
+ var d = new DOMParser().parseFromString(xml, "application/xml");
23832
+ var cs = d.getElementsByTagNameNS(W, "comment");
23833
+ for (var i = 0; i < cs.length; i++) {
23834
+ var c = cs[i];
23835
+ var id = c.getAttributeNS(W, "id") || c.getAttribute("w:id");
23836
+ if (id == null) continue;
23837
+ out[String(id)] = {
23838
+ text: (c.textContent || "").replace(/\s+/g, " ").trim(),
23839
+ author: c.getAttributeNS(W, "author") || c.getAttribute("w:author") || ""
23840
+ };
23841
+ }
23842
+ } catch (e) {}
23843
+ return out;
23844
+ }
23845
+
23846
+ // word/diagrams/dataN.xml -> the diagram's text, one entry per node, in
23847
+ // document order.
23848
+ //
23849
+ // SmartArt has no browser equivalent -- it is a laid-out graphic driven by a
23850
+ // layout algorithm -- but its CONTENT is ordinary text, and text is what the
23851
+ // reader actually needs. An org chart that imports as an outline is usable; an
23852
+ // org chart that imports as nothing is a hole in the document.
23853
+ //
23854
+ // Nodes with presentation-only roles (`dgm:prSet` with no text, and the
23855
+ // ptType "pres"/"parTrans"/"sibTrans" connector points) carry no content and
23856
+ // would otherwise contribute blank list items.
23857
+ function parseDiagram(xml) {
23858
+ var out = [];
23859
+ try {
23860
+ var DGM = "http://schemas.openxmlformats.org/drawingml/2006/diagram";
23861
+ var d = new DOMParser().parseFromString(xml, "application/xml");
23862
+ var pts = d.getElementsByTagNameNS(DGM, "pt");
23863
+ for (var i = 0; i < pts.length; i++) {
23864
+ var type = pts[i].getAttribute("type") || "";
23865
+ if (type === "pres" || type === "parTrans" || type === "sibTrans") continue;
23866
+ var t = pts[i].getElementsByTagNameNS(DGM, "t")[0];
23867
+ if (!t) continue;
23868
+ var text = (t.textContent || "").replace(/\s+/g, " ").trim();
23869
+ if (text) out.push(text);
23870
+ }
23871
+ } catch (e) {}
23872
+ return out;
23873
+ }
23874
+
23875
+ // numId -> { level -> "bullet" | "decimal" | ... }. Word stores every list
23876
+ // the same way in document.xml; only numbering.xml says whether it renders
23877
+ // as bullets or numbers, which is why a naive converter turns every ordered
23878
+ // list into a <ul>.
23879
+ function parseNumbering(xml) {
23880
+ var out = {};
23881
+ try {
23882
+ var W = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
23883
+ var d = new DOMParser().parseFromString(xml, "application/xml");
23884
+ function val(el) { return el ? (el.getAttributeNS(W, "val") || el.getAttribute("w:val") || "") : ""; }
23885
+
23886
+ // abstractNumId -> { ilvl -> numFmt }
23887
+ var abstracts = {};
23888
+ var aNums = d.getElementsByTagNameNS(W, "abstractNum");
23889
+ for (var i = 0; i < aNums.length; i++) {
23890
+ var aid = aNums[i].getAttributeNS(W, "abstractNumId") || aNums[i].getAttribute("w:abstractNumId");
23891
+ var levels = {};
23892
+ var lvls = aNums[i].getElementsByTagNameNS(W, "lvl");
23893
+ for (var j = 0; j < lvls.length; j++) {
23894
+ var ilvl = lvls[j].getAttributeNS(W, "ilvl") || lvls[j].getAttribute("w:ilvl") || "0";
23895
+ var fmt = val(lvls[j].getElementsByTagNameNS(W, "numFmt")[0]);
23896
+ levels[ilvl] = fmt || "decimal";
23897
+ }
23898
+ if (aid != null) abstracts[aid] = levels;
23899
+ }
23900
+ // num -> abstractNumId
23901
+ var nums = d.getElementsByTagNameNS(W, "num");
23902
+ for (var k = 0; k < nums.length; k++) {
23903
+ var nid = nums[k].getAttributeNS(W, "numId") || nums[k].getAttribute("w:numId");
23904
+ var ref = nums[k].getElementsByTagNameNS(W, "abstractNumId")[0];
23905
+ var aref = val(ref);
23906
+ if (nid != null && abstracts[aref]) out[nid] = abstracts[aref];
23907
+ }
23908
+ } catch (e) {}
23909
+ return out;
23910
+ }
23911
+
23912
+ // ---------------------------------------------------------------------
23913
+ // OMML (Office Math Markup) -> LaTeX.
23914
+ //
23915
+ // Word does not store equations as text, MathML or an image: it stores an
23916
+ // <m:oMath> tree in its OWN namespace, interleaved between the runs of a
23917
+ // paragraph. A converter that walks w:r elements never sees it, so every
23918
+ // equation in the document disappears without a trace -- and because the
23919
+ // surrounding sentence still imports, nothing looks broken.
23920
+ //
23921
+ // The target is the editor's own inline-math format
23922
+ // (<span class="rte-math-inline" data-tex="...">), so imported equations
23923
+ // are editable and re-render through whichever renderer the host page
23924
+ // loads, exactly like one typed in the math dialog.
23925
+ //
23926
+ // This covers the constructs Word's equation editor actually produces.
23927
+ // Anything unrecognised degrades to its literal text rather than vanishing
23928
+ // -- a wrong-looking formula is recoverable, a missing one is not.
23929
+ var OMML_NS = "http://schemas.openxmlformats.org/officeDocument/2006/math";
23930
+
23931
+ // Word writes operators as Unicode, but a TeX renderer wants command names.
23932
+ // Passing "∑" through untouched produces a glyph that KaTeX cannot size or
23933
+ // place limits on.
23934
+ var MATH_SYMBOLS = {
23935
+ "∑": "\\sum", "∏": "\\prod", "∐": "\\coprod",
23936
+ "∫": "\\int", "∬": "\\iint", "∭": "\\iiint", "∮": "\\oint",
23937
+ "⋃": "\\bigcup", "⋂": "\\bigcap",
23938
+ "±": "\\pm", "∓": "\\mp", "×": "\\times", "÷": "\\div",
23939
+ "−": "-", "≠": "\\neq", "≤": "\\leq", "≥": "\\geq",
23940
+ "≈": "\\approx", "≡": "\\equiv", "∝": "\\propto",
23941
+ "∞": "\\infty", "∂": "\\partial", "∇": "\\nabla",
23942
+ "√": "\\sqrt", "∠": "\\angle", "⋅": "\\cdot", "…": "\\dots",
23943
+ "→": "\\to", "←": "\\leftarrow", "⇒": "\\Rightarrow", "⇔": "\\Leftrightarrow",
23944
+ "∈": "\\in", "∉": "\\notin", "⊂": "\\subset", "⊆": "\\subseteq",
23945
+ "∪": "\\cup", "∩": "\\cap", "∅": "\\emptyset",
23946
+ "∀": "\\forall", "∃": "\\exists", "¬": "\\neg",
23947
+ "∧": "\\land", "∨": "\\lor", "∴": "\\therefore",
23948
+ "α": "\\alpha", "β": "\\beta", "γ": "\\gamma", "δ": "\\delta",
23949
+ "ε": "\\epsilon", "ζ": "\\zeta", "η": "\\eta", "θ": "\\theta",
23950
+ "ι": "\\iota", "κ": "\\kappa", "λ": "\\lambda", "μ": "\\mu",
23951
+ "ν": "\\nu", "ξ": "\\xi", "π": "\\pi", "ρ": "\\rho",
23952
+ "σ": "\\sigma", "τ": "\\tau", "υ": "\\upsilon", "φ": "\\varphi",
23953
+ "χ": "\\chi", "ψ": "\\psi", "ω": "\\omega",
23954
+ "Γ": "\\Gamma", "Δ": "\\Delta", "Θ": "\\Theta", "Λ": "\\Lambda",
23955
+ "Ξ": "\\Xi", "Π": "\\Pi", "Σ": "\\Sigma", "Φ": "\\Phi",
23956
+ "Ψ": "\\Psi", "Ω": "\\Omega"
23957
+ };
23958
+ // Accent character -> TeX accent command (m:acc carries the mark as a chr).
23959
+ var MATH_ACCENTS = {
23960
+ "̂": "\\hat", "̃": "\\tilde", "̄": "\\bar", "̅": "\\overline",
23961
+ "̆": "\\breve", "̇": "\\dot", "̈": "\\ddot", "̊": "\\mathring",
23962
+ "̌": "\\check", "→": "\\vec", "⃗": "\\vec", "́": "\\acute", "̀": "\\grave"
23963
+ };
23964
+
23965
+ function ommlToTex(node) {
23966
+ var M = OMML_NS;
23967
+ function attrVal(parent, ln) {
23968
+ // Properties sit in a child element whose only content is m:val.
23969
+ for (var i = 0; i < parent.childNodes.length; i++) {
23970
+ var c = parent.childNodes[i];
23971
+ if (c.nodeType === 1 && c.localName === ln) {
23972
+ return c.getAttributeNS(M, "val") || c.getAttribute("m:val") || "";
23973
+ }
23974
+ }
23975
+ return "";
23976
+ }
23977
+ function propOf(el, propName, ln) {
23978
+ var p = child(el, propName);
23979
+ return p ? attrVal(p, ln) : "";
23980
+ }
23981
+ function child(el, ln) {
23982
+ for (var i = 0; i < el.childNodes.length; i++) {
23983
+ var c = el.childNodes[i];
23984
+ if (c.nodeType === 1 && c.localName === ln && c.namespaceURI === M) return c;
23985
+ }
23986
+ return null;
23987
+ }
23988
+ function children(el, ln) {
23989
+ var out = [];
23990
+ for (var i = 0; i < el.childNodes.length; i++) {
23991
+ var c = el.childNodes[i];
23992
+ if (c.nodeType === 1 && c.localName === ln && c.namespaceURI === M) out.push(c);
23993
+ }
23994
+ return out;
23995
+ }
23996
+ // An argument slot: braces so multi-character content binds correctly.
23997
+ // "x+1" without them turns \frac{x+1}{2} into \fracx+12.
23998
+ function arg(el) {
23999
+ return "{" + (el ? walk(el).trim() : "") + "}";
24000
+ }
24001
+ // A slot where braces are optional. Emitting them unconditionally is
24002
+ // correct but produces "{x}^{2}" and "{{i}^{2}}" -- valid TeX that is
24003
+ // unreadable the moment the user opens the equation in the math dialog.
24004
+ // A lone letter, digit or command needs none.
24005
+ function atom(el) {
24006
+ var t = el ? walk(el).trim() : "";
24007
+ if (/^[A-Za-z0-9]$/.test(t) || /^\\[A-Za-z]+$/.test(t)) return t;
24008
+ return "{" + t + "}";
24009
+ }
24010
+ function mapText(s) {
24011
+ var out = "";
24012
+ for (var i = 0; i < s.length; i++) {
24013
+ var ch = s.charAt(i);
24014
+ var sym = MATH_SYMBOLS[ch];
24015
+ if (sym) { out += sym + " "; continue; }
24016
+ // TeX metacharacters inside literal math text.
24017
+ if ("#$%&_{}".indexOf(ch) >= 0) { out += "\\" + ch; continue; }
24018
+ if (ch === "\\") { out += "\\backslash "; continue; }
24019
+ out += ch;
24020
+ }
24021
+ return out;
24022
+ }
24023
+ function walk(el) {
24024
+ var tex = "";
24025
+ for (var i = 0; i < el.childNodes.length; i++) {
24026
+ var c = el.childNodes[i];
24027
+ if (c.nodeType !== 1) continue;
24028
+ if (c.namespaceURI !== M) { tex += mapText(c.textContent || ""); continue; }
24029
+ tex += convert(c);
24030
+ }
24031
+ return tex;
24032
+ }
24033
+ function convert(el) {
24034
+ var ln = el.localName;
24035
+ switch (ln) {
24036
+ case "oMath":
24037
+ case "oMathPara":
24038
+ case "e":
24039
+ case "num":
24040
+ case "den":
24041
+ case "sub":
24042
+ case "sup":
24043
+ case "deg":
24044
+ case "lim":
24045
+ case "fName":
24046
+ return walk(el);
24047
+ // Properties describe how to render, not what to render; emitting
24048
+ // their text would leak stray characters into the formula.
24049
+ case "rPr": case "ctrlPr": case "fPr": case "radPr": case "naryPr":
24050
+ case "dPr": case "sSupPr": case "sSubPr": case "sSubSupPr": case "accPr":
24051
+ case "barPr": case "funcPr": case "mPr": case "limLowPr": case "limUppPr":
24052
+ case "groupChrPr": case "mcPr": case "eqArrPr": case "boxPr": case "borderBoxPr":
24053
+ case "phantPr": case "sPrePr":
24054
+ return "";
24055
+ case "r":
24056
+ return mapText(el.textContent || "");
24057
+ case "t":
24058
+ return mapText(el.textContent || "");
24059
+ case "f": {
24060
+ // A "no bar" fraction is Word's binomial/stacked form.
24061
+ var type = propOf(el, "fPr", "type");
24062
+ var n = arg(child(el, "num")), d = arg(child(el, "den"));
24063
+ if (type === "noBar") return "\\binom" + n + d;
24064
+ if (type === "skw" || type === "lin") return n + "/" + d;
24065
+ return "\\frac" + n + d;
24066
+ }
24067
+ case "sSup": return atom(child(el, "e")) + "^" + arg(child(el, "sup"));
24068
+ case "sSub": return atom(child(el, "e")) + "_" + arg(child(el, "sub"));
24069
+ case "sSubSup": return atom(child(el, "e")) + "_" + arg(child(el, "sub")) + "^" + arg(child(el, "sup"));
24070
+ case "sPre": return "{}_" + arg(child(el, "sub")) + "^" + arg(child(el, "sup")) + arg(child(el, "e"));
24071
+ case "rad": {
24072
+ // degHide means a plain square root; otherwise it is \sqrt[n]{}.
24073
+ var hide = propOf(el, "radPr", "degHide");
24074
+ var deg = child(el, "deg");
24075
+ var body = arg(child(el, "e"));
24076
+ if (hide === "1" || hide === "on" || hide === "true" || !deg || !(deg.textContent || "").trim()) return "\\sqrt" + body;
24077
+ return "\\sqrt[" + walk(deg) + "]" + body;
24078
+ }
24079
+ case "nary": {
24080
+ // The operator itself is an ATTRIBUTE (m:chr), not text. Miss
24081
+ // it and every summation imports as a bare limit pair.
24082
+ var chr = propOf(el, "naryPr", "chr") || "∫";
24083
+ var op = MATH_SYMBOLS[chr] || mapText(chr);
24084
+ var subHide = propOf(el, "naryPr", "subHide");
24085
+ var supHide = propOf(el, "naryPr", "supHide");
24086
+ var s = op;
24087
+ if (subHide !== "1" && subHide !== "on" && child(el, "sub")) s += "_" + arg(child(el, "sub"));
24088
+ if (supHide !== "1" && supHide !== "on" && child(el, "sup")) s += "^" + arg(child(el, "sup"));
24089
+ // The integrand takes no braces: \sum_{i=1}^{n} i^{2}, not
24090
+ // \sum_{i=1}^{n} {i^{2}}.
24091
+ var nbody = child(el, "e");
24092
+ return s + " " + (nbody ? walk(nbody).trim() : "");
24093
+ }
24094
+ case "d": {
24095
+ // \left/\right so the fences grow with their content.
24096
+ var beg = propOf(el, "dPr", "begChr");
24097
+ var end = propOf(el, "dPr", "endChr");
24098
+ var sep = propOf(el, "dPr", "sepChr") || "|";
24099
+ if (beg === "") beg = "(";
24100
+ if (end === "") end = ")";
24101
+ function fence(ch, side) {
24102
+ if (!ch) return side === "l" ? "\\left." : "\\right.";
24103
+ if (ch === "{" || ch === "}") return "\\" + ch;
24104
+ if (ch === "|") return "|";
24105
+ if (ch === "‖") return "\\|";
24106
+ // THREE different codepoints render as an angle
24107
+ // bracket and are indistinguishable on screen: the
24108
+ // mathematical pair (U+27E8/9), the CJK pair
24109
+ // (U+3008/9) and the deprecated pair (U+2329/A) that
24110
+ // several generators still emit. Comparing against a
24111
+ // literal in the source would silently match only one
24112
+ // of them, so compare by codepoint.
24113
+ var cp = ch.charCodeAt(0);
24114
+ if (cp === 0x27E8 || cp === 0x3008 || cp === 0x2329) return "\\langle";
24115
+ if (cp === 0x27E9 || cp === 0x3009 || cp === 0x232A) return "\\rangle";
24116
+ if (ch === "⌊") return "\\lfloor";
24117
+ if (ch === "⌋") return "\\rfloor";
24118
+ if (ch === "⌈") return "\\lceil";
24119
+ if (ch === "⌉") return "\\rceil";
24120
+ return ch;
24121
+ }
24122
+ var parts = children(el, "e");
24123
+ var inner = [];
24124
+ for (var q = 0; q < parts.length; q++) inner.push(walk(parts[q]));
24125
+ return "\\left" + fence(beg, "l") + inner.join(" " + fence(sep, "m") + " ") + "\\right" + fence(end, "r");
24126
+ }
24127
+ case "func": {
24128
+ // Word stores "sin"/"log" as ordinary text; without
24129
+ // \operatorname TeX renders it as s*i*n in italics.
24130
+ var name = walk(child(el, "fName")).trim();
24131
+ var known = /^(sin|cos|tan|cot|sec|csc|sinh|cosh|tanh|log|ln|lg|exp|lim|max|min|det|dim|gcd|arg|deg|hom|ker|Pr|sup|inf)$/;
24132
+ var head = known.test(name) ? "\\" + name : (name ? "\\operatorname{" + name + "}" : "");
24133
+ return head + arg(child(el, "e"));
24134
+ }
24135
+ case "limLow": {
24136
+ var base = walk(child(el, "e")).trim();
24137
+ if (base === "lim" || base === "\\lim") return "\\lim_" + arg(child(el, "lim"));
24138
+ return "\\underset" + arg(child(el, "lim")) + "{" + base + "}";
24139
+ }
24140
+ case "limUpp":
24141
+ return "\\overset" + arg(child(el, "lim")) + arg(child(el, "e"));
24142
+ case "acc": {
24143
+ var mark = propOf(el, "accPr", "chr") || "̂";
24144
+ var cmd = MATH_ACCENTS[mark] || "\\hat";
24145
+ return cmd + arg(child(el, "e"));
24146
+ }
24147
+ case "bar":
24148
+ return (propOf(el, "barPr", "pos") === "bot" ? "\\underline" : "\\overline") + arg(child(el, "e"));
24149
+ case "groupChr": {
24150
+ var g = propOf(el, "groupChrPr", "chr");
24151
+ if (g === "⏟") return "\\underbrace" + arg(child(el, "e"));
24152
+ return "\\overbrace" + arg(child(el, "e"));
24153
+ }
24154
+ case "borderBox":
24155
+ return "\\boxed" + arg(child(el, "e"));
24156
+ case "box":
24157
+ case "phant":
24158
+ return walk(el);
24159
+ case "m": {
24160
+ // Matrix: rows are m:mr, cells are m:e inside them.
24161
+ var rows = children(el, "mr"), lines = [];
24162
+ for (var r = 0; r < rows.length; r++) {
24163
+ var cells = children(rows[r], "e"), cs = [];
24164
+ for (var cix = 0; cix < cells.length; cix++) cs.push(walk(cells[cix]));
24165
+ lines.push(cs.join(" & "));
24166
+ }
24167
+ return "\\begin{matrix}" + lines.join(" \\\\ ") + "\\end{matrix}";
24168
+ }
24169
+ case "eqArr": {
24170
+ var eqs = children(el, "e"), rowsOut = [];
24171
+ for (var e2 = 0; e2 < eqs.length; e2++) rowsOut.push(walk(eqs[e2]));
24172
+ return "\\begin{aligned}" + rowsOut.join(" \\\\ ") + "\\end{aligned}";
24173
+ }
24174
+ default:
24175
+ // Unknown construct: keep the content rather than losing it.
24176
+ return walk(el);
24177
+ }
24178
+ }
24179
+ try {
24180
+ return convert(node).replace(/\s+/g, " ").trim();
24181
+ } catch (e) { return (node.textContent || "").trim(); }
24182
+ }
24183
+
24184
+ function docxXmlToHtml(xml, ctx) {
24185
+ ctx = ctx || { rels: {}, numbering: {}, media: {} };
24186
+ if (!ctx.diagrams) ctx.diagrams = {};
24187
+ var doc = new DOMParser().parseFromString(xml, "application/xml");
24188
+ var W = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
24189
+ var R = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
24190
+
24191
+ function relTarget(el) {
24192
+ if (!el) return null;
24193
+ var id = el.getAttributeNS(R, "id") || el.getAttribute("r:id") ||
24194
+ el.getAttributeNS(R, "embed") || el.getAttribute("r:embed");
24195
+ if (!id) return null;
24196
+ return ctx.rels[id] || null;
24197
+ }
24198
+
24199
+ // <w:drawing>/<w:pict> -> <img> from word/media, inlined as a data URI.
24200
+ function imageHtml(node) {
24201
+ var blips = node.getElementsByTagName("*");
24202
+ for (var i = 0; i < blips.length; i++) {
24203
+ if (blips[i].localName !== "blip" && blips[i].localName !== "imagedata") continue;
24204
+ var rel = relTarget(blips[i]);
24205
+ if (!rel) continue;
24206
+ // Targets are relative to word/: "media/image1.png".
24207
+ var path = rel.target.replace(/^\.\//, "");
24208
+ var key = path.indexOf("word/") === 0 ? path : "word/" + path;
24209
+ var uri = ctx.media[key];
24210
+ if (uri) return '<img src="' + uri + '" alt="">';
24211
+ if (rel.external) return '<img src="' + esc(rel.target) + '" alt="">';
24212
+ // A vector metafile (WMF/EMF) has no browser-renderable form, so
24213
+ // there is no data URI for it. Dropping it silently leaves the
24214
+ // reader with no idea a figure was ever there -- and no filename
24215
+ // to go looking for in the original.
24216
+ if (/\.(wmf|emf|emz|wmz)$/i.test(path)) {
24217
+ var fileName = path.split("/").pop();
24218
+ queueBlock('<p class="rte-imported-unsupported" data-source="' + esc(fileName) +
24219
+ '"><em>[Unsupported image: ' + esc(fileName) +
24220
+ " — Windows metafiles have no browser-renderable form]</em></p>");
24221
+ return "";
24222
+ }
24223
+ }
24224
+ queueBlock(diagramHtml(node));
24225
+ return "";
24226
+ }
24227
+
24228
+ // SmartArt: the drawing references word/diagrams/dataN.xml through
24229
+ // r:dm. Rendered as a labelled list -- the layout cannot be reproduced,
24230
+ // but every word of it survives and stays editable.
24231
+ function diagramHtml(node) {
24232
+ var all = node.getElementsByTagName("*");
24233
+ for (var i = 0; i < all.length; i++) {
24234
+ if (all[i].localName !== "relIds") continue;
24235
+ var id = all[i].getAttributeNS(R, "dm") || all[i].getAttribute("r:dm");
24236
+ var rel = id ? ctx.rels[id] : null;
24237
+ if (!rel) continue;
24238
+ var path = rel.target.replace(/^\.\//, "");
24239
+ var key = path.indexOf("word/") === 0 ? path : "word/" + path;
24240
+ var nodes = ctx.diagrams[key];
24241
+ if (!nodes || !nodes.length) continue;
24242
+ var items = "";
24243
+ for (var n = 0; n < nodes.length; n++) items += "<li>" + esc(nodes[n]) + "</li>";
24244
+ return '<div class="rte-imported-smartart" style="' + SMARTART_STYLE + '"><ul>' + items + "</ul></div>";
24245
+ }
24246
+ return "";
24247
+ }
24248
+ function els(parent, ln) { return parent.getElementsByTagNameNS(W, ln); }
24249
+ function firstChildEl(parent, ln) {
24250
+ for (var i = 0; i < parent.childNodes.length; i++) {
24251
+ var c = parent.childNodes[i];
24252
+ if (c.nodeType === 1 && c.localName === ln && c.namespaceURI === W) return c;
24253
+ }
24254
+ return null;
24255
+ }
24256
+ function runText(r) {
24257
+ var t = "", kids = r.childNodes;
24258
+ for (var i = 0; i < kids.length; i++) {
24259
+ var c = kids[i];
24260
+ if (c.nodeType !== 1) continue;
24261
+ // Deleted text is stored as w:delText, never w:t — read only w:t
24262
+ // and every tracked deletion imports as an empty run.
24263
+ if (c.localName === "t" || c.localName === "delText") t += c.textContent || "";
24264
+ else if (c.localName === "tab") t += "\t";
24265
+ else if (c.localName === "br" || c.localName === "cr") t += "\n";
24266
+ }
24267
+ return t;
24268
+ }
24269
+ function runHtml(r) {
24270
+ // A run can carry a picture instead of text; without this every
24271
+ // image in the document is silently dropped on import.
24272
+ var pics = "";
24273
+ for (var d = 0; d < r.childNodes.length; d++) {
24274
+ var ch = r.childNodes[d];
24275
+ if (ch.nodeType === 1 && (ch.localName === "drawing" || ch.localName === "pict")) {
24276
+ pics += imageHtml(ch);
24277
+ }
24278
+ // A run holding a footnote reference has no text of its own.
24279
+ if (ch.nodeType === 1 && ch.localName === "footnoteReference") {
24280
+ var fid = ch.getAttributeNS(W, "id") || ch.getAttribute("w:id");
24281
+ var body = fid != null ? ctx.footnotes[String(fid)] : null;
24282
+ if (body) pics += footnoteMarker(body);
24283
+ }
24284
+ // Endnotes render through the same notes machinery: Word puts
24285
+ // both at the end of the document, and the distinction is not
24286
+ // one HTML has a separate representation for.
24287
+ if (ch.nodeType === 1 && ch.localName === "endnoteReference") {
24288
+ var eid = ch.getAttributeNS(W, "id") || ch.getAttribute("w:id");
24289
+ var ebody = eid != null ? ctx.endnotes[String(eid)] : null;
24290
+ if (ebody) pics += footnoteMarker(ebody);
24291
+ }
24292
+ // TEXT BOXES. Their content is nested several levels below the
24293
+ // run (w:pict > v:shape > v:textbox > w:txbxContent, or the
24294
+ // DrawingML mc:AlternateContent equivalent), so a reader that
24295
+ // only looks at a run's DIRECT children drops every word inside
24296
+ // them -- silently, with no sign anything is missing.
24297
+ if (ch.nodeType === 1 && (ch.localName === "pict" || ch.localName === "drawing" ||
24298
+ ch.localName === "object" || ch.localName === "AlternateContent")) {
24299
+ collectTextBoxes(ch);
24300
+ }
24301
+ }
24302
+ var txt = esc(runText(r));
24303
+ if (!txt) return pics;
24304
+ txt = txt.replace(/\n/g, "<br>");
24305
+ var rpr = firstChildEl(r, "rPr");
24306
+ if (rpr) {
24307
+ if (firstChildEl(rpr, "b")) txt = "<strong>" + txt + "</strong>";
24308
+ if (firstChildEl(rpr, "i")) txt = "<em>" + txt + "</em>";
24309
+ if (firstChildEl(rpr, "u")) txt = "<u>" + txt + "</u>";
24310
+ if (firstChildEl(rpr, "strike")) txt = "<s>" + txt + "</s>";
24311
+ var vert = firstChildEl(rpr, "vertAlign");
24312
+ if (vert) {
24313
+ var va = vert.getAttributeNS(W, "val") || vert.getAttribute("w:val") || "";
24314
+ if (va === "superscript") txt = "<sup>" + txt + "</sup>";
24315
+ else if (va === "subscript") txt = "<sub>" + txt + "</sub>";
24316
+ }
24317
+ // Character colour and size. w:sz is in HALF-points, so 24 = 12pt;
24318
+ // forgetting the halving makes every imported document twice the
24319
+ // size it should be.
24320
+ var css = "";
24321
+ var col = firstChildEl(rpr, "color");
24322
+ if (col) {
24323
+ var cv = col.getAttributeNS(W, "val") || col.getAttribute("w:val") || "";
24324
+ if (cv && /^[0-9A-Fa-f]{6}$/.test(cv)) css += "color:#" + cv + ";";
24325
+ }
24326
+ var hl = firstChildEl(rpr, "highlight");
24327
+ if (hl) {
24328
+ var hv = hl.getAttributeNS(W, "val") || hl.getAttribute("w:val") || "";
24329
+ if (hv && hv !== "none") css += "background-color:" + hv + ";";
24330
+ }
24331
+ var sz = firstChildEl(rpr, "sz");
24332
+ if (sz) {
24333
+ var sv = parseInt(sz.getAttributeNS(W, "val") || sz.getAttribute("w:val") || "", 10);
24334
+ if (sv > 0) css += "font-size:" + (sv / 2) + "pt;";
24335
+ }
24336
+ if (css) txt = '<span style="' + css + '">' + txt + "</span>";
24337
+ }
24338
+ return pics + txt;
24339
+ }
24340
+
24341
+ // Block-level content discovered while rendering a paragraph: text
24342
+ // boxes, SmartArt outlines, and placeholders for images the browser
24343
+ // cannot render. None of them may be emitted inline inside the
24344
+ // paragraph that referenced them -- a <div> inside a <p> is invalid and
24345
+ // browsers silently close the paragraph around it -- so each is
24346
+ // buffered here, already wrapped, and flushed straight after.
24347
+ var pendingBlocks = [];
24348
+ function queueBlock(html) {
24349
+ // Dedup on the whole string: an mc:AlternateContent block carries
24350
+ // the same graphic twice, once per rendering flavour.
24351
+ if (html && pendingBlocks.indexOf(html) < 0) pendingBlocks.push(html);
24352
+ }
24353
+ function collectTextBoxes(node) {
24354
+ var boxes = node.getElementsByTagName("*");
24355
+ for (var i = 0; i < boxes.length; i++) {
24356
+ if (boxes[i].localName !== "txbxContent") continue;
24357
+ var inner = "";
24358
+ var kids = boxes[i].childNodes;
24359
+ for (var k = 0; k < kids.length; k++) {
24360
+ var c = kids[k];
24361
+ if (c.nodeType !== 1) continue;
24362
+ if (c.localName === "p") {
24363
+ var t = paraInner(c);
24364
+ if (t) inner += "<p>" + t + "</p>";
24365
+ } else if (c.localName === "tbl") {
24366
+ inner += tableHtml(c);
24367
+ }
24368
+ }
24369
+ if (inner) queueBlock('<div class="rte-imported-textbox" style="' + TEXTBOX_STYLE + '">' + inner + "</div>");
24370
+ }
24371
+ }
24372
+
24373
+ function flushBlocks() {
24374
+ if (!pendingBlocks.length) return "";
24375
+ var html = pendingBlocks.join("");
24376
+ pendingBlocks = [];
24377
+ return html;
24378
+ }
24379
+
24380
+ // Emit a marker in the shape footnotes.js already understands, and stash
24381
+ // the body so the notes section can be built at the end. The plugin
24382
+ // renumbers on load, so the number written here is provisional.
24383
+ var importedNotes = [];
24384
+ // OMML -> the editor's own inline-math span, so an imported equation is
24385
+ // editable in the math dialog and renders through whatever renderer the
24386
+ // host page loads. The visible text is the TeX itself: that is what a
24387
+ // page with no renderer shows, and it is readable rather than blank.
24388
+ function mathHtml(node) {
24389
+ var tex = ommlToTex(node);
24390
+ if (!tex) return "";
24391
+ var display = node.localName === "oMathPara";
24392
+ return '<span class="rte-math-inline' + (display ? " rte-math-display" : "") +
24393
+ '" data-tex="' + esc(tex) + '">' + esc(tex) + "</span>";
24394
+ }
24395
+
24396
+ function footnoteMarker(text) {
24397
+ var id = "fnimp" + (importedNotes.length + 1);
24398
+ importedNotes.push({ id: id, text: text });
24399
+ var n = importedNotes.length;
24400
+ return '<sup class="rte-fn-ref" data-fn-id="' + id + '" data-fn-number="' + n +
24401
+ '" id="fnref-' + id + '" contenteditable="false">' + n + "</sup>";
24402
+ }
24403
+
24404
+ function footnotesSection() {
24405
+ if (!importedNotes.length) return "";
24406
+ var items = "";
24407
+ for (var i = 0; i < importedNotes.length; i++) {
24408
+ var f = importedNotes[i];
24409
+ items += '<li class="rte-fn-note" data-fn-id="' + f.id + '" data-fn-number="' + (i + 1) +
24410
+ '" id="fn-' + f.id + '">' + esc(f.text) +
24411
+ '<a class="rte-fn-back" data-fn-id="' + f.id + '" href="#fnref-' + f.id +
24412
+ '" contenteditable="false" title="Back to reference">↩</a></li>';
24413
+ }
24414
+ return '<section class="rte-footnotes"><h2 class="rte-fn-title">Footnotes</h2>' +
24415
+ '<ol class="rte-fn-list" data-numbering="decimal">' + items + "</ol></section>";
24416
+ }
24417
+ // Runs inside a w:ins / w:del wrapper, rendered with the review markup
24418
+ // that the DOCX *export* already round-trips (<ins data-author>/<del>).
24419
+ function revisionHtml(node, tag) {
24420
+ var inner = "";
24421
+ for (var i = 0; i < node.childNodes.length; i++) {
24422
+ var c = node.childNodes[i];
24423
+ if (c.nodeType !== 1) continue;
24424
+ if (c.localName === "r") inner += runHtml(c);
24425
+ else if (c.localName === "ins") inner += revisionHtml(c, "ins");
24426
+ else if (c.localName === "del") inner += revisionHtml(c, "del");
24427
+ }
24428
+ if (!inner) return "";
24429
+ var author = node.getAttributeNS(W, "author") || node.getAttribute("w:author") || "";
24430
+ var date = node.getAttributeNS(W, "date") || node.getAttribute("w:date") || "";
24431
+ return "<" + tag +
24432
+ (author ? ' data-author="' + esc(author) + '"' : "") +
24433
+ (date ? ' data-date="' + esc(date) + '"' : "") +
24434
+ ">" + inner + "</" + tag + ">";
24435
+ }
24436
+
24437
+ function paraInner(p) {
24438
+ var h = "", kids = p.childNodes;
24439
+ // Word marks a commented RANGE with start/end markers around the runs,
24440
+ // so the wrapper has to be opened and closed as we walk, not derived
24441
+ // from any single element.
24442
+ var openComments = [];
24443
+ function commentOpen(id) {
24444
+ var c = ctx.comments[String(id)];
24445
+ if (!c) return "";
24446
+ openComments.push(id);
24447
+ return '<span data-comment="' + esc(c.text) + '"' +
24448
+ (c.author ? ' data-comment-author="' + esc(c.author) + '"' : "") + ">";
24449
+ }
24450
+ for (var i = 0; i < kids.length; i++) {
24451
+ var c = kids[i];
24452
+ if (c.nodeType === 1 && c.localName === "commentRangeStart") {
24453
+ h += commentOpen(c.getAttributeNS(W, "id") || c.getAttribute("w:id"));
24454
+ continue;
24455
+ }
24456
+ if (c.nodeType === 1 && c.localName === "commentRangeEnd") {
24457
+ if (openComments.length) { openComments.pop(); h += "</span>"; }
24458
+ continue;
24459
+ }
24460
+ if (c.nodeType === 1 && (c.localName === "ins" || c.localName === "del") && c.namespaceURI === W) {
24461
+ h += revisionHtml(c, c.localName);
24462
+ continue;
24463
+ }
24464
+ // EQUATIONS. OMML is a sibling of the runs, in its own
24465
+ // namespace -- a walker that only recognises w:r skips it and
24466
+ // the equation is gone. m:oMathPara is the display (own-line)
24467
+ // wrapper around one or more m:oMath.
24468
+ if (c.nodeType === 1 && c.namespaceURI === OMML_NS &&
24469
+ (c.localName === "oMath" || c.localName === "oMathPara")) {
24470
+ h += mathHtml(c);
24471
+ continue;
24472
+ }
24473
+ if (c.nodeType === 1 && c.localName === "r" && c.namespaceURI === W) h += runHtml(c);
24474
+ else if (c.nodeType === 1 && c.localName === "hyperlink") {
24475
+ var inner = "";
24476
+ for (var j = 0; j < c.childNodes.length; j++) if (c.childNodes[j].localName === "r") inner += runHtml(c.childNodes[j]);
24477
+ // Resolve r:id through the rels part. Previously the run text
24478
+ // was emitted bare and the URL was thrown away, so every link
24479
+ // in an imported document became plain text.
24480
+ var rel = relTarget(c);
24481
+ var anchor = c.getAttributeNS(W, "anchor") || c.getAttribute("w:anchor");
24482
+ var href = rel ? rel.target : (anchor ? "#" + anchor : null);
24483
+ h += href ? ('<a href="' + esc(href) + '">' + (inner || esc(href)) + "</a>") : inner;
24484
+ }
24485
+ }
24486
+ // A comment range left open at the end of the paragraph would leak an
24487
+ // unbalanced <span> into the document.
24488
+ while (openComments.length) { openComments.pop(); h += "</span>"; }
24489
+ return h;
24490
+ }
24491
+ function paraStyle(p) {
24492
+ var ppr = firstChildEl(p, "pPr"); if (!ppr) return {};
24493
+ var info = {};
24494
+ var ps = firstChildEl(ppr, "pStyle");
24495
+ if (ps) {
24496
+ var v = ps.getAttributeNS(W, "val") || ps.getAttribute("w:val") || "";
24497
+ var m = /heading(\d)/i.exec(v);
24498
+ if (m) info.heading = Math.min(6, parseInt(m[1], 10));
24499
+ // docxexport.js writes blockquotes as the "Quote" paragraph style;
24500
+ // without this they came back as plain <p> and the round-trip lost
24501
+ // every blockquote. Match Quote / IntenseQuote / BlockQuote.
24502
+ else if (/^(intense)?quote$|blockquote/i.test(v.replace(/\s+/g, ""))) info.quote = true;
24503
+ }
24504
+ var numPr = firstChildEl(ppr, "numPr");
24505
+ if (numPr) {
24506
+ info.list = true;
24507
+ var ilvl = firstChildEl(numPr, "ilvl");
24508
+ var numId = firstChildEl(numPr, "numId");
24509
+ info.level = parseInt(ilvl ? (ilvl.getAttributeNS(W, "val") || ilvl.getAttribute("w:val") || "0") : "0", 10) || 0;
24510
+ var nid = numId ? (numId.getAttributeNS(W, "val") || numId.getAttribute("w:val") || "") : "";
24511
+ var levels = ctx.numbering[nid];
24512
+ var fmt = levels ? levels[String(info.level)] : null;
24513
+ // Word marks bullets with numFmt="bullet"; anything else is an
24514
+ // ordered list. Defaulting to bullet when numbering.xml is absent
24515
+ // matches the old behaviour rather than inventing <ol>s.
24516
+ info.ordered = !!fmt && fmt !== "bullet" && fmt !== "none";
24517
+ }
24518
+ var jc = firstChildEl(ppr, "jc");
24519
+ if (jc) {
24520
+ var a = jc.getAttributeNS(W, "val") || jc.getAttribute("w:val") || "";
24521
+ if (a === "center" || a === "right" || a === "both") {
24522
+ info.align = (a === "both") ? "justify" : a;
24523
+ }
24524
+ }
24525
+ return info;
24526
+ }
24527
+ var body = els(doc, "body")[0];
24528
+ if (!body) return "";
24529
+ var out = [];
24530
+ // Stack of open lists so w:ilvl produces real nesting instead of a flat
24531
+ // run of <li>s. liOpen tracks whether an <li> is still open at each
24532
+ // depth, because a nested list must live INSIDE its parent <li> --
24533
+ // <ol><li>a</li><ol>...</ol></ol> is invalid HTML, and shipping invalid
24534
+ // markup out of an importer undermines the whole clean-output promise.
24535
+ var listStack = [];
24536
+ var liOpen = [];
24537
+ function closeListsTo(depth) {
24538
+ while (listStack.length > depth) {
24539
+ var d = listStack.length - 1;
24540
+ if (liOpen[d]) { out.push("</li>"); liOpen[d] = false; }
24541
+ out.push("</" + listStack.pop() + ">");
24542
+ liOpen.pop();
24543
+ }
24544
+ }
24545
+ for (var i = 0; i < body.childNodes.length; i++) {
24546
+ var node = body.childNodes[i];
24547
+ if (node.nodeType !== 1) continue;
24548
+ // A display equation can sit at body level rather than inside a
24549
+ // w:p, so the "wordprocessingml namespace only" filter below would
24550
+ // drop it.
24551
+ if (node.namespaceURI === OMML_NS &&
24552
+ (node.localName === "oMathPara" || node.localName === "oMath")) {
24553
+ closeListsTo(0);
24554
+ var mh = mathHtml(node);
24555
+ if (mh) out.push("<p>" + mh + "</p>");
24556
+ continue;
24557
+ }
24558
+ if (node.namespaceURI !== W) continue;
24559
+ if (node.localName === "p") {
24560
+ var st = paraStyle(node);
24561
+ var inner = paraInner(node);
24562
+ if (st.list) {
24563
+ var want = (st.level || 0) + 1;
24564
+ var tag = st.ordered ? "ol" : "ul";
24565
+ // Come back up to this depth FIRST. Checking the type before
24566
+ // this ran compared against the wrong level, so a bullet
24567
+ // following a deeper numbered item silently joined the <ol>.
24568
+ if (listStack.length > want) closeListsTo(want);
24569
+ // Now at this depth: a different list type means a new list.
24570
+ if (listStack.length === want && listStack[want - 1] !== tag) closeListsTo(want - 1);
24571
+ // Going deeper leaves the parent <li> open so the sublist
24572
+ // nests inside it.
24573
+ while (listStack.length < want) {
24574
+ out.push("<" + tag + ">");
24575
+ listStack.push(tag);
24576
+ liOpen.push(false);
24577
+ }
24578
+ if (liOpen[want - 1]) { out.push("</li>"); liOpen[want - 1] = false; }
24579
+ out.push("<li>" + (inner || ""));
24580
+ liOpen[want - 1] = true;
24581
+ continue;
24582
+ }
24583
+ closeListsTo(0);
24584
+ if (st.heading) out.push("<h" + st.heading + ">" + (inner || "") + "</h" + st.heading + ">");
24585
+ else if (st.quote) out.push("<blockquote>" + (inner || "<br>") + "</blockquote>");
24586
+ else {
24587
+ var style = st.align ? ' style="text-align:' + st.align + '"' : "";
24588
+ // A paragraph that contained ONLY a text box has no text of
24589
+ // its own; emitting an empty <p> before the box adds a blank
24590
+ // line that was never in the document.
24591
+ var boxes = flushBlocks();
24592
+ if (inner || !boxes) out.push("<p" + style + ">" + (inner || "<br>") + "</p>");
24593
+ if (boxes) out.push(boxes);
24594
+ }
24595
+ } else if (node.localName === "tbl") {
24596
+ closeListsTo(0);
24597
+ out.push(tableHtml(node));
24598
+ }
24599
+ }
24600
+ closeListsTo(0);
24601
+ // A text box hanging off the last paragraph, or off a heading/list item,
24602
+ // still has to land somewhere.
24603
+ var trailing = flushBlocks();
24604
+ if (trailing) out.push(trailing);
24605
+ // The notes section goes last, after every marker has been collected.
24606
+ var notes = footnotesSection();
24607
+ if (notes) out.push(notes);
24608
+ return out.join("\n");
24609
+
24610
+ function tableHtml(tbl) {
24611
+ var rows = [], kids = tbl.childNodes;
24612
+ for (var i = 0; i < kids.length; i++) {
24613
+ var tr = kids[i];
24614
+ if (tr.nodeType !== 1 || tr.localName !== "tr") continue;
24615
+ // docxexport.js marks a header row with <w:trPr><w:tblHeader/>.
24616
+ // Without honouring it, every cell imported as <td> and the table
24617
+ // lost its header semantics on round-trip - which then fails the
24618
+ // accessibility checker's table-missing-header rule.
24619
+ var trPr = firstChildEl(tr, "trPr");
24620
+ var isHeaderRow = !!(trPr && firstChildEl(trPr, "tblHeader"));
24621
+ var cellTag = isHeaderRow ? "th" : "td";
24622
+ var cells = [];
24623
+ for (var j = 0; j < tr.childNodes.length; j++) {
24624
+ var tc = tr.childNodes[j];
24625
+ if (tc.nodeType !== 1 || tc.localName !== "tc") continue;
24626
+ var cellHtml = "";
24627
+ for (var k = 0; k < tc.childNodes.length; k++) {
24628
+ if (tc.childNodes[k].localName === "p") cellHtml += "<p>" + (paraInner(tc.childNodes[k]) || "<br>") + "</p>";
24629
+ }
24630
+ cells.push("<" + cellTag + ">" + cellHtml + "</" + cellTag + ">");
24631
+ }
24632
+ rows.push("<tr>" + cells.join("") + "</tr>");
24633
+ }
24634
+ return "<table>" + rows.join("") + "</table>";
24635
+ }
24636
+ }
24637
+
24638
+ function notify(msg) {
24639
+ try {
24640
+ if (editor && typeof editor.createDialog === "function") {
24641
+ var d = editor.createDialog((editor.getLangText && editor.getLangText("importtitle")) || "Import document", "rte-dialog-import");
24642
+ var w = d.ownerDocument.createElement("div");
24643
+ w.style.cssText = "padding:16px;max-width:420px;font:13px -apple-system,Segoe UI,sans-serif;line-height:1.5";
24644
+ w.textContent = msg;
24645
+ d.appendChild(w);
24646
+ return;
24647
+ }
24648
+ } catch (e) {}
24649
+ if (window.console) console.warn("documentimport:", msg);
24650
+ }
24651
+ }
24636
24652
 
24637
24653
  if (!window.RTE_DefaultConfig) window.RTE_DefaultConfig = {};
24638
24654