Sources/OrgPresentation/Display.swift

06941b2cf25c6ccc1629723cd7951910ce15e67a
orgstar/Sources/OrgPresentation/Display.swift history · blame · raw

166 lines · 8149 bytes

  1import Foundation
  2import OrgCore
  3
  4/// How a file shows when it opens, from the display settings and its `#+STARTUP` words.
  5public struct StartupDisplay: Sendable, Equatable {
  6    /// Headings, drawers and blocks folded.
  7    public var folds: FoldState
  8    /// The folded drawers and blocks.
  9    public var wrappers: [Wrapper]
 10    /// `org-indent-mode` (`indent`, `noindent`).
 11    public var indented: Bool
 12    /// `org-hide-leading-stars` (`hidestars`, `showstars`).
 13    public var hideStars: Bool
 14    /// `org-startup-with-inline-images` (`inlineimages`, `noinlineimages`).
 15    public var inlineImages: Bool
 16    /// `org-startup-with-latex-preview` (`latexpreview`, `nolatexpreview`).
 17    public var latexPreview = false
 18    /// `org-startup-align-all-tables` (`align`, `noalign`).
 19    public var alignTables: Bool
 20    /// `org-startup-truncated`.
 21    public var truncated: Bool
 22}
 23
 24/// Org's display, shared by the Mac and iOS editors.
 25extension Presentation {
 26    public static func startupDisplay(_ tree: OrgTree, options: EditingOptions) -> StartupDisplay {
 27        let words = startupOptions(tree).map { $0.lowercased() }
 28        var folds = startupFoldState(tree) ?? FoldState()
 29        // VISIBILITY properties and archived trees, unless everything shows.
 30        if startupFoldState(tree) != nil, !words.contains("showeverything") {
 31            folds = applyVisibilityProperties(folds, in: tree)
 32        }
 33        let wrappers = startupWrappers(tree, hideDrawers: options.hideDrawerStartup, hideBlocks: options.hideBlockStartup)
 34        folds.wrapperFolds = Set(wrappers.map(\.start))
 35        var display = StartupDisplay(
 36            folds: folds, wrappers: wrappers,
 37            indented: words.contains("indent") ? true : words.contains("noindent") ? false : options.startupIndented,
 38            hideStars: words.contains("hidestars") ? true : words.contains("showstars") ? false : options.hideLeadingStars,
 39            inlineImages: InlineImages.startup(tree) ?? options.startupWithInlineImages,
 40            alignTables: words.contains("align") || (options.startupAlignAllTables && !words.contains("noalign")),
 41            truncated: options.startupTruncated
 42        )
 43        display.latexPreview = startupLatexPreview(tree) ?? options.startupWithLatexPreview
 44        return display
 45    }
 46
 47    /// Whether `role` hides while markup is hidden: link brackets and targets as with
 48    /// `org-link-descriptive`; emphasis markers only when Emacs hides them too.
 49    public static func hidesWithMarkup(_ role: StyleRole, options: EditingOptions) -> Bool {
 50        switch role {
 51        case .linkMarkup: true
 52        case .markup: options.hideEmphasisMarkers
 53        default: false
 54        }
 55    }
 56
 57    /// Whether a style run is skipped: leading stars show as the heading's color unless the
 58    /// view is indented or hides them.
 59    public static func skipsLeadingStars(_ role: StyleRole, indented: Bool, hideStars: Bool) -> Bool {
 60        role == .leadingStars && !indented && !hideStars
 61    }
 62
 63    /// One line's indentation under org-indent, in columns.
 64    public struct LineIndent: Sendable, Equatable {
 65        public let range: Range<Int>
 66        public let firstLine: Int
 67        public let wrapped: Int
 68    }
 69
 70    /// org-indent's indentation for the lines in `range`: each run of `indents`, with body lines
 71    /// wrapping under their own text (past leading blanks, a list bullet and a checkbox) as
 72    /// adaptive-wrap does in Emacs.
 73    public static func lineIndents(_ tree: OrgTree, in range: Range<Int>) -> [LineIndent] {
 74        let text = tree.text as NSString
 75        var out: [LineIndent] = []
 76        for run in indents(tree, in: range) {
 77            let clipped = run.range.clamped(to: range)
 78            guard !clipped.isEmpty else { continue }
 79            guard run.firstLine == run.wrapped else {
 80                out.append(LineIndent(range: clipped, firstLine: run.firstLine, wrapped: run.wrapped))
 81                continue
 82            }
 83            var location = clipped.lowerBound
 84            while location < clipped.upperBound {
 85                let line = text.lineRange(for: NSRange(location: location, length: 0))
 86                let hanging = hangingColumns(text.substring(with: line))
 87                let lineRange = max(line.location, clipped.lowerBound)..<min(NSMaxRange(line), clipped.upperBound)
 88                out.append(LineIndent(range: lineRange, firstLine: run.firstLine, wrapped: run.wrapped + hanging))
 89                location = NSMaxRange(line)
 90            }
 91        }
 92        return out
 93    }
 94
 95    /// Columns a wrapped continuation of `line` should start past the line's own start.
 96    public static func hangingColumns(_ line: String) -> Int {
 97        var columns = 0
 98        var rest = Substring(line)
 99        while let c = rest.first, c == " " || c == "\t" {
100            columns = c == "\t" ? (columns / 8 + 1) * 8 : columns + 1
101            rest = rest.dropFirst()
102        }
103        // A bullet (`-`, `+`, `*` when indented, `1.`, `1)`) and its space, then a checkbox.
104        var bullet = 0
105        if let first = rest.first, first == "-" || first == "+" || (first == "*" && columns > 0) {
106            bullet = 1
107        } else {
108            let digits = rest.prefix { $0.isASCII && $0.isNumber }
109            if !digits.isEmpty, let separator = rest.dropFirst(digits.count).first, separator == "." || separator == ")" {
110                bullet = digits.count + 1
111            }
112        }
113        guard bullet > 0, rest.dropFirst(bullet).first == " " else { return columns }
114        columns += bullet + 1
115        let afterBullet = rest.dropFirst(bullet + 1)
116        if afterBullet.count >= 4, afterBullet.first == "[", "X x-".contains(afterBullet.dropFirst().first!),
117           afterBullet.dropFirst(2).first == "]", afterBullet.dropFirst(3).first == " " {
118            columns += 4
119        }
120        return columns
121    }
122
123    /// `org-pretty-entities` for the lines in `range`, with each run's line start: not on the
124    /// line starting at `revealedLine`, in comments or in blocks; sub/superscripts not in
125    /// `scriptExclusions` (emphasis, links, keywords), as `org-raise-scripts` leaves them.
126    public static func prettyRuns(
127        _ text: NSString, in range: Range<Int>, revealedLine: Int?, inBlock: (Int) -> Bool,
128        scriptExclusions: [Range<Int>], subSuperscriptsNeedBraces: Bool
129    ) -> [(lineStart: Int, run: PrettyEntities.Run)] {
130        var out: [(lineStart: Int, run: PrettyEntities.Run)] = []
131        var location = range.lowerBound
132        while location < range.upperBound {
133            let line = text.lineRange(for: NSRange(location: location, length: 0))
134            guard line.length > 0 else { break }
135            location = NSMaxRange(line)
136            if line.location == revealedLine || inBlock(line.location) { continue }
137            let content = text.substring(with: line)
138            if Self.isCommentOrKeyword(content) { continue }
139            for run in PrettyEntities.runs(in: content, subSuperscriptsNeedBraces: subSuperscriptsNeedBraces) {
140                if case .script(_, let body, _) = run {
141                    let bodyStart = line.location + body.lowerBound
142                    if body.isEmpty || scriptExclusions.contains(where: { $0.contains(bodyStart) }) { continue }
143                }
144                out.append((line.location, run))
145            }
146        }
147        return out
148    }
149
150    /// `^[ \t]*#([ +]|$)`: a comment or keyword line, which shows no entities.
151    static func isCommentOrKeyword(_ line: String) -> Bool {
152        let body = line.drop { $0 == " " || $0 == "\t" }
153        guard body.first == "#" else { return false }
154        let next = body.dropFirst().first
155        // `$` only at the end: the pattern ran on the line with its newline.
156        return next == nil || next == " " || next == "+"
157    }
158
159    /// Roles whose text keeps sub/superscript markers as written.
160    public static func excludesScripts(_ role: StyleRole) -> Bool {
161        switch role {
162        case .bold, .italic, .underline, .strikeThrough, .verbatim, .code, .link, .linkMarkup, .keyword: true
163        default: false
164        }
165    }
166}