Sources/OrgPresentation/Display.swift

223 lines · 10964 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    /// Roles drawn in the fixed-pitch font when the body font is proportional, as Emacs's
 96    /// mixed-pitch-mode keeps `mixed-pitch-fixed-pitch-faces`: text that lines up by column.
 97    public static func isFixedPitch(_ role: StyleRole) -> Bool {
 98        switch role {
 99        case .table, .rule, .block, .blockDelimiter, .verbatim, .code, .inlineSource, .metadata, .keyword, .tags, .timestamp, .syntax: true
100        default: false
101        }
102    }
103
104    /// The start of each line in `range` that sets where its text begins, for the fixed-pitch
105    /// font under a proportional body: a heading's stars and space, and the leading blanks,
106    /// bullet and checkbox `hangingColumns` counts. org-indent's indentation is in columns of
107    /// the fixed-pitch font, so these keep text lined up under it.
108    public static func fixedPitchPrefixes(_ text: NSString, in range: Range<Int>) -> [Range<Int>] {
109        var out: [Range<Int>] = []
110        var location = range.lowerBound
111        while location < range.upperBound {
112            let line = text.lineRange(for: NSRange(location: location, length: 0))
113            guard line.length > 0 else { break }
114            location = NSMaxRange(line)
115            let content = text.substring(with: line)
116            let stars = content.prefix { $0 == "*" }.count
117            let length: Int
118            if stars > 0, content.dropFirst(stars).first == " " {
119                length = stars + 1
120            } else {
121                length = hangingPrefix(content).utf16.count
122            }
123            if length > 0 { out.append(line.location..<(line.location + length)) }
124        }
125        return out
126    }
127
128    /// The characters `hangingColumns` counts: leading blanks, then a bullet, its space and a
129    /// checkbox.
130    static func hangingPrefix(_ line: String) -> Substring {
131        let blanks = line.prefix { $0 == " " || $0 == "\t" }
132        let rest = line.dropFirst(blanks.count)
133        var bullet = 0
134        if let first = rest.first, first == "-" || first == "+" || (first == "*" && !blanks.isEmpty) {
135            bullet = 1
136        } else {
137            let digits = rest.prefix { $0.isASCII && $0.isNumber }
138            if !digits.isEmpty, let separator = rest.dropFirst(digits.count).first, separator == "." || separator == ")" {
139                bullet = digits.count + 1
140            }
141        }
142        guard bullet > 0, rest.dropFirst(bullet).first == " " else { return blanks }
143        var length = blanks.count + bullet + 1
144        let afterBullet = rest.dropFirst(bullet + 1)
145        if afterBullet.count >= 4, afterBullet.first == "[", "X x-".contains(afterBullet.dropFirst().first!),
146           afterBullet.dropFirst(2).first == "]", afterBullet.dropFirst(3).first == " " {
147            length += 4
148        }
149        return line.prefix(length)
150    }
151
152    /// Columns a wrapped continuation of `line` should start past the line's own start.
153    public static func hangingColumns(_ line: String) -> Int {
154        var columns = 0
155        var rest = Substring(line)
156        while let c = rest.first, c == " " || c == "\t" {
157            columns = c == "\t" ? (columns / 8 + 1) * 8 : columns + 1
158            rest = rest.dropFirst()
159        }
160        // A bullet (`-`, `+`, `*` when indented, `1.`, `1)`) and its space, then a checkbox.
161        var bullet = 0
162        if let first = rest.first, first == "-" || first == "+" || (first == "*" && columns > 0) {
163            bullet = 1
164        } else {
165            let digits = rest.prefix { $0.isASCII && $0.isNumber }
166            if !digits.isEmpty, let separator = rest.dropFirst(digits.count).first, separator == "." || separator == ")" {
167                bullet = digits.count + 1
168            }
169        }
170        guard bullet > 0, rest.dropFirst(bullet).first == " " else { return columns }
171        columns += bullet + 1
172        let afterBullet = rest.dropFirst(bullet + 1)
173        if afterBullet.count >= 4, afterBullet.first == "[", "X x-".contains(afterBullet.dropFirst().first!),
174           afterBullet.dropFirst(2).first == "]", afterBullet.dropFirst(3).first == " " {
175            columns += 4
176        }
177        return columns
178    }
179
180    /// `org-pretty-entities` for the lines in `range`, with each run's line start: not on the
181    /// line starting at `revealedLine`, in comments or in blocks; sub/superscripts not in
182    /// `scriptExclusions` (emphasis, links, keywords), as `org-raise-scripts` leaves them.
183    public static func prettyRuns(
184        _ text: NSString, in range: Range<Int>, revealedLine: Int?, inBlock: (Int) -> Bool,
185        scriptExclusions: [Range<Int>], subSuperscriptsNeedBraces: Bool
186    ) -> [(lineStart: Int, run: PrettyEntities.Run)] {
187        var out: [(lineStart: Int, run: PrettyEntities.Run)] = []
188        var location = range.lowerBound
189        while location < range.upperBound {
190            let line = text.lineRange(for: NSRange(location: location, length: 0))
191            guard line.length > 0 else { break }
192            location = NSMaxRange(line)
193            if line.location == revealedLine || inBlock(line.location) { continue }
194            let content = text.substring(with: line)
195            if Self.isCommentOrKeyword(content) { continue }
196            for run in PrettyEntities.runs(in: content, subSuperscriptsNeedBraces: subSuperscriptsNeedBraces) {
197                if case .script(_, let body, _) = run {
198                    let bodyStart = line.location + body.lowerBound
199                    if body.isEmpty || scriptExclusions.contains(where: { $0.contains(bodyStart) }) { continue }
200                }
201                out.append((line.location, run))
202            }
203        }
204        return out
205    }
206
207    /// `^[ \t]*#([ +]|$)`: a comment or keyword line, which shows no entities.
208    static func isCommentOrKeyword(_ line: String) -> Bool {
209        let body = line.drop { $0 == " " || $0 == "\t" }
210        guard body.first == "#" else { return false }
211        let next = body.dropFirst().first
212        // `$` only at the end: the pattern ran on the line with its newline.
213        return next == nil || next == " " || next == "+"
214    }
215
216    /// Roles whose text keeps sub/superscript markers as written.
217    public static func excludesScripts(_ role: StyleRole) -> Bool {
218        switch role {
219        case .bold, .italic, .underline, .strikeThrough, .verbatim, .code, .link, .linkMarkup, .keyword: true
220        default: false
221        }
222    }
223}