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