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