Sources/OrgEditorAppKit/OrgEditor+Styling.swift

49c5da97098ed000be935c19462d4102812b0471
orgstar/Sources/OrgEditorAppKit/OrgEditor+Styling.swift

185 lines · 9913 bytes

10 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        if isMarkdown {
 23            for run in Presentation.markdownStyles(markdown, in: range, highlighter: highlighter) {
 24                guard let clipped = clip(run.range, to: range) else { continue }
 25                theme.apply(run.role, to: storage, range: clipped)
 26            }
 27            applyHighlights(range, in: storage)
 28            return
 29        }
 30        guard isOrg else {
 31            for run in plainRuns() where run.range.overlaps(range) {
 32                guard let clipped = clip(run.range, to: range) else { continue }
 33                theme.apply(.syntax(run.category), to: storage, range: clipped)
 34            }
 35            return
 36        }
 37        let revealed = caretLine
 38        let (changes, scriptExclusions) = Presentation.styleChanges(
 39            document.tree, in: range, highlighter: highlighter, indented: indented, hideStars: hideStars,
 40            showMarkup: showMarkup, options: options, revealed: revealed.location..<NSMaxRange(revealed)
 41        )
 42        var tags: [Range<Int>] = []
 43        for change in changes {
 44            switch change {
 45            case .indent(let line): storage.addAttribute(.paragraphStyle, value: paragraphStyle(line.firstLine, line.wrapped), range: NSRange(line.range))
 46            case .role(let role, let range):
 47                theme.apply(role, to: storage, range: NSRange(range))
 48                if role == .tags { tags.append(range) }
 49            case .hidden(let range): storage.addAttributes(theme.hidden, range: NSRange(range))
 50            }
 51        }
 52        if theme.mixedPitch {
 53            for prefix in Presentation.fixedPitchPrefixes(storage.string as NSString, in: range) {
 54                guard let clipped = clip(prefix, to: range) else { continue }
 55                storage.addAttribute(.font, value: theme.fixedPitch(storage, clipped), range: clipped)
 56            }
 57        }
 58        if !showMarkup, options.prettyEntities { prettify(range, in: storage, revealed: revealed, scriptExclusions: scriptExclusions) }
 59        applyShrunk(range, in: storage)
 60        applyHighlights(range, in: storage)
 61        applyImages(range, in: storage, revealed: revealed)
 62        applyLatex(range, in: storage, revealed: revealed)
 63        fitTagGaps(tags, in: storage)
 64    }
 65
 66    /// The text container's width, for tag gaps: the narrowest view's, as images are sized.
 67    var tagGapAvailableWidth: CGFloat {
 68        let widths = textViews.compactMap { view in view.textContainer.map { $0.size.width - 2 * $0.lineFragmentPadding } }
 69        return widths.filter { $0 > 0 }.min() ?? 0
 70    }
 71
 72    /// Draws the spaces before each heading's tags in `tags` as one gap that fits the view
 73    /// (`Presentation.tagGapWidth`): all but the last space hidden, the last widened.
 74    func fitTagGaps(_ tags: [Range<Int>], in storage: NSTextStorage) {
 75        guard !tags.isEmpty else { return }
 76        let available = tagGapAvailableWidth
 77        guard available > 0 else { return }
 78        // The storage's own string: `string` copies the whole text.
 79        let text = storage.mutableString
 80        for range in tags where range.upperBound <= text.length {
 81            guard let gap = Presentation.tagGap(tags: range, in: text) else { continue }
 82            let line = text.lineRange(for: NSRange(location: gap.gap.lowerBound, length: 0))
 83            let indent = (storage.attribute(.paragraphStyle, at: line.location, effectiveRange: nil) as? NSParagraphStyle)?.firstLineHeadIndent ?? 0
 84            // Without the paragraph style, whose indent is taken from the width apart.
 85            func width(_ range: Range<Int>) -> CGFloat {
 86                let part = NSMutableAttributedString(attributedString: storage.attributedSubstring(from: NSRange(range)))
 87                part.removeAttribute(.paragraphStyle, range: NSRange(location: 0, length: part.length))
 88                return part.size().width
 89            }
 90            // Spaces measured before the tags: trailing spaces may not count.
 91            let last = gap.gap.upperBound - 1
 92            let title = width(line.location..<gap.gap.lowerBound), tagsWidth = width(gap.tags)
 93            let space = width(last..<gap.tags.upperBound) - tagsWidth
 94            // A point to spare, so rounding doesn't wrap the tags.
 95            guard let shown = Presentation.tagGapWidth(
 96                title: title, gap: width(line.location..<gap.tags.upperBound) - title - tagsWidth, space: space, tags: tagsWidth,
 97                available: available - indent - 1
 98            ) else { continue }
 99            storage.addAttributes(theme.hidden, range: NSRange(gap.gap.lowerBound..<last))
100            storage.addAttribute(.kern, value: max(0, shown - space), range: NSRange(location: last, length: 1))
101        }
102    }
103
104    /// Draws tag gaps again once the view's width has changed, after the layout pass that changed it.
105    func refitTagGaps() {
106        guard isOrg, !fittingTagGaps else { return }
107        fittingTagGaps = true
108        DispatchQueue.main.async { [weak self] in
109            guard let self else { return }
110            self.fittingTagGaps = false
111            guard self.tagGapWidth != self.tagGapAvailableWidth else { return }
112            let text = self.document.text as NSString
113            for gap in Presentation.tagGaps(self.document.tree) where gap.tags.upperBound <= text.length {
114                let line = text.lineRange(for: NSRange(location: gap.gap.lowerBound, length: 0))
115                self.restyleOutsideEditing(line.location..<NSMaxRange(line))
116            }
117            self.tagGapWidth = self.tagGapAvailableWidth
118        }
119    }
120
121    /// `org-pretty-entities`: entities drawn as their character over the entity's last
122    /// character (the rest hidden), sub/superscripts raised without their markers.
123    private func prettify(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange, scriptExclusions: [Range<Int>]) {
124        let runs = Presentation.prettyRuns(
125            storage.string as NSString, in: range, revealedLine: revealed.location, inBlock: { shaded.containing($0) != nil },
126            scriptExclusions: scriptExclusions, subSuperscriptsNeedBraces: options.subSuperscriptsNeedBraces
127        )
128        for (lineStart, run) in runs {
129            switch run {
130            case .entity(let r, let display):
131                let start = lineStart + r.lowerBound
132                let last = lineStart + r.upperBound - 1
133                if last > start { storage.addAttributes(theme.hidden, range: NSRange(location: start, length: last - start)) }
134                storage.addAttributes([.foregroundColor: NSColor.clear, .orgEntityDisplay: display], range: NSRange(location: last, length: 1))
135            case .script(let markers, let body, let superscript):
136                for marker in markers {
137                    storage.addAttributes(theme.hidden, range: NSRange(location: lineStart + marker.lowerBound, length: marker.count))
138                }
139                let size = theme.font.pointSize
140                storage.addAttributes([
141                    .font: theme.mixedPitch ? theme.body.withSize(size * 0.7) : NSFont.monospacedSystemFont(ofSize: size * 0.7, weight: .regular),
142                    .baselineOffset: (superscript ? 0.3 : -0.3) * size,
143                ], range: NSRange(location: lineStart + body.lowerBound, length: body.count))
144            }
145        }
146    }
147
148    /// Moving to another line shows its markup and hides the last one's.
149    func revealCaretLine() {
150        // LaTeX previews and images show their source on the caret's line whether or not markup shows.
151        guard !showMarkup || showsLatex || showsImages, isOrg else { return }
152        let line = caretLine
153        guard line != revealedLine else { return }
154        let text = textView.string as NSString
155        // The old line may have moved with edits since; restyle the line now at its start.
156        let old = revealedLine.flatMap { $0.location <= text.length ? text.lineRange(for: NSRange(location: $0.location, length: 0)) : nil }
157        revealedLine = line
158        for range in [old, line].compactMap({ $0 }) where range.location < styledUpTo {
159            restyleOutsideEditing(range.location..<NSMaxRange(range))
160        }
161    }
162
163    /// Code highlights for the whole file in plain mode.
164    private func plainRuns() -> [(range: Range<Int>, category: SyntaxCategory)] {
165        guard case .plain(let language?) = mode, let highlighter else { return [] }
166        if let codeRuns, codeRuns.revision == document.revision { return codeRuns.runs }
167        let runs = highlighter.highlights(language: language, code: document.text)
168        codeRuns = (document.revision, runs)
169        return runs
170    }
171
172    private func paragraphStyle(_ firstLine: Int, _ wrapped: Int) -> NSParagraphStyle {
173        let key = IndentKey(firstLine: firstLine, wrapped: wrapped)
174        if let style = paragraphStyles[key] { return style }
175        let style = theme.paragraphStyle(firstLine: firstLine, wrapped: wrapped)
176        paragraphStyles[key] = style
177        return style
178    }
179
180    private func clip(_ run: Range<Int>, to range: Range<Int>) -> NSRange? {
181        let clipped = run.clamped(to: range)
182        return clipped.isEmpty ? nil : NSRange(clipped)
183    }
184}
185#endif
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form