Sources/OrgstarMobile/MobileEditor.swift

9b3c99f98cf4b0b8fa0181a4210ad5f07795c2e9
orgstar/Sources/OrgstarMobile/MobileEditor.swift

726 lines · 36361 bytes

  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`: lines that are only an image link show the image.
132    var showsImages = false
133    /// `org-latex-preview`: LaTeX fragments show as typeset math.
134    var showsLatex = false
135    /// The view width images were last sized for.
136    var imageWidth: CGFloat = 0
137    /// The file's folder, for relative image paths.
138    let baseDirectory: URL?
139    /// An `attachment:` link's file, from its name, offset and the tree; nil leaves those links
140    /// as text.
141    var attachmentPath: ((String, Int, OrgTree) -> String?)?
142    static let imageCache = NSCache<NSString, UIImage>()
143    var loading = false
144    var restyleScheduled: Range<Int>?
145    /// Narrowed table columns (`org-table-shrink`).
146    var shrunk = ShrunkColumns()
147    /// A command's edits being applied, which keep shrunk columns narrow.
148    private var commandEditing = false
149
150    init(
151        document: DocumentState, editable: Bool, options: EditingOptions = .org, theme spec: ThemeSpec = .default,
152        showMarkup: Bool = true, baseDirectory: URL? = nil
153    ) {
154        self.document = document
155        self.options = options
156        self.showMarkup = showMarkup
157        self.baseDirectory = baseDirectory
158        theme = MobileTheme(spec)
159        let keyed = KeyedTextView(usingTextLayoutManager: true)
160        textView = keyed
161        textViews = [keyed]
162        super.init()
163        configure(keyed, editable: editable)
164        textView.textStorage.delegate = self
165        (textView.textLayoutManager?.textContentManager as? NSTextContentStorage)?.delegate = self
166        let startup = Presentation.startupDisplay(document.tree, options: options)
167        indented = startup.indented
168        hideStars = startup.hideStars
169        showsImages = startup.inlineImages
170        showsLatex = startup.latexPreview
171        shrunk = ShrunkColumns.startup(document.tree)
172        applyThemeToView()
173        load(document.text)
174        setFolds(startup.folds)
175        if startup.alignTables { _ = perform(AlignAllTables()) }
176        truncatesLines = startup.truncated
177        textView.selectedRange = NSRange(location: 0, length: 0)
178    }
179
180    /// What every view of the buffer has: the keymap, the editor as its delegates and the fold
181    /// tap. Views in one scene share its undo stack.
182    private func configure(_ view: KeyedTextView, editable: Bool) {
183        view.keyHandler = { [weak self, weak view] key in
184            guard let self else { return false }
185            if let view { focus(view) }
186            return handleKey(key)
187        }
188        view.onLayout = { [weak self] in self?.viewResized() }
189        view.onFiles = { [weak self, weak view] files in
190            guard let self, let onFiles else { return false }
191            if let view { focus(view) }
192            onFiles(files)
193            return true
194        }
195        view.onImage = { [weak self, weak view] data, ext in
196            guard let self, let onImage else { return false }
197            if let view { focus(view) }
198            onImage(data, ext)
199            return true
200        }
201        view.textDropDelegate = view
202        view.isEditable = editable
203        view.autocorrectionType = .no
204        view.autocapitalizationType = .none
205        view.smartQuotesType = .no
206        view.smartDashesType = .no
207        view.smartInsertDeleteType = .no
208        // The editor checks spelling itself, outside code, links and keywords.
209        view.spellCheckingType = .no
210        view.keyboardDismissMode = .interactive
211        view.alwaysBounceVertical = true
212        view.textContainerInset = UIEdgeInsets(top: 12, left: 8, bottom: 24, right: 8)
213        view.delegate = self
214        view.textLayoutManager?.delegate = self
215        let foldTap = UITapGestureRecognizer(target: self, action: #selector(tappedFold))
216        foldTap.delegate = self
217        view.addGestureRecognizer(foldTap)
218    }
219
220    // MARK: - Views
221
222    /// Another view of the buffer, for another pane: its own layout manager on the buffer's
223    /// content storage, so text, folds and styles are shared and the caret and scroll aren't.
224    func addView() -> UITextView {
225        guard let storage = textViews[0].textLayoutManager?.textContentManager as? NSTextContentStorage else { return textViews[0] }
226        let manager = NSTextLayoutManager()
227        manager.delegate = self
228        let container = NSTextContainer(size: CGSize(width: 0, height: CGFloat.greatestFiniteMagnitude))
229        manager.textContainer = container
230        storage.addTextLayoutManager(manager)
231        let view = KeyedTextView(frame: .zero, textContainer: container)
232        configure(view, editable: textViews[0].isEditable)
233        textViews.append(view)
234        applyThemeToView(view)
235        if truncatesLines { view.truncates = true }
236        updateCursor()
237        return view
238    }
239
240    /// Drops a view `addView` made; the first stays with the editor.
241    func removeView(_ view: UITextView) {
242        guard view !== textViews[0], let index = textViews.firstIndex(where: { $0 === view }) else { return }
243        textViews.remove(at: index)
244        if let manager = view.textLayoutManager, let storage = manager.textContentManager { storage.removeTextLayoutManager(manager) }
245        view.delegate = nil
246        onFocus[ObjectIdentifier(view)] = nil
247        if textView === view { textView = textViews[0] }
248    }
249
250    /// What each view's screen does when its view takes focus: the editor's callbacks are
251    /// that screen's from then on.
252    var onFocus: [ObjectIdentifier: () -> Void] = [:]
253
254    /// Commands act on `view` from now on.
255    func focus(_ view: UITextView) {
256        guard view !== textView, textViews.contains(where: { $0 === view }) else { return }
257        textView = view
258        onFocus[ObjectIdentifier(view)]?()
259    }
260
261    /// Every view's layout manager.
262    var layoutManagers: [NSTextLayoutManager] { textViews.compactMap(\.textLayoutManager) }
263
264    // MARK: - DocumentBuffer
265
266    var selection: [Range<Int>] {
267        let selected = textView.selectedRange
268        return [selected.location..<NSMaxRange(selected)]
269    }
270
271    func update<T>(_ change: (inout DocumentState) throws -> T) rethrows -> T {
272        let before = document.text
273        let defaultsBefore = document.defaults
274        let selected = textView.selectedRange
275        let result = try change(&document)
276        if document.text != before {
277            // A save that merged a change from disk, or a revert: the view shows the new text.
278            shrunk = ShrunkColumns()
279            load(document.text)
280            let length = (document.text as NSString).length
281            textView.selectedRange = NSRange(location: min(selected.location, length), length: 0)
282            textView.undoManager?.removeAllActions()
283            setFolds(fold)
284        } else if document.defaults != defaultsBefore {
285            restyle(0..<(document.text as NSString).length)
286        }
287        return result
288    }
289
290    func perform(_ command: any OrgCommand, now: Date = Date(), answers: [String: String] = [:]) -> CommandStep {
291        let context = EditContext(
292            revision: document.revision, text: document.text, tree: document.tree, selection: selection,
293            now: now, answers: answers, hidden: hidden.all, options: options, knownTags: knownTags
294        )
295        let step = command.run(in: context)
296        switch step {
297        case .commit(let result):
298            guard textView.isEditable || result.edits.isEmpty else {
299                onMessage?("This file is read-only.")
300                return .failed("read-only")
301            }
302            commandEditing = true
303            applyEdits(result.edits)
304            commandEditing = false
305            if let selected = result.selection?.first {
306                unfold(around: selected.lowerBound)
307                textView.selectedRange = NSRange(location: selected.lowerBound, length: selected.count)
308                textView.scrollRangeToVisible(textView.selectedRange)
309            }
310            for effect in result.effects {
311                switch effect {
312                case .message(let text): onMessage?(text)
313                case .fold(let start):
314                    var state = fold
315                    state.folds.insert(start)
316                    setFolds(state)
317                case .refreshSetup: onRefreshSetup?()
318                case .timer(let timer): TimerModel.shared.set(timer)
319                default: break
320                }
321            }
322        case .failed(let message):
323            onMessage?(message)
324        case .prompt(let prompt):
325            onPrompt?(prompt) { [weak self] answer in
326                guard let self else { return }
327                guard let answer else { return self.onMessage?("Quit") ?? () }
328                _ = self.perform(command, now: now, answers: answers.merging([prompt.key: answer]) { $1 })
329            }
330        case .external(.editBlock(let edit)) where onEditBlock != nil:
331            onEditBlock?(edit)
332        case .external(.babel(let job)) where onBabel != nil:
333            onBabel?(job)
334        case .external(.tangle(let scope)) where onTangle != nil:
335            onTangle?(scope)
336        case .external(.agenda(let start, let count)) where onAgenda != nil:
337            onAgenda?(start, count)
338        case .external(.columnView(let view)) where onColumnView != nil:
339            onColumnView?(view)
340        case .external(let request):
341            // The fields written before a formula only Emacs can do stay, as Emacs leaves them
342            // when a formula fails.
343            if case .emacsTable(_, _, _, _, _, _, let partial?) = request { _ = perform(PrecomputedEdit(partial)) }
344            // `org-sbe` without Babel shows its paywall.
345            if case .emacsTable(_, _, _, TableBlocks.lockedReason, _, _, _) = request {
346                ProAccess.shared.allows(.babel)
347                return step
348            }
349            onMessage?(Self.unavailable(request, title: command.title))
350        }
351        return step
352    }
353
354    /// Why a request the app doesn't handle did nothing: only table recalculation needs Emacs.
355    static func unavailable(_ request: ExternalRequest, title: String) -> String {
356        if case .emacsTable(_, _, _, let reason, _, let formula?, _) = request {
357            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")
358        }
359        if case .emacsTable(_, _, _, let reason, _, _, _) = request {
360            return String(localized: "This table needs Emacs, which runs on the Mac: \(TableReason.localized(reason)).", comment: "Table formulas only Emacs can calculate")
361        }
362        return String(localized: "\(CommandTitle.localized(title)) isn't available on iPhone and iPad.", comment: "A command that runs only on the Mac")
363    }
364
365    // MARK: - Commands by name and key
366
367    /// Runs what `keys` (as `C-c C-t`) is bound to in the Emacs keymap, for the caret's context.
368    func run(keys: String) {
369        guard let chords = KeySequence.parse(keys) else { return }
370        let context = editContext()
371        let binding = keymap.candidates(for: chords).first { binding in
372            (binding.when.map { KeyContext.holds($0, in: context) } ?? true) && applies(binding.command, in: context)
373        }
374        guard let binding else { return onMessage?("Nothing to do here") ?? () }
375        run(binding.command)
376    }
377
378    func run(_ id: String) {
379        switch id {
380        case "org.cycle":
381            if !cycleAtCaret() { onMessage?("Not on a heading, drawer or block") }
382        case "org.cycle-global": cycleGlobal()
383        case _ where id.hasPrefix("org.fold."): foldCommand(id)
384        case "org.link.open": openLinkAtCaret()
385        case "org.toggle-inline-images": toggleImages()
386        case "org.latex-preview": toggleLatex()
387        case "editor.toggle-truncate-lines":
388            truncatesLines.toggle()
389            onMessage?(truncatesLines ? "Truncate long lines enabled" : "Truncate long lines disabled")
390        case "edit.isearch-forward": startISearch(forward: true)
391        case "edit.isearch-backward": startISearch(forward: false)
392        case "edit.isearch-forward-regexp": startISearch(forward: true, regexp: true)
393        case "edit.isearch-backward-regexp": startISearch(forward: false, regexp: true)
394        case "editor.toggle-auto-fill":
395            autoFillOverride = !autoFills
396            onMessage?(autoFills ? "Auto-Fill mode enabled in current buffer" : "Auto-Fill mode disabled in current buffer")
397        case "edit.undo": textView.undoManager?.undo()
398        case "edit.redo": textView.undoManager?.redo()
399        case "org.table.toggle-column-width", "org.table.shrink", "org.table.expand": tableColumnWidth(id)
400        case _ where id.hasPrefix("app.") || Self.linkCommands.contains(id):
401            if let onAppCommand { onAppCommand(id) } else { onMessage?("Not available on iOS yet") }
402        default:
403            if let command = Commands.command(id) {
404                _ = perform(command)
405            } else {
406                onMessage?("Not available on iOS yet")
407            }
408        }
409    }
410
411    /// Link commands that need the stored links or the file, which the screen has.
412    static let linkCommands: Set<String> = ["org.link.store", "org.id.store-link", "org.link.insert"]
413
414    func applies(_ id: String, in context: EditContext) -> Bool {
415        if let command = Commands.command(id) { return command.applies(in: context) }
416        switch id {
417        case "org.cycle":
418            return Presentation.heading(containing: context.caret, in: context.tree) != nil || Wrappers.toggleable(at: context.caret, in: context.tree) != nil
419        case _ where id.hasPrefix("org.fold."): return true
420        case "org.cycle-global", "edit.undo", "edit.redo", "org.toggle-inline-images", "org.latex-preview", "editor.toggle-truncate-lines",
421             "editor.toggle-auto-fill", "edit.isearch-forward", "edit.isearch-backward",
422             "edit.isearch-forward-regexp", "edit.isearch-backward-regexp": return true
423        case "app.clock.in", "app.clock.out", "app.clock.cancel", "app.clock.goto", "app.clock.in-recent", "app.clock.in-last",
424             "app.clock.goto-recent", "app.clock.default", "app.clock.resolve", "app.toggle-markup": return onAppCommand != nil
425        case "app.refile.goto", "app.table-import", "app.crypt.encrypt-entries", "app.crypt.forget-passphrase", "app.attach.attach", "app.attach.url",
426             "app.attach.new", "app.attach.open", "app.attach.reveal", "app.attach.delete", "app.attach.delete-all", "app.attach.sync",
427             "app.attach.set-directory", "app.attach.unset-directory", "app.backlinks", "app.node.find", "app.node.insert",
428             "app.node.rename-from-front-matter": return onAppCommand != nil
429        case _ where id.hasPrefix("app.node."): return onAppCommand != nil
430        case _ where id.hasPrefix("app.dailies."): return onAppCommand != nil
431        case "app.crypt.encrypt-entry": return onAppCommand != nil && OrgCrypt.heading(context.text, at: context.caret) != nil && OrgCrypt.encryptedRange(context.text, at: context.caret) == nil
432        case "app.crypt.open-entry", "app.crypt.decrypt-entry": return onAppCommand != nil && OrgCrypt.encryptedRange(context.text, at: context.caret) != nil
433        case "app.table-export", "app.plot": return onAppCommand != nil && ImportTable.exportText(context.text, at: context.caret, path: "") != nil
434        case "app.refile", "app.refile.copy", "app.archive": return onAppCommand != nil && Presentation.heading(containing: context.caret, in: context.tree) != nil
435        case "app.copy-rich-text", "app.export.html-open", "app.export-body-only", "app.export.icalendar-agenda", "app.export.icalendar-combined": return onAppCommand != nil
436        case _ where id.hasPrefix("app.publish"): return onAppCommand != nil
437        case _ where Self.linkCommands.contains(id): return onAppCommand != nil
438        case "org.link.open": return OpenLinkAtPoint().applies(in: context)
439        case "org.table.toggle-column-width", "org.table.shrink", "org.table.expand":
440            return TableShrink.table(at: context.caret, in: context.text) != nil
441        default: return false
442        }
443    }
444
445    // MARK: - Hardware keyboard
446
447    lazy var dispatcher = KeyDispatcher(keymap: keymap)
448
449    private static let named: [UIKeyboardHIDUsage: String] = [
450        .keyboardTab: "TAB", .keyboardReturnOrEnter: "RET", .keypadEnter: "RET", .keyboardSpacebar: "SPC",
451        .keyboardEscape: "ESC", .keyboardDeleteOrBackspace: "DEL", .keyboardDeleteForward: "<delete>",
452        .keyboardLeftArrow: "<left>", .keyboardRightArrow: "<right>", .keyboardUpArrow: "<up>", .keyboardDownArrow: "<down>",
453        .keyboardHome: "<home>", .keyboardEnd: "<end>", .keyboardPageUp: "<prior>", .keyboardPageDown: "<next>",
454    ]
455
456    /// A key press as a chord; Option is Meta, as `option-as-meta` makes it on the Mac.
457    static func chord(_ key: UIKey) -> KeyChord? {
458        var modifiers: KeyChord.Modifiers = []
459        let flags = key.modifierFlags
460        if flags.contains(.control) { modifiers.insert(.control) }
461        if flags.contains(.alternate) { modifiers.insert(.meta) }
462        if flags.contains(.command) { modifiers.insert(.command) }
463        if let name = named[key.keyCode] {
464            if flags.contains(.shift) { modifiers.insert(.shift) }
465            return KeyChord(name, modifiers)
466        }
467        var characters = key.charactersIgnoringModifiers
468        if flags.contains(.shift), characters.count == 1, characters.lowercased() == characters { characters = characters.uppercased() }
469        guard characters.count == 1 else { return nil }
470        return KeyChord(characters, modifiers)
471    }
472
473    /// The Emacs keymap's commands on an iPad keyboard. Keys it doesn't bind, Command shortcuts
474    /// and editing keys (C-a, C-e, C-k...) are the text system's.
475    func handleKey(_ key: UIKey) -> Bool {
476        movedByArrow = [.keyboardUpArrow, .keyboardDownArrow, .keyboardLeftArrow, .keyboardRightArrow].contains(key.keyCode)
477        guard let chord = Self.chord(key), !chord.modifiers.contains(.command) else { return false }
478        if isearch != nil, isearchKey(chord) { return true }
479        if modal { return handleModal(chord) }
480        // Option alone types characters unless it begins a binding.
481        if chord.modifiers == [.meta], dispatcher.pending.isEmpty,
482           keymap.candidates(for: [chord]).isEmpty, !keymap.isPrefix([chord]) { return false }
483        switch dispatcher.feed(chord) {
484        case .pending(let keys):
485            onMessage?(KeySequence.format(keys) + "-")
486            return true
487        case .cancelled:
488            onMessage?("Quit")
489            return true
490        case .undefined(let keys):
491            onMessage?("\(KeySequence.format(keys)) is undefined")
492            return true
493        case .unbound:
494            return false
495        case .complete(let keys, let candidates):
496            let context = editContext()
497            let runnable = candidates.first { binding in
498                (binding.when.map { KeyContext.holds($0, in: context) } ?? true) && applies(binding.command, in: context)
499            }
500            // A sequence runs its command even where it doesn't apply, which says why, as on the Mac.
501            guard let binding = runnable ?? (keys.count > 1 ? candidates.first : nil) else { return false }
502            if keys.count == 1, binding.command.hasPrefix("edit."), !["edit.undo", "edit.redo"].contains(binding.command) { return false }
503            run(binding.command)
504            return true
505        }
506    }
507
508    func editContext() -> EditContext {
509        EditContext(revision: document.revision, text: document.text, tree: document.tree, selection: selection, hidden: hidden.all, options: options, knownTags: knownTags)
510    }
511
512    private func openLinkAtCaret() {
513        let caret = textView.selectedRange.location
514        if let link = Links.link(at: caret, text: document.text, tree: document.tree)?.link {
515            onLink?(link)
516        } else if let days = Links.timestampDays(at: caret, text: document.text) {
517            onAgenda?(days.start, days.count)
518        } else {
519            onMessage?("No link here")
520        }
521    }
522
523    // MARK: - Editing
524
525    /// Applies `edits` (against the current text) through the text view as one undo step.
526    func applyEdits(_ edits: [TextEdit]) {
527        let interval = Perf.begin("editor.applyEdits")
528        defer { interval.end() }
529        guard !edits.isEmpty else { return }
530        applyingEdits = true
531        defer { applyingEdits = false }
532        // Straight into the storage: replacing through text input would take the active
533        // keyboard's substitutions (smart dashes) when another view has the keyboard.
534        let storage = textView.textStorage
535        let old = storage.string as NSString
536        // By lines, so a fold between two changes stays.
537        let ascending = edits.flatMap { splitByLines($0, in: storage.string) }.sorted { $0.range.lowerBound < $1.range.lowerBound }
538        var inverse: [TextEdit] = []
539        var delta = 0
540        for edit in ascending {
541            let start = edit.range.lowerBound + delta
542            let length = (edit.replacement as NSString).length
543            inverse.append(TextEdit(range: start..<start + length, replacement: old.substring(with: NSRange(edit.range))))
544            delta += length - edit.range.count
545        }
546        let caret = textView.selectedRange
547        // One at a time, last first: each is processed alone, so folds between them stay.
548        for edit in ascending.reversed() {
549            storage.replaceCharacters(in: NSRange(edit.range), with: edit.replacement)
550        }
551        textView.undoManager?.registerUndo(withTarget: self) { editor in
552            editor.applyEdits(inverse)
553            editor.textView.selectedRange = caret
554        }
555    }
556
557    /// The storage changed (typing, a command, undo): the document takes the same edit, and
558    /// folds and styles follow.
559    fileprivate func storageEdited(range: NSRange, delta: Int) {
560        let interval = Perf.begin("editor.edit")
561        defer { interval.end() }
562        guard !loading else { return }
563        let old = range.location..<(range.location + range.length - delta)
564        let replacement = (textView.textStorage.string as NSString).substring(with: range)
565        let edit = TextEdit(range: old, replacement: replacement)
566        do {
567            try document.apply([edit], baseRevision: document.revision)
568        } catch {
569            // Out of step: the view's text wins.
570            shrunk = ShrunkColumns()
571            load(textView.textStorage.string)
572            return
573        }
574        vim.changed(edit)
575        for table in shrunk.map(through: edit, in: textView.textStorage.string, command: commandEditing) { scheduleRestyle(table) }
576        fold = FoldState(
577            folds: Self.map(fold.folds, old, delta), bodyFolds: Self.map(fold.bodyFolds, old, delta),
578            wrapperFolds: Self.map(fold.wrapperFolds, old, delta)
579        )
580        scheduleRestyle(range.location..<NSMaxRange(range))
581        onChange?()
582    }
583
584    /// Starts after the edit move with it; ones inside it go.
585    static func map(_ starts: Set<Int>, _ old: Range<Int>, _ delta: Int) -> Set<Int> {
586        Set(starts.compactMap { start in
587            if start >= old.upperBound { return start + delta }
588            return start <= old.lowerBound ? start : nil
589        })
590    }
591
592}
593
594extension MobileEditor: UITextViewDelegate {
595    func textViewDidBeginEditing(_ textView: UITextView) {
596        focus(textView)
597    }
598
599    /// Another view's caret moves with edits made in this one; only the focused view's
600    /// selection drives the display.
601    func textView(_ textView: UITextView, editMenuForTextIn range: NSRange, suggestedActions: [UIMenuElement]) -> UIMenu? {
602        options.spellCheck ? spellingMenu(for: range, in: textView, suggested: suggestedActions) : nil
603    }
604
605    func textViewDidChangeSelection(_ textView: UITextView) {
606        if textView.isFirstResponder { focus(textView) }
607        guard textView === self.textView else { return }
608        selectionChanged()
609    }
610
611    /// `electric-pair-mode` for typed brackets and quotes, DEL and RET, and `auto-fill-mode`
612    /// for a typed space, from either keyboard.
613    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
614        if isearch != nil, !applyingEdits {
615            isearchTyped(text)
616            return false
617        }
618        if !applyingEdits { typedOutsideInsert() }
619        if autoFills, !applyingEdits, textView.markedTextRange == nil, text == " ", range == textView.selectedRange {
620            _ = perform(AutoFillSpace())
621            return false
622        }
623        guard options.electricPair, !applyingEdits, textView.markedTextRange == nil else { return true }
624        let selected = textView.selectedRange
625        let key: String
626        if text.isEmpty, selected.length == 0, range.length == 1, NSMaxRange(range) == selected.location {
627            key = "DEL"
628        } else if range == selected, text == "\n" {
629            key = "RET"
630        } else if range == selected, ElectricPairKey.characters.contains(text) {
631            key = text
632        } else {
633            return true
634        }
635        let command = ElectricPairKey(key: key)
636        guard command.applies(in: editContext()) else { return true }
637        _ = perform(command)
638        return false
639    }
640}
641
642extension MobileEditor: UIGestureRecognizerDelegate {
643    /// The drawer or block a tap at `point` folds or unfolds: a folded one's `…`, the space after
644    /// its first line, or anywhere on an open drawer's first line.
645    private func foldToggle(at point: CGPoint, in view: UITextView? = nil) -> Int? {
646        let textView = view ?? textView
647        guard let manager = textView.textLayoutManager, let content = manager.textContentManager else { return nil }
648        let inContainer = CGPoint(x: point.x - textView.textContainerInset.left, y: point.y - textView.textContainerInset.top)
649        guard let fragment = manager.textLayoutFragment(for: inContainer), let range = fragment.textElement?.elementRange else { return nil }
650        let start = content.offset(from: content.documentRange.location, to: range.location)
651        guard let line = fragment.textLineFragments.first(where: { $0.characterRange.length > 0 }) ?? fragment.textLineFragments.first else { return nil }
652        if hidden.isFolded(start) { return inContainer.x - fragment.layoutFragmentFrame.minX >= line.typographicBounds.maxX ? start : nil }
653        guard Wrappers.starting(at: start, in: document.tree)?.kind == .drawer,
654              inContainer.y - fragment.layoutFragmentFrame.minY < line.typographicBounds.maxY else { return nil }
655        return start
656    }
657
658    /// A tap on a fold's `…` opens it, and one on an open drawer's first line folds it, as TAB
659    /// on the line does.
660    @objc fileprivate func tappedFold(_ tap: UITapGestureRecognizer) {
661        if let view = tap.view as? UITextView { focus(view) }
662        guard let start = foldToggle(at: tap.location(in: textView)),
663              let next = Presentation.cycle(at: start, in: document.tree, fold) else { return }
664        setFolds(next)
665    }
666
667    func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
668        guard let view = gestureRecognizer.view as? UITextView else { return false }
669        return foldToggle(at: gestureRecognizer.location(in: view), in: view) != nil
670    }
671
672    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith other: UIGestureRecognizer) -> Bool {
673        true
674    }
675}
676
677extension MobileEditor: NSTextStorageDelegate {
678    nonisolated func textStorage(
679        _ textStorage: NSTextStorage, didProcessEditing editedMask: NSTextStorage.EditActions, range editedRange: NSRange, changeInLength delta: Int
680    ) {
681        guard editedMask.contains(.editedCharacters) else { return }
682        MainActor.assumeIsolated { storageEdited(range: editedRange, delta: delta) }
683    }
684}
685
686extension MobileEditor: NSTextContentStorageDelegate {
687    /// Folded text isn't enumerated, so it isn't laid out or drawn.
688    nonisolated func textContentManager(
689        _ textContentManager: NSTextContentManager, shouldEnumerate textElement: NSTextElement, options: NSTextContentManager.EnumerationOptions = []
690    ) -> Bool {
691        guard let range = textElement.elementRange else { return true }
692        let documentStart = textContentManager.documentRange.location
693        let start = textContentManager.offset(from: documentStart, to: range.location)
694        let end = textContentManager.offset(from: documentStart, to: range.endLocation)
695        return !hidden.covers(start, end)
696    }
697}
698
699extension MobileEditor: NSTextLayoutManagerDelegate {
700    /// Folded headings, drawers and blocks end with `…`; blocks are on a band; image lines
701    /// show their image; pretty entities draw their character.
702    nonisolated func textLayoutManager(
703        _ textLayoutManager: NSTextLayoutManager, textLayoutFragmentFor location: NSTextLocation, in textElement: NSTextElement
704    ) -> NSTextLayoutFragment {
705        let range = textElement.elementRange
706        guard let range, let manager = textLayoutManager.textContentManager else { return NSTextLayoutFragment(textElement: textElement, range: range) }
707        let offset = manager.offset(from: manager.documentRange.location, to: range.location)
708        let folded = hidden.isFolded(offset)
709        let band = shaded.containing(offset) != nil ? fragmentStyle.blockBand : nil
710        let string = (textElement as? NSTextParagraph)?.attributedString
711        let image = string.flatMap(OrgLineFragment.image)
712        let entities = string.map(OrgLineFragment.hasEntities) ?? false
713        let latex = string.map(OrgLineFragment.hasLatex) ?? false
714        guard folded || band != nil || image != nil || entities || latex else { return NSTextLayoutFragment(textElement: textElement, range: range) }
715        let fragment = OrgLineFragment(textElement: textElement, range: range)
716        fragment.folded = folded
717        fragment.band = band
718        if band != nil {
719            fragment.start = offset
720            fragment.style = fragmentStyle
721        }
722        fragment.image = image
723        return fragment
724    }
725}
726#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