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