Sources/OrgstarMobile/MobileEditor.swift

5b5584bafaafd3d627ecb2778987cef0e743de9c
orgstar/Sources/OrgstarMobile/MobileEditor.swift

867 lines · 44117 bytes

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