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 | let isHeader = headerCount > 0 && index < headerCount | 201 | let isHeader = headerCount > 0 && index < headerCount |
| 202 | if isHeader, !wroteHeader { html += "<thead>\n"; wroteHeader = true } | 202 | if isHeader, !wroteHeader { html += "<thead>\n"; wroteHeader = true } |
| 203 | if !isHeader, !inBody { html += "<tbody>\n"; inBody = true } | 203 | if !isHeader, !inBody { html += "<tbody>\n"; inBody = true } |
| 204 | html += "<tr>\n" | 204 | html += renderRow(cells, header: isHeader, alignments: table.alignments, ¬es) |
| 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" | ||
| 212 | } | 205 | } |
| 213 | } | 206 | } |
| 214 | if inBody { html += "</tbody>\n" } | 207 | if inBody { html += "</tbody>\n" } |
| 215 | return html + "</table>\n" | 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 | /// The `<img>` for a figure, or nil when the source cannot be resolved to a safe URL — | 224 | /// The `<img>` for a figure, or nil when the source cannot be resolved to a safe URL — |
| 219 | /// in which case the caller falls back to text rather than pointing at something unsafe. | 225 | /// in which case the caller falls back to text rather than pointing at something unsafe. |
| 220 | private func imageTag(_ figure: OrgFigure, caption: [OrgObject]?) -> String? { | 226 | private func imageTag(_ figure: OrgFigure, caption: [OrgObject]?) -> String? { |
Sources/OrgSwift/AST/OrgInlineParser.swift +74 −77
| @@ -39,100 +39,97 @@ extension OrgParser { | |||
| 39 | let lastEnd = lastEnvironmentEnd(text) | 39 | let lastEnd = lastEnvironmentEnd(text) |
| 40 | // A closer that is missing once is missing for every later opener of its kind. | 40 | // A closer that is missing once is missing for every later opener of its kind. |
| 41 | var missing: Set<String> = [] | 41 | var missing: Set<String> = [] |
| 42 | func noteMissing<T>(_ closer: String) -> T? { | ||
| 43 | missing.insert(closer) | ||
| 44 | return nil | ||
| 45 | } | ||
| 46 | 42 | ||
| 47 | func flushPlain() { | 43 | func flushPlain() { |
| 48 | if !plain.isEmpty { objects.append(.text(plain)); plain = "" } | 44 | if !plain.isEmpty { objects.append(.text(plain)); plain = "" } |
| 49 | } | 45 | } |
| 50 | 46 | ||
| 51 | while i < chars.count { | 47 | while i < chars.count { |
| 52 | // Bracket links: [[target]] or [[target][description]] | 48 | guard let hit = scanObject(chars, at: i, lastEnd: lastEnd, missing: &missing) else { |
| 53 | if chars[i] == "[", i + 1 < chars.count, chars[i + 1] == "[", | 49 | plain.append(chars[i]) |
| 54 | !missing.contains("]]"), let link = scanLink(chars, from: i) ?? noteMissing("]]") { | 50 | i += 1 |
| 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 | ||
| 70 | continue | 51 | continue |
| 71 | } | 52 | } |
| 72 | 53 | if hit.mergesText, case .text(let text) = hit.object { | |
| 73 | // Footnote reference: [fn:label] or [fn:label:inline] | 54 | plain += text |
| 74 | if chars[i] == "[", let note = scanFootnote(chars, from: i) { | 55 | } else { |
| 75 | flushPlain() | 56 | flushPlain() |
| 76 | objects.append(note.object) | 57 | objects.append(hit.object) |
| 77 | i = note.next | ||
| 78 | continue | ||
| 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] | 65 | /// An inline object found at a position, and where scanning resumes. |
| 82 | if chars[i] == "<" || chars[i] == "[", let stamp = scanTimestamp(chars, from: i) { | 66 | private struct InlineHit { |
| 83 | flushPlain() | 67 | let object: OrgObject |
| 84 | objects.append(stamp.object) | 68 | let next: Int |
| 85 | i = stamp.next | 69 | /// Plain text from a scanner (an unclosed LaTeX opener) that joins the |
| 86 | continue | 70 | /// surrounding text run. |
| 87 | } | 71 | var mergesText = false |
| 72 | } | ||
| 88 | 73 | ||
| 89 | // Bare URL autolink. | 74 | /// The first inline object starting at `i`, trying each construct in priority order. |
| 90 | if chars[i] == "h", let url = scanBareURL(chars, from: i) { | 75 | private static func scanObject( |
| 91 | flushPlain() | 76 | _ chars: [Character], at i: Int, lastEnd: (offset: Int, name: String)?, missing: inout Set<String> |
| 92 | objects.append(url.object) | 77 | ) -> InlineHit? { |
| 93 | i = url.next | 78 | // Bracket links: [[target]] or [[target][description]] |
| 94 | continue | 79 | if chars[i] == "[", i + 1 < chars.count, chars[i + 1] == "[", !missing.contains("]]") { |
| 95 | } | 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. | 84 | // LaTeX fragments: $…$, $$…$$, \(…\), \[…\], \begin{…}…\end{…} |
| 98 | if isWordCharacter(chars[i]), i == 0 || !isEmailBoundaryCharacter(chars[i - 1]), | 85 | if chars[i] == "$" || chars[i] == "\\", let math = scanMath(chars, from: i, lastEnd: lastEnd, missing: &missing) { |
| 99 | let email = scanEmail(chars, from: i) { | 86 | return InlineHit(object: math.object, next: math.next, mergesText: true) |
| 100 | flushPlain() | 87 | } |
| 101 | objects.append(email.object) | ||
| 102 | i = email.next | ||
| 103 | continue | ||
| 104 | } | ||
| 105 | 88 | ||
| 106 | // Emphasis: *bold* /italic/ _underline_ +strike+ =verbatim= ~code~ | 89 | // Footnote reference: [fn:label] or [fn:label:inline] |
| 107 | if let marker = emphasisMarker(chars[i]), boundaryBefore(chars, i), | 90 | if chars[i] == "[", let note = scanFootnote(chars, from: i) { |
| 108 | let span = scanEmphasis(chars, from: i, marker: chars[i]) { | 91 | return InlineHit(object: note.object, next: note.next) |
| 109 | flushPlain() | 92 | } |
| 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 | } | ||
| 121 | 93 | ||
| 122 | // Superscript: x^2 or x^{group} | 94 | // Timestamps: <2024-01-15 Mon 10:30> or [2024-01-15 Mon] |
| 123 | if chars[i] == "^", i > 0, isWordCharacter(chars[i - 1]), | 95 | if chars[i] == "<" || chars[i] == "[", let stamp = scanTimestamp(chars, from: i) { |
| 124 | let sup = scanSuperscript(chars, from: i) { | 96 | return InlineHit(object: stamp.object, next: stamp.next) |
| 125 | flushPlain() | 97 | } |
| 126 | objects.append(.superscript(parseInline(sup.body))) | ||
| 127 | i = sup.next | ||
| 128 | continue | ||
| 129 | } | ||
| 130 | 98 | ||
| 131 | plain.append(chars[i]) | 99 | // Bare URL autolink. |
| 132 | i += 1 | 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 | // MARK: - Scanners | 135 | // MARK: - Scanners |
Sources/OrgSwift/AST/OrgParser.swift +87 −78
| @@ -8,18 +8,34 @@ import Foundation | |||
| 8 | public enum OrgParser { | 8 | public enum OrgParser { |
| 9 | 9 | ||
| 10 | public static func parse(_ source: String) -> OrgDocument { | 10 | public static func parse(_ source: String) -> OrgDocument { |
| 11 | var document = OrgDocument() | ||
| 12 | let lines = source | 11 | let lines = source |
| 13 | .replacingOccurrences(of: "\r\n", with: "\n") | 12 | .replacingOccurrences(of: "\r\n", with: "\n") |
| 14 | .replacingOccurrences(of: "\r", with: "\n") | 13 | .replacingOccurrences(of: "\r", with: "\n") |
| 15 | .components(separatedBy: "\n") | 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 | var index = 0 | 28 | var index = 0 |
| 17 | let latexEnds = latexEndLines(lines) | ||
| 18 | var pendingCaption: String? | 29 | var pendingCaption: String? |
| 19 | var pendingName: String? | 30 | var pendingName: String? |
| 20 | var pendingAttrs: [(key: String, value: String)] = [] | 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 | pendingCaption = nil | 39 | pendingCaption = nil |
| 24 | pendingName = nil | 40 | pendingName = nil |
| 25 | pendingAttrs = [] | 41 | pendingAttrs = [] |
| @@ -27,11 +43,11 @@ public enum OrgParser { | |||
| 27 | 43 | ||
| 28 | /// Append a block, wrapping it in `.captioned` when an affiliated `#+CAPTION:` or | 44 | /// Append a block, wrapping it in `.captioned` when an affiliated `#+CAPTION:` or |
| 29 | /// `#+NAME:` precedes it — org's exporter turns that pairing into a `<figure>`. | 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 | if pendingCaption != nil || pendingName != nil { | 47 | if pendingCaption != nil || pendingName != nil { |
| 32 | document.elements.append(.captioned( | 48 | document.elements.append(.captioned( |
| 33 | name: pendingName, | 49 | name: pendingName, |
| 34 | caption: pendingCaption.map(parseInline), | 50 | caption: pendingCaption.map(OrgParser.parseInline), |
| 35 | content: element | 51 | content: element |
| 36 | )) | 52 | )) |
| 37 | } else { | 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 | let line = lines[index] | 59 | let line = lines[index] |
| 44 | let trimmed = line.trimmingCharacters(in: .whitespaces) | 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 | // Comments. | 64 | // Comments. |
| 49 | if trimmed == "#" || trimmed.hasPrefix("# ") { index += 1; continue } | 65 | if trimmed == "#" || trimmed.hasPrefix("# ") { index += 1; return } |
| 50 | 66 | ||
| 51 | // Property drawers are heading metadata; org's exporter drops them. | 67 | // Property drawers are heading metadata; org's exporter drops them. |
| 52 | if trimmed == ":PROPERTIES:" { | 68 | if trimmed == ":PROPERTIES:" { |
| 53 | index += 1 | 69 | skipPropertyDrawer() |
| 54 | while index < lines.count, | 70 | return |
| 55 | lines[index].trimmingCharacters(in: .whitespaces) != ":END:" { | ||
| 56 | index += 1 | ||
| 57 | } | ||
| 58 | if index < lines.count { index += 1 } | ||
| 59 | continue | ||
| 60 | } | 71 | } |
| 61 | 72 | ||
| 62 | // Affiliated keywords and document metadata. | 73 | // Affiliated keywords and document metadata. |
| 63 | if let directive = orgKeywordDirective(in: trimmed) { | 74 | if let directive = orgKeywordDirective(in: trimmed) { |
| 64 | switch directive.keyword { | 75 | applyDirective(directive.keyword, directive.value) |
| 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 | } | ||
| 70 | index += 1 | 76 | index += 1 |
| 71 | continue | 77 | return |
| 72 | } | 78 | } |
| 73 | 79 | ||
| 74 | // Blocks: #+begin_… / #+end_… | 80 | if parseSingleLine(trimmed) || parseMultiLine(line, trimmed) { |
| 75 | if trimmed.lowercased().hasPrefix("#+begin_") { | ||
| 76 | let (element, next) = parseBlock(lines, from: index) | ||
| 77 | if let element { append(element) } | ||
| 78 | index = next | ||
| 79 | flushPending() | 81 | flushPending() |
| 80 | continue | 82 | return |
| 81 | } | 83 | } |
| 82 | 84 | ||
| 83 | // Heading. | 85 | parseParagraph() |
| 84 | if let match = trimmed.firstMatch(of: /^(\*{1,6})\s+(.+)$/) { | 86 | flushPending() |
| 85 | document.elements.append(.heading(parseHeading(stars: match.1.count, rest: String(match.2)))) | 87 | } |
| 86 | index += 1 | ||
| 87 | flushPending() | ||
| 88 | continue | ||
| 89 | } | ||
| 90 | 88 | ||
| 91 | // Horizontal rule. | 89 | mutating func skipPropertyDrawer() { |
| 92 | if isOrgHorizontalRule(trimmed) { | 90 | index += 1 |
| 93 | document.elements.append(.horizontalRule) | 91 | while index < lines.count, |
| 92 | lines[index].trimmingCharacters(in: .whitespaces) != ":END:" { | ||
| 94 | index += 1 | 93 | index += 1 |
| 95 | flushPending() | ||
| 96 | continue | ||
| 97 | } | 94 | } |
| 95 | if index < lines.count { index += 1 } | ||
| 96 | } | ||
| 98 | 97 | ||
| 99 | // Footnote definition. | 98 | mutating func applyDirective(_ keyword: String, _ value: String) { |
| 100 | if let def = orgFootnoteDefinition(in: trimmed) { | 99 | switch keyword { |
| 101 | document.elements.append(.footnoteDefinition(label: def.label, content: parseInline(def.text))) | 100 | case "caption": pendingCaption = value |
| 102 | index += 1 | 101 | case "name": pendingName = value |
| 103 | flushPending() | 102 | case "attr_html": pendingAttrs = OrgParser.parseAttributes(value) |
| 104 | continue | 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. | 107 | /// A heading, horizontal rule, footnote definition, or standalone image on |
| 108 | if let path = standaloneOrgImage(in: trimmed) { | 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 | document.elements.append(.figure(OrgFigure( | 118 | document.elements.append(.figure(OrgFigure( |
| 110 | source: path, | 119 | source: path, |
| 111 | caption: pendingCaption.map(parseInline), | 120 | caption: pendingCaption.map(OrgParser.parseInline), |
| 112 | attributes: pendingAttrs | 121 | attributes: pendingAttrs |
| 113 | ))) | 122 | ))) |
| 114 | index += 1 | 123 | } else { |
| 115 | flushPending() | 124 | return false |
| 116 | continue | ||
| 117 | } | 125 | } |
| 126 | index += 1 | ||
| 127 | return true | ||
| 128 | } | ||
| 118 | 129 | ||
| 119 | // Table. | 130 | /// A block, table, list, or LaTeX block starting on this line. Returns false |
| 120 | if isTableLine(trimmed) { | 131 | /// if the line starts none of those. |
| 121 | let (table, next) = parseTable(lines, from: index) | 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 | append(.table(table)) | 140 | append(.table(table)) |
| 123 | index = next | 141 | index = next |
| 124 | flushPending() | 142 | } else if isListMarkerLine(trimmed), !isIndentedContinuationLine(line) { |
| 125 | continue | 143 | let (list, next) = OrgParser.parseList(lines, from: index) |
| 126 | } | ||
| 127 | |||
| 128 | // List. | ||
| 129 | if isListMarkerLine(trimmed), !isIndentedContinuationLine(line) { | ||
| 130 | let (list, next) = parseList(lines, from: index) | ||
| 131 | document.elements.append(.list(list)) | 144 | document.elements.append(.list(list)) |
| 132 | index = next | 145 | index = next |
| 133 | flushPending() | 146 | } else if let (raw, next) = OrgParser.parseLatexBlock(lines, from: index, ends: latexEnds) { |
| 134 | continue | 147 | // A LaTeX block: \begin{name} alone on its line, through the matching \end{name}. |
| 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) { | ||
| 139 | append(.latexBlock(raw)) | 148 | append(.latexBlock(raw)) |
| 140 | index = next | 149 | index = next |
| 141 | flushPending() | 150 | } else { |
| 142 | continue | 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 | var paragraph: [String] = [] | 158 | var paragraph: [String] = [] |
| 147 | while index < lines.count { | 159 | while index < lines.count { |
| 148 | let candidate = lines[index] | 160 | let candidate = lines[index] |
| @@ -150,19 +162,16 @@ public enum OrgParser { | |||
| 150 | // The first line is always taken: nothing above claimed it, and | 162 | // The first line is always taken: nothing above claimed it, and |
| 151 | // leaving it would parse the same line forever. | 163 | // leaving it would parse the same line forever. |
| 152 | if !paragraph.isEmpty, | 164 | if !paragraph.isEmpty, |
| 153 | candidateTrimmed.isEmpty || startsNewConstruct(candidateTrimmed, raw: candidate) | 165 | candidateTrimmed.isEmpty || OrgParser.startsNewConstruct(candidateTrimmed, raw: candidate) |
| 154 | || latexEnd(candidateTrimmed) != nil | 166 | || OrgParser.latexEnd(candidateTrimmed) != nil |
| 155 | || latexBlockEnd(lines, from: index, ends: latexEnds) != nil { break } | 167 | || OrgParser.latexBlockEnd(lines, from: index, ends: latexEnds) != nil { break } |
| 156 | paragraph.append(candidateTrimmed) | 168 | paragraph.append(candidateTrimmed) |
| 157 | index += 1 | 169 | index += 1 |
| 158 | } | 170 | } |
| 159 | if !paragraph.isEmpty { | 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 | /// Would this line begin a construct other than the paragraph currently being consumed? | 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 | func imageURLResolver() -> ((String) -> String?)? { | 89 | func imageURLResolver() -> ((String) -> String?)? { |
| 90 | guard let owner, let repositoryName else { return nil } | 90 | repositoryResolver(pathSegment: imagePathSegment, resolveRepositoryAssetURL) |
| 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 | } | ||
| 106 | } | 91 | } |
| 107 | 92 | ||
| 108 | func linkURLResolver() -> ((String) -> String?)? { | 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 | guard let owner, let repositoryName else { return nil } | 105 | guard let owner, let repositoryName else { return nil } |
| 110 | let host = host | 106 | let host = host |
| 111 | let ref = ref | 107 | let ref = ref |
| 112 | let readmePath = readmePath | 108 | let readmePath = readmePath |
| 113 | let segment = linkPathSegment | ||
| 114 | return { source in | 109 | return { source in |
| 115 | resolveRepositoryLinkURL( | 110 | resolve(source, host, owner, repositoryName, ref, readmePath, pathSegment) |
| 116 | source, | ||
| 117 | host: host, | ||
| 118 | owner: owner, | ||
| 119 | repositoryName: repositoryName, | ||
| 120 | ref: ref, | ||
| 121 | readmePath: readmePath, | ||
| 122 | pathSegment: segment | ||
| 123 | ) | ||
| 124 | } | 111 | } |
| 125 | } | 112 | } |
| 126 | } | 113 | } |
Sources/OrgSwift/Skeleton.swift +24 −15
| @@ -133,28 +133,37 @@ public enum OrgSkeleton { | |||
| 133 | var search = 0 | 133 | var search = 0 |
| 134 | while let pos = indexOf(chars, nameChars, from: search) { | 134 | while let pos = indexOf(chars, nameChars, from: search) { |
| 135 | let beforeOK = pos == 0 || chars[pos - 1].isWhitespace | 135 | let beforeOK = pos == 0 || chars[pos - 1].isWhitespace |
| 136 | var after = pos + nameChars.count | 136 | let after = skipSpaces(chars, from: pos + nameChars.count) |
| 137 | while after < chars.count && chars[after].isWhitespace { after += 1 } | ||
| 138 | if beforeOK && after < chars.count && chars[after] == "=" { | 137 | if beforeOK && after < chars.count && chars[after] == "=" { |
| 139 | var value = after + 1 | 138 | return readAttributeValue(chars, from: skipSpaces(chars, from: 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]) | ||
| 152 | } | 139 | } |
| 153 | search = pos + nameChars.count | 140 | search = pos + nameChars.count |
| 154 | } | 141 | } |
| 155 | return nil | 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 | private static func indexOf(_ haystack: [Character], _ needle: [Character], from: Int) -> Int? { | 167 | private static func indexOf(_ haystack: [Character], _ needle: [Character], from: Int) -> Int? { |
| 159 | if needle.isEmpty { return from } | 168 | if needle.isEmpty { return from } |
| 160 | var k = from | 169 | var k = from |
Sources/OrgSwiftUI/OrgInlineStyler.swift +61 −44
| @@ -24,57 +24,74 @@ struct OrgInlineStyler { | |||
| 24 | style: Font.TextStyle = .body, bold forceBold: Bool = false | 24 | style: Font.TextStyle = .body, bold forceBold: Bool = false |
| 25 | ) -> AttributedString { | 25 | ) -> AttributedString { |
| 26 | var string = renderer.inline(objects, ¬es) | 26 | var string = renderer.inline(objects, ¬es) |
| 27 | |||
| 28 | for range in string.runs.map(\.range) { | 27 | for range in string.runs.map(\.range) { |
| 29 | let intents = string[range].inlinePresentationIntent ?? [] | 28 | styleRun(&string, range, style: style, forceBold: forceBold) |
| 30 | let role = string[range][OrgRoleAttribute.self] | 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 | 41 | private func styleRun( |
| 33 | var monospaced = false | 42 | _ string: inout AttributedString, _ range: Range<AttributedString.Index>, |
| 34 | var bold = forceBold | 43 | style: Font.TextStyle, forceBold: Bool |
| 35 | var italic = false | 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 } | 56 | Self.applyRole(string[range][OrgRoleAttribute.self], &string, range, &run) |
| 38 | if intents.contains(.emphasized) { italic = true } | ||
| 39 | if intents.contains(.code) { | ||
| 40 | monospaced = true | ||
| 41 | string[range].backgroundColor = .secondary.opacity(0.12) | ||
| 42 | } | ||
| 43 | 57 | ||
| 44 | switch role { | 58 | if string[range][OrgMathAttribute.self] != nil { |
| 45 | case .underline: | 59 | string[range][OrgMathStyleAttribute.self] = run.textStyle |
| 46 | string[range].underlineStyle = .single | 60 | } |
| 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 | } | ||
| 64 | 61 | ||
| 65 | if string[range][OrgMathAttribute.self] != nil { | 62 | // Always set the font, never only on modified runs: a run with no emphasis |
| 66 | string[range][OrgMathStyleAttribute.self] = textStyle | 63 | // would otherwise inherit the surrounding view's font and a heading, table cell |
| 67 | } | 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 | 71 | private static func applyRole( |
| 70 | // would otherwise inherit the surrounding view's font and a heading, table cell | 72 | _ role: OrgRole?, _ string: inout AttributedString, _ range: Range<AttributedString.Index>, |
| 71 | // or footnote would render at body size. | 73 | _ run: inout RunStyle |
| 72 | var font = Font.system(textStyle, design: monospaced ? .monospaced : .default) | 74 | ) { |
| 73 | if bold { font = font.bold() } | 75 | switch role { |
| 74 | if italic { font = font.italic() } | 76 | case .underline: |
| 75 | string[range].font = font | 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 | /// One step down the semantic scale, for superscripts and footnote markers. | 97 | /// One step down the semantic scale, for superscripts and footnote markers. |