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