Sources/OrgstarMobile/MobileEditor+Modal.swift
367 lines · 16763 bytes
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 Self.vimRegisters = vim.registers
66 Self.vimClipboardRecord = vim.clipboardRecord
67 apply(actions)
68 if !wasInsert, vim.mode == .insert {
69 insertSnapshot = document.text
70 } else if vim.mode != .insert {
71 insertSnapshot = nil
72 }
73 }
74 updateCursor()
75 return true
76 }
77
78 func insertTyped(_ key: KeyChord) {
79 let text = key.key == "SPC" ? " " : key.key == "RET" ? "\n" : key.key == "TAB" ? "\t" : key.key
80 guard key.modifiers.isEmpty || key.modifiers == [.shift], text.count == 1 else { return }
81 textView.insertText(text)
82 }
83
84 /// Typing on the on-screen keyboard outside insert state: the keys can't reach the engine,
85 /// so the text goes in as from insert state.
86 func typedOutsideInsert() {
87 guard modal, vim.mode != .insert else { return }
88 vim.reset()
89 vim.enterInsert(at: textView.selectedRange.location, keys: [KeyChord("i")])
90 insertSnapshot = document.text
91 updateCursor()
92 }
93
94 var halfPage: Int {
95 let lineHeight = max(1, theme.font.lineHeight)
96 return max(1, Int(textView.bounds.height / lineHeight / 2))
97 }
98
99 /// The text the window shows.
100 var visibleText: Range<Int>? {
101 let top = CGPoint(x: textView.textContainerInset.left, y: textView.contentOffset.y + textView.textContainerInset.top)
102 let bottom = CGPoint(x: textView.bounds.width - 1, y: textView.contentOffset.y + textView.bounds.height - 1)
103 guard let first = textView.characterRange(at: top), let last = textView.characterRange(at: bottom) else { return nil }
104 let lower = textView.offset(from: textView.beginningOfDocument, to: first.start)
105 let upper = textView.offset(from: textView.beginningOfDocument, to: last.end)
106 return lower..<max(lower, upper)
107 }
108
109 private func setCaret(_ offset: Int) {
110 let length = (document.text as NSString).length
111 textView.selectedRange = NSRange(location: min(max(0, offset), length), length: 0)
112 textView.scrollRangeToVisible(textView.selectedRange)
113 }
114
115 func apply(_ actions: [Vim.Action]) {
116 for action in actions {
117 switch action {
118 case .edit(let edits, let caret):
119 visualCaret = nil
120 guard textView.isEditable else {
121 onMessage?("This file is read-only.")
122 continue
123 }
124 applyEdits(edits)
125 setCaret(caret)
126 case .move(let caret):
127 setCaret(caret)
128 visualCaret = caret
129 case .select(let range):
130 textView.selectedRange = NSRange(range)
131 case .selectBlock(let ranges):
132 // One selection: from the first line's start to the last line's end.
133 if let first = ranges.first, let last = ranges.last {
134 textView.selectedRange = NSRange(location: first.lowerBound, length: max(0, last.upperBound - first.lowerBound))
135 }
136 case .command(let id):
137 run(id)
138 case .visualLines(let count):
139 moveLines(count)
140 case .undo(let count):
141 for _ in 0..<count { textView.undoManager?.undo() }
142 case .redo(let count):
143 for _ in 0..<count { textView.undoManager?.redo() }
144 case .setClipboard(let text):
145 UIPasteboard.general.string = text
146 case .prompt(let kind):
147 prompt(kind)
148 case .commandWindow(let kind):
149 prompt(kind, history: true)
150 case .ex(let command):
151 ex(command)
152 case .fill(let range, let keep):
153 visualCaret = nil
154 textView.selectedRange = NSRange(location: textView.selectedRange.location, length: 0)
155 _ = perform(FillRegion(range: range, keep: keep))
156 case .message(let text):
157 onMessage?(text)
158 case .setMark(let name, let offset):
159 vimMarks[name] = offset
160 case .jumped(let from):
161 jumpList = Array(jumpList.prefix(jumpIndex))
162 if jumpList.last != from { jumpList.append(from) }
163 if jumpList.count > 100 { jumpList.removeFirst(jumpList.count - 100) }
164 jumpIndex = jumpList.count
165 case .jumpBack(let count):
166 if jumpIndex == jumpList.count {
167 jumpList.append(textView.selectedRange.location)
168 jumpIndex = jumpList.count - 1
169 }
170 guard jumpIndex - count >= 0 else { continue }
171 jumpIndex -= count
172 reveal(jumpList[jumpIndex])
173 case .jumpForward(let count):
174 guard jumpIndex + count < jumpList.count else { continue }
175 jumpIndex += count
176 reveal(jumpList[jumpIndex])
177 case .recordMacro(let name):
178 if let name {
179 recordingRegister = name
180 recordedKeys = []
181 onMessage?("Defining keyboard macro…")
182 } else if let register = recordingRegister {
183 Self.macros[register] = Array(recordedKeys.dropLast())
184 recordingRegister = nil
185 onMessage?("Keyboard macro defined")
186 }
187 case .playMacro(let name, let count):
188 guard let keys = Self.macros[name], !keys.isEmpty else {
189 onMessage?("No macro in register \(name)")
190 continue
191 }
192 guard replayingMacro < 20 else { continue }
193 replayingMacro += 1
194 defer { replayingMacro -= 1 }
195 for _ in 0..<count {
196 for key in keys where !handleModal(key) { insertTyped(key) }
197 }
198 case .scroll(let place):
199 scrollCaretLine(place)
200 }
201 }
202 }
203
204 /// `gj` and `gk` by text lines, keeping the column.
205 private func moveLines(_ count: Int) {
206 let ns = document.text as NSString
207 var caret = textView.selectedRange.location
208 let column = caret - ns.lineRange(for: NSRange(location: caret, length: 0)).location
209 for _ in 0..<abs(count) {
210 let line = ns.lineRange(for: NSRange(location: caret, length: 0))
211 if count > 0 {
212 guard NSMaxRange(line) < ns.length else { break }
213 caret = NSMaxRange(line)
214 } else {
215 guard line.location > 0 else { break }
216 caret = ns.lineRange(for: NSRange(location: line.location - 1, length: 0)).location
217 }
218 }
219 let line = ns.lineRange(for: NSRange(location: caret, length: 0))
220 var end = 0
221 ns.getLineStart(nil, end: nil, contentsEnd: &end, for: line)
222 setCaret(min(line.location + column, max(line.location, end - 1)))
223 }
224
225 /// `zz`, `zt` and `zb`.
226 private func scrollCaretLine(_ place: Vim.ScrollLine) {
227 guard let position = textView.selectedTextRange?.start else { return }
228 let rect = textView.caretRect(for: position)
229 let height = textView.bounds.height - textView.adjustedContentInset.top - textView.adjustedContentInset.bottom
230 var y: CGFloat = switch place {
231 case .top: rect.minY
232 case .center: rect.midY - height / 2
233 case .bottom: rect.maxY - height
234 }
235 y -= textView.adjustedContentInset.top
236 let maxY = max(-textView.adjustedContentInset.top, textView.contentSize.height - textView.bounds.height + textView.adjustedContentInset.bottom)
237 textView.setContentOffset(CGPoint(x: textView.contentOffset.x, y: min(max(-textView.adjustedContentInset.top, y), maxY)), animated: false)
238 }
239
240 /// `/`, `?` and `:`; with `history` (`q:`), the earlier ones to pick and edit.
241 private func prompt(_ kind: String, history: Bool = false) {
242 let earlier = Array((Self.promptHistory[kind] ?? []).reversed())
243 let request = history ? Prompt(key: kind, message: kind, choices: earlier, requireMatch: false) : Prompt(key: kind, message: kind)
244 onPrompt?(request) { [weak self] answer in
245 guard let self, let answer, !answer.isEmpty else { return }
246 var list = Self.promptHistory[kind] ?? []
247 list.removeAll { $0 == answer }
248 list.append(answer)
249 Self.promptHistory[kind] = Array(list.suffix(100))
250 if kind == ":" {
251 self.ex(answer)
252 } else {
253 self.apply(self.vim.search(answer, forward: kind == "/", Vim.Context(text: self.document.text, caret: self.textView.selectedRange.location)))
254 }
255 self.updateCursor()
256 }
257 }
258
259 /// `:w`, `:N` and `:s` / `:%s`; files save on their own on iOS.
260 func ex(_ command: String) {
261 let trimmed = command.trimmingCharacters(in: .whitespaces)
262 switch trimmed {
263 case "w", "write", "wq", "x": onAppCommand?("app.save")
264 case "noh", "nohlsearch": break
265 default:
266 if let line = Int(trimmed) {
267 let ns = document.text as NSString
268 var offset = 0
269 for _ in 1..<max(1, line) {
270 let range = ns.lineRange(for: NSRange(location: offset, length: 0))
271 guard NSMaxRange(range) < ns.length else { break }
272 offset = NSMaxRange(range)
273 }
274 setCaret(offset)
275 return
276 }
277 if let m = trimmed.firstMatch(of: /^(%?)s\/((?:[^\/\\]|\\.)*)\/((?:[^\/\\]|\\.)*)\/?([gi]*)$/) {
278 substitute(whole: !m.1.isEmpty, pattern: String(m.2), replacement: String(m.3), flags: String(m.4))
279 return
280 }
281 onMessage?("Not an editor command: \(trimmed)")
282 }
283 }
284
285 private func substitute(whole: Bool, pattern: String, replacement: String, flags: String) {
286 guard let regex = try? NSRegularExpression(pattern: pattern, options: flags.contains("i") ? [.caseInsensitive] : []) else {
287 onMessage?("Invalid pattern: \(pattern)")
288 return
289 }
290 let ns = document.text as NSString
291 let lines = whole ? NSRange(location: 0, length: ns.length) : ns.lineRange(for: NSRange(location: textView.selectedRange.location, length: 0))
292 let template = replacement.replacingOccurrences(of: "\\\\([0-9])", with: "\\$$1", options: .regularExpression)
293 var edits: [TextEdit] = []
294 var location = lines.location
295 while location < NSMaxRange(lines) {
296 let line = ns.lineRange(for: NSRange(location: location, length: 0))
297 let matches = regex.matches(in: ns as String, range: line)
298 for m in flags.contains("g") ? matches : Array(matches.prefix(1)) {
299 edits.append(TextEdit(range: m.range.location..<NSMaxRange(m.range), replacement: regex.replacementString(for: m, in: ns as String, offset: 0, template: template)))
300 }
301 location = NSMaxRange(line)
302 }
303 guard !edits.isEmpty else {
304 onMessage?("Pattern not found: \(pattern)")
305 return
306 }
307 applyEdits(edits)
308 onMessage?("\(edits.count) substitution\(edits.count == 1 ? "" : "s")")
309 }
310
311 /// A block caret outside insert and replace states, drawn by a cursor view of ours in
312 /// place of the selection display's while keys are modal.
313 func updateCursor() {
314 let block = modal && vim.mode != .insert && vim.mode != .replace
315 for case let interaction as UITextSelectionDisplayInteraction in textViews.flatMap(\.interactions) {
316 if let cursor = interaction.cursorView as? ModalCursorView {
317 if cursor.block != block {
318 cursor.block = block
319 interaction.setNeedsSelectionUpdate()
320 }
321 } else if modal {
322 let cursor = ModalCursorView()
323 cursor.width = theme.font.pointSize * 0.6
324 cursor.tintColor = textView.tintColor
325 cursor.block = block
326 interaction.cursorView = cursor
327 interaction.setNeedsSelectionUpdate()
328 }
329 }
330 }
331}
332
333/// The caret with modal keys: a bar in insert and replace states, evil's character-wide box
334/// in the others.
335final class ModalCursorView: UIView, UITextCursorView {
336 var isBlinking = false
337 var block = false {
338 didSet { setNeedsLayout() }
339 }
340 var width: CGFloat = 10 {
341 didSet { setNeedsLayout() }
342 }
343 private let box = CALayer()
344
345 override init(frame: CGRect) {
346 super.init(frame: frame)
347 clipsToBounds = false
348 isUserInteractionEnabled = false
349 layer.addSublayer(box)
350 }
351
352 required init?(coder: NSCoder) { nil }
353
354 func resetBlinkAnimation() {}
355
356 override func layoutSubviews() {
357 super.layoutSubviews()
358 box.frame = CGRect(x: 0, y: 0, width: block ? width : 2, height: bounds.height)
359 box.backgroundColor = (block ? tintColor.withAlphaComponent(0.45) : tintColor).cgColor
360 }
361
362 override func tintColorDidChange() {
363 super.tintColorDidChange()
364 setNeedsLayout()
365 }
366}
367#endif