Sources/OrgstarMobile/MobileEditor.swift
823 lines · 41823 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 "app.refile", "app.refile.copy", "app.archive": return onAppCommand != nil && Presentation.heading(containing: context.caret, in: context.tree) != nil
483 case "app.copy-rich-text", "app.export.html-open", "app.export-body-only", "app.export.icalendar-agenda", "app.export.icalendar-combined": return onAppCommand != nil
484 case _ where id.hasPrefix("app.publish"): return onAppCommand != nil
485 case _ where Self.linkCommands.contains(id): return onAppCommand != nil
486 case "org.link.open": return OpenLinkAtPoint().applies(in: context)
487 case "org.table.toggle-column-width", "org.table.shrink", "org.table.expand":
488 return TableShrink.table(at: context.caret, in: context.text) != nil
489 default: return false
490 }
491 }
492
493 // MARK: - Hardware keyboard
494
495 lazy var dispatcher = KeyDispatcher(keymap: keymap)
496
497 private static let named: [UIKeyboardHIDUsage: String] = [
498 .keyboardTab: "TAB", .keyboardReturnOrEnter: "RET", .keypadEnter: "RET", .keyboardSpacebar: "SPC",
499 .keyboardEscape: "ESC", .keyboardDeleteOrBackspace: "DEL", .keyboardDeleteForward: "<delete>",
500 .keyboardLeftArrow: "<left>", .keyboardRightArrow: "<right>", .keyboardUpArrow: "<up>", .keyboardDownArrow: "<down>",
501 .keyboardHome: "<home>", .keyboardEnd: "<end>", .keyboardPageUp: "<prior>", .keyboardPageDown: "<next>",
502 ]
503
504 /// A key press as a chord; Option is Meta, as `option-as-meta` makes it on the Mac.
505 static func chord(_ key: UIKey) -> KeyChord? {
506 var modifiers: KeyChord.Modifiers = []
507 let flags = key.modifierFlags
508 if flags.contains(.control) { modifiers.insert(.control) }
509 if flags.contains(.alternate) { modifiers.insert(.meta) }
510 if flags.contains(.command) { modifiers.insert(.command) }
511 if let name = named[key.keyCode] {
512 if flags.contains(.shift) { modifiers.insert(.shift) }
513 return KeyChord(name, modifiers)
514 }
515 var characters = key.charactersIgnoringModifiers
516 if flags.contains(.shift), characters.count == 1, characters.lowercased() == characters { characters = characters.uppercased() }
517 guard characters.count == 1 else { return nil }
518 return KeyChord(characters, modifiers)
519 }
520
521 /// The Emacs keymap's commands on an iPad keyboard. Keys it doesn't bind, Command shortcuts
522 /// and editing keys (C-a, C-e, C-k...) are the text system's.
523 func handleKey(_ key: UIKey) -> Bool {
524 movedByArrow = [.keyboardUpArrow, .keyboardDownArrow, .keyboardLeftArrow, .keyboardRightArrow].contains(key.keyCode)
525 guard let chord = Self.chord(key), !chord.modifiers.contains(.command) else { return false }
526 return handleChord(chord)
527 }
528
529 /// A key, typed or replayed from a keyboard macro. False lets the text system have it.
530 func handleChord(_ chord: KeyChord) -> Bool {
531 if kmacroDepth == 0 { Self.kmacro.record(chord, begins: dispatcher.pending.isEmpty) }
532 if let key = macroRepeatKey {
533 macroRepeatKey = nil
534 if chord == key, dispatcher.pending.isEmpty, isearch == nil {
535 callLastMacro(count: 1, repeatKey: key)
536 return true
537 }
538 }
539 if isearch != nil, isearchKey(chord) { return true }
540 if let handled = snippetKey(chord) { return handled }
541 if modal { return handleModal(chord) }
542 // Option alone types characters unless it begins a binding.
543 if chord.modifiers == [.meta], dispatcher.pending.isEmpty,
544 keymap.candidates(for: [chord]).isEmpty, !keymap.isPrefix([chord]) { return false }
545 switch dispatcher.feed(chord) {
546 case .pending(let keys):
547 onMessage?(KeySequence.format(keys) + "-")
548 return true
549 case .cancelled:
550 fail("Quit")
551 return true
552 case .undefined(let keys):
553 fail("\(KeySequence.format(keys)) is undefined")
554 return true
555 case .unbound:
556 return snippetTab(chord)
557 case .complete(let keys, let candidates):
558 let context = editContext()
559 let runnable = candidates.first { binding in
560 (binding.when.map { KeyContext.holds($0, in: context) } ?? true) && applies(binding.command, in: context)
561 }
562 // A sequence runs its command even where it doesn't apply, which says why, as on the Mac.
563 let argument = dispatcher.argument != nil
564 guard let binding = runnable ?? (keys.count > 1 || argument ? candidates.first : nil) else { return keys.count == 1 && !argument && snippetTab(chord) }
565 // A prefix argument (C-u, C-u 3) counts keyboard macros only.
566 if argument, !binding.command.hasPrefix("macro.") {
567 fail("\(KeySequence.format(keys)) doesn't take a prefix argument")
568 return true
569 }
570 if keys.count == 1, binding.command.hasPrefix("edit."), !["edit.undo", "edit.redo"].contains(binding.command) { return false }
571 commandKeys = keys
572 defer { commandKeys = nil }
573 run(binding.command)
574 return true
575 }
576 }
577
578 func editContext() -> EditContext {
579 EditContext(revision: document.revision, text: document.text, tree: document.tree, selection: selection, hidden: hidden.all, options: options, knownTags: knownTags)
580 }
581
582 private func openLinkAtCaret() {
583 let caret = textView.selectedRange.location
584 if let link = Links.link(at: caret, text: document.text, tree: document.tree)?.link {
585 onLink?(link)
586 } else if let days = Links.timestampDays(at: caret, text: document.text) {
587 onAgenda?(days.start, days.count)
588 } else {
589 onMessage?("No link here")
590 }
591 }
592
593 // MARK: - Editing
594
595 /// Applies `edits` (against the current text) through the text view as one undo step.
596 func applyEdits(_ edits: [TextEdit]) {
597 let interval = Perf.begin("editor.applyEdits")
598 defer { interval.end() }
599 guard !edits.isEmpty else { return }
600 applyingEdits = true
601 defer { applyingEdits = false }
602 // Straight into the storage: replacing through text input would take the active
603 // keyboard's substitutions (smart dashes) when another view has the keyboard.
604 let storage = textView.textStorage
605 let old = storage.string as NSString
606 // By lines, so a fold between two changes stays.
607 let ascending = edits.flatMap { splitByLines($0, in: storage.string) }.sorted { $0.range.lowerBound < $1.range.lowerBound }
608 var inverse: [TextEdit] = []
609 var delta = 0
610 for edit in ascending {
611 let start = edit.range.lowerBound + delta
612 let length = (edit.replacement as NSString).length
613 inverse.append(TextEdit(range: start..<start + length, replacement: old.substring(with: NSRange(edit.range))))
614 delta += length - edit.range.count
615 }
616 let caret = textView.selectedRange
617 // One at a time, last first: each is processed alone, so folds between them stay.
618 for edit in ascending.reversed() {
619 storage.replaceCharacters(in: NSRange(edit.range), with: edit.replacement)
620 }
621 textView.undoManager?.registerUndo(withTarget: self) { editor in
622 editor.applyEdits(inverse)
623 editor.textView.selectedRange = caret
624 }
625 }
626
627 /// The storage changed (typing, a command, undo): the document takes the same edit, and
628 /// folds and styles follow.
629 fileprivate func storageEdited(range: NSRange, delta: Int) {
630 let interval = Perf.begin("editor.edit")
631 defer { interval.end() }
632 guard !loading else { return }
633 let old = range.location..<(range.location + range.length - delta)
634 let replacement = (textView.textStorage.string as NSString).substring(with: range)
635 let edit = TextEdit(range: old, replacement: replacement)
636 snippetEdited(edit)
637 let oldTree = document.tree
638 let oldText = document.text as NSString
639 do {
640 try document.apply([edit], baseRevision: document.revision)
641 } catch {
642 // Out of step: the view's text wins.
643 shrunk = ShrunkColumns()
644 load(textView.textStorage.string)
645 return
646 }
647 let newText = textView.textStorage.string as NSString
648 styled.map(through: edit, in: newText)
649 let affected = Presentation.restyleRange(for: edit, old: (oldTree, oldText), new: (document.tree, newText))
650 vim.changed(edit)
651 // Walking the tree for blocks costs more than typing; only an edit on a line that could
652 // start or end one needs it, others move the ranges.
653 let newEnd = edit.range.lowerBound + (replacement as NSString).length
654 if Presentation.mayChangeBlocks(oldText, edit.range) || Presentation.mayChangeBlocks(newText, edit.range.lowerBound..<newEnd) {
655 blocksMayChange = true
656 } else {
657 shaded.set(ViewState(selection: shaded.all).mapped(through: [edit]).selection, folded: [])
658 }
659 for table in shrunk.map(through: edit, in: textView.textStorage.string, command: commandEditing) { scheduleRestyle(table) }
660 fold = FoldState(
661 folds: Self.map(fold.folds, old, delta), bodyFolds: Self.map(fold.bodyFolds, old, delta),
662 wrapperFolds: Self.map(fold.wrapperFolds, old, delta)
663 )
664 scheduleRestyle(affected.lowerBound..<min(affected.upperBound, newText.length))
665 onChange?()
666 }
667
668 /// Starts after the edit move with it; ones inside it go.
669 static func map(_ starts: Set<Int>, _ old: Range<Int>, _ delta: Int) -> Set<Int> {
670 Set(starts.compactMap { start in
671 if start >= old.upperBound { return start + delta }
672 return start <= old.lowerBound ? start : nil
673 })
674 }
675
676}
677
678extension MobileEditor: UITextViewDelegate {
679 func textViewDidBeginEditing(_ textView: UITextView) {
680 focus(textView)
681 }
682
683 /// Another view's caret moves with edits made in this one; only the focused view's
684 /// selection drives the display.
685 func textView(_ textView: UITextView, editMenuForTextIn range: NSRange, suggestedActions: [UIMenuElement]) -> UIMenu? {
686 let suggested = range.length > 0 && textView.isEditable ? suggestedActions + [formatMenu] : suggestedActions
687 if options.spellCheck, let menu = spellingMenu(for: range, in: textView, suggested: suggested) { return menu }
688 return suggested.count == suggestedActions.count ? nil : UIMenu(children: suggested)
689 }
690
691 /// Org's emphasis for the selection, in its edit menu.
692 private var formatMenu: UIMenu {
693 let styles: [(title: String, symbol: String, command: String)] = [
694 (String(localized: "Bold"), "bold", "org.emphasize.bold"),
695 (String(localized: "Italic"), "italic", "org.emphasize.italic"),
696 (String(localized: "Code"), "chevron.left.forwardslash.chevron.right", "org.emphasize.code"),
697 ]
698 return UIMenu(title: String(localized: "Format"), image: UIImage(systemName: "bold.italic.underline"), children: styles.map { style in
699 UIAction(title: style.title, image: UIImage(systemName: style.symbol)) { [weak self] _ in self?.run(style.command) }
700 })
701 }
702
703 func textViewDidChangeSelection(_ textView: UITextView) {
704 if textView.isFirstResponder { focus(textView) }
705 guard textView === self.textView else { return }
706 selectionChanged()
707 }
708
709 /// `electric-pair-mode` for typed brackets and quotes, DEL and RET, and `auto-fill-mode`
710 /// for a typed space, from either keyboard.
711 func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
712 if isearch != nil, !applyingEdits {
713 isearchTyped(text)
714 return false
715 }
716 if !applyingEdits { typedOutsideInsert() }
717 if autoFills, !applyingEdits, textView.markedTextRange == nil, text == " ", range == textView.selectedRange {
718 _ = perform(AutoFillSpace())
719 return false
720 }
721 guard options.electricPair, !applyingEdits, textView.markedTextRange == nil else { return true }
722 let selected = textView.selectedRange
723 let key: String
724 if text.isEmpty, selected.length == 0, range.length == 1, NSMaxRange(range) == selected.location {
725 key = "DEL"
726 } else if range == selected, text == "\n" {
727 key = "RET"
728 } else if range == selected, ElectricPairKey.characters.contains(text) {
729 key = text
730 } else {
731 return true
732 }
733 let command = ElectricPairKey(key: key)
734 guard command.applies(in: editContext()) else { return true }
735 _ = perform(command)
736 return false
737 }
738}
739
740extension MobileEditor: UIGestureRecognizerDelegate {
741 /// The drawer or block a tap at `point` folds or unfolds: a folded one's `…`, the space after
742 /// its first line, or anywhere on an open drawer's first line.
743 private func foldToggle(at point: CGPoint, in view: UITextView? = nil) -> Int? {
744 let textView = view ?? textView
745 guard let manager = textView.textLayoutManager, let content = manager.textContentManager else { return nil }
746 let inContainer = CGPoint(x: point.x - textView.textContainerInset.left, y: point.y - textView.textContainerInset.top)
747 guard let fragment = manager.textLayoutFragment(for: inContainer), let range = fragment.textElement?.elementRange else { return nil }
748 let start = content.offset(from: content.documentRange.location, to: range.location)
749 guard let line = fragment.textLineFragments.first(where: { $0.characterRange.length > 0 }) ?? fragment.textLineFragments.first else { return nil }
750 if hidden.isFolded(start) { return inContainer.x - fragment.layoutFragmentFrame.minX >= line.typographicBounds.maxX ? start : nil }
751 guard Wrappers.starting(at: start, in: document.tree)?.kind == .drawer,
752 inContainer.y - fragment.layoutFragmentFrame.minY < line.typographicBounds.maxY else { return nil }
753 return start
754 }
755
756 /// A tap on a fold's `…` opens it, and one on an open drawer's first line folds it, as TAB
757 /// on the line does.
758 @objc fileprivate func tappedFold(_ tap: UITapGestureRecognizer) {
759 if let view = tap.view as? UITextView { focus(view) }
760 guard let start = foldToggle(at: tap.location(in: textView)),
761 let next = Presentation.cycle(at: start, in: document.tree, fold) else { return }
762 setFolds(next)
763 }
764
765 func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
766 guard let view = gestureRecognizer.view as? UITextView else { return false }
767 return foldToggle(at: gestureRecognizer.location(in: view), in: view) != nil
768 }
769
770 func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith other: UIGestureRecognizer) -> Bool {
771 true
772 }
773}
774
775extension MobileEditor: NSTextStorageDelegate {
776 nonisolated func textStorage(
777 _ textStorage: NSTextStorage, didProcessEditing editedMask: NSTextStorage.EditActions, range editedRange: NSRange, changeInLength delta: Int
778 ) {
779 guard editedMask.contains(.editedCharacters) else { return }
780 MainActor.assumeIsolated { storageEdited(range: editedRange, delta: delta) }
781 }
782}
783
784extension MobileEditor: NSTextContentStorageDelegate {
785 /// Folded text isn't enumerated, so it isn't laid out or drawn.
786 nonisolated func textContentManager(
787 _ textContentManager: NSTextContentManager, shouldEnumerate textElement: NSTextElement, options: NSTextContentManager.EnumerationOptions = []
788 ) -> Bool {
789 guard let range = textElement.elementRange else { return true }
790 let documentStart = textContentManager.documentRange.location
791 let start = textContentManager.offset(from: documentStart, to: range.location)
792 let end = textContentManager.offset(from: documentStart, to: range.endLocation)
793 return !hidden.covers(start, end)
794 }
795}
796
797extension MobileEditor: NSTextLayoutManagerDelegate {
798 /// Folded headings, drawers and blocks end with `…`; blocks are on a band; image links
799 /// show their image; pretty entities draw their character.
800 nonisolated func textLayoutManager(
801 _ textLayoutManager: NSTextLayoutManager, textLayoutFragmentFor location: NSTextLocation, in textElement: NSTextElement
802 ) -> NSTextLayoutFragment {
803 let range = textElement.elementRange
804 guard let range, let manager = textLayoutManager.textContentManager else { return NSTextLayoutFragment(textElement: textElement, range: range) }
805 let offset = manager.offset(from: manager.documentRange.location, to: range.location)
806 let folded = hidden.isFolded(offset)
807 let band = shaded.containing(offset) != nil ? fragmentStyle.blockBand : nil
808 let string = (textElement as? NSTextParagraph)?.attributedString
809 let image = string.map(OrgLineFragment.hasImages) ?? false
810 let entities = string.map(OrgLineFragment.hasEntities) ?? false
811 let latex = string.map(OrgLineFragment.hasLatex) ?? false
812 guard folded || band != nil || image || entities || latex else { return NSTextLayoutFragment(textElement: textElement, range: range) }
813 let fragment = OrgLineFragment(textElement: textElement, range: range)
814 fragment.folded = folded
815 fragment.band = band
816 if band != nil {
817 fragment.start = offset
818 fragment.style = fragmentStyle
819 }
820 return fragment
821 }
822}
823#endif