Sources/OrgstarMobile/MobileEditor.swift

d24a6c5c43d3e63039ff8395d03b8399ecede125
orgstar/Sources/OrgstarMobile/MobileEditor.swift

857 lines · 43689 bytes

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