Sources/OrgstarMobile/MobileEditor+Modal.swift

d56fe8ddca3a5799ae51e521cbb0ee1c4e3af9a5
orgstar/Sources/OrgstarMobile/MobileEditor+Modal.swift

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