Sources/OrgPresentation/Display.swift

254 lines · 12961 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    /// An image link and where its image goes.
 48    public struct ImagePlacement: Sendable, Equatable {
 49        public let link: InlineImages.Link
 50        /// The link is all its line holds, so the image takes the line. Otherwise the image
 51        /// stands in the text where the link is, as Org's display property puts it.
 52        public let ownLine: Bool
 53    }
 54
 55    public static func imagePlacements(_ links: [InlineImages.Link], in text: NSString) -> [ImagePlacement] {
 56        links.filter { $0.range.upperBound <= text.length }.map { link in
 57            let line = text.lineRange(for: NSRange(location: link.range.lowerBound, length: 0))
 58            let before = text.substring(with: NSRange(location: line.location, length: link.range.lowerBound - line.location))
 59            let after = NSMaxRange(line) > link.range.upperBound ? text.substring(with: NSRange(location: link.range.upperBound, length: NSMaxRange(line) - link.range.upperBound)) : ""
 60            return ImagePlacement(link: link, ownLine: (before + after).allSatisfy { $0 == " " || $0 == "\t" || $0.isNewline })
 61        }
 62    }
 63
 64    /// An image's size in points: `width` from `#+ATTR_ORG`, else its own, never wider than
 65    /// `maxWidth`, keeping its proportions.
 66    public static func imageSize(natural: CGSize, width: Int?, maxWidth: CGFloat) -> CGSize {
 67        let shown = min(width.map { CGFloat($0) } ?? natural.width, maxWidth)
 68        return CGSize(width: shown, height: natural.width > 0 ? shown * natural.height / natural.width : 0)
 69    }
 70
 71    /// The size of a font whose line is `height` tall, given a font of `pointSize` whose line
 72    /// is `lineHeight` tall. An image in the text sits on a hidden character in that font,
 73    /// which makes its line, and no other line of the paragraph, as tall as the image.
 74    public static func imageFontSize(height: CGFloat, pointSize: CGFloat, lineHeight: CGFloat) -> CGFloat {
 75        lineHeight > 0 ? max(0.01, height * pointSize / lineHeight) : pointSize
 76    }
 77
 78    /// Whether `role` hides while markup is hidden: link brackets and targets as with
 79    /// `org-link-descriptive`; emphasis markers only when Emacs hides them too.
 80    public static func hidesWithMarkup(_ role: StyleRole, options: EditingOptions) -> Bool {
 81        switch role {
 82        case .linkMarkup: true
 83        case .markup: options.hideEmphasisMarkers
 84        default: false
 85        }
 86    }
 87
 88    /// Whether a style run is skipped: leading stars show as the heading's color unless the
 89    /// view is indented or hides them.
 90    public static func skipsLeadingStars(_ role: StyleRole, indented: Bool, hideStars: Bool) -> Bool {
 91        role == .leadingStars && !indented && !hideStars
 92    }
 93
 94    /// One line's indentation under org-indent, in columns.
 95    public struct LineIndent: Sendable, Equatable {
 96        public let range: Range<Int>
 97        public let firstLine: Int
 98        public let wrapped: Int
 99    }
100
101    /// org-indent's indentation for the lines in `range`: each run of `indents`, with body lines
102    /// wrapping under their own text (past leading blanks, a list bullet and a checkbox) as
103    /// adaptive-wrap does in Emacs.
104    public static func lineIndents(_ tree: OrgTree, in range: Range<Int>) -> [LineIndent] {
105        let text = tree.text as NSString
106        var out: [LineIndent] = []
107        for run in indents(tree, in: range) {
108            let clipped = run.range.clamped(to: range)
109            guard !clipped.isEmpty else { continue }
110            guard run.firstLine == run.wrapped else {
111                out.append(LineIndent(range: clipped, firstLine: run.firstLine, wrapped: run.wrapped))
112                continue
113            }
114            var location = clipped.lowerBound
115            while location < clipped.upperBound {
116                let line = text.lineRange(for: NSRange(location: location, length: 0))
117                let hanging = hangingColumns(text.substring(with: line))
118                let lineRange = max(line.location, clipped.lowerBound)..<min(NSMaxRange(line), clipped.upperBound)
119                out.append(LineIndent(range: lineRange, firstLine: run.firstLine, wrapped: run.wrapped + hanging))
120                location = NSMaxRange(line)
121            }
122        }
123        return out
124    }
125
126    /// Roles drawn in the fixed-pitch font when the body font is proportional, as Emacs's
127    /// mixed-pitch-mode keeps `mixed-pitch-fixed-pitch-faces`: text that lines up by column.
128    public static func isFixedPitch(_ role: StyleRole) -> Bool {
129        switch role {
130        case .table, .rule, .block, .blockDelimiter, .verbatim, .code, .inlineSource, .metadata, .keyword, .tags, .timestamp, .syntax: true
131        default: false
132        }
133    }
134
135    /// The start of each line in `range` that sets where its text begins, for the fixed-pitch
136    /// font under a proportional body: a heading's stars and space, and the leading blanks,
137    /// bullet and checkbox `hangingColumns` counts. org-indent's indentation is in columns of
138    /// the fixed-pitch font, so these keep text lined up under it.
139    public static func fixedPitchPrefixes(_ text: NSString, in range: Range<Int>) -> [Range<Int>] {
140        var out: [Range<Int>] = []
141        var location = range.lowerBound
142        while location < range.upperBound {
143            let line = text.lineRange(for: NSRange(location: location, length: 0))
144            guard line.length > 0 else { break }
145            location = NSMaxRange(line)
146            let content = text.substring(with: line)
147            let stars = content.prefix { $0 == "*" }.count
148            let length: Int
149            if stars > 0, content.dropFirst(stars).first == " " {
150                length = stars + 1
151            } else {
152                length = hangingPrefix(content).utf16.count
153            }
154            if length > 0 { out.append(line.location..<(line.location + length)) }
155        }
156        return out
157    }
158
159    /// The characters `hangingColumns` counts: leading blanks, then a bullet, its space and a
160    /// checkbox.
161    static func hangingPrefix(_ line: String) -> Substring {
162        let blanks = line.prefix { $0 == " " || $0 == "\t" }
163        let rest = line.dropFirst(blanks.count)
164        var bullet = 0
165        if let first = rest.first, first == "-" || first == "+" || (first == "*" && !blanks.isEmpty) {
166            bullet = 1
167        } else {
168            let digits = rest.prefix { $0.isASCII && $0.isNumber }
169            if !digits.isEmpty, let separator = rest.dropFirst(digits.count).first, separator == "." || separator == ")" {
170                bullet = digits.count + 1
171            }
172        }
173        guard bullet > 0, rest.dropFirst(bullet).first == " " else { return blanks }
174        var length = blanks.count + bullet + 1
175        let afterBullet = rest.dropFirst(bullet + 1)
176        if afterBullet.count >= 4, afterBullet.first == "[", "X x-".contains(afterBullet.dropFirst().first!),
177           afterBullet.dropFirst(2).first == "]", afterBullet.dropFirst(3).first == " " {
178            length += 4
179        }
180        return line.prefix(length)
181    }
182
183    /// Columns a wrapped continuation of `line` should start past the line's own start.
184    public static func hangingColumns(_ line: String) -> Int {
185        var columns = 0
186        var rest = Substring(line)
187        while let c = rest.first, c == " " || c == "\t" {
188            columns = c == "\t" ? (columns / 8 + 1) * 8 : columns + 1
189            rest = rest.dropFirst()
190        }
191        // A bullet (`-`, `+`, `*` when indented, `1.`, `1)`) and its space, then a checkbox.
192        var bullet = 0
193        if let first = rest.first, first == "-" || first == "+" || (first == "*" && columns > 0) {
194            bullet = 1
195        } else {
196            let digits = rest.prefix { $0.isASCII && $0.isNumber }
197            if !digits.isEmpty, let separator = rest.dropFirst(digits.count).first, separator == "." || separator == ")" {
198                bullet = digits.count + 1
199            }
200        }
201        guard bullet > 0, rest.dropFirst(bullet).first == " " else { return columns }
202        columns += bullet + 1
203        let afterBullet = rest.dropFirst(bullet + 1)
204        if afterBullet.count >= 4, afterBullet.first == "[", "X x-".contains(afterBullet.dropFirst().first!),
205           afterBullet.dropFirst(2).first == "]", afterBullet.dropFirst(3).first == " " {
206            columns += 4
207        }
208        return columns
209    }
210
211    /// `org-pretty-entities` for the lines in `range`, with each run's line start: not on the
212    /// line starting at `revealedLine`, in comments or in blocks; sub/superscripts not in
213    /// `scriptExclusions` (emphasis, links, keywords), as `org-raise-scripts` leaves them.
214    public static func prettyRuns(
215        _ text: NSString, in range: Range<Int>, revealedLine: Int?, inBlock: (Int) -> Bool,
216        scriptExclusions: [Range<Int>], subSuperscriptsNeedBraces: Bool
217    ) -> [(lineStart: Int, run: PrettyEntities.Run)] {
218        var out: [(lineStart: Int, run: PrettyEntities.Run)] = []
219        var location = range.lowerBound
220        while location < range.upperBound {
221            let line = text.lineRange(for: NSRange(location: location, length: 0))
222            guard line.length > 0 else { break }
223            location = NSMaxRange(line)
224            if line.location == revealedLine || inBlock(line.location) { continue }
225            let content = text.substring(with: line)
226            if Self.isCommentOrKeyword(content) { continue }
227            for run in PrettyEntities.runs(in: content, subSuperscriptsNeedBraces: subSuperscriptsNeedBraces) {
228                if case .script(_, let body, _) = run {
229                    let bodyStart = line.location + body.lowerBound
230                    if body.isEmpty || scriptExclusions.contains(where: { $0.contains(bodyStart) }) { continue }
231                }
232                out.append((line.location, run))
233            }
234        }
235        return out
236    }
237
238    /// `^[ \t]*#([ +]|$)`: a comment or keyword line, which shows no entities.
239    static func isCommentOrKeyword(_ line: String) -> Bool {
240        let body = line.drop { $0 == " " || $0 == "\t" }
241        guard body.first == "#" else { return false }
242        let next = body.dropFirst().first
243        // `$` only at the end: the pattern ran on the line with its newline.
244        return next == nil || next == " " || next == "+"
245    }
246
247    /// Roles whose text keeps sub/superscript markers as written.
248    public static func excludesScripts(_ role: StyleRole) -> Bool {
249        switch role {
250        case .bold, .italic, .underline, .strikeThrough, .verbatim, .code, .link, .linkMarkup, .keyword: true
251        default: false
252        }
253    }
254}