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