Ask paste: long pastes go in at once, <pre> stays verbatim, deep blocks keep their breaks
Tests: paste.json gains Fable's prose-plus-<pre> sample, a <pre> with blank lines and backticks, a 40-deep thread and an !important weight; PasteMarkdownTests reads them all. TestAskLongPasteIsQuick pastes 4,000 lines with nothing stubbed and checks the time and the whole value; TestAskPasteIsBounded no longer stubs the field's insert either. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Summary
Fable's re-review. R1: the web's insertText grows with the square of the lines, so a paste of over 300 lines goes in with setRangeText (no native Undo for those, the field's 16,000 limit kept) and an input event. R2: a <pre> is now a fenced code block with its text verbatim (indentation, blank lines; the fence outgrows any backtick run; the line break after <pre> goes), held out of the clean-up, on web and native alike. R3: past the 32-level cap a block is still a line and a cell a space, and the skip list still skips, on both. R6 (trivial one): font-weight ... !important counts.
4 files changed,
+180
−59
internal/browsertest/paste_test.go+47 −10internal/browsertest/testdata/paste.json+20 −0internal/look/static/ask.js+46 −22native/apple/Sources/BaseKit/Ask/PasteMarkdown.swift+67 −27
CI passed — run details
CI log
=== build === CGO_ENABLED=0 go build ./... === vet === go vet ./... === fmt-check === === staticcheck === go run honnef.co/go/tools/cmd/staticcheck@v0.7.0 ./... === govulncheck === go run golang.org/x/vuln/cmd/govulncheck@v1.8.0 ./... No vulnerabilities found. === gitleaks === [90m12:32PM[0m [32mINF[0m [1mUnknown SCM platform. Use --platform to include links in findings.[0m [36mhost=[0mamadan.net [90m12:32PM[0m [32mINF[0m [1m1 commits scanned.[0m [90m12:32PM[0m [32mINF[0m [1mscanned ~2492254 bytes (2.49 MB) in 688ms[0m [90m12:32PM[0m [32mINF[0m [1mno leaks found[0m === budget === go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget size budget size: 22 directories within budget === script-test === scripts/prepare-apps_test.sh ok releases lookup failure stops before ship ok app owned elsewhere stops the script ok apps listing failure stops before create ok ambiguous release dir is refused ok explicit version resolves the ambiguity ok releases match is exact, not substring ok shipped version is only promoted, existing app not created ok fresh account creates, ships, promotes to edge, enables ok failing promote stops the script ok ship is retried while uploads are rate limited all passed hack/fonts_test.sh fonts_test: ok === test === go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -count=1 ./... receipt: test step 8.406s against a 60s target (the gate's other steps are not in this figure) receipt: 16 packages ran, 0 cached, 6 without tests, 0 failed receipt: slow package 6.401s amadan.net/oficina/base/internal/webtest receipt: slow package 661ms amadan.net/oficina/base/internal/issuer receipt: slow package 595ms amadan.net/oficina/base/internal/operations receipt: slow package 206ms amadan.net/oficina/base/internal/consumer receipt: slow package 170ms amadan.net/oficina/base/internal/web receipt: slow test 1.52s amadan.net/oficina/base/internal/webtest TestHomeDoesNotWaitOnAStalledSnapshot receipt: slow test 1.08s amadan.net/oficina/base/internal/webtest TestAskZoneIsToldOnce receipt: slow test 520ms amadan.net/oficina/base/internal/operations TestOperationsRefusals receipt: slow test 380ms amadan.net/oficina/base/internal/issuer TestAuthorizeSignsForInstalledApp receipt: slow test 250ms amadan.net/oficina/base/internal/issuer TestAuthorizeRefusals === native === strings: copy review's strings.json is not here (git-ignored); its comparison skipped strings: 119 in the catalog, 116 used worktree-lib_test: ok
diff --git a/internal/browsertest/paste_test.go b/internal/browsertest/paste_test.go| index 56b2ada..4aa9e01 100644 |
| --- a/internal/browsertest/paste_test.go |
| +++ b/internal/browsertest/paste_test.go |
| @@ -6,6 +6,7 @@ import ( |
| "encoding/json" |
| "os" |
| "strconv" |
| + "strings" |
| "testing" |
| "time" |
| @@ -86,32 +87,26 @@ func TestAskPasteMarkdown(t *testing.T) { |
| func TestAskPasteIsBounded(t *testing.T) { |
| rig, _ := askBase(t) |
| openPanel(t, rig) |
| - // The conversion alone: the field's own insert of 16,000 characters |
| - // is the browser's, timed apart. |
| + // The whole paste, the field's own insert included. |
| got := harness.Evaluate[string](rig, `(() => { |
| const f = document.querySelector("#ask-text"); |
| - const insert = document.execCommand; |
| - let typed = null; |
| - document.execCommand = (command, ui, text) => { typed = text; return true; }; |
| const run = (html) => { |
| - f.focus(); typed = null; |
| + f.focus(); f.value = ""; |
| const data = new DataTransfer(); |
| data.setData("text/html", html); |
| const e = new ClipboardEvent("paste", { clipboardData: data, bubbles: true, cancelable: true }); |
| const t0 = performance.now(); |
| f.dispatchEvent(e); |
| - return { ms: performance.now() - t0, value: typed || "" }; |
| + return { ms: performance.now() - t0, value: f.value }; |
| }; |
| const out = []; |
| - try { |
| + { |
| const items = run("<ul>" + "<li><b>item</b></li>".repeat(50000) + "</ul>"); |
| if (items.ms > 200) out.push("50,000 items took " + Math.round(items.ms) + " ms"); |
| if (!items.value.startsWith("- **item**\n- **item**") || items.value.length > 16100) out.push("items pasted " + items.value.length + " characters"); |
| const deep = run("<div><b>".repeat(5000) + "deep" + "</b></div>".repeat(5000)); |
| if (deep.ms > 500) out.push("5,000 levels took " + Math.round(deep.ms) + " ms"); |
| if (deep.value !== "**deep**") out.push("deep pasted " + JSON.stringify(deep.value.slice(0, 40))); |
| - } finally { |
| - document.execCommand = insert; |
| } |
| return out.join("; "); |
| })()`) |
| @@ -120,6 +115,48 @@ func TestAskPasteIsBounded(t *testing.T) { |
| } |
| } |
| +// Fable's R1: the whole paste of about 4,000 lines, the field's own |
| +// insert included (nothing stubbed), is quick, and the field holds all of |
| +// it, with the panel's listeners told. |
| +func TestAskLongPasteIsQuick(t *testing.T) { |
| + rig, _ := askBase(t) |
| + openPanel(t, rig) |
| + var r struct { |
| + MS float64 `json:"ms"` |
| + Value string `json:"value"` |
| + Input bool `json:"input"` |
| + } |
| + raw := harness.Evaluate[string](rig, `(() => { |
| + const f = document.querySelector("#ask-text"); |
| + f.focus(); f.value = ""; |
| + let input = false; |
| + f.addEventListener("input", () => { input = true; }, { once: true }); |
| + const data = new DataTransfer(); |
| + data.setData("text/html", "<p><b>Rows</b></p>" + Array.from({ length: 4000 }, (_, i) => "<div>r" + (i % 10) + "</div>").join("")); |
| + const e = new ClipboardEvent("paste", { clipboardData: data, bubbles: true, cancelable: true }); |
| + const t0 = performance.now(); |
| + f.dispatchEvent(e); |
| + return JSON.stringify({ ms: performance.now() - t0, value: f.value, input }); |
| + })()`) |
| + if err := json.Unmarshal([]byte(raw), &r); err != nil { |
| + t.Fatal(err) |
| + } |
| + var want strings.Builder |
| + want.WriteString("**Rows**\n") |
| + for i := range 4000 { |
| + want.WriteString("\nr" + strconv.Itoa(i%10)) |
| + } |
| + if r.Value != want.String() { |
| + t.Errorf("pasted %d characters, want %d", len(r.Value), want.Len()) |
| + } |
| + if r.MS > 500 { |
| + t.Errorf("4,000 lines took %.0f ms", r.MS) |
| + } |
| + if !r.Input { |
| + t.Error("no input event: the panel's listeners weren't told") |
| + } |
| +} |
| + |
| // The person's own messages are drawn in the Assistant's little Markdown, |
| // with emphasis only at word boundaries, by the script and the server |
| // alike (internal/web/testdata/person.json, which the server's and the |
diff --git a/internal/browsertest/testdata/paste.json b/internal/browsertest/testdata/paste.json| index d7f7e49..080abda 100644 |
| --- a/internal/browsertest/testdata/paste.json |
| +++ b/internal/browsertest/testdata/paste.json |
| @@ -68,5 +68,25 @@ |
| "name": "Fable's S2: Xcode's RTF (bold keywords in Menlo) is code (the app only: the web has no RTF)", |
| "rtf": "{\\rtf1\\ansi\\ansicpg1252\\cocoartf2822\n\\cocoatextscaling0\\cocoaplatform0{\\fonttbl\\f0\\fnil\\fcharset0 Menlo-Bold;\\f1\\fnil\\fcharset0 Menlo-Regular;}\n{\\colortbl;\\red255\\green255\\blue255;\\red155\\green35\\blue147;}\n\\pard\\tx593\\pardeftab593\\pardirnatural\\partightenfactor0\n\n\\f0\\b\\fs24 \\cf2 func\n\\f1\\b0 \\cf0 greet() \\{\\\n \n\\f0\\b \\cf2 let\n\\f1\\b0 \\cf0 x = 2*3\\\n \n\\f0\\b \\cf2 return\n\\f1\\b0 \\cf0 x\\\n\\}}", |
| "markdown": null |
| + }, |
| + { |
| + "name": "Fable's R2: a <pre> in prose keeps its indentation, as a fenced block", |
| + "html": "<p><b>Do this:</b></p><pre> x = 1\n y = 2</pre>", |
| + "markdown": "**Do this:**\n\n```\n x = 1\n y = 2\n```" |
| + }, |
| + { |
| + "name": "A <pre> keeps its blank lines and backticks; the line break after <pre> goes", |
| + "html": "<p>Then <b>restart</b> the service and check the log for errors:</p><pre>\nsystemctl restart base\n\n journalctl -u base # ```tail```</pre><p>That's all.</p>", |
| + "markdown": "Then **restart** the service and check the log for errors:\n\n````\nsystemctl restart base\n\n journalctl -u base # ```tail```\n````\n\nThat's all." |
| + }, |
| + { |
| + "name": "Fable's R3: past 32 levels a block is still a line and a cell a space; a button is still skipped", |
| + "html": "<p><b>Thread</b></p><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><p>one</p><p>two</p><div>three</div><table><tr><td>a</td><td>b</td></tr></table><button>Btn</button>tail</div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div>", |
| + "markdown": "**Thread**\n\none\ntwo\nthree\na b\ntail" |
| + }, |
| + { |
| + "name": "font-weight with !important is bold", |
| + "html": "<span style=\"font-weight: bold !important\">Bold</span> words", |
| + "markdown": "**Bold** words" |
| } |
| ] |
diff --git a/internal/look/static/ask.js b/internal/look/static/ask.js| index 919b90c..141ef04 100644 |
| --- a/internal/look/static/ask.js |
| +++ b/internal/look/static/ask.js |
| @@ -1684,11 +1684,15 @@ function start(root) { |
| typeIn(md); |
| }); |
| // typeIn puts text in place of the field's selection as typing would, |
| - // so Undo takes it back; where insertText isn't offered, at the cursor |
| - // without undo. |
| + // so Undo takes it back. A text of many lines goes in at once instead |
| + // (insertText grows with the square of the lines: 4,000 take seconds), |
| + // without Undo, and so does any where insertText isn't offered; the |
| + // field's limit holds either way. |
| function typeIn(text) { |
| - if (document.execCommand("insertText", false, text)) return; |
| - field.setRangeText(text, field.selectionStart, field.selectionEnd, "end"); |
| + if (text.split("\n", 301).length <= 300 && document.execCommand("insertText", false, text)) return; |
| + const start = field.selectionStart, end = field.selectionEnd; |
| + const room = field.maxLength >= 0 ? field.maxLength - (field.value.length - (end - start)) : text.length; |
| + field.setRangeText(text.slice(0, Math.max(0, room)), start, end, "end"); |
| field.dispatchEvent(new Event("input", { bubbles: true })); |
| } |
| @@ -1711,11 +1715,16 @@ function start(root) { |
| const skip = new Set(["SCRIPT", "STYLE", "HEAD", "TITLE", "TEMPLATE", "NOSCRIPT", "IFRAME", "OBJECT", "EMBED", "SVG", "MATH", "CANVAS", "VIDEO", "AUDIO", "PICTURE", "IMG", "BUTTON", "SELECT", "INPUT", "TEXTAREA"]); |
| const raw = new Set(["SCRIPT", "STYLE", "TEXTAREA", "TITLE", "TEMPLATE", "NOSCRIPT", "IFRAME"]); |
| const lines = new Set(["DIV", "SECTION", "ARTICLE", "HEADER", "FOOTER", "MAIN", "NAV", "ASIDE", "BLOCKQUOTE", "FIGURE", "FIGCAPTION", "ADDRESS", "CENTER", "DETAILS", "SUMMARY", "FORM", "FIELDSET", "TABLE", "THEAD", "TBODY", "TFOOT", "TR", "CAPTION", "DL", "DT", "DD", "HR"]); |
| - const code = new Set(["PRE", "CODE", "TT", "SAMP", "KBD"]); |
| + const code = new Set(["CODE", "TT", "SAMP", "KBD"]); |
| + const blocks = new Set([...lines, "P", "LI", "UL", "OL", "H1", "H2", "H3", "H4", "H5", "H6", "PRE"]); |
| const monoFont = /monospace|menlo|monaco|consolas|courier|sf ?mono|fira (code|mono)|jetbrains|source code|cascadia|ubuntu mono|dejavu sans mono|roboto mono|plex mono|andale mono|lucida console/i; |
| // The output, built once: its pieces, its length, and how many line |
| // breaks it ends with. |
| const out = []; |
| + // A <pre>'s text, kept out of the clean-up at the end: its spaces and |
| + // blank lines are the code's. Each stands in the output as NUL, its |
| + // number, NUL (the parser never leaves a NUL in text). |
| + const verbatim = []; |
| let length = 0, breaks = 0; |
| const put = (s) => { |
| if (!s) return; |
| @@ -1749,7 +1758,7 @@ function start(root) { |
| // and the like). |
| const declared = (style, name) => { |
| const m = new RegExp("(?:^|;)\\s*" + name + "\\s*:\\s*([^;]*)", "i").exec(style); |
| - return m ? m[1].trim() : null; |
| + return m ? m[1].replace(/!\s*important\s*$/i, "").trim() : null; |
| }; |
| const walk = (node, st, depth) => { |
| if (length > maxOut) return; |
| @@ -1757,28 +1766,26 @@ function start(root) { |
| const counted = node.data.replace(/\s+/g, "").length; |
| chars += counted; |
| if (st.mono) mono += counted; |
| - let t = st.pre ? node.data : node.data.replace(/[ \t\n\r\f\u00a0]+/g, " "); |
| + let t = node.data.replace(/[ \t\n\r\f\u00a0]+/g, " "); |
| // One space between words, whichever side of a tag it was. |
| - if (!st.pre && t[0] === " " && runs.length && runs[runs.length - 1].text.endsWith(" ")) t = t.slice(1); |
| - if (st.pre) { |
| - const parts = t.split(/\r\n?|\n/); |
| - parts.forEach((part, i) => { |
| - if (i) { flush(); put("\n"); open = false; } |
| - if (part) runs.push({ text: part, bold: false, italic: false, href: "" }); |
| - }); |
| - } else if (t) runs.push({ text: t, bold: st.heading ? false : st.bold, italic: st.heading ? false : st.italic, href: st.href }); |
| + if (t[0] === " " && runs.length && runs[runs.length - 1].text.endsWith(" ")) t = t.slice(1); |
| + if (t) runs.push({ text: t, bold: st.heading ? false : st.bold, italic: st.heading ? false : st.italic, href: st.href }); |
| return; |
| } |
| if (node.nodeType !== 1) return; |
| const tag = node.tagName.toUpperCase(); |
| if (tag === "BR") return lineBreak(); |
| - // Too deep: its text and line breaks only, as the app's tree has it. |
| + if (skip.has(tag)) return; |
| + // Too deep: its text, a block a line of its own and a cell a space, |
| + // as the app's tree has it. |
| if (depth >= maxDepth) { |
| - if (raw.has(tag)) return; |
| + const block = blocks.has(tag); |
| + if (block) ensure(1); |
| for (const c of node.childNodes) walk(c, st, depth); |
| + if (block) ensure(1); |
| + if (tag === "TD" || tag === "TH") runs.push({ text: " ", bold: false, italic: false, href: "" }); |
| return; |
| } |
| - if (skip.has(tag)) return; |
| const next = { ...st }; |
| if (tag === "B" || tag === "STRONG") next.bold = true; |
| if (tag === "I" || tag === "EM") next.italic = true; |
| @@ -1846,9 +1853,25 @@ function start(root) { |
| return; |
| } |
| if (tag === "PRE") { |
| + // Verbatim, as a fenced code block longer than any run of |
| + // backticks in it. |
| + let code = ""; |
| + const read = (n) => { |
| + if (n.nodeType === 3) code += n.data; |
| + else if (n.nodeType === 1 && n.tagName.toUpperCase() === "BR") code += "\n"; |
| + else if (n.nodeType === 1 && !skip.has(n.tagName.toUpperCase())) for (const c of n.childNodes) read(c); |
| + }; |
| + read(node); |
| + code = code.replace(/\r\n?/g, "\n").replace(/\n$/, ""); |
| + const counted = code.replace(/\s+/g, "").length; |
| + chars += counted; |
| + mono += counted; |
| + if (!code.trim()) return; |
| + const fence = "`".repeat(Math.max(3, ...(code.match(/`+/g) || []).map((r) => r.length + 1))); |
| ensure(2); |
| - next.pre = true; |
| - children(); |
| + put(fence + "\n\0" + verbatim.length + "\0\n" + fence); |
| + verbatim.push(code); |
| + formatted = true; |
| ensure(2); |
| return; |
| } |
| @@ -1896,10 +1919,11 @@ function start(root) { |
| return s.replace(/ +$/, ""); |
| }; |
| // The body is depth -1: 32 levels under it are kept, as in the app. |
| - walk(doc.body, { bold: false, italic: false, href: "", heading: false, pre: false, mono: false }, -1); |
| + walk(doc.body, { bold: false, italic: false, href: "", heading: false, mono: false }, -1); |
| flush(); |
| if (!formatted || mono * 2 > chars) return null; |
| - return out.join("").split("\n").map((l) => l.replace(/[ \t]+$/, "")).join("\n").replace(/\n{3,}/g, "\n\n").replace(/^\n+|\n+$/g, ""); |
| + return out.join("").split("\n").map((l) => l.replace(/[ \t]+$/, "")).join("\n").replace(/\n{3,}/g, "\n\n").replace(/^\n+|\n+$/g, "") |
| + .replace(/\0(\d+)\0/g, (_, n) => verbatim[Number(n)]); |
| } |
| cancel.addEventListener("submit", (e) => { |
diff --git a/native/apple/Sources/BaseKit/Ask/PasteMarkdown.swift b/native/apple/Sources/BaseKit/Ask/PasteMarkdown.swift| index ac060fe..cd2cdab 100644 |
| --- a/native/apple/Sources/BaseKit/Ask/PasteMarkdown.swift |
| +++ b/native/apple/Sources/BaseKit/Ask/PasteMarkdown.swift |
| @@ -24,7 +24,9 @@ enum PasteMarkdown { |
| static func fromHTML(_ html: String) -> String? { |
| guard html.utf16.count <= maxHTML else { return nil } |
| var walker = Walker() |
| - return walker.markdown(HTMLTree.parse(html)) |
| + // (A NUL marks a <pre>'s place in the walk's output, as a page's |
| + // parser never leaves one in text.) |
| + return walker.markdown(HTMLTree.parse(html.replacingOccurrences(of: "\0", with: ""))) |
| } |
| /// A clipboard's HTML bytes as text: UTF-8, or UTF-16 with its mark. |
| @@ -64,12 +66,16 @@ struct HTMLTree: Equatable { |
| let s = Array(html.unicodeScalars) |
| var stack = [HTMLTree(tag: "body")] |
| // Elements opened past the depth cap: not in the tree (their text |
| - // and line breaks go to the deepest one that is), but their end |
| - // tags still match them. |
| - var dropped: [String] = [] |
| + // and line breaks go to the deepest one that is; a block is a line |
| + // of its own, a cell a space, and what the walk skips is skipped), |
| + // but their end tags still match them. |
| + enum Drop { case inline, block, cell, skip } |
| + var dropped: [(name: String, kind: Drop)] = [] |
| + var skipping = 0 |
| + func mark(_ tag: String) { stack[stack.count - 1].children.append(HTMLTree(tag: tag)) } |
| var at = 0 |
| func appendText(_ t: String) { |
| - guard !t.isEmpty else { return } |
| + guard !t.isEmpty, skipping == 0 else { return } |
| stack[stack.count - 1].children.append(HTMLTree(text: MarkdownEntities.link(t))) |
| } |
| func close(_ index: Int) { |
| @@ -135,7 +141,14 @@ struct HTMLTree: Equatable { |
| at = min(s.count, cursor + 1) |
| appendText(text); text = "" |
| if closing { |
| - if dropped.last == name { dropped.removeLast() } else if let index = open(name), index > 0 { close(index) } |
| + if dropped.last?.name == name { |
| + switch dropped.removeLast().kind { |
| + case .skip: skipping -= 1 |
| + case .block: mark(Walker.line) |
| + case .cell: mark(Walker.cell) |
| + case .inline: break |
| + } |
| + } else if let index = open(name), index > 0 { close(index) } |
| continue |
| } |
| if closesP.contains(name), let p = open("p"), !(stack[(p + 1)...].contains { $0.tag == "li" || $0.tag == "td" || $0.tag == "th" }) { close(p) } |
| @@ -157,10 +170,15 @@ struct HTMLTree: Equatable { |
| at += 1 |
| continue |
| } |
| - if void.contains(name) || selfClosing { |
| + if skipping > 0 { |
| + if !void.contains(name), !selfClosing { dropped.append((name, .skip)); skipping += 1 } |
| + } else if void.contains(name) || selfClosing { |
| stack[stack.count - 1].children.append(element) |
| } else if stack.count > PasteMarkdown.maxDepth { |
| - dropped.append(name) |
| + let kind: Drop = Walker.skip.contains(name) ? .skip : Walker.blocks.contains(name) ? .block : name == "td" || name == "th" ? .cell : .inline |
| + if kind == .skip { skipping += 1 } |
| + if kind == .block { mark(Walker.line) } |
| + dropped.append((name, kind)) |
| } else { |
| stack.append(element) |
| } |
| @@ -197,7 +215,7 @@ struct HTMLTree: Equatable { |
| } |
| if runsFrom < NSMaxRange(content) { |
| text.enumerateAttributes(in: NSRange(location: runsFrom, length: NSMaxRange(content) - runsFrom)) { attributes, run, _ in |
| - var node = HTMLTree(text: string.substring(with: run)) |
| + var node = HTMLTree(text: string.substring(with: run).replacingOccurrences(of: "\0", with: "")) |
| if let link = attributes[.link] { |
| let href = (link as? URL)?.absoluteString ?? (link as? String) ?? "" |
| node = HTMLTree(tag: "a", attributes: ["href": href], children: [node]) |
| @@ -250,8 +268,12 @@ struct HTMLTree: Equatable { |
| /// ask.js's pasteMarkdown walk, line for line. |
| private struct Walker { |
| struct Run { var text: String; var bold: Bool; var italic: Bool; var href: String } |
| - struct Style { var bold = false, italic = false, href = "", heading = false, pre = false, mono = false } |
| - static let code: Set<String> = ["pre", "code", "tt", "samp", "kbd"] |
| + struct Style { var bold = false, italic = false, href = "", heading = false, mono = false } |
| + static let code: Set<String> = ["code", "tt", "samp", "kbd"] |
| + static let blocks = lines.union(["p", "li", "ul", "ol", "h1", "h2", "h3", "h4", "h5", "h6", "pre"]) |
| + /// Marks HTMLTree.parse leaves for blocks and cells past the depth |
| + /// cap (no tag a page can write starts with "_"). |
| + static let line = "_line", cell = "_cell" |
| static let raw: Set<String> = ["script", "style", "textarea", "title", "template", "noscript", "iframe"] |
| static let monoFont = try! NSRegularExpression(pattern: "monospace|menlo|monaco|consolas|courier|sf ?mono|fira (code|mono)|jetbrains|source code|cascadia|ubuntu mono|dejavu sans mono|roboto mono|plex mono|andale mono|lucida console", options: .caseInsensitive) |
| final class List { let ordered: Bool; var n: Int; let indent: String; var inner: String |
| @@ -269,6 +291,10 @@ private struct Walker { |
| var lists: [List] = [] |
| /// Characters of text (not spaces), and how many of them are code's. |
| var chars = 0, mono = 0 |
| + /// Each <pre>'s text, standing in the output as NUL, its number, NUL |
| + /// until the clean-up is done: its spaces and blank lines are the |
| + /// code's. |
| + var verbatim: [String] = [] |
| mutating func markdown(_ tree: HTMLTree) -> String? { |
| walk(tree, Style(), depth: -1) |
| @@ -282,6 +308,7 @@ private struct Walker { |
| var result = trimmed.replacingOccurrences(of: #"\n{3,}"#, with: "\n\n", options: .regularExpression) |
| while result.first == "\n" { result.removeFirst() } |
| while result.last == "\n" { result.removeLast() } |
| + for (n, code) in verbatim.enumerated().reversed() { result = result.replacingOccurrences(of: "\0\(n)\0", with: code) } |
| return result |
| } |
| @@ -313,18 +340,10 @@ private struct Walker { |
| let counted = node.text.unicodeScalars.reduce(0) { $0 + ($1.properties.isWhitespace ? 0 : $1.utf16.count) } |
| chars += counted |
| if st.mono { mono += counted } |
| - if st.pre { |
| - let parts = node.text.replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n").components(separatedBy: "\n") |
| - for (i, part) in parts.enumerated() { |
| - if i > 0 { flush(); out += "\n"; open = false } |
| - if !part.isEmpty { runs.append(Run(text: part, bold: false, italic: false, href: "")) } |
| - } |
| - } else { |
| - var t = node.text.replacingOccurrences(of: "[ \\t\\n\\r\\f\u{00a0}]+", with: " ", options: .regularExpression) |
| - // One space between words, whichever side of a tag it was. |
| - if t.first == " ", runs.last?.text.last == " " { t.removeFirst() } |
| - if !t.isEmpty { runs.append(Run(text: t, bold: st.heading ? false : st.bold, italic: st.heading ? false : st.italic, href: st.href)) } |
| - } |
| + var t = node.text.replacingOccurrences(of: "[ \\t\\n\\r\\f\u{00a0}]+", with: " ", options: .regularExpression) |
| + // One space between words, whichever side of a tag it was. |
| + if t.first == " ", runs.last?.text.last == " " { t.removeFirst() } |
| + if !t.isEmpty { runs.append(Run(text: t, bold: st.heading ? false : st.bold, italic: st.heading ? false : st.italic, href: st.href)) } |
| return |
| } |
| let tag = node.tag |
| @@ -334,7 +353,9 @@ private struct Walker { |
| return |
| } |
| // (The body is depth -1; its children 0. HTMLTree.parse never makes |
| - // anything deeper than the cap.) |
| + // anything deeper than the cap, and marks what it flattened.) |
| + if tag == Self.line { ensure(1); return } |
| + if tag == Self.cell { runs.append(Run(text: " ", bold: false, italic: false, href: "")); return } |
| if Self.skip.contains(tag) { return } |
| var next = st |
| if tag == "b" || tag == "strong" { next.bold = true } |
| @@ -404,9 +425,28 @@ private struct Walker { |
| return |
| } |
| if tag == "pre" { |
| + // Verbatim, as a fenced code block longer than any run of |
| + // backticks in it. |
| + var code = "" |
| + func read(_ n: HTMLTree) { |
| + if n.tag.isEmpty { code += n.text } else if n.tag == "br" { code += "\n" } else if !Self.skip.contains(n.tag) { n.children.forEach(read) } |
| + } |
| + read(node) |
| + code = code.replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n") |
| + // A page drops the line break just after <pre>. |
| + if code.hasPrefix("\n") { code.removeFirst() } |
| + if code.hasSuffix("\n") { code.removeLast() } |
| + let counted = code.unicodeScalars.reduce(0) { $0 + ($1.properties.isWhitespace ? 0 : $1.utf16.count) } |
| + chars += counted |
| + mono += counted |
| + guard !code.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return } |
| + var longest = 0, run = 0 |
| + for c in code { run = c == "`" ? run + 1 : 0; longest = max(longest, run) } |
| + let fence = String(repeating: "`", count: max(3, longest + 1)) |
| ensure(2) |
| - next.pre = true |
| - children(&self) |
| + out += fence + "\n\0\(verbatim.count)\0\n" + fence |
| + verbatim.append(code) |
| + formatted = true |
| ensure(2) |
| return |
| } |
| @@ -463,7 +503,7 @@ private struct Walker { |
| guard let re = try? NSRegularExpression(pattern: "(?:^|;)\\s*\(name)\\s*:\\s*([^;]*)", options: .caseInsensitive), |
| let m = re.firstMatch(in: style, range: NSRange(style.startIndex..., in: style)), |
| let r = Range(m.range(at: 1), in: style) else { return nil } |
| - return style[r].trimmingCharacters(in: .whitespaces) |
| + return style[r].replacingOccurrences(of: #"!\s*important\s*$"#, with: "", options: [.regularExpression, .caseInsensitive]).trimmingCharacters(in: .whitespaces) |
| } |
| /// An href as a page reads it (spaces at its ends go, tabs and line |