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