Sources/OrgstarMobile/MobileEditor.swift

58f3b73e8ff337e5a15111fbb32c0d57cf2346da
orgstar/Sources/OrgstarMobile/MobileEditor.swift history · blame · raw

746 lines · 37637 bytes

29 symbols in this file
  1#if os(iOS)
  2import OrgApp
  3import OrgCore
  4import OrgDocument
  5import OrgHighlight
  6import OrgPresentation
  7import UIKit
  8
  9/// The iOS editor: a TextKit 2 text view that is the open file's live state, as the Mac's
 10/// `OrgEditor` is. Typing and undo go through the text view and into the document; commands
 11/// run on the document and apply their edits as one undo step; headings, drawers and blocks
 12/// fold as TAB cycles them.
 13@MainActor
 14final class MobileEditor: NSObject, DocumentBuffer {
 15    /// One highlighter for every editor and the reader: it caches compiled grammars and results.
 16    static let highlighter = TreeSitterHighlighter()
 17    private(set) var document: DocumentState
 18    /// The views showing the buffer, one per pane; the first is made with the editor.
 19    private(set) var textViews: [UITextView]
 20    /// The view with focus, or the last to have had it: the one commands act on.
 21    private(set) var textView: UITextView
 22    var options: EditingOptions = .org {
 23        didSet {
 24            if options.spellCheck != oldValue.spellCheck { restyleAll() }
 25            if !showMarkup, options.hideEmphasisMarkers != oldValue.hideEmphasisMarkers || options.prettyEntities != oldValue.prettyEntities {
 26                restyleAll()
 27            }
 28        }
 29    }
 30    /// Colors and type; a change, or a new Dynamic Type size, restyles the file.
 31    var themeSpec: ThemeSpec {
 32        get { theme.spec }
 33        set {
 34            let new = MobileTheme(newValue)
 35            guard new.spec != theme.spec || new.font != theme.font || new.body != theme.body else { return }
 36            theme = new
 37            paragraphStyles = [:]
 38            applyThemeToView()
 39            restyleAll()
 40        }
 41    }
 42    /// Link brackets and targets, and emphasis markers when `org-hide-emphasis-markers` hides
 43    /// them, shown. Hidden markup shows on the caret's line, so it can be edited.
 44    var showMarkup = true {
 45        didSet { if showMarkup != oldValue { restyleAll() } }
 46    }
 47    /// An incremental search in progress, and the last search string, for C-s C-s.
 48    var isearch: ISearch?
 49    static var lastISearch: String?
 50    /// `auto-fill-mode` for this buffer: the settings' unless toggled here.
 51    var autoFillOverride: Bool?
 52    var autoFills: Bool { autoFillOverride ?? options.autoFill }
 53    var keymap = KeymapPreset.emacs.keymap {
 54        didSet { dispatcher = KeyDispatcher(keymap: keymap) }
 55    }
 56    /// The Doom preset's modal editing, and its state: the engine, the caret in visual
 57    /// states, marks, the jump list, what insert state began with, and macros.
 58    var modal = false {
 59        didSet {
 60            if modal != oldValue { vim = Vim() }
 61            updateCursor()
 62        }
 63    }
 64    var vim = Vim()
 65    var visualCaret: Int?
 66    var vimMarks: [Character: Int] = [:]
 67    var jumpList: [Int] = []
 68    var jumpIndex = 0
 69    var insertSnapshot: String?
 70    var recordingRegister: Character?
 71    var recordedKeys: [KeyChord] = []
 72    var replayingMacro = 0
 73    static var vimRegisters: [Character: (text: String, linewise: Bool)] = [:]
 74    static var vimClipboardRecord: (text: String, linewise: Bool)?
 75    static var macros: [Character: [KeyChord]] = [:]
 76    /// What `:`, `/` and `?` read, oldest first, for `q:`.
 77    static var promptHistory: [String: [String]] = [:]
 78    /// The last `:s`, for `&` and `g&`.
 79    static var lastSubstitute: (pattern: String, replacement: String, flags: String)?
 80    /// The file's path, for the `%` register.
 81    var fileName: String?
 82    var onChange: (() -> Void)?
 83    var onMessage: ((String) -> Void)?
 84    var onPrompt: ((Prompt, @escaping (String?) -> Void) -> Void)?
 85    var onLink: ((OrgLink) -> Void)?
 86    /// Edits being applied, which the typing hooks leave alone.
 87    private var applyingEdits = false
 88    /// Source blocks to write to their files (C-c C-v t).
 89    var onTangle: ((Tangle.Scope) -> Void)?
 90    /// A source block to run (C-c C-c).
 91    var onBabel: ((BabelJob) -> Void)?
 92    /// The file's setup files to read again (C-c C-c on a keyword line).
 93    var onRefreshSetup: (() -> Void)?
 94    /// A block, a table's formulas or a field to edit apart (C-c ', C-c `).
 95    var onEditBlock: ((BlockEdit) -> Void)?
 96    /// A followed timestamp's agenda days: the first (a `Days` number) and how many.
 97    var onAgenda: ((Int, Int) -> Void)?
 98    /// Shows a column view.
 99    var onColumnView: ((ColumnView.View) -> Void)?
100    /// Commands the app runs, as `app.clock.in`.
101    var onAppCommand: ((String) -> Void)?
102    /// Where paste looks for an image; scripts checking the app set another.
103    static var pasteboard = UIPasteboard.general
104    /// Files dropped at the caret; nil leaves them to the text view.
105    var onFiles: (([URL]) -> Void)?
106    /// An image pasted at the caret, with its extension (`yank-media`).
107    var onImage: ((Data, String) -> Void)?
108    /// Tags used across the workspace, for completion.
109    var knownTags: @Sendable () -> [String] = { [] }
110
111    var theme: MobileTheme
112    var fold = FoldState()
113    var globalVisibility: GlobalVisibility?
114    let hidden = LockedRanges()
115    /// An arrow key moved the caret, and where it was before; the caret skips folds then.
116    var movedByArrow = false
117    var previousCaret = 0
118    /// Blocks drawn on a band.
119    let shaded = LockedRanges()
120    let fragmentStyle = FragmentStyle()
121    var selectionColor: UIColor = .clear
122    /// `org-indent-mode` and `org-hide-leading-stars`, from the settings and `#+STARTUP`.
123    var indented = true
124    var hideStars = false
125    /// One paragraph style per indent pair.
126    var paragraphStyles: [[Int]: NSParagraphStyle] = [:]
127    /// `SpellCheck.skipped` for a revision of the buffer.
128    var spellSkipCache: (revision: Int, ranges: [Range<Int>])?
129    /// The line last revealed while markup is hidden, to hide again when the caret leaves.
130    var revealedLine: NSRange?
131    /// `org-toggle-inline-images`: image links show their image.
132    var showsImages = false
133    /// Links with a description show their image too.
134    var imagesIncludeLinked = false
135    /// `org-latex-preview`: LaTeX fragments show as typeset math.
136    var showsLatex = false
137    /// The view width images were last sized for.
138    var imageWidth: CGFloat = 0
139    /// The file's folder, for relative image paths.
140    let baseDirectory: URL?
141    /// An `attachment:` link's file, from its name, offset and the tree; nil leaves those links
142    /// as text.
143    var attachmentPath: ((String, Int, OrgTree) -> String?)?
144    static let imageCache = NSCache<NSString, UIImage>()
145    var loading = false
146    var restyleScheduled: Range<Int>?
147    /// An edit since the last restyle touched a line that can start or end a block.
148    var blocksMayChange = false
149    /// Text before its end is styled; after it, the text waits for the background passes.
150    var styled = StyledExtent()
151    var stylingScheduled = false
152    /// Narrowed table columns (`org-table-shrink`).
153    var shrunk = ShrunkColumns()
154    /// A command's edits being applied, which keep shrunk columns narrow.
155    private var commandEditing = false
156
157    init(
158        document: DocumentState, editable: Bool, options: EditingOptions = .org, theme spec: ThemeSpec = .default,
159        showMarkup: Bool = true, baseDirectory: URL? = nil
160    ) {
161        self.document = document
162        self.options = options
163        self.showMarkup = showMarkup
164        self.baseDirectory = baseDirectory
165        theme = MobileTheme(spec)
166        let keyed = KeyedTextView(usingTextLayoutManager: true)
167        textView = keyed
168        textViews = [keyed]
169        super.init()
170        configure(keyed, editable: editable)
171        textView.textStorage.delegate = self
172        (textView.textLayoutManager?.textContentManager as? NSTextContentStorage)?.delegate = self
173        let startup = Presentation.startupDisplay(document.tree, options: options)
174        indented = startup.indented
175        hideStars = startup.hideStars
176        showsImages = startup.inlineImages
177        showsLatex = startup.latexPreview
178        shrunk = ShrunkColumns.startup(document.tree)
179        applyThemeToView()
180        load(document.text)
181        setFolds(startup.folds)
182        if startup.alignTables { _ = perform(AlignAllTables()) }
183        truncatesLines = startup.truncated
184        textView.selectedRange = NSRange(location: 0, length: 0)
185    }
186
187    /// What every view of the buffer has: the keymap, the editor as its delegates and the fold
188    /// tap. Views in one scene share its undo stack.
189    private func configure(_ view: KeyedTextView, editable: Bool) {
190        view.keyHandler = { [weak self, weak view] key in
191            guard let self else { return false }
192            if let view { focus(view) }
193            return handleKey(key)
194        }
195        view.onLayout = { [weak self] in self?.viewResized() }
196        view.onFiles = { [weak self, weak view] files in
197            guard let self, let onFiles else { return false }
198            if let view { focus(view) }
199            onFiles(files)
200            return true
201        }
202        view.onImage = { [weak self, weak view] data, ext in
203            guard let self, let onImage else { return false }
204            if let view { focus(view) }
205            onImage(data, ext)
206            return true
207        }
208        view.textDropDelegate = view
209        view.isEditable = editable
210        view.autocorrectionType = .no
211        view.autocapitalizationType = .none
212        view.smartQuotesType = .no
213        view.smartDashesType = .no
214        view.smartInsertDeleteType = .no
215        // The editor checks spelling itself, outside code, links and keywords.
216        view.spellCheckingType = .no
217        view.keyboardDismissMode = .interactive
218        view.alwaysBounceVertical = true
219        view.textContainerInset = UIEdgeInsets(top: 12, left: 8, bottom: 24, right: 8)
220        view.delegate = self
221        view.textLayoutManager?.delegate = self
222        let foldTap = UITapGestureRecognizer(target: self, action: #selector(tappedFold))
223        foldTap.delegate = self
224        view.addGestureRecognizer(foldTap)
225    }
226
227    // MARK: - Views
228
229    /// Another view of the buffer, for another pane: its own layout manager on the buffer's
230    /// content storage, so text, folds and styles are shared and the caret and scroll aren't.
231    func addView() -> UITextView {
232        guard let storage = textViews[0].textLayoutManager?.textContentManager as? NSTextContentStorage else { return textViews[0] }
233        let manager = NSTextLayoutManager()
234        manager.delegate = self
235        let container = NSTextContainer(size: CGSize(width: 0, height: CGFloat.greatestFiniteMagnitude))
236        manager.textContainer = container
237        storage.addTextLayoutManager(manager)
238        let view = KeyedTextView(frame: .zero, textContainer: container)
239        configure(view, editable: textViews[0].isEditable)
240        textViews.append(view)
241        applyThemeToView(view)
242        if truncatesLines { view.truncates = true }
243        updateCursor()
244        return view
245    }
246
247    /// Drops a view `addView` made; the first stays with the editor.
248    func removeView(_ view: UITextView) {
249        guard view !== textViews[0], let index = textViews.firstIndex(where: { $0 === view }) else { return }
250        textViews.remove(at: index)
251        if let manager = view.textLayoutManager, let storage = manager.textContentManager { storage.removeTextLayoutManager(manager) }
252        view.delegate = nil
253        onFocus[ObjectIdentifier(view)] = nil
254        if textView === view { textView = textViews[0] }
255    }
256
257    /// What each view's screen does when its view takes focus: the editor's callbacks are
258    /// that screen's from then on.
259    var onFocus: [ObjectIdentifier: () -> Void] = [:]
260
261    /// Commands act on `view` from now on.
262    func focus(_ view: UITextView) {
263        guard view !== textView, textViews.contains(where: { $0 === view }) else { return }
264        textView = view
265        onFocus[ObjectIdentifier(view)]?()
266    }
267
268    /// Every view's layout manager.
269    var layoutManagers: [NSTextLayoutManager] { textViews.compactMap(\.textLayoutManager) }
270
271    // MARK: - DocumentBuffer
272
273    var selection: [Range<Int>] {
274        let selected = textView.selectedRange
275        return [selected.location..<NSMaxRange(selected)]
276    }
277
278    func update<T>(_ change: (inout DocumentState) throws -> T) rethrows -> T {
279        let before = document.text
280        let defaultsBefore = document.defaults
281        let selected = textView.selectedRange
282        let result = try change(&document)
283        if document.text != before {
284            // A save that merged a change from disk, or a revert: the view shows the new text.
285            shrunk = ShrunkColumns()
286            load(document.text)
287            let length = (document.text as NSString).length
288            textView.selectedRange = NSRange(location: min(selected.location, length), length: 0)
289            textView.undoManager?.removeAllActions()
290            setFolds(fold)
291        } else if document.defaults != defaultsBefore {
292            restartStyling()
293        }
294        return result
295    }
296
297    func perform(_ command: any OrgCommand, now: Date = Date(), answers: [String: String] = [:]) -> CommandStep {
298        let context = EditContext(
299            revision: document.revision, text: document.text, tree: document.tree, selection: selection,
300            now: now, answers: answers, hidden: hidden.all, options: options, knownTags: knownTags
301        )
302        let step = command.run(in: context)
303        switch step {
304        case .commit(let result):
305            guard textView.isEditable || result.edits.isEmpty else {
306                onMessage?("This file is read-only.")
307                return .failed("read-only")
308            }
309            commandEditing = true
310            applyEdits(result.edits)
311            commandEditing = false
312            if let selected = result.selection?.first {
313                unfold(around: selected.lowerBound)
314                textView.selectedRange = NSRange(location: selected.lowerBound, length: selected.count)
315                textView.scrollRangeToVisible(textView.selectedRange)
316            }
317            for effect in result.effects {
318                switch effect {
319                case .message(let text): onMessage?(text)
320                case .fold(let start):
321                    var state = fold
322                    state.folds.insert(start)
323                    setFolds(state)
324                case .refreshSetup: onRefreshSetup?()
325                case .timer(let timer): TimerModel.shared.set(timer)
326                default: break
327                }
328            }
329        case .failed(let message):
330            onMessage?(message)
331        case .prompt(let prompt):
332            onPrompt?(prompt) { [weak self] answer in
333                guard let self else { return }
334                guard let answer else { return self.onMessage?("Quit") ?? () }
335                _ = self.perform(command, now: now, answers: answers.merging([prompt.key: answer]) { $1 })
336            }
337        case .external(.editBlock(let edit)) where onEditBlock != nil:
338            onEditBlock?(edit)
339        case .external(.babel(let job)) where onBabel != nil:
340            onBabel?(job)
341        case .external(.tangle(let scope)) where onTangle != nil:
342            onTangle?(scope)
343        case .external(.agenda(let start, let count)) where onAgenda != nil:
344            onAgenda?(start, count)
345        case .external(.columnView(let view)) where onColumnView != nil:
346            onColumnView?(view)
347        case .external(let request):
348            // The fields written before a formula only Emacs can do stay, as Emacs leaves them
349            // when a formula fails.
350            if case .emacsTable(_, _, _, _, _, _, let partial?) = request { _ = perform(PrecomputedEdit(partial)) }
351            // `org-sbe` without Babel shows its paywall.
352            if case .emacsTable(_, _, _, TableBlocks.lockedReason, _, _, _) = request {
353                ProAccess.shared.allows(.babel)
354                return step
355            }
356            onMessage?(Self.unavailable(request, title: command.title))
357        }
358        return step
359    }
360
361    /// Why a request the app doesn't handle did nothing: only table recalculation needs Emacs.
362    static func unavailable(_ request: ExternalRequest, title: String) -> String {
363        if case .emacsTable(_, _, _, let reason, _, let formula?, _) = request {
364            return String(localized: "The table was recalculated up to \(formula), which needs Emacs on the Mac: \(TableReason.localized(reason)).", comment: "Table formulas calculated up to one only Emacs can calculate")
365        }
366        if case .emacsTable(_, _, _, let reason, _, _, _) = request {
367            return String(localized: "This table needs Emacs, which runs on the Mac: \(TableReason.localized(reason)).", comment: "Table formulas only Emacs can calculate")
368        }
369        return String(localized: "\(CommandTitle.localized(title)) isn't available on iPhone and iPad.", comment: "A command that runs only on the Mac")
370    }
371
372    // MARK: - Commands by name and key
373
374    /// Runs what `keys` (as `C-c C-t`) is bound to in the Emacs keymap, for the caret's context.
375    func run(keys: String) {
376        guard let chords = KeySequence.parse(keys) else { return }
377        let context = editContext()
378        let binding = keymap.candidates(for: chords).first { binding in
379            (binding.when.map { KeyContext.holds($0, in: context) } ?? true) && applies(binding.command, in: context)
380        }
381        guard let binding else { return onMessage?("Nothing to do here") ?? () }
382        run(binding.command)
383    }
384
385    func run(_ id: String) {
386        switch id {
387        case "org.cycle":
388            if !cycleAtCaret() { onMessage?("Not on a heading, drawer or block") }
389        case "org.cycle-global": cycleGlobal()
390        case _ where id.hasPrefix("org.fold."): foldCommand(id)
391        case "org.link.open": openLinkAtCaret()
392        case "org.toggle-inline-images": toggleImages()
393        case "org.toggle-inline-images-linked": toggleImages(includeLinked: true)
394        case "org.latex-preview": toggleLatex()
395        case "editor.toggle-truncate-lines":
396            truncatesLines.toggle()
397            onMessage?(truncatesLines ? "Truncate long lines enabled" : "Truncate long lines disabled")
398        case "edit.isearch-forward": startISearch(forward: true)
399        case "edit.isearch-backward": startISearch(forward: false)
400        case "edit.isearch-forward-regexp": startISearch(forward: true, regexp: true)
401        case "edit.isearch-backward-regexp": startISearch(forward: false, regexp: true)
402        case "editor.toggle-auto-fill":
403            autoFillOverride = !autoFills
404            onMessage?(autoFills ? "Auto-Fill mode enabled in current buffer" : "Auto-Fill mode disabled in current buffer")
405        case "edit.undo": textView.undoManager?.undo()
406        case "edit.redo": textView.undoManager?.redo()
407        case "org.table.toggle-column-width", "org.table.shrink", "org.table.expand": tableColumnWidth(id)
408        case _ where id.hasPrefix("app.") || Self.linkCommands.contains(id):
409            if let onAppCommand { onAppCommand(id) } else { onMessage?("Not available on iOS yet") }
410        default:
411            if let command = Commands.command(id) {
412                _ = perform(command)
413            } else {
414                onMessage?("Not available on iOS yet")
415            }
416        }
417    }
418
419    /// Link commands that need the stored links or the file, which the screen has.
420    static let linkCommands: Set<String> = ["org.link.store", "org.id.store-link", "org.link.insert"]
421
422    func applies(_ id: String, in context: EditContext) -> Bool {
423        if let command = Commands.command(id) { return command.applies(in: context) }
424        switch id {
425        case "org.cycle":
426            return Presentation.heading(containing: context.caret, in: context.tree) != nil || Wrappers.toggleable(at: context.caret, in: context.tree) != nil
427        case _ where id.hasPrefix("org.fold."): return true
428        case "org.cycle-global", "edit.undo", "edit.redo", "org.toggle-inline-images", "org.toggle-inline-images-linked", "org.latex-preview", "editor.toggle-truncate-lines",
429             "editor.toggle-auto-fill", "edit.isearch-forward", "edit.isearch-backward",
430             "edit.isearch-forward-regexp", "edit.isearch-backward-regexp": return true
431        case "app.clock.in", "app.clock.out", "app.clock.cancel", "app.clock.goto", "app.clock.in-recent", "app.clock.in-last",
432             "app.clock.goto-recent", "app.clock.default", "app.clock.resolve", "app.toggle-markup": return onAppCommand != nil
433        case "app.refile.goto", "app.table-import", "app.crypt.encrypt-entries", "app.crypt.forget-passphrase", "app.attach.attach", "app.attach.url",
434             "app.attach.new", "app.attach.open", "app.attach.reveal", "app.attach.delete", "app.attach.delete-all", "app.attach.sync",
435             "app.attach.set-directory", "app.attach.unset-directory", "app.backlinks", "app.node.find", "app.node.insert",
436             "app.node.rename-from-front-matter": return onAppCommand != nil
437        case _ where id.hasPrefix("app.node."): return onAppCommand != nil
438        case _ where id.hasPrefix("app.dailies."): return onAppCommand != nil
439        case "app.crypt.encrypt-entry": return onAppCommand != nil && OrgCrypt.heading(context.text, at: context.caret) != nil && OrgCrypt.encryptedRange(context.text, at: context.caret) == nil
440        case "app.crypt.open-entry", "app.crypt.decrypt-entry": return onAppCommand != nil && OrgCrypt.encryptedRange(context.text, at: context.caret) != nil
441        case "app.table-export", "app.plot": return onAppCommand != nil && ImportTable.exportText(context.text, at: context.caret, path: "") != nil
442        case "app.refile", "app.refile.copy", "app.archive": return onAppCommand != nil && Presentation.heading(containing: context.caret, in: context.tree) != nil
443        case "app.copy-rich-text", "app.export.html-open", "app.export-body-only", "app.export.icalendar-agenda", "app.export.icalendar-combined": return onAppCommand != nil
444        case _ where id.hasPrefix("app.publish"): return onAppCommand != nil
445        case _ where Self.linkCommands.contains(id): return onAppCommand != nil
446        case "org.link.open": return OpenLinkAtPoint().applies(in: context)
447        case "org.table.toggle-column-width", "org.table.shrink", "org.table.expand":
448            return TableShrink.table(at: context.caret, in: context.text) != nil
449        default: return false
450        }
451    }
452
453    // MARK: - Hardware keyboard
454
455    lazy var dispatcher = KeyDispatcher(keymap: keymap)
456
457    private static let named: [UIKeyboardHIDUsage: String] = [
458        .keyboardTab: "TAB", .keyboardReturnOrEnter: "RET", .keypadEnter: "RET", .keyboardSpacebar: "SPC",
459        .keyboardEscape: "ESC", .keyboardDeleteOrBackspace: "DEL", .keyboardDeleteForward: "<delete>",
460        .keyboardLeftArrow: "<left>", .keyboardRightArrow: "<right>", .keyboardUpArrow: "<up>", .keyboardDownArrow: "<down>",
461        .keyboardHome: "<home>", .keyboardEnd: "<end>", .keyboardPageUp: "<prior>", .keyboardPageDown: "<next>",
462    ]
463
464    /// A key press as a chord; Option is Meta, as `option-as-meta` makes it on the Mac.
465    static func chord(_ key: UIKey) -> KeyChord? {
466        var modifiers: KeyChord.Modifiers = []
467        let flags = key.modifierFlags
468        if flags.contains(.control) { modifiers.insert(.control) }
469        if flags.contains(.alternate) { modifiers.insert(.meta) }
470        if flags.contains(.command) { modifiers.insert(.command) }
471        if let name = named[key.keyCode] {
472            if flags.contains(.shift) { modifiers.insert(.shift) }
473            return KeyChord(name, modifiers)
474        }
475        var characters = key.charactersIgnoringModifiers
476        if flags.contains(.shift), characters.count == 1, characters.lowercased() == characters { characters = characters.uppercased() }
477        guard characters.count == 1 else { return nil }
478        return KeyChord(characters, modifiers)
479    }
480
481    /// The Emacs keymap's commands on an iPad keyboard. Keys it doesn't bind, Command shortcuts
482    /// and editing keys (C-a, C-e, C-k...) are the text system's.
483    func handleKey(_ key: UIKey) -> Bool {
484        movedByArrow = [.keyboardUpArrow, .keyboardDownArrow, .keyboardLeftArrow, .keyboardRightArrow].contains(key.keyCode)
485        guard let chord = Self.chord(key), !chord.modifiers.contains(.command) else { return false }
486        if isearch != nil, isearchKey(chord) { return true }
487        if modal { return handleModal(chord) }
488        // Option alone types characters unless it begins a binding.
489        if chord.modifiers == [.meta], dispatcher.pending.isEmpty,
490           keymap.candidates(for: [chord]).isEmpty, !keymap.isPrefix([chord]) { return false }
491        switch dispatcher.feed(chord) {
492        case .pending(let keys):
493            onMessage?(KeySequence.format(keys) + "-")
494            return true
495        case .cancelled:
496            onMessage?("Quit")
497            return true
498        case .undefined(let keys):
499            onMessage?("\(KeySequence.format(keys)) is undefined")
500            return true
501        case .unbound:
502            return false
503        case .complete(let keys, let candidates):
504            let context = editContext()
505            let runnable = candidates.first { binding in
506                (binding.when.map { KeyContext.holds($0, in: context) } ?? true) && applies(binding.command, in: context)
507            }
508            // A sequence runs its command even where it doesn't apply, which says why, as on the Mac.
509            guard let binding = runnable ?? (keys.count > 1 ? candidates.first : nil) else { return false }
510            if keys.count == 1, binding.command.hasPrefix("edit."), !["edit.undo", "edit.redo"].contains(binding.command) { return false }
511            run(binding.command)
512            return true
513        }
514    }
515
516    func editContext() -> EditContext {
517        EditContext(revision: document.revision, text: document.text, tree: document.tree, selection: selection, hidden: hidden.all, options: options, knownTags: knownTags)
518    }
519
520    private func openLinkAtCaret() {
521        let caret = textView.selectedRange.location
522        if let link = Links.link(at: caret, text: document.text, tree: document.tree)?.link {
523            onLink?(link)
524        } else if let days = Links.timestampDays(at: caret, text: document.text) {
525            onAgenda?(days.start, days.count)
526        } else {
527            onMessage?("No link here")
528        }
529    }
530
531    // MARK: - Editing
532
533    /// Applies `edits` (against the current text) through the text view as one undo step.
534    func applyEdits(_ edits: [TextEdit]) {
535        let interval = Perf.begin("editor.applyEdits")
536        defer { interval.end() }
537        guard !edits.isEmpty else { return }
538        applyingEdits = true
539        defer { applyingEdits = false }
540        // Straight into the storage: replacing through text input would take the active
541        // keyboard's substitutions (smart dashes) when another view has the keyboard.
542        let storage = textView.textStorage
543        let old = storage.string as NSString
544        // By lines, so a fold between two changes stays.
545        let ascending = edits.flatMap { splitByLines($0, in: storage.string) }.sorted { $0.range.lowerBound < $1.range.lowerBound }
546        var inverse: [TextEdit] = []
547        var delta = 0
548        for edit in ascending {
549            let start = edit.range.lowerBound + delta
550            let length = (edit.replacement as NSString).length
551            inverse.append(TextEdit(range: start..<start + length, replacement: old.substring(with: NSRange(edit.range))))
552            delta += length - edit.range.count
553        }
554        let caret = textView.selectedRange
555        // One at a time, last first: each is processed alone, so folds between them stay.
556        for edit in ascending.reversed() {
557            storage.replaceCharacters(in: NSRange(edit.range), with: edit.replacement)
558        }
559        textView.undoManager?.registerUndo(withTarget: self) { editor in
560            editor.applyEdits(inverse)
561            editor.textView.selectedRange = caret
562        }
563    }
564
565    /// The storage changed (typing, a command, undo): the document takes the same edit, and
566    /// folds and styles follow.
567    fileprivate func storageEdited(range: NSRange, delta: Int) {
568        let interval = Perf.begin("editor.edit")
569        defer { interval.end() }
570        guard !loading else { return }
571        let old = range.location..<(range.location + range.length - delta)
572        let replacement = (textView.textStorage.string as NSString).substring(with: range)
573        let edit = TextEdit(range: old, replacement: replacement)
574        let oldTree = document.tree
575        let oldText = document.text as NSString
576        do {
577            try document.apply([edit], baseRevision: document.revision)
578        } catch {
579            // Out of step: the view's text wins.
580            shrunk = ShrunkColumns()
581            load(textView.textStorage.string)
582            return
583        }
584        let newText = textView.textStorage.string as NSString
585        styled.map(through: edit, in: newText)
586        let affected = Presentation.restyleRange(for: edit, old: (oldTree, oldText), new: (document.tree, newText))
587        vim.changed(edit)
588        // Walking the tree for blocks costs more than typing; only an edit on a line that could
589        // start or end one needs it, others move the ranges.
590        let newEnd = edit.range.lowerBound + (replacement as NSString).length
591        if Presentation.mayChangeBlocks(oldText, edit.range) || Presentation.mayChangeBlocks(newText, edit.range.lowerBound..<newEnd) {
592            blocksMayChange = true
593        } else {
594            shaded.set(ViewState(selection: shaded.all).mapped(through: [edit]).selection, folded: [])
595        }
596        for table in shrunk.map(through: edit, in: textView.textStorage.string, command: commandEditing) { scheduleRestyle(table) }
597        fold = FoldState(
598            folds: Self.map(fold.folds, old, delta), bodyFolds: Self.map(fold.bodyFolds, old, delta),
599            wrapperFolds: Self.map(fold.wrapperFolds, old, delta)
600        )
601        scheduleRestyle(affected.lowerBound..<min(affected.upperBound, newText.length))
602        onChange?()
603    }
604
605    /// Starts after the edit move with it; ones inside it go.
606    static func map(_ starts: Set<Int>, _ old: Range<Int>, _ delta: Int) -> Set<Int> {
607        Set(starts.compactMap { start in
608            if start >= old.upperBound { return start + delta }
609            return start <= old.lowerBound ? start : nil
610        })
611    }
612
613}
614
615extension MobileEditor: UITextViewDelegate {
616    func textViewDidBeginEditing(_ textView: UITextView) {
617        focus(textView)
618    }
619
620    /// Another view's caret moves with edits made in this one; only the focused view's
621    /// selection drives the display.
622    func textView(_ textView: UITextView, editMenuForTextIn range: NSRange, suggestedActions: [UIMenuElement]) -> UIMenu? {
623        options.spellCheck ? spellingMenu(for: range, in: textView, suggested: suggestedActions) : nil
624    }
625
626    func textViewDidChangeSelection(_ textView: UITextView) {
627        if textView.isFirstResponder { focus(textView) }
628        guard textView === self.textView else { return }
629        selectionChanged()
630    }
631
632    /// `electric-pair-mode` for typed brackets and quotes, DEL and RET, and `auto-fill-mode`
633    /// for a typed space, from either keyboard.
634    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
635        if isearch != nil, !applyingEdits {
636            isearchTyped(text)
637            return false
638        }
639        if !applyingEdits { typedOutsideInsert() }
640        if autoFills, !applyingEdits, textView.markedTextRange == nil, text == " ", range == textView.selectedRange {
641            _ = perform(AutoFillSpace())
642            return false
643        }
644        guard options.electricPair, !applyingEdits, textView.markedTextRange == nil else { return true }
645        let selected = textView.selectedRange
646        let key: String
647        if text.isEmpty, selected.length == 0, range.length == 1, NSMaxRange(range) == selected.location {
648            key = "DEL"
649        } else if range == selected, text == "\n" {
650            key = "RET"
651        } else if range == selected, ElectricPairKey.characters.contains(text) {
652            key = text
653        } else {
654            return true
655        }
656        let command = ElectricPairKey(key: key)
657        guard command.applies(in: editContext()) else { return true }
658        _ = perform(command)
659        return false
660    }
661}
662
663extension MobileEditor: UIGestureRecognizerDelegate {
664    /// The drawer or block a tap at `point` folds or unfolds: a folded one's `…`, the space after
665    /// its first line, or anywhere on an open drawer's first line.
666    private func foldToggle(at point: CGPoint, in view: UITextView? = nil) -> Int? {
667        let textView = view ?? textView
668        guard let manager = textView.textLayoutManager, let content = manager.textContentManager else { return nil }
669        let inContainer = CGPoint(x: point.x - textView.textContainerInset.left, y: point.y - textView.textContainerInset.top)
670        guard let fragment = manager.textLayoutFragment(for: inContainer), let range = fragment.textElement?.elementRange else { return nil }
671        let start = content.offset(from: content.documentRange.location, to: range.location)
672        guard let line = fragment.textLineFragments.first(where: { $0.characterRange.length > 0 }) ?? fragment.textLineFragments.first else { return nil }
673        if hidden.isFolded(start) { return inContainer.x - fragment.layoutFragmentFrame.minX >= line.typographicBounds.maxX ? start : nil }
674        guard Wrappers.starting(at: start, in: document.tree)?.kind == .drawer,
675              inContainer.y - fragment.layoutFragmentFrame.minY < line.typographicBounds.maxY else { return nil }
676        return start
677    }
678
679    /// A tap on a fold's `…` opens it, and one on an open drawer's first line folds it, as TAB
680    /// on the line does.
681    @objc fileprivate func tappedFold(_ tap: UITapGestureRecognizer) {
682        if let view = tap.view as? UITextView { focus(view) }
683        guard let start = foldToggle(at: tap.location(in: textView)),
684              let next = Presentation.cycle(at: start, in: document.tree, fold) else { return }
685        setFolds(next)
686    }
687
688    func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
689        guard let view = gestureRecognizer.view as? UITextView else { return false }
690        return foldToggle(at: gestureRecognizer.location(in: view), in: view) != nil
691    }
692
693    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith other: UIGestureRecognizer) -> Bool {
694        true
695    }
696}
697
698extension MobileEditor: NSTextStorageDelegate {
699    nonisolated func textStorage(
700        _ textStorage: NSTextStorage, didProcessEditing editedMask: NSTextStorage.EditActions, range editedRange: NSRange, changeInLength delta: Int
701    ) {
702        guard editedMask.contains(.editedCharacters) else { return }
703        MainActor.assumeIsolated { storageEdited(range: editedRange, delta: delta) }
704    }
705}
706
707extension MobileEditor: NSTextContentStorageDelegate {
708    /// Folded text isn't enumerated, so it isn't laid out or drawn.
709    nonisolated func textContentManager(
710        _ textContentManager: NSTextContentManager, shouldEnumerate textElement: NSTextElement, options: NSTextContentManager.EnumerationOptions = []
711    ) -> Bool {
712        guard let range = textElement.elementRange else { return true }
713        let documentStart = textContentManager.documentRange.location
714        let start = textContentManager.offset(from: documentStart, to: range.location)
715        let end = textContentManager.offset(from: documentStart, to: range.endLocation)
716        return !hidden.covers(start, end)
717    }
718}
719
720extension MobileEditor: NSTextLayoutManagerDelegate {
721    /// Folded headings, drawers and blocks end with `…`; blocks are on a band; image links
722    /// show their image; pretty entities draw their character.
723    nonisolated func textLayoutManager(
724        _ textLayoutManager: NSTextLayoutManager, textLayoutFragmentFor location: NSTextLocation, in textElement: NSTextElement
725    ) -> NSTextLayoutFragment {
726        let range = textElement.elementRange
727        guard let range, let manager = textLayoutManager.textContentManager else { return NSTextLayoutFragment(textElement: textElement, range: range) }
728        let offset = manager.offset(from: manager.documentRange.location, to: range.location)
729        let folded = hidden.isFolded(offset)
730        let band = shaded.containing(offset) != nil ? fragmentStyle.blockBand : nil
731        let string = (textElement as? NSTextParagraph)?.attributedString
732        let image = string.map(OrgLineFragment.hasImages) ?? false
733        let entities = string.map(OrgLineFragment.hasEntities) ?? false
734        let latex = string.map(OrgLineFragment.hasLatex) ?? false
735        guard folded || band != nil || image || entities || latex else { return NSTextLayoutFragment(textElement: textElement, range: range) }
736        let fragment = OrgLineFragment(textElement: textElement, range: range)
737        fragment.folded = folded
738        fragment.band = band
739        if band != nil {
740            fragment.start = offset
741            fragment.style = fragmentStyle
742        }
743        return fragment
744    }
745}
746#endif