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