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