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