Sources/OrgEditorAppKit/ViewToggles.swift

114 lines · 4795 bytes

  1#if os(macOS)
  2import AppKit
  3import OrgCore
  4import OrgPresentation
  5
  6/// Spell checking, line truncation and mouse clicks on heading stars and checkboxes.
  7extension OrgEditor {
  8    // MARK: - Spell checking
  9
 10    public var spellChecking: Bool {
 11        get { textView.isContinuousSpellCheckingEnabled }
 12        set {
 13            for view in textViews { view.isContinuousSpellCheckingEnabled = newValue }
 14            if !newValue, let storage = textView.textStorage {
 15                storage.removeAttribute(.spellingState, range: NSRange(location: 0, length: storage.length))
 16            }
 17        }
 18    }
 19
 20    func toggleSpellCheck() {
 21        spellChecking.toggle()
 22        onMessage?(spellChecking ? "Spell checking enabled" : "Spell checking disabled")
 23    }
 24
 25    /// Ranges spell-fu skips in Org, for this revision of the text.
 26    func spellSkipped() -> [Range<Int>] {
 27        if let cached = spellSkipCache, cached.text == document.text { return cached.ranges }
 28        let ranges = isOrg ? SpellCheck.skipped(document.tree) : []
 29        spellSkipCache = (document.text, ranges)
 30        return ranges
 31    }
 32
 33    // MARK: - Truncation
 34
 35    /// `toggle-truncate-lines`: long lines run off the right edge instead of wrapping.
 36    public var truncatesLines: Bool {
 37        get { !(textView.textContainer?.widthTracksTextView ?? true) }
 38        set {
 39            guard let container = textView.textContainer, newValue != truncatesLines else { return }
 40            let scroll = textView.enclosingScrollView
 41            keepingTopLine {
 42                scroll?.hasHorizontalScroller = newValue
 43                textView.isHorizontallyResizable = newValue
 44                if newValue {
 45                    container.widthTracksTextView = false
 46                    container.size = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
 47                    textView.autoresizingMask = [.width, .height]
 48                } else {
 49                    let width = scroll?.contentSize.width ?? textView.frame.width
 50                    textView.setFrameSize(NSSize(width: width, height: textView.frame.height))
 51                    container.size = NSSize(width: width, height: CGFloat.greatestFiniteMagnitude)
 52                    container.widthTracksTextView = true
 53                    textView.autoresizingMask = [.width]
 54                }
 55                textLayoutManager.invalidateLayout(for: textLayoutManager.documentRange)
 56            }
 57            // Truncated lines take the whole width; wrapped ones the text width again.
 58            (textView as? OrgTextView)?.updateGutter()
 59            textView.needsDisplay = true
 60        }
 61    }
 62
 63    func toggleTruncateLines() {
 64        truncatesLines.toggle()
 65        onMessage?(truncatesLines ? "Truncate long lines enabled" : "Truncate long lines disabled")
 66    }
 67
 68    // MARK: - Clicks
 69
 70    /// A click on a heading's stars cycles it; a click on a checkbox toggles it.
 71    func click(at offset: Int) -> Bool {
 72        guard isOrg else { return false }
 73        var node = document.tree.root
 74        while let child = node.child(containing: offset) ?? node.child(containing: offset - 1) {
 75            node = child
 76            if child.kind == .heading || child.kind == .item { break }
 77        }
 78        let tokens = node.tokens.filter { $0.range.lowerBound <= offset && offset <= $0.range.upperBound }
 79        if node.kind == .heading, tokens.contains(where: { $0.kind == .stars }) {
 80            setCaret(node.range.lowerBound)
 81            _ = cycleAtCaret()
 82            return true
 83        }
 84        if node.kind == .item, let box = tokens.first(where: { $0.kind == .checkbox }) {
 85            setCaret(box.range.lowerBound)
 86            run("org.checkbox.toggle")
 87            return true
 88        }
 89        return false
 90    }
 91}
 92
 93extension OrgEditor: NSTextViewDelegate {
 94    public func textViewDidChangeSelection(_ notification: Notification) {
 95        // Another view's caret moving (a mapped selection, say) is its own business.
 96        guard (notification.object as AnyObject?) === textView else { return }
 97        selectionChanged()
 98        if completionPopup != nil, let popup = completionPopup, textView.selectedRange().location != popup.completion.range.upperBound {
 99            refreshCompletion()
100        }
101    }
102
103    public func textDidChange(_ notification: Notification) {
104        textTyped()
105    }
106
107    /// No spelling marks in code, links, dates, tags or keywords.
108    public func textView(_ textView: NSTextView, shouldSetSpellingState value: Int, range affectedCharRange: NSRange) -> Int {
109        guard value != 0 else { return value }
110        let range = affectedCharRange.location..<NSMaxRange(affectedCharRange)
111        return spellSkipped().contains { $0.overlaps(range) } ? 0 : value
112    }
113}
114#endif