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