Sources/OrgstarMobile/MobileEditor.swift

b6a348930a231ab1ffd793a69f2d512f8b60bad8
orgstar/Sources/OrgstarMobile/MobileEditor.swift

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