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