Sources/OrgEditorAppKit/OrgEditor+Styling.swift

58f3b73e8ff337e5a15111fbb32c0d57cf2346da
orgstar/Sources/OrgEditorAppKit/OrgEditor+Styling.swift history · blame · raw

118 lines · 6078 bytes

7 symbols in this file
  1#if os(macOS)
  2import AppKit
  3import OrgCore
  4import OrgPresentation
  5
  6extension OrgEditor {
  7    // MARK: - Styling
  8
  9    func restyleOutsideEditing(_ range: Range<Int>) {
 10        guard let storage = textView.textStorage else { return }
 11        storage.beginEditing()
 12        restyle(range, in: storage)
 13        storage.endEditing()
 14    }
 15
 16    /// Sets attributes for whole lines in `range`. Safe inside `didProcessEditing`, where
 17    /// attribute changes are allowed and characters must not change.
 18    func restyle(_ range: Range<Int>, in storage: NSTextStorage) {
 19        guard !range.isEmpty else { return }
 20        let whole = NSRange(range)
 21        storage.setAttributes(theme.base, range: whole)
 22        guard isOrg else {
 23            for run in plainRuns() where run.range.overlaps(range) {
 24                guard let clipped = clip(run.range, to: range) else { continue }
 25                theme.apply(.syntax(run.category), to: storage, range: clipped)
 26            }
 27            return
 28        }
 29        let revealed = caretLine
 30        let (changes, scriptExclusions) = Presentation.styleChanges(
 31            document.tree, in: range, highlighter: highlighter, indented: indented, hideStars: hideStars,
 32            showMarkup: showMarkup, options: options, revealed: revealed.location..<NSMaxRange(revealed)
 33        )
 34        for change in changes {
 35            switch change {
 36            case .indent(let line): storage.addAttribute(.paragraphStyle, value: paragraphStyle(line.firstLine, line.wrapped), range: NSRange(line.range))
 37            case .role(let role, let range): theme.apply(role, to: storage, range: NSRange(range))
 38            case .hidden(let range): storage.addAttributes(theme.hidden, range: NSRange(range))
 39            }
 40        }
 41        if theme.mixedPitch {
 42            for prefix in Presentation.fixedPitchPrefixes(storage.string as NSString, in: range) {
 43                guard let clipped = clip(prefix, to: range) else { continue }
 44                storage.addAttribute(.font, value: theme.fixedPitch(storage, clipped), range: clipped)
 45            }
 46        }
 47        if !showMarkup, options.prettyEntities { prettify(range, in: storage, revealed: revealed, scriptExclusions: scriptExclusions) }
 48        applyShrunk(range, in: storage)
 49        applyHighlights(range, in: storage)
 50        applyImages(range, in: storage, revealed: revealed)
 51        applyLatex(range, in: storage, revealed: revealed)
 52    }
 53
 54    /// `org-pretty-entities`: entities drawn as their character over the entity's last
 55    /// character (the rest hidden), sub/superscripts raised without their markers.
 56    private func prettify(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange, scriptExclusions: [Range<Int>]) {
 57        let runs = Presentation.prettyRuns(
 58            storage.string as NSString, in: range, revealedLine: revealed.location, inBlock: { shaded.containing($0) != nil },
 59            scriptExclusions: scriptExclusions, subSuperscriptsNeedBraces: options.subSuperscriptsNeedBraces
 60        )
 61        for (lineStart, run) in runs {
 62            switch run {
 63            case .entity(let r, let display):
 64                let start = lineStart + r.lowerBound
 65                let last = lineStart + r.upperBound - 1
 66                if last > start { storage.addAttributes(theme.hidden, range: NSRange(location: start, length: last - start)) }
 67                storage.addAttributes([.foregroundColor: NSColor.clear, .orgEntityDisplay: display], range: NSRange(location: last, length: 1))
 68            case .script(let markers, let body, let superscript):
 69                for marker in markers {
 70                    storage.addAttributes(theme.hidden, range: NSRange(location: lineStart + marker.lowerBound, length: marker.count))
 71                }
 72                let size = theme.font.pointSize
 73                storage.addAttributes([
 74                    .font: theme.mixedPitch ? theme.body.withSize(size * 0.7) : NSFont.monospacedSystemFont(ofSize: size * 0.7, weight: .regular),
 75                    .baselineOffset: (superscript ? 0.3 : -0.3) * size,
 76                ], range: NSRange(location: lineStart + body.lowerBound, length: body.count))
 77            }
 78        }
 79    }
 80
 81    /// Moving to another line shows its markup and hides the last one's.
 82    func revealCaretLine() {
 83        // LaTeX previews and images show their source on the caret's line whether or not markup shows.
 84        guard !showMarkup || showsLatex || showsImages, isOrg else { return }
 85        let line = caretLine
 86        guard line != revealedLine else { return }
 87        let text = textView.string as NSString
 88        // The old line may have moved with edits since; restyle the line now at its start.
 89        let old = revealedLine.flatMap { $0.location <= text.length ? text.lineRange(for: NSRange(location: $0.location, length: 0)) : nil }
 90        revealedLine = line
 91        for range in [old, line].compactMap({ $0 }) where range.location < styledUpTo {
 92            restyleOutsideEditing(range.location..<NSMaxRange(range))
 93        }
 94    }
 95
 96    /// Code highlights for the whole file in plain mode.
 97    private func plainRuns() -> [(range: Range<Int>, category: SyntaxCategory)] {
 98        guard case .plain(let language?) = mode, let highlighter else { return [] }
 99        if let codeRuns, codeRuns.revision == document.revision { return codeRuns.runs }
100        let runs = highlighter.highlights(language: language, code: document.text)
101        codeRuns = (document.revision, runs)
102        return runs
103    }
104
105    private func paragraphStyle(_ firstLine: Int, _ wrapped: Int) -> NSParagraphStyle {
106        let key = IndentKey(firstLine: firstLine, wrapped: wrapped)
107        if let style = paragraphStyles[key] { return style }
108        let style = theme.paragraphStyle(firstLine: firstLine, wrapped: wrapped)
109        paragraphStyles[key] = style
110        return style
111    }
112
113    private func clip(_ run: Range<Int>, to range: Range<Int>) -> NSRange? {
114        let clipped = run.clamped(to: range)
115        return clipped.isEmpty ? nil : NSRange(clipped)
116    }
117}
118#endif