#if os(iOS) import OrgCore import UIKit /// Modal editing with the Doom preset on a hardware keyboard, as the Mac's editor does it: /// keys go to the keymap for the current evil state first, then to `Vim`. Text typed on the /// on-screen keyboard in normal state goes in as insert state does. extension MobileEditor { func handleModal(_ chord: KeyChord) -> Bool { if recordingRegister != nil, replayingMacro == 0 { recordedKeys.append(chord) } dispatcher.mode = vim.mode.keymapMode if !vim.pending.isEmpty, vim.mode != .insert { return feedVim([chord]) } switch dispatcher.feed(chord) { case .pending(let keys): onMessage?(KeySequence.format(keys) + "-") return true case .cancelled: return true case .complete(let keys, let candidates): let context = editContext() if let binding = candidates.first(where: { binding in (binding.when.map { KeyContext.holds($0, in: context) } ?? true) && applies(binding.command, in: context) }) { run(binding.command) updateCursor() return true } return feedVim(keys) case .undefined(let keys): // The leader and Emacs prefixes mean nothing to evil, as on the Mac. if let first = keys.first, first == KeyChord("SPC") || !first.modifiers.isDisjoint(with: [.control, .meta]) { onMessage?("\(KeySequence.format(keys)) is undefined") return true } return feedVim(keys) case .unbound: return feedVim([chord]) } } /// Plays keys into the engine. False hands a single key in insert state to the text system. func feedVim(_ keys: [KeyChord]) -> Bool { for key in keys { if vim.mode == .insert, vim.passesThrough(key) { if keys.count == 1 { return false } insertTyped(key) continue } let leaving = key == KeyChord("ESC") || key == KeyChord("[", .control) || key == KeyChord("g", .control) if vim.mode == .insert, leaving, let snapshot = insertSnapshot, let edit = TextEdit.between(snapshot, document.text).first, edit.range.count == 0 { vim.inserted(edit.replacement) } let wasInsert = vim.mode == .insert let visual = [.visual, .visualLine, .visualBlock].contains(vim.mode) let caret = visual ? (visualCaret ?? textView.selectedRange.location) : textView.selectedRange.location var marks = vimMarks if jumpIndex > 0, jumpIndex <= jumpList.count { marks["'"] = jumpList[jumpIndex - 1] } vim.registers = Self.vimRegisters vim.clipboardRecord = Self.vimClipboardRecord // Reading the clipboard asks for permission, so only the keys that paste read it. let pastes = key.modifiers.isEmpty && (key.key == "p" || key.key == "P") let clipboard = pastes ? UIPasteboard.general.string : Self.vimClipboardRecord?.text let actions = vim.feed(key, Vim.Context(text: document.text, caret: caret, clipboard: clipboard, halfPage: halfPage, marks: marks, visible: visibleText, org: true, fileName: fileName, lastEx: Self.promptHistory[":"]?.last)) Self.vimRegisters = vim.registers Self.vimClipboardRecord = vim.clipboardRecord apply(actions) if !wasInsert, vim.mode == .insert { insertSnapshot = document.text } else if vim.mode != .insert { insertSnapshot = nil } } updateCursor() return true } func insertTyped(_ key: KeyChord) { let text = key.key == "SPC" ? " " : key.key == "RET" ? "\n" : key.key == "TAB" ? "\t" : key.key guard key.modifiers.isEmpty || key.modifiers == [.shift], text.count == 1 else { return } textView.insertText(text) } /// Typing on the on-screen keyboard outside insert state: the keys can't reach the engine, /// so the text goes in as from insert state. func typedOutsideInsert() { guard modal, vim.mode != .insert else { return } vim.reset() vim.enterInsert(at: textView.selectedRange.location, keys: [KeyChord("i")]) insertSnapshot = document.text updateCursor() } var halfPage: Int { let lineHeight = max(1, theme.font.lineHeight) return max(1, Int(textView.bounds.height / lineHeight / 2)) } /// The text the window shows. var visibleText: Range? { let top = CGPoint(x: textView.textContainerInset.left, y: textView.contentOffset.y + textView.textContainerInset.top) let bottom = CGPoint(x: textView.bounds.width - 1, y: textView.contentOffset.y + textView.bounds.height - 1) guard let first = textView.characterRange(at: top), let last = textView.characterRange(at: bottom) else { return nil } let lower = textView.offset(from: textView.beginningOfDocument, to: first.start) let upper = textView.offset(from: textView.beginningOfDocument, to: last.end) return lower.. 100 { jumpList.removeFirst(jumpList.count - 100) } jumpIndex = jumpList.count case .jumpBack(let count): if jumpIndex == jumpList.count { jumpList.append(textView.selectedRange.location) jumpIndex = jumpList.count - 1 } guard jumpIndex - count >= 0 else { continue } jumpIndex -= count reveal(jumpList[jumpIndex]) case .jumpForward(let count): guard jumpIndex + count < jumpList.count else { continue } jumpIndex += count reveal(jumpList[jumpIndex]) case .recordMacro(let name): if let name { recordingRegister = name recordedKeys = [] onMessage?("Defining keyboard macro…") } else if let register = recordingRegister { Self.macros[register] = Array(recordedKeys.dropLast()) recordingRegister = nil onMessage?("Keyboard macro defined") } case .playMacro(let name, let count): guard let keys = Self.macros[name], !keys.isEmpty else { onMessage?("No macro in register \(name)") continue } guard replayingMacro < 20 else { continue } replayingMacro += 1 defer { replayingMacro -= 1 } for _ in 0.. 0 { guard NSMaxRange(line) < ns.length else { break } caret = NSMaxRange(line) } else { guard line.location > 0 else { break } caret = ns.lineRange(for: NSRange(location: line.location - 1, length: 0)).location } } let line = ns.lineRange(for: NSRange(location: caret, length: 0)) var end = 0 ns.getLineStart(nil, end: nil, contentsEnd: &end, for: line) setCaret(min(line.location + column, max(line.location, end - 1))) } /// `zz`, `zt` and `zb`. private func scrollCaretLine(_ place: Vim.ScrollLine) { guard let position = textView.selectedTextRange?.start else { return } let rect = textView.caretRect(for: position) let height = textView.bounds.height - textView.adjustedContentInset.top - textView.adjustedContentInset.bottom var y: CGFloat = switch place { case .top: rect.minY case .center: rect.midY - height / 2 case .bottom: rect.maxY - height } y -= textView.adjustedContentInset.top let maxY = max(-textView.adjustedContentInset.top, textView.contentSize.height - textView.bounds.height + textView.adjustedContentInset.bottom) textView.setContentOffset(CGPoint(x: textView.contentOffset.x, y: min(max(-textView.adjustedContentInset.top, y), maxY)), animated: false) } /// C-e and C-y: the window down or up by lines; the cursor stays in it, as in Emacs. private func scrollLines(_ count: Int) { let inset = textView.adjustedContentInset let maxY = max(-inset.top, textView.contentSize.height - textView.bounds.height + inset.bottom) let y = textView.contentOffset.y + CGFloat(count) * max(1, theme.font.lineHeight) textView.setContentOffset(CGPoint(x: textView.contentOffset.x, y: min(max(-inset.top, y), maxY)), animated: false) guard vim.mode == .normal, let visible = visibleText, !visible.isEmpty else { return } let caret = textView.selectedRange.location let ns = document.text as NSString // Without scrolling back to where the cursor was. if caret < visible.lowerBound { textView.selectedRange = NSRange(location: ns.lineRange(for: NSRange(location: visible.lowerBound, length: 0)).location, length: 0) } else if caret >= visible.upperBound { textView.selectedRange = NSRange(location: ns.lineRange(for: NSRange(location: visible.upperBound - 1, length: 0)).location, length: 0) } } /// `zl`, `zh`, `zL` and `zH`: the window right or left by columns or half its width, which /// moves nothing while lines wrap. private func scrollColumns(_ count: Int, halfWidths: Bool) { let step = halfWidths ? textView.bounds.width / 2 : (" " as NSString).size(withAttributes: [.font: theme.font]).width let maxX = max(0, textView.contentSize.width - textView.bounds.width) let x = textView.contentOffset.x + CGFloat(count) * step textView.setContentOffset(CGPoint(x: min(max(0, x), maxX), y: textView.contentOffset.y), animated: false) } /// `/`, `?` and `:`; with `history` (`q:`), the earlier ones to pick and edit. private func prompt(_ kind: String, history: Bool = false) { let earlier = Array((Self.promptHistory[kind] ?? []).reversed()) let request = history ? Prompt(key: kind, message: kind, choices: earlier, requireMatch: false) : Prompt(key: kind, message: kind) onPrompt?(request) { [weak self] answer in guard let self, let answer, !answer.isEmpty else { return } var list = Self.promptHistory[kind] ?? [] list.removeAll { $0 == answer } list.append(answer) Self.promptHistory[kind] = Array(list.suffix(100)) if kind == ":" { self.ex(answer) } else { self.apply(self.vim.search(answer, forward: kind == "/", Vim.Context(text: self.document.text, caret: self.textView.selectedRange.location))) } self.updateCursor() } } /// `:w`, `:N` and `:s` / `:%s`; files save on their own on iOS. func ex(_ command: String) { let trimmed = command.trimmingCharacters(in: .whitespaces) switch trimmed { case "w", "write", "wq", "x": onAppCommand?("app.save") case "noh", "nohlsearch": break case "s", "&", "&&", "%&&": // The last substitution again; `&&` keeps its flags. guard let last = Self.lastSubstitute else { return } substitute(whole: trimmed.hasPrefix("%"), pattern: last.pattern, replacement: last.replacement, flags: trimmed.hasSuffix("&&") ? last.flags : "") default: if let line = Int(trimmed) { let ns = document.text as NSString var offset = 0 for _ in 1..