Sources/OrgEditorAppKit/OrgEditor+Snippets.swift

a6efdda15d73f36320bc8a9004ecfbe07a6211f9
orgstar/Sources/OrgEditorAppKit/OrgEditor+Snippets.swift

142 lines · 5890 bytes

  1#if os(macOS)
  2import AppKit
  3import OrgCore
  4
  5/// Snippets: TAB after a trigger where TAB means nothing else expands it, then TAB and S-TAB
  6/// move between its fields until the last is left, Escape is pressed, or the caret or an edit
  7/// leaves the snippet. The active field has a band behind it, the others a fainter one.
  8extension OrgEditor {
  9    /// TAB with no binding that runs here: expands the trigger before the caret, if any.
 10    func snippetTab(_ chord: KeyChord) -> Bool {
 11        guard isOrg, chord == KeyChord("TAB"), !textView.hasMarkedText() else { return false }
 12        let expand = ExpandSnippet()
 13        guard expand.applies(in: context()) else { return false }
 14        perform(expand)
 15        return true
 16    }
 17
 18    /// Keys while a snippet's fields are filled in; nil lets the key through.
 19    func snippetKey(_ chord: KeyChord) -> Bool? {
 20        guard snippetSession != nil else { return nil }
 21        switch chord {
 22        case KeyChord("TAB"):
 23            nextSnippetField()
 24            return true
 25        case KeyChord("TAB", .shift):
 26            previousSnippetField()
 27            return true
 28        case KeyChord("ESC"):
 29            endSnippet()
 30            // Doom leaves insert state as well.
 31            return modal ? nil : true
 32        default:
 33            return nil
 34        }
 35    }
 36
 37    func nextSnippetField() {
 38        guard var session = snippetSession else { return }
 39        switch session.next() {
 40        case .field(let range):
 41            snippetSession = session
 42            select(range)
 43        case .exit(let range):
 44            endSnippet()
 45            select(range)
 46        }
 47    }
 48
 49    func previousSnippetField() {
 50        guard var session = snippetSession else { return }
 51        let range = session.previous()
 52        snippetSession = session
 53        select(range)
 54    }
 55
 56    func startSnippet(_ session: SnippetSession) {
 57        snippetSession = session
 58        highlightSnippet()
 59    }
 60
 61    func endSnippet() {
 62        snippetSession = nil
 63        highlightSnippet()
 64    }
 65
 66    private func select(_ range: Range<Int>) {
 67        if hidden.containing(range.lowerBound) != nil { unfold(around: range.lowerBound) }
 68        setCaret(range.lowerBound)
 69        if !range.isEmpty { textView.setSelectedRange(NSRange(range)) }
 70        highlightSnippet()
 71    }
 72
 73    /// An edit of the buffer; one outside the snippet ends it.
 74    func snippetEdited(_ edit: TextEdit) {
 75        guard var session = snippetSession else { return }
 76        snippetSession = session.map(edit) ? session : nil
 77    }
 78
 79    /// After a change: mirrors take their field's new text.
 80    func updateSnippetMirrors() {
 81        guard let session = snippetSession, !updatingMirrors, !textView.hasMarkedText() else { return highlightSnippet() }
 82        let edits = session.mirrorEdits(in: document.text)
 83        if !edits.isEmpty {
 84            updatingMirrors = true
 85            let selected = textView.selectedRange()
 86            let caret = selected.location
 87            applyEdits(edits)
 88            updatingMirrors = false
 89            // The caret stays in the field, moved by mirrors before it.
 90            let shift = edits.filter { $0.range.upperBound <= caret }.reduce(0) { $0 + $1.replacement.utf16.count - $1.range.count }
 91            textView.setSelectedRange(NSRange(location: caret + shift, length: selected.length))
 92        }
 93        highlightSnippet()
 94    }
 95
 96    /// The caret moved: outside the snippet, it ends.
 97    func snippetSelectionChanged() {
 98        guard let session = snippetSession, !updatingMirrors else { return }
 99        let selected = textView.selectedRange()
100        if !session.contains(selected.location) || !session.contains(NSMaxRange(selected)) { endSnippet() }
101    }
102
103    /// Draws the fields of the session, and removes what was drawn for the last one.
104    func highlightSnippet() {
105        let length = utf16Length
106        var covered = snippetHighlight.flatMap { $0.upperBound <= length ? $0 : $0.lowerBound < length ? $0.lowerBound..<length : nil }
107        if let extent = snippetSession?.extent, extent.upperBound <= length {
108            covered = covered.map { min($0.lowerBound, extent.lowerBound)..<max($0.upperBound, extent.upperBound) } ?? extent
109        }
110        for manager in layoutManagers {
111            if let covered, let range = textRange(covered) {
112                manager.removeRenderingAttribute(.backgroundColor, for: range)
113            }
114            guard let session = snippetSession else { continue }
115            for (index, field) in session.fields.enumerated() {
116                for (n, r) in field.ranges.enumerated() where !r.isEmpty && r.upperBound <= length {
117                    guard let range = textRange(r) else { continue }
118                    if index == session.active, n == 0 {
119                        manager.addRenderingAttribute(.backgroundColor, value: NSColor.findHighlightColor.withAlphaComponent(0.35), for: range)
120                    } else {
121                        manager.addRenderingAttribute(.backgroundColor, value: NSColor.gray.withAlphaComponent(0.2), for: range)
122                    }
123                }
124            }
125        }
126        snippetHighlight = snippetSession?.extent
127    }
128
129    private func textRange(_ r: Range<Int>) -> NSTextRange? {
130        let manager = textContentStorage
131        guard let start = manager.location(manager.documentRange.location, offsetBy: r.lowerBound),
132              let end = manager.location(start, offsetBy: r.count) else { return nil }
133        return NSTextRange(location: start, end: end)
134    }
135
136    /// Chosen from the completion list: the trigger typed so far becomes the snippet.
137    func expandCompleted(_ completion: Completion, _ trigger: String) {
138        textView.setSelectedRange(NSRange(location: completion.range.lowerBound, length: completion.range.count))
139        perform(ExpandNamedSnippet(trigger: trigger))
140    }
141}
142#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