Sources/OrgstarMobile/MobileEditor+Modal.swift

403 lines · 19214 bytes

18 symbols in this file
  1#if os(iOS)
  2import OrgCore
  3import UIKit
  4
  5/// Modal editing with the Doom preset on a hardware keyboard, as the Mac's editor does it:
  6/// keys go to the keymap for the current evil state first, then to `Vim`. Text typed on the
  7/// on-screen keyboard in normal state goes in as insert state does.
  8extension MobileEditor {
  9    func handleModal(_ chord: KeyChord) -> Bool {
 10        if recordingRegister != nil, replayingMacro == 0 { recordedKeys.append(chord) }
 11        dispatcher.mode = vim.mode.keymapMode
 12        if !vim.pending.isEmpty, vim.mode != .insert { return feedVim([chord]) }
 13        switch dispatcher.feed(chord) {
 14        case .pending(let keys):
 15            onMessage?(KeySequence.format(keys) + "-")
 16            return true
 17        case .cancelled:
 18            return true
 19        case .complete(let keys, let candidates):
 20            let context = editContext()
 21            if let binding = candidates.first(where: { binding in
 22                (binding.when.map { KeyContext.holds($0, in: context) } ?? true) && applies(binding.command, in: context)
 23            }) {
 24                run(binding.command)
 25                updateCursor()
 26                return true
 27            }
 28            return feedVim(keys)
 29        case .undefined(let keys):
 30            // The leader and Emacs prefixes mean nothing to evil, as on the Mac.
 31            if let first = keys.first, first == KeyChord("SPC") || !first.modifiers.isDisjoint(with: [.control, .meta]) {
 32                onMessage?("\(KeySequence.format(keys)) is undefined")
 33                return true
 34            }
 35            return feedVim(keys)
 36        case .unbound:
 37            return feedVim([chord])
 38        }
 39    }
 40
 41    /// Plays keys into the engine. False hands a single key in insert state to the text system.
 42    func feedVim(_ keys: [KeyChord]) -> Bool {
 43        for key in keys {
 44            if vim.mode == .insert, vim.passesThrough(key) {
 45                if keys.count == 1 { return false }
 46                insertTyped(key)
 47                continue
 48            }
 49            let leaving = key == KeyChord("ESC") || key == KeyChord("[", .control) || key == KeyChord("g", .control)
 50            if vim.mode == .insert, leaving, let snapshot = insertSnapshot,
 51               let edit = TextEdit.between(snapshot, document.text).first, edit.range.count == 0 {
 52                vim.inserted(edit.replacement)
 53            }
 54            let wasInsert = vim.mode == .insert
 55            let visual = [.visual, .visualLine, .visualBlock].contains(vim.mode)
 56            let caret = visual ? (visualCaret ?? textView.selectedRange.location) : textView.selectedRange.location
 57            var marks = vimMarks
 58            if jumpIndex > 0, jumpIndex <= jumpList.count { marks["'"] = jumpList[jumpIndex - 1] }
 59            vim.registers = Self.vimRegisters
 60            vim.clipboardRecord = Self.vimClipboardRecord
 61            // Reading the clipboard asks for permission, so only the keys that paste read it.
 62            let pastes = key.modifiers.isEmpty && (key.key == "p" || key.key == "P")
 63            let clipboard = pastes ? UIPasteboard.general.string : Self.vimClipboardRecord?.text
 64            let actions = vim.feed(key, Vim.Context(text: document.text, caret: caret, clipboard: clipboard, halfPage: halfPage, marks: marks, visible: visibleText, org: true,
 65                                                    fileName: fileName, lastEx: Self.promptHistory[":"]?.last))
 66            Self.vimRegisters = vim.registers
 67            Self.vimClipboardRecord = vim.clipboardRecord
 68            apply(actions)
 69            if !wasInsert, vim.mode == .insert {
 70                insertSnapshot = document.text
 71            } else if vim.mode != .insert {
 72                insertSnapshot = nil
 73            }
 74        }
 75        updateCursor()
 76        return true
 77    }
 78
 79    func insertTyped(_ key: KeyChord) {
 80        let text = key.key == "SPC" ? " " : key.key == "RET" ? "\n" : key.key == "TAB" ? "\t" : key.key
 81        guard key.modifiers.isEmpty || key.modifiers == [.shift], text.count == 1 else { return }
 82        textView.insertText(text)
 83    }
 84
 85    /// Typing on the on-screen keyboard outside insert state: the keys can't reach the engine,
 86    /// so the text goes in as from insert state.
 87    func typedOutsideInsert() {
 88        guard modal, vim.mode != .insert else { return }
 89        vim.reset()
 90        vim.enterInsert(at: textView.selectedRange.location, keys: [KeyChord("i")])
 91        insertSnapshot = document.text
 92        updateCursor()
 93    }
 94
 95    var halfPage: Int {
 96        let lineHeight = max(1, theme.font.lineHeight)
 97        return max(1, Int(textView.bounds.height / lineHeight / 2))
 98    }
 99
100    /// The text the window shows.
101    var visibleText: Range<Int>? {
102        let top = CGPoint(x: textView.textContainerInset.left, y: textView.contentOffset.y + textView.textContainerInset.top)
103        let bottom = CGPoint(x: textView.bounds.width - 1, y: textView.contentOffset.y + textView.bounds.height - 1)
104        guard let first = textView.characterRange(at: top), let last = textView.characterRange(at: bottom) else { return nil }
105        let lower = textView.offset(from: textView.beginningOfDocument, to: first.start)
106        let upper = textView.offset(from: textView.beginningOfDocument, to: last.end)
107        return lower..<max(lower, upper)
108    }
109
110    private func setCaret(_ offset: Int) {
111        let length = (document.text as NSString).length
112        textView.selectedRange = NSRange(location: min(max(0, offset), length), length: 0)
113        textView.scrollRangeToVisible(textView.selectedRange)
114    }
115
116    func apply(_ actions: [Vim.Action]) {
117        for action in actions {
118            switch action {
119            case .edit(let edits, let caret):
120                visualCaret = nil
121                guard textView.isEditable else {
122                    onMessage?("This file is read-only.")
123                    continue
124                }
125                applyEdits(edits)
126                setCaret(caret)
127            case .move(let caret):
128                setCaret(caret)
129                visualCaret = caret
130            case .select(let range):
131                textView.selectedRange = NSRange(range)
132            case .selectBlock(let ranges):
133                // One selection: from the first line's start to the last line's end.
134                if let first = ranges.first, let last = ranges.last {
135                    textView.selectedRange = NSRange(location: first.lowerBound, length: max(0, last.upperBound - first.lowerBound))
136                }
137            case .command(let id):
138                run(id)
139            case .visualLines(let count):
140                moveLines(count)
141            case .undo(let count):
142                for _ in 0..<count { textView.undoManager?.undo() }
143            case .redo(let count):
144                for _ in 0..<count { textView.undoManager?.redo() }
145            case .setClipboard(let text):
146                UIPasteboard.general.string = text
147            case .prompt(let kind):
148                prompt(kind)
149            case .commandWindow(let kind):
150                prompt(kind, history: true)
151            case .ex(let command):
152                ex(command)
153            case .fill(let range, let keep):
154                visualCaret = nil
155                textView.selectedRange = NSRange(location: textView.selectedRange.location, length: 0)
156                _ = perform(FillRegion(range: range, keep: keep))
157            case .message(let text):
158                onMessage?(text)
159            case .setMark(let name, let offset):
160                vimMarks[name] = offset
161            case .jumped(let from):
162                jumpList = Array(jumpList.prefix(jumpIndex))
163                if jumpList.last != from { jumpList.append(from) }
164                if jumpList.count > 100 { jumpList.removeFirst(jumpList.count - 100) }
165                jumpIndex = jumpList.count
166            case .jumpBack(let count):
167                if jumpIndex == jumpList.count {
168                    jumpList.append(textView.selectedRange.location)
169                    jumpIndex = jumpList.count - 1
170                }
171                guard jumpIndex - count >= 0 else { continue }
172                jumpIndex -= count
173                reveal(jumpList[jumpIndex])
174            case .jumpForward(let count):
175                guard jumpIndex + count < jumpList.count else { continue }
176                jumpIndex += count
177                reveal(jumpList[jumpIndex])
178            case .recordMacro(let name):
179                if let name {
180                    recordingRegister = name
181                    recordedKeys = []
182                    onMessage?("Defining keyboard macro…")
183                } else if let register = recordingRegister {
184                    Self.macros[register] = Array(recordedKeys.dropLast())
185                    recordingRegister = nil
186                    onMessage?("Keyboard macro defined")
187                }
188            case .playMacro(let name, let count):
189                guard let keys = Self.macros[name], !keys.isEmpty else {
190                    onMessage?("No macro in register \(name)")
191                    continue
192                }
193                guard replayingMacro < 20 else { continue }
194                replayingMacro += 1
195                defer { replayingMacro -= 1 }
196                for _ in 0..<count {
197                    for key in keys where !handleModal(key) { insertTyped(key) }
198                }
199            case .scroll(let place):
200                scrollCaretLine(place)
201            case .scrollLines(let count):
202                scrollLines(count)
203            case .scrollColumns(let count, let halfWidths):
204                scrollColumns(count, halfWidths: halfWidths)
205            }
206        }
207    }
208
209    /// `gj` and `gk` by text lines, keeping the column.
210    private func moveLines(_ count: Int) {
211        let ns = document.text as NSString
212        var caret = textView.selectedRange.location
213        let column = caret - ns.lineRange(for: NSRange(location: caret, length: 0)).location
214        for _ in 0..<abs(count) {
215            let line = ns.lineRange(for: NSRange(location: caret, length: 0))
216            if count > 0 {
217                guard NSMaxRange(line) < ns.length else { break }
218                caret = NSMaxRange(line)
219            } else {
220                guard line.location > 0 else { break }
221                caret = ns.lineRange(for: NSRange(location: line.location - 1, length: 0)).location
222            }
223        }
224        let line = ns.lineRange(for: NSRange(location: caret, length: 0))
225        var end = 0
226        ns.getLineStart(nil, end: nil, contentsEnd: &end, for: line)
227        setCaret(min(line.location + column, max(line.location, end - 1)))
228    }
229
230    /// `zz`, `zt` and `zb`.
231    private func scrollCaretLine(_ place: Vim.ScrollLine) {
232        guard let position = textView.selectedTextRange?.start else { return }
233        let rect = textView.caretRect(for: position)
234        let height = textView.bounds.height - textView.adjustedContentInset.top - textView.adjustedContentInset.bottom
235        var y: CGFloat = switch place {
236        case .top: rect.minY
237        case .center: rect.midY - height / 2
238        case .bottom: rect.maxY - height
239        }
240        y -= textView.adjustedContentInset.top
241        let maxY = max(-textView.adjustedContentInset.top, textView.contentSize.height - textView.bounds.height + textView.adjustedContentInset.bottom)
242        textView.setContentOffset(CGPoint(x: textView.contentOffset.x, y: min(max(-textView.adjustedContentInset.top, y), maxY)), animated: false)
243    }
244
245    /// C-e and C-y: the window down or up by lines; the cursor stays in it, as in Emacs.
246    private func scrollLines(_ count: Int) {
247        let inset = textView.adjustedContentInset
248        let maxY = max(-inset.top, textView.contentSize.height - textView.bounds.height + inset.bottom)
249        let y = textView.contentOffset.y + CGFloat(count) * max(1, theme.font.lineHeight)
250        textView.setContentOffset(CGPoint(x: textView.contentOffset.x, y: min(max(-inset.top, y), maxY)), animated: false)
251        guard vim.mode == .normal, let visible = visibleText, !visible.isEmpty else { return }
252        let caret = textView.selectedRange.location
253        let ns = document.text as NSString
254        // Without scrolling back to where the cursor was.
255        if caret < visible.lowerBound {
256            textView.selectedRange = NSRange(location: ns.lineRange(for: NSRange(location: visible.lowerBound, length: 0)).location, length: 0)
257        } else if caret >= visible.upperBound {
258            textView.selectedRange = NSRange(location: ns.lineRange(for: NSRange(location: visible.upperBound - 1, length: 0)).location, length: 0)
259        }
260    }
261
262    /// `zl`, `zh`, `zL` and `zH`: the window right or left by columns or half its width, which
263    /// moves nothing while lines wrap.
264    private func scrollColumns(_ count: Int, halfWidths: Bool) {
265        let step = halfWidths ? textView.bounds.width / 2 : (" " as NSString).size(withAttributes: [.font: theme.font]).width
266        let maxX = max(0, textView.contentSize.width - textView.bounds.width)
267        let x = textView.contentOffset.x + CGFloat(count) * step
268        textView.setContentOffset(CGPoint(x: min(max(0, x), maxX), y: textView.contentOffset.y), animated: false)
269    }
270
271    /// `/`, `?` and `:`; with `history` (`q:`), the earlier ones to pick and edit.
272    private func prompt(_ kind: String, history: Bool = false) {
273        let earlier = Array((Self.promptHistory[kind] ?? []).reversed())
274        let request = history ? Prompt(key: kind, message: kind, choices: earlier, requireMatch: false) : Prompt(key: kind, message: kind)
275        onPrompt?(request) { [weak self] answer in
276            guard let self, let answer, !answer.isEmpty else { return }
277            var list = Self.promptHistory[kind] ?? []
278            list.removeAll { $0 == answer }
279            list.append(answer)
280            Self.promptHistory[kind] = Array(list.suffix(100))
281            if kind == ":" {
282                self.ex(answer)
283            } else {
284                self.apply(self.vim.search(answer, forward: kind == "/", Vim.Context(text: self.document.text, caret: self.textView.selectedRange.location)))
285            }
286            self.updateCursor()
287        }
288    }
289
290    /// `:w`, `:N` and `:s` / `:%s`; files save on their own on iOS.
291    func ex(_ command: String) {
292        let trimmed = command.trimmingCharacters(in: .whitespaces)
293        switch trimmed {
294        case "w", "write", "wq", "x": onAppCommand?("app.save")
295        case "noh", "nohlsearch": break
296        case "s", "&", "&&", "%&&":
297            // The last substitution again; `&&` keeps its flags.
298            guard let last = Self.lastSubstitute else { return }
299            substitute(whole: trimmed.hasPrefix("%"), pattern: last.pattern, replacement: last.replacement, flags: trimmed.hasSuffix("&&") ? last.flags : "")
300        default:
301            if let line = Int(trimmed) {
302                let ns = document.text as NSString
303                var offset = 0
304                for _ in 1..<max(1, line) {
305                    let range = ns.lineRange(for: NSRange(location: offset, length: 0))
306                    guard NSMaxRange(range) < ns.length else { break }
307                    offset = NSMaxRange(range)
308                }
309                setCaret(offset)
310                return
311            }
312            if let m = trimmed.firstMatch(of: /^(%?)s\/((?:[^\/\\]|\\.)*)\/((?:[^\/\\]|\\.)*)\/?([gi]*)$/) {
313                Self.lastSubstitute = (String(m.2), String(m.3), String(m.4))
314                substitute(whole: !m.1.isEmpty, pattern: String(m.2), replacement: String(m.3), flags: String(m.4))
315                return
316            }
317            onMessage?("Not an editor command: \(trimmed)")
318        }
319    }
320
321    private func substitute(whole: Bool, pattern: String, replacement: String, flags: String) {
322        guard let regex = try? NSRegularExpression(pattern: pattern, options: flags.contains("i") ? [.caseInsensitive] : []) else {
323            onMessage?("Invalid pattern: \(pattern)")
324            return
325        }
326        let ns = document.text as NSString
327        let lines = whole ? NSRange(location: 0, length: ns.length) : ns.lineRange(for: NSRange(location: textView.selectedRange.location, length: 0))
328        let template = replacement.replacingOccurrences(of: "\\\\([0-9])", with: "\\$$1", options: .regularExpression)
329        var edits: [TextEdit] = []
330        var location = lines.location
331        while location < NSMaxRange(lines) {
332            let line = ns.lineRange(for: NSRange(location: location, length: 0))
333            let matches = regex.matches(in: ns as String, range: line)
334            for m in flags.contains("g") ? matches : Array(matches.prefix(1)) {
335                edits.append(TextEdit(range: m.range.location..<NSMaxRange(m.range), replacement: regex.replacementString(for: m, in: ns as String, offset: 0, template: template)))
336            }
337            location = NSMaxRange(line)
338        }
339        guard !edits.isEmpty else {
340            onMessage?("Pattern not found: \(pattern)")
341            return
342        }
343        applyEdits(edits)
344        onMessage?("\(edits.count) substitution\(edits.count == 1 ? "" : "s")")
345    }
346
347    /// A block caret outside insert and replace states, drawn by a cursor view of ours in
348    /// place of the selection display's while keys are modal.
349    func updateCursor() {
350        let block = modal && vim.mode != .insert && vim.mode != .replace
351        for case let interaction as UITextSelectionDisplayInteraction in textViews.flatMap(\.interactions) {
352            if let cursor = interaction.cursorView as? ModalCursorView {
353                if cursor.block != block {
354                    cursor.block = block
355                    interaction.setNeedsSelectionUpdate()
356                }
357            } else if modal {
358                let cursor = ModalCursorView()
359                cursor.width = theme.font.pointSize * 0.6
360                cursor.tintColor = textView.tintColor
361                cursor.block = block
362                interaction.cursorView = cursor
363                interaction.setNeedsSelectionUpdate()
364            }
365        }
366    }
367}
368
369/// The caret with modal keys: a bar in insert and replace states, evil's character-wide box
370/// in the others.
371final class ModalCursorView: UIView, UITextCursorView {
372    var isBlinking = false
373    var block = false {
374        didSet { setNeedsLayout() }
375    }
376    var width: CGFloat = 10 {
377        didSet { setNeedsLayout() }
378    }
379    private let box = CALayer()
380
381    override init(frame: CGRect) {
382        super.init(frame: frame)
383        clipsToBounds = false
384        isUserInteractionEnabled = false
385        layer.addSublayer(box)
386    }
387
388    required init?(coder: NSCoder) { nil }
389
390    func resetBlinkAnimation() {}
391
392    override func layoutSubviews() {
393        super.layoutSubviews()
394        box.frame = CGRect(x: 0, y: 0, width: block ? width : 2, height: bounds.height)
395        box.backgroundColor = (block ? tintColor.withAlphaComponent(0.45) : tintColor).cgColor
396    }
397
398    override func tintColorDidChange() {
399        super.tintColorDidChange()
400        setNeedsLayout()
401    }
402}
403#endif