Sources/OrgstarMobile/MobileEditor.swift

a15753a827b5ab7a0ccf3a0873890771c2979ee7
orgstar/Sources/OrgstarMobile/MobileEditor.swift

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