Commit 76ed01cb1d
Verified · cmc
Layout: unified · split
.qlty/.gitignore added +7
| @@ -0,0 +1,7 @@ | ||
| 1 | * | |
| 2 | !configs | |
| 3 | !configs/** | |
| 4 | !hooks | |
| 5 | !hooks/** | |
| 6 | !qlty.toml | |
| 7 | !.gitignore | |
.qlty/qlty.toml added +44
| @@ -0,0 +1,44 @@ | ||
| 1 | config_version = "0" | |
| 2 | ||
| 3 | exclude_patterns = [ | |
| 4 | "**/vendor/**", | |
| 5 | "**/node_modules/**", | |
| 6 | "**/testdata/**", | |
| 7 | "**/dist/**", | |
| 8 | "**/.build/**", | |
| 9 | "**/build/**", | |
| 10 | "**/*.min.*", | |
| 11 | "**/generated/**", | |
| 12 | ".claude/**", | |
| 13 | "**/Pods/**", | |
| 14 | ] | |
| 15 | ||
| 16 | test_patterns = [ | |
| 17 | "**/test/**", | |
| 18 | "**/tests/**", | |
| 19 | "**/Tests/**", | |
| 20 | "**/*_test.*", | |
| 21 | "**/test_*.*", | |
| 22 | "**/*.test.*", | |
| 23 | "**/*Tests.swift", | |
| 24 | "e2e/**", | |
| 25 | ] | |
| 26 | ||
| 27 | [[source]] | |
| 28 | name = "default" | |
| 29 | default = true | |
| 30 | ||
| 31 | [[plugin]] | |
| 32 | name = "osv-scanner" | |
| 33 | ||
| 34 | [[plugin]] | |
| 35 | name = "trufflehog" | |
| 36 | ||
| 37 | # Early returns are guard clauses, which keep the happy path unindented. | |
| 38 | [smells.return_statements] | |
| 39 | enabled = false | |
| 40 | ||
| 41 | # Total file complexity is the sum of its functions, which function_complexity | |
| 42 | # already checks. | |
| 43 | [smells.file_complexity] | |
| 44 | enabled = false | |
Sources/OrgSwift/AST/OrgHTMLTreeRenderer.swift +14 −8
| @@ -201,20 +201,26 @@ public struct OrgHTMLTreeRenderer { | ||
| 201 | 201 | let isHeader = headerCount > 0 && index < headerCount |
| 202 | 202 | if isHeader, !wroteHeader { html += "<thead>\n"; wroteHeader = true } |
| 203 | 203 | if !isHeader, !inBody { html += "<tbody>\n"; inBody = true } |
| 204 | html += "<tr>\n" | |
| 205 | for (column, cell) in cells.enumerated() { | |
| 206 | let tag = isHeader ? "th" : "td" | |
| 207 | let alignment = column < table.alignments.count ? table.alignments[column] : nil | |
| 208 | let style = alignment.map { #" style="text-align: \#($0.rawValue);""# } ?? "" | |
| 209 | html += "<\(tag)\(style)>" + renderInline(cell, ¬es) + "</\(tag)>\n" | |
| 210 | } | |
| 211 | html += "</tr>\n" | |
| 204 | html += renderRow(cells, header: isHeader, alignments: table.alignments, ¬es) | |
| 212 | 205 | } |
| 213 | 206 | } |
| 214 | 207 | if inBody { html += "</tbody>\n" } |
| 215 | 208 | return html + "</table>\n" |
| 216 | 209 | } |
| 217 | 210 | |
| 211 | private func renderRow( | |
| 212 | _ cells: [[OrgObject]], header: Bool, alignments: [OrgAlignment?], _ notes: inout OrgFootnotes | |
| 213 | ) -> String { | |
| 214 | var html = "<tr>\n" | |
| 215 | for (column, cell) in cells.enumerated() { | |
| 216 | let tag = header ? "th" : "td" | |
| 217 | let alignment = column < alignments.count ? alignments[column] : nil | |
| 218 | let style = alignment.map { #" style="text-align: \#($0.rawValue);""# } ?? "" | |
| 219 | html += "<\(tag)\(style)>" + renderInline(cell, ¬es) + "</\(tag)>\n" | |
| 220 | } | |
| 221 | return html + "</tr>\n" | |
| 222 | } | |
| 223 | ||
| 218 | 224 | /// The `<img>` for a figure, or nil when the source cannot be resolved to a safe URL — |
| 219 | 225 | /// in which case the caller falls back to text rather than pointing at something unsafe. |
| 220 | 226 | private func imageTag(_ figure: OrgFigure, caption: [OrgObject]?) -> String? { |
Sources/OrgSwift/AST/OrgInlineParser.swift +74 −77
| @@ -39,100 +39,97 @@ extension OrgParser { | ||
| 39 | 39 | let lastEnd = lastEnvironmentEnd(text) |
| 40 | 40 | // A closer that is missing once is missing for every later opener of its kind. |
| 41 | 41 | var missing: Set<String> = [] |
| 42 | func noteMissing<T>(_ closer: String) -> T? { | |
| 43 | missing.insert(closer) | |
| 44 | return nil | |
| 45 | } | |
| 46 | 42 | |
| 47 | 43 | func flushPlain() { |
| 48 | 44 | if !plain.isEmpty { objects.append(.text(plain)); plain = "" } |
| 49 | 45 | } |
| 50 | 46 | |
| 51 | 47 | while i < chars.count { |
| 52 | // Bracket links: [[target]] or [[target][description]] | |
| 53 | if chars[i] == "[", i + 1 < chars.count, chars[i + 1] == "[", | |
| 54 | !missing.contains("]]"), let link = scanLink(chars, from: i) ?? noteMissing("]]") { | |
| 55 | flushPlain() | |
| 56 | objects.append(link.object) | |
| 57 | i = link.next | |
| 58 | continue | |
| 59 | } | |
| 60 | ||
| 61 | // LaTeX fragments: $…$, $$…$$, \(…\), \[…\], \begin{…}…\end{…} | |
| 62 | if chars[i] == "$" || chars[i] == "\\", let math = scanMath(chars, from: i, lastEnd: lastEnd, missing: &missing) { | |
| 63 | if case .text(let text) = math.object { | |
| 64 | plain += text | |
| 65 | } else { | |
| 66 | flushPlain() | |
| 67 | objects.append(math.object) | |
| 68 | } | |
| 69 | i = math.next | |
| 48 | guard let hit = scanObject(chars, at: i, lastEnd: lastEnd, missing: &missing) else { | |
| 49 | plain.append(chars[i]) | |
| 50 | i += 1 | |
| 70 | 51 | continue |
| 71 | 52 | } |
| 72 | ||
| 73 | // Footnote reference: [fn:label] or [fn:label:inline] | |
| 74 | if chars[i] == "[", let note = scanFootnote(chars, from: i) { | |
| 53 | if hit.mergesText, case .text(let text) = hit.object { | |
| 54 | plain += text | |
| 55 | } else { | |
| 75 | 56 | flushPlain() |
| 76 | objects.append(note.object) | |
| 77 | i = note.next | |
| 78 | continue | |
| 57 | objects.append(hit.object) | |
| 79 | 58 | } |
| 59 | i = hit.next | |
| 60 | } | |
| 61 | flushPlain() | |
| 62 | return objects | |
| 63 | } | |
| 80 | 64 | |
| 81 | // Timestamps: <2024-01-15 Mon 10:30> or [2024-01-15 Mon] | |
| 82 | if chars[i] == "<" || chars[i] == "[", let stamp = scanTimestamp(chars, from: i) { | |
| 83 | flushPlain() | |
| 84 | objects.append(stamp.object) | |
| 85 | i = stamp.next | |
| 86 | continue | |
| 87 | } | |
| 65 | /// An inline object found at a position, and where scanning resumes. | |
| 66 | private struct InlineHit { | |
| 67 | let object: OrgObject | |
| 68 | let next: Int | |
| 69 | /// Plain text from a scanner (an unclosed LaTeX opener) that joins the | |
| 70 | /// surrounding text run. | |
| 71 | var mergesText = false | |
| 72 | } | |
| 88 | 73 | |
| 89 | // Bare URL autolink. | |
| 90 | if chars[i] == "h", let url = scanBareURL(chars, from: i) { | |
| 91 | flushPlain() | |
| 92 | objects.append(url.object) | |
| 93 | i = url.next | |
| 94 | continue | |
| 95 | } | |
| 74 | /// The first inline object starting at `i`, trying each construct in priority order. | |
| 75 | private static func scanObject( | |
| 76 | _ chars: [Character], at i: Int, lastEnd: (offset: Int, name: String)?, missing: inout Set<String> | |
| 77 | ) -> InlineHit? { | |
| 78 | // Bracket links: [[target]] or [[target][description]] | |
| 79 | if chars[i] == "[", i + 1 < chars.count, chars[i + 1] == "[", !missing.contains("]]") { | |
| 80 | if let link = scanLink(chars, from: i) { return InlineHit(object: link.object, next: link.next) } | |
| 81 | missing.insert("]]") | |
| 82 | } | |
| 96 | 83 | |
| 97 | // Bare email autolink, at a word boundary so `a.b@c.d` is not matched mid-token. | |
| 98 | if isWordCharacter(chars[i]), i == 0 || !isEmailBoundaryCharacter(chars[i - 1]), | |
| 99 | let email = scanEmail(chars, from: i) { | |
| 100 | flushPlain() | |
| 101 | objects.append(email.object) | |
| 102 | i = email.next | |
| 103 | continue | |
| 104 | } | |
| 84 | // LaTeX fragments: $…$, $$…$$, \(…\), \[…\], \begin{…}…\end{…} | |
| 85 | if chars[i] == "$" || chars[i] == "\\", let math = scanMath(chars, from: i, lastEnd: lastEnd, missing: &missing) { | |
| 86 | return InlineHit(object: math.object, next: math.next, mergesText: true) | |
| 87 | } | |
| 105 | 88 | |
| 106 | // Emphasis: *bold* /italic/ _underline_ +strike+ =verbatim= ~code~ | |
| 107 | if let marker = emphasisMarker(chars[i]), boundaryBefore(chars, i), | |
| 108 | let span = scanEmphasis(chars, from: i, marker: chars[i]) { | |
| 109 | flushPlain() | |
| 110 | switch marker { | |
| 111 | case .bold: objects.append(.bold(parseInline(span.body))) | |
| 112 | case .italic: objects.append(.italic(parseInline(span.body))) | |
| 113 | case .underline: objects.append(.underline(parseInline(span.body))) | |
| 114 | case .strike: objects.append(.strikeThrough(parseInline(span.body))) | |
| 115 | case .verbatim: objects.append(.verbatim(span.body)) | |
| 116 | case .code: objects.append(.code(span.body)) | |
| 117 | } | |
| 118 | i = span.next | |
| 119 | continue | |
| 120 | } | |
| 89 | // Footnote reference: [fn:label] or [fn:label:inline] | |
| 90 | if chars[i] == "[", let note = scanFootnote(chars, from: i) { | |
| 91 | return InlineHit(object: note.object, next: note.next) | |
| 92 | } | |
| 121 | 93 | |
| 122 | // Superscript: x^2 or x^{group} | |
| 123 | if chars[i] == "^", i > 0, isWordCharacter(chars[i - 1]), | |
| 124 | let sup = scanSuperscript(chars, from: i) { | |
| 125 | flushPlain() | |
| 126 | objects.append(.superscript(parseInline(sup.body))) | |
| 127 | i = sup.next | |
| 128 | continue | |
| 129 | } | |
| 94 | // Timestamps: <2024-01-15 Mon 10:30> or [2024-01-15 Mon] | |
| 95 | if chars[i] == "<" || chars[i] == "[", let stamp = scanTimestamp(chars, from: i) { | |
| 96 | return InlineHit(object: stamp.object, next: stamp.next) | |
| 97 | } | |
| 130 | 98 | |
| 131 | plain.append(chars[i]) | |
| 132 | i += 1 | |
| 99 | // Bare URL autolink. | |
| 100 | if chars[i] == "h", let url = scanBareURL(chars, from: i) { | |
| 101 | return InlineHit(object: url.object, next: url.next) | |
| 102 | } | |
| 103 | ||
| 104 | // Bare email autolink, at a word boundary so `a.b@c.d` is not matched mid-token. | |
| 105 | if isWordCharacter(chars[i]), i == 0 || !isEmailBoundaryCharacter(chars[i - 1]), | |
| 106 | let email = scanEmail(chars, from: i) { | |
| 107 | return InlineHit(object: email.object, next: email.next) | |
| 108 | } | |
| 109 | ||
| 110 | // Emphasis: *bold* /italic/ _underline_ +strike+ =verbatim= ~code~ | |
| 111 | if let marker = emphasisMarker(chars[i]), boundaryBefore(chars, i), | |
| 112 | let span = scanEmphasis(chars, from: i, marker: chars[i]) { | |
| 113 | return InlineHit(object: emphasisObject(marker, span.body), next: span.next) | |
| 114 | } | |
| 115 | ||
| 116 | // Superscript: x^2 or x^{group} | |
| 117 | if chars[i] == "^", i > 0, isWordCharacter(chars[i - 1]), | |
| 118 | let sup = scanSuperscript(chars, from: i) { | |
| 119 | return InlineHit(object: .superscript(parseInline(sup.body)), next: sup.next) | |
| 120 | } | |
| 121 | return nil | |
| 122 | } | |
| 123 | ||
| 124 | private static func emphasisObject(_ marker: Emphasis, _ body: String) -> OrgObject { | |
| 125 | switch marker { | |
| 126 | case .bold: return .bold(parseInline(body)) | |
| 127 | case .italic: return .italic(parseInline(body)) | |
| 128 | case .underline: return .underline(parseInline(body)) | |
| 129 | case .strike: return .strikeThrough(parseInline(body)) | |
| 130 | case .verbatim: return .verbatim(body) | |
| 131 | case .code: return .code(body) | |
| 133 | 132 | } |
| 134 | flushPlain() | |
| 135 | return objects | |
| 136 | 133 | } |
| 137 | 134 | |
| 138 | 135 | // MARK: - Scanners |
Sources/OrgSwift/AST/OrgParser.swift +87 −78
| @@ -8,18 +8,34 @@ import Foundation | ||
| 8 | 8 | public enum OrgParser { |
| 9 | 9 | |
| 10 | 10 | public static func parse(_ source: String) -> OrgDocument { |
| 11 | var document = OrgDocument() | |
| 12 | 11 | let lines = source |
| 13 | 12 | .replacingOccurrences(of: "\r\n", with: "\n") |
| 14 | 13 | .replacingOccurrences(of: "\r", with: "\n") |
| 15 | 14 | .components(separatedBy: "\n") |
| 15 | var state = State(lines: lines) | |
| 16 | while state.index < lines.count { | |
| 17 | state.step() | |
| 18 | } | |
| 19 | return state.document | |
| 20 | } | |
| 21 | ||
| 22 | /// The document so far, the current line, and any affiliated keywords | |
| 23 | /// waiting for the block they apply to. | |
| 24 | private struct State { | |
| 25 | let lines: [String] | |
| 26 | let latexEnds: [String: [Int]] | |
| 27 | var document = OrgDocument() | |
| 16 | 28 | var index = 0 |
| 17 | let latexEnds = latexEndLines(lines) | |
| 18 | 29 | var pendingCaption: String? |
| 19 | 30 | var pendingName: String? |
| 20 | 31 | var pendingAttrs: [(key: String, value: String)] = [] |
| 21 | 32 | |
| 22 | func flushPending() { | |
| 33 | init(lines: [String]) { | |
| 34 | self.lines = lines | |
| 35 | self.latexEnds = OrgParser.latexEndLines(lines) | |
| 36 | } | |
| 37 | ||
| 38 | mutating func flushPending() { | |
| 23 | 39 | pendingCaption = nil |
| 24 | 40 | pendingName = nil |
| 25 | 41 | pendingAttrs = [] |
| @@ -27,11 +43,11 @@ public enum OrgParser { | ||
| 27 | 43 | |
| 28 | 44 | /// Append a block, wrapping it in `.captioned` when an affiliated `#+CAPTION:` or |
| 29 | 45 | /// `#+NAME:` precedes it — org's exporter turns that pairing into a `<figure>`. |
| 30 | func append(_ element: OrgElement) { | |
| 46 | mutating func append(_ element: OrgElement) { | |
| 31 | 47 | if pendingCaption != nil || pendingName != nil { |
| 32 | 48 | document.elements.append(.captioned( |
| 33 | 49 | name: pendingName, |
| 34 | caption: pendingCaption.map(parseInline), | |
| 50 | caption: pendingCaption.map(OrgParser.parseInline), | |
| 35 | 51 | content: element |
| 36 | 52 | )) |
| 37 | 53 | } else { |
| @@ -39,110 +55,106 @@ public enum OrgParser { | ||
| 39 | 55 | } |
| 40 | 56 | } |
| 41 | 57 | |
| 42 | while index < lines.count { | |
| 58 | mutating func step() { | |
| 43 | 59 | let line = lines[index] |
| 44 | 60 | let trimmed = line.trimmingCharacters(in: .whitespaces) |
| 45 | 61 | |
| 46 | if trimmed.isEmpty { index += 1; continue } | |
| 62 | if trimmed.isEmpty { index += 1; return } | |
| 47 | 63 | |
| 48 | 64 | // Comments. |
| 49 | if trimmed == "#" || trimmed.hasPrefix("# ") { index += 1; continue } | |
| 65 | if trimmed == "#" || trimmed.hasPrefix("# ") { index += 1; return } | |
| 50 | 66 | |
| 51 | 67 | // Property drawers are heading metadata; org's exporter drops them. |
| 52 | 68 | if trimmed == ":PROPERTIES:" { |
| 53 | index += 1 | |
| 54 | while index < lines.count, | |
| 55 | lines[index].trimmingCharacters(in: .whitespaces) != ":END:" { | |
| 56 | index += 1 | |
| 57 | } | |
| 58 | if index < lines.count { index += 1 } | |
| 59 | continue | |
| 69 | skipPropertyDrawer() | |
| 70 | return | |
| 60 | 71 | } |
| 61 | 72 | |
| 62 | 73 | // Affiliated keywords and document metadata. |
| 63 | 74 | if let directive = orgKeywordDirective(in: trimmed) { |
| 64 | switch directive.keyword { | |
| 65 | case "caption": pendingCaption = directive.value | |
| 66 | case "name": pendingName = directive.value | |
| 67 | case "attr_html": pendingAttrs = parseAttributes(directive.value) | |
| 68 | default: document.keywords.append((directive.keyword, directive.value)) | |
| 69 | } | |
| 75 | applyDirective(directive.keyword, directive.value) | |
| 70 | 76 | index += 1 |
| 71 | continue | |
| 77 | return | |
| 72 | 78 | } |
| 73 | 79 | |
| 74 | // Blocks: #+begin_… / #+end_… | |
| 75 | if trimmed.lowercased().hasPrefix("#+begin_") { | |
| 76 | let (element, next) = parseBlock(lines, from: index) | |
| 77 | if let element { append(element) } | |
| 78 | index = next | |
| 80 | if parseSingleLine(trimmed) || parseMultiLine(line, trimmed) { | |
| 79 | 81 | flushPending() |
| 80 | continue | |
| 82 | return | |
| 81 | 83 | } |
| 82 | 84 | |
| 83 | // Heading. | |
| 84 | if let match = trimmed.firstMatch(of: /^(\*{1,6})\s+(.+)$/) { | |
| 85 | document.elements.append(.heading(parseHeading(stars: match.1.count, rest: String(match.2)))) | |
| 86 | index += 1 | |
| 87 | flushPending() | |
| 88 | continue | |
| 89 | } | |
| 85 | parseParagraph() | |
| 86 | flushPending() | |
| 87 | } | |
| 90 | 88 | |
| 91 | // Horizontal rule. | |
| 92 | if isOrgHorizontalRule(trimmed) { | |
| 93 | document.elements.append(.horizontalRule) | |
| 89 | mutating func skipPropertyDrawer() { | |
| 90 | index += 1 | |
| 91 | while index < lines.count, | |
| 92 | lines[index].trimmingCharacters(in: .whitespaces) != ":END:" { | |
| 94 | 93 | index += 1 |
| 95 | flushPending() | |
| 96 | continue | |
| 97 | 94 | } |
| 95 | if index < lines.count { index += 1 } | |
| 96 | } | |
| 98 | 97 | |
| 99 | // Footnote definition. | |
| 100 | if let def = orgFootnoteDefinition(in: trimmed) { | |
| 101 | document.elements.append(.footnoteDefinition(label: def.label, content: parseInline(def.text))) | |
| 102 | index += 1 | |
| 103 | flushPending() | |
| 104 | continue | |
| 98 | mutating func applyDirective(_ keyword: String, _ value: String) { | |
| 99 | switch keyword { | |
| 100 | case "caption": pendingCaption = value | |
| 101 | case "name": pendingName = value | |
| 102 | case "attr_html": pendingAttrs = OrgParser.parseAttributes(value) | |
| 103 | default: document.keywords.append((keyword, value)) | |
| 105 | 104 | } |
| 105 | } | |
| 106 | 106 | |
| 107 | // A standalone image link, promoted to a figure by an affiliated caption/attrs. | |
| 108 | if let path = standaloneOrgImage(in: trimmed) { | |
| 107 | /// A heading, horizontal rule, footnote definition, or standalone image on | |
| 108 | /// this line. Returns false if the line is none of those. | |
| 109 | mutating func parseSingleLine(_ trimmed: String) -> Bool { | |
| 110 | if let match = trimmed.firstMatch(of: /^(\*{1,6})\s+(.+)$/) { | |
| 111 | document.elements.append(.heading(OrgParser.parseHeading(stars: match.1.count, rest: String(match.2)))) | |
| 112 | } else if isOrgHorizontalRule(trimmed) { | |
| 113 | document.elements.append(.horizontalRule) | |
| 114 | } else if let def = orgFootnoteDefinition(in: trimmed) { | |
| 115 | document.elements.append(.footnoteDefinition(label: def.label, content: OrgParser.parseInline(def.text))) | |
| 116 | } else if let path = standaloneOrgImage(in: trimmed) { | |
| 117 | // A standalone image link, promoted to a figure by an affiliated caption/attrs. | |
| 109 | 118 | document.elements.append(.figure(OrgFigure( |
| 110 | 119 | source: path, |
| 111 | caption: pendingCaption.map(parseInline), | |
| 120 | caption: pendingCaption.map(OrgParser.parseInline), | |
| 112 | 121 | attributes: pendingAttrs |
| 113 | 122 | ))) |
| 114 | index += 1 | |
| 115 | flushPending() | |
| 116 | continue | |
| 123 | } else { | |
| 124 | return false | |
| 117 | 125 | } |
| 126 | index += 1 | |
| 127 | return true | |
| 128 | } | |
| 118 | 129 | |
| 119 | // Table. | |
| 120 | if isTableLine(trimmed) { | |
| 121 | let (table, next) = parseTable(lines, from: index) | |
| 130 | /// A block, table, list, or LaTeX block starting on this line. Returns false | |
| 131 | /// if the line starts none of those. | |
| 132 | mutating func parseMultiLine(_ line: String, _ trimmed: String) -> Bool { | |
| 133 | if trimmed.lowercased().hasPrefix("#+begin_") { | |
| 134 | // Blocks: #+begin_… / #+end_… | |
| 135 | let (element, next) = OrgParser.parseBlock(lines, from: index) | |
| 136 | if let element { append(element) } | |
| 137 | index = next | |
| 138 | } else if isTableLine(trimmed) { | |
| 139 | let (table, next) = OrgParser.parseTable(lines, from: index) | |
| 122 | 140 | append(.table(table)) |
| 123 | 141 | index = next |
| 124 | flushPending() | |
| 125 | continue | |
| 126 | } | |
| 127 | ||
| 128 | // List. | |
| 129 | if isListMarkerLine(trimmed), !isIndentedContinuationLine(line) { | |
| 130 | let (list, next) = parseList(lines, from: index) | |
| 142 | } else if isListMarkerLine(trimmed), !isIndentedContinuationLine(line) { | |
| 143 | let (list, next) = OrgParser.parseList(lines, from: index) | |
| 131 | 144 | document.elements.append(.list(list)) |
| 132 | 145 | index = next |
| 133 | flushPending() | |
| 134 | continue | |
| 135 | } | |
| 136 | ||
| 137 | // A LaTeX block: \begin{name} alone on its line, through the matching \end{name}. | |
| 138 | if let (raw, next) = parseLatexBlock(lines, from: index, ends: latexEnds) { | |
| 146 | } else if let (raw, next) = OrgParser.parseLatexBlock(lines, from: index, ends: latexEnds) { | |
| 147 | // A LaTeX block: \begin{name} alone on its line, through the matching \end{name}. | |
| 139 | 148 | append(.latexBlock(raw)) |
| 140 | 149 | index = next |
| 141 | flushPending() | |
| 142 | continue | |
| 150 | } else { | |
| 151 | return false | |
| 143 | 152 | } |
| 153 | return true | |
| 154 | } | |
| 144 | 155 | |
| 145 | // Paragraph: consume until a blank line or a line that starts another construct. | |
| 156 | /// Consume until a blank line or a line that starts another construct. | |
| 157 | mutating func parseParagraph() { | |
| 146 | 158 | var paragraph: [String] = [] |
| 147 | 159 | while index < lines.count { |
| 148 | 160 | let candidate = lines[index] |
| @@ -150,19 +162,16 @@ public enum OrgParser { | ||
| 150 | 162 | // The first line is always taken: nothing above claimed it, and |
| 151 | 163 | // leaving it would parse the same line forever. |
| 152 | 164 | if !paragraph.isEmpty, |
| 153 | candidateTrimmed.isEmpty || startsNewConstruct(candidateTrimmed, raw: candidate) | |
| 154 | || latexEnd(candidateTrimmed) != nil | |
| 155 | || latexBlockEnd(lines, from: index, ends: latexEnds) != nil { break } | |
| 165 | candidateTrimmed.isEmpty || OrgParser.startsNewConstruct(candidateTrimmed, raw: candidate) | |
| 166 | || OrgParser.latexEnd(candidateTrimmed) != nil | |
| 167 | || OrgParser.latexBlockEnd(lines, from: index, ends: latexEnds) != nil { break } | |
| 156 | 168 | paragraph.append(candidateTrimmed) |
| 157 | 169 | index += 1 |
| 158 | 170 | } |
| 159 | 171 | if !paragraph.isEmpty { |
| 160 | document.elements.append(.paragraph(parseInline(paragraph.joined(separator: " ")))) | |
| 172 | document.elements.append(.paragraph(OrgParser.parseInline(paragraph.joined(separator: " ")))) | |
| 161 | 173 | } |
| 162 | flushPending() | |
| 163 | 174 | } |
| 164 | ||
| 165 | return document | |
| 166 | 175 | } |
| 167 | 176 | |
| 168 | 177 | /// Would this line begin a construct other than the paragraph currently being consumed? |
Sources/OrgSwift/OrgRenderer.swift +13 −26
| @@ -87,40 +87,27 @@ public struct OrgRenderOptions: Sendable { | ||
| 87 | 87 | } |
| 88 | 88 | |
| 89 | 89 | func imageURLResolver() -> ((String) -> String?)? { |
| 90 | guard let owner, let repositoryName else { return nil } | |
| 91 | let host = host | |
| 92 | let ref = ref | |
| 93 | let readmePath = readmePath | |
| 94 | let segment = imagePathSegment | |
| 95 | return { source in | |
| 96 | resolveRepositoryAssetURL( | |
| 97 | source, | |
| 98 | host: host, | |
| 99 | owner: owner, | |
| 100 | repositoryName: repositoryName, | |
| 101 | ref: ref, | |
| 102 | readmePath: readmePath, | |
| 103 | pathSegment: segment | |
| 104 | ) | |
| 105 | } | |
| 90 | repositoryResolver(pathSegment: imagePathSegment, resolveRepositoryAssetURL) | |
| 106 | 91 | } |
| 107 | 92 | |
| 108 | 93 | func linkURLResolver() -> ((String) -> String?)? { |
| 94 | repositoryResolver(pathSegment: linkPathSegment, resolveRepositoryLinkURL) | |
| 95 | } | |
| 96 | ||
| 97 | private typealias RepositoryURLFunction = ( | |
| 98 | String, String, String, String, String, String?, String | |
| 99 | ) -> String? | |
| 100 | ||
| 101 | /// `resolve` bound to this repository, or nil when the owner or name is unknown. | |
| 102 | private func repositoryResolver( | |
| 103 | pathSegment: String, _ resolve: @escaping RepositoryURLFunction | |
| 104 | ) -> ((String) -> String?)? { | |
| 109 | 105 | guard let owner, let repositoryName else { return nil } |
| 110 | 106 | let host = host |
| 111 | 107 | let ref = ref |
| 112 | 108 | let readmePath = readmePath |
| 113 | let segment = linkPathSegment | |
| 114 | 109 | return { source in |
| 115 | resolveRepositoryLinkURL( | |
| 116 | source, | |
| 117 | host: host, | |
| 118 | owner: owner, | |
| 119 | repositoryName: repositoryName, | |
| 120 | ref: ref, | |
| 121 | readmePath: readmePath, | |
| 122 | pathSegment: segment | |
| 123 | ) | |
| 110 | resolve(source, host, owner, repositoryName, ref, readmePath, pathSegment) | |
| 124 | 111 | } |
| 125 | 112 | } |
| 126 | 113 | } |
Sources/OrgSwift/Skeleton.swift +24 −15
| @@ -133,28 +133,37 @@ public enum OrgSkeleton { | ||
| 133 | 133 | var search = 0 |
| 134 | 134 | while let pos = indexOf(chars, nameChars, from: search) { |
| 135 | 135 | let beforeOK = pos == 0 || chars[pos - 1].isWhitespace |
| 136 | var after = pos + nameChars.count | |
| 137 | while after < chars.count && chars[after].isWhitespace { after += 1 } | |
| 136 | let after = skipSpaces(chars, from: pos + nameChars.count) | |
| 138 | 137 | if beforeOK && after < chars.count && chars[after] == "=" { |
| 139 | var value = after + 1 | |
| 140 | while value < chars.count && chars[value].isWhitespace { value += 1 } | |
| 141 | guard value < chars.count else { return nil } | |
| 142 | let quote = chars[value] | |
| 143 | if quote == "\"" || quote == "'" { | |
| 144 | var end = value + 1 | |
| 145 | while end < chars.count && chars[end] != quote { end += 1 } | |
| 146 | guard end < chars.count else { return nil } | |
| 147 | return String(chars[(value + 1)..<end]) | |
| 148 | } | |
| 149 | var end = value | |
| 150 | while end < chars.count && !chars[end].isWhitespace { end += 1 } | |
| 151 | return String(chars[value..<end]) | |
| 138 | return readAttributeValue(chars, from: skipSpaces(chars, from: after + 1)) | |
| 152 | 139 | } |
| 153 | 140 | search = pos + nameChars.count |
| 154 | 141 | } |
| 155 | 142 | return nil |
| 156 | 143 | } |
| 157 | 144 | |
| 145 | private static func skipSpaces(_ chars: [Character], from start: Int) -> Int { | |
| 146 | var i = start | |
| 147 | while i < chars.count && chars[i].isWhitespace { i += 1 } | |
| 148 | return i | |
| 149 | } | |
| 150 | ||
| 151 | /// A quoted or bare attribute value starting at `value`, or nil if it is | |
| 152 | /// missing or its quote never closes. | |
| 153 | private static func readAttributeValue(_ chars: [Character], from value: Int) -> String? { | |
| 154 | guard value < chars.count else { return nil } | |
| 155 | let quote = chars[value] | |
| 156 | if quote == "\"" || quote == "'" { | |
| 157 | var end = value + 1 | |
| 158 | while end < chars.count && chars[end] != quote { end += 1 } | |
| 159 | guard end < chars.count else { return nil } | |
| 160 | return String(chars[(value + 1)..<end]) | |
| 161 | } | |
| 162 | var end = value | |
| 163 | while end < chars.count && !chars[end].isWhitespace { end += 1 } | |
| 164 | return String(chars[value..<end]) | |
| 165 | } | |
| 166 | ||
| 158 | 167 | private static func indexOf(_ haystack: [Character], _ needle: [Character], from: Int) -> Int? { |
| 159 | 168 | if needle.isEmpty { return from } |
| 160 | 169 | var k = from |
Sources/OrgSwiftUI/OrgInlineStyler.swift +61 −44
| @@ -24,57 +24,74 @@ struct OrgInlineStyler { | ||
| 24 | 24 | style: Font.TextStyle = .body, bold forceBold: Bool = false |
| 25 | 25 | ) -> AttributedString { |
| 26 | 26 | var string = renderer.inline(objects, ¬es) |
| 27 | ||
| 28 | 27 | for range in string.runs.map(\.range) { |
| 29 | let intents = string[range].inlinePresentationIntent ?? [] | |
| 30 | let role = string[range][OrgRoleAttribute.self] | |
| 28 | styleRun(&string, range, style: style, forceBold: forceBold) | |
| 29 | } | |
| 30 | return string | |
| 31 | } | |
| 32 | ||
| 33 | /// How one run's font is built. | |
| 34 | private struct RunStyle { | |
| 35 | var textStyle: Font.TextStyle | |
| 36 | var monospaced = false | |
| 37 | var bold: Bool | |
| 38 | var italic: Bool | |
| 39 | } | |
| 31 | 40 | |
| 32 | var textStyle = style | |
| 33 | var monospaced = false | |
| 34 | var bold = forceBold | |
| 35 | var italic = false | |
| 41 | private func styleRun( | |
| 42 | _ string: inout AttributedString, _ range: Range<AttributedString.Index>, | |
| 43 | style: Font.TextStyle, forceBold: Bool | |
| 44 | ) { | |
| 45 | let intents = string[range].inlinePresentationIntent ?? [] | |
| 46 | var run = RunStyle( | |
| 47 | textStyle: style, | |
| 48 | bold: forceBold || intents.contains(.stronglyEmphasized), | |
| 49 | italic: intents.contains(.emphasized) | |
| 50 | ) | |
| 51 | if intents.contains(.code) { | |
| 52 | run.monospaced = true | |
| 53 | string[range].backgroundColor = .secondary.opacity(0.12) | |
| 54 | } | |
| 36 | 55 | |
| 37 | if intents.contains(.stronglyEmphasized) { bold = true } | |
| 38 | if intents.contains(.emphasized) { italic = true } | |
| 39 | if intents.contains(.code) { | |
| 40 | monospaced = true | |
| 41 | string[range].backgroundColor = .secondary.opacity(0.12) | |
| 42 | } | |
| 56 | Self.applyRole(string[range][OrgRoleAttribute.self], &string, range, &run) | |
| 43 | 57 | |
| 44 | switch role { | |
| 45 | case .underline: | |
| 46 | string[range].underlineStyle = .single | |
| 47 | case .strikeThrough: | |
| 48 | string[range].strikethroughStyle = .single | |
| 49 | case .superscript, .footnoteReference: | |
| 50 | // No portable superscript attribute, so raise it and step the style down. | |
| 51 | textStyle = Self.smaller(textStyle) | |
| 52 | string[range].baselineOffset = 5 | |
| 53 | if role == .footnoteReference { string[range].foregroundColor = .accentColor } | |
| 54 | case .timestamp: | |
| 55 | string[range].foregroundColor = .secondary | |
| 56 | case .image: | |
| 57 | // An inline image inside a paragraph shows its alt text; the block-level | |
| 58 | // `.figure` case is where an image is actually loaded. | |
| 59 | italic = true | |
| 60 | string[range].foregroundColor = .secondary | |
| 61 | case nil: | |
| 62 | break | |
| 63 | } | |
| 58 | if string[range][OrgMathAttribute.self] != nil { | |
| 59 | string[range][OrgMathStyleAttribute.self] = run.textStyle | |
| 60 | } | |
| 64 | 61 | |
| 65 | if string[range][OrgMathAttribute.self] != nil { | |
| 66 | string[range][OrgMathStyleAttribute.self] = textStyle | |
| 67 | } | |
| 62 | // Always set the font, never only on modified runs: a run with no emphasis | |
| 63 | // would otherwise inherit the surrounding view's font and a heading, table cell | |
| 64 | // or footnote would render at body size. | |
| 65 | var font = Font.system(run.textStyle, design: run.monospaced ? .monospaced : .default) | |
| 66 | if run.bold { font = font.bold() } | |
| 67 | if run.italic { font = font.italic() } | |
| 68 | string[range].font = font | |
| 69 | } | |
| 68 | 70 | |
| 69 | // Always set the font, never only on modified runs: a run with no emphasis | |
| 70 | // would otherwise inherit the surrounding view's font and a heading, table cell | |
| 71 | // or footnote would render at body size. | |
| 72 | var font = Font.system(textStyle, design: monospaced ? .monospaced : .default) | |
| 73 | if bold { font = font.bold() } | |
| 74 | if italic { font = font.italic() } | |
| 75 | string[range].font = font | |
| 71 | private static func applyRole( | |
| 72 | _ role: OrgRole?, _ string: inout AttributedString, _ range: Range<AttributedString.Index>, | |
| 73 | _ run: inout RunStyle | |
| 74 | ) { | |
| 75 | switch role { | |
| 76 | case .underline: | |
| 77 | string[range].underlineStyle = .single | |
| 78 | case .strikeThrough: | |
| 79 | string[range].strikethroughStyle = .single | |
| 80 | case .superscript, .footnoteReference: | |
| 81 | // No portable superscript attribute, so raise it and step the style down. | |
| 82 | run.textStyle = smaller(run.textStyle) | |
| 83 | string[range].baselineOffset = 5 | |
| 84 | if role == .footnoteReference { string[range].foregroundColor = .accentColor } | |
| 85 | case .timestamp: | |
| 86 | string[range].foregroundColor = .secondary | |
| 87 | case .image: | |
| 88 | // An inline image inside a paragraph shows its alt text; the block-level | |
| 89 | // `.figure` case is where an image is actually loaded. | |
| 90 | run.italic = true | |
| 91 | string[range].foregroundColor = .secondary | |
| 92 | case nil: | |
| 93 | break | |
| 76 | 94 | } |
| 77 | return string | |
| 78 | 95 | } |
| 79 | 96 | |
| 80 | 97 | /// One step down the semantic scale, for superscripts and footnote markers. |