Sources/OrgstarMobile/MobileEditor.swift

ecedad8fac1deba0bacd11a5a65f20ba1659029d
orgstar/Sources/OrgstarMobile/MobileEditor.swift

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