Sources/OrgstarMobile/MobileEditor.swift

22ff42f0ad29d59255e2ac93e0b3a28f66fca672
orgstar/Sources/OrgstarMobile/MobileEditor.swift

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