Sources/OrgstarMobile/MobileEditor.swift
531 lines · 25592 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 let textView: UITextView
19 var options: EditingOptions = .org {
20 didSet {
21 textView.spellCheckingType = options.spellCheck ? .yes : .no
22 if !showMarkup, options.hideEmphasisMarkers != oldValue.hideEmphasisMarkers || options.prettyEntities != oldValue.prettyEntities {
23 restyleAll()
24 }
25 }
26 }
27 /// Colors and type; a change, or a new Dynamic Type size, restyles the file.
28 var themeSpec: ThemeSpec {
29 get { theme.spec }
30 set {
31 let new = MobileTheme(newValue)
32 guard new.spec != theme.spec || new.font != theme.font else { return }
33 theme = new
34 paragraphStyles = [:]
35 applyThemeToView()
36 restyleAll()
37 }
38 }
39 /// Link brackets and targets, and emphasis markers when `org-hide-emphasis-markers` hides
40 /// them, shown. Hidden markup shows on the caret's line, so it can be edited.
41 var showMarkup = true {
42 didSet { if showMarkup != oldValue { restyleAll() } }
43 }
44 var keymap = KeymapPreset.emacs.keymap
45 var onChange: (() -> Void)?
46 var onMessage: ((String) -> Void)?
47 var onPrompt: ((Prompt, @escaping (String?) -> Void) -> Void)?
48 var onLink: ((OrgLink) -> Void)?
49 /// Edits being applied, which the typing hooks leave alone.
50 private var applyingEdits = false
51 /// Source blocks to write to their files (C-c C-v t).
52 var onTangle: ((Tangle.Scope) -> Void)?
53 /// A source block to run (C-c C-c).
54 var onBabel: ((BabelJob) -> Void)?
55 /// The file's setup files to read again (C-c C-c on a keyword line).
56 var onRefreshSetup: (() -> Void)?
57 /// A block, a table's formulas or a field to edit apart (C-c ', C-c `).
58 var onEditBlock: ((BlockEdit) -> Void)?
59 /// A followed timestamp's agenda days: the first (a `Days` number) and how many.
60 var onAgenda: ((Int, Int) -> Void)?
61 /// Commands the app runs, as `app.clock.in`.
62 var onAppCommand: ((String) -> Void)?
63 /// Tags used across the workspace, for completion.
64 var knownTags: @Sendable () -> [String] = { [] }
65
66 var theme: MobileTheme
67 internal(set) var fold = FoldState()
68 var globalVisibility: GlobalVisibility?
69 let hidden = LockedRanges()
70 /// Blocks drawn on a band.
71 let shaded = LockedRanges()
72 let fragmentStyle = FragmentStyle()
73 var selectionColor: UIColor = .clear
74 /// `org-indent-mode` and `org-hide-leading-stars`, from the settings and `#+STARTUP`.
75 var indented = true
76 var hideStars = false
77 /// One paragraph style per indent pair.
78 var paragraphStyles: [[Int]: NSParagraphStyle] = [:]
79 /// The line last revealed while markup is hidden, to hide again when the caret leaves.
80 var revealedLine: NSRange?
81 /// `org-toggle-inline-images`: lines that are only an image link show the image.
82 internal(set) var showsImages = false
83 /// The view width images were last sized for.
84 var imageWidth: CGFloat = 0
85 /// The file's folder, for relative image paths.
86 let baseDirectory: URL?
87 static let imageCache = NSCache<NSString, UIImage>()
88 var loading = false
89 var restyleScheduled: Range<Int>?
90 /// Narrowed table columns (`org-table-shrink`).
91 var shrunk = ShrunkColumns()
92 /// A command's edits being applied, which keep shrunk columns narrow.
93 private var commandEditing = false
94
95 init(
96 document: DocumentState, editable: Bool, options: EditingOptions = .org, theme spec: ThemeSpec = .default,
97 showMarkup: Bool = true, baseDirectory: URL? = nil
98 ) {
99 self.document = document
100 self.options = options
101 self.showMarkup = showMarkup
102 self.baseDirectory = baseDirectory
103 theme = MobileTheme(spec)
104 let keyed = KeyedTextView(usingTextLayoutManager: true)
105 textView = keyed
106 super.init()
107 keyed.keyHandler = { [weak self] key in self?.handleKey(key) ?? false }
108 keyed.onLayout = { [weak self] in self?.viewResized() }
109 textView.isEditable = editable
110 textView.autocorrectionType = .no
111 textView.autocapitalizationType = .none
112 textView.smartQuotesType = .no
113 textView.smartDashesType = .no
114 textView.smartInsertDeleteType = .no
115 textView.spellCheckingType = options.spellCheck ? .yes : .no
116 textView.keyboardDismissMode = .interactive
117 textView.alwaysBounceVertical = true
118 textView.textContainerInset = UIEdgeInsets(top: 12, left: 8, bottom: 24, right: 8)
119 textView.delegate = self
120 textView.textStorage.delegate = self
121 textView.textLayoutManager?.delegate = self
122 (textView.textLayoutManager?.textContentManager as? NSTextContentStorage)?.delegate = self
123 let foldTap = UITapGestureRecognizer(target: self, action: #selector(tappedFold))
124 foldTap.delegate = self
125 textView.addGestureRecognizer(foldTap)
126 let startup = Presentation.startupDisplay(document.tree, options: options)
127 indented = startup.indented
128 hideStars = startup.hideStars
129 showsImages = startup.inlineImages
130 shrunk = ShrunkColumns.startup(document.tree)
131 applyThemeToView()
132 load(document.text)
133 setFolds(startup.folds)
134 if startup.alignTables { _ = perform(AlignAllTables()) }
135 truncatesLines = startup.truncated
136 textView.selectedRange = NSRange(location: 0, length: 0)
137 }
138
139 // MARK: - DocumentBuffer
140
141 var selection: [Range<Int>] {
142 let selected = textView.selectedRange
143 return [selected.location..<NSMaxRange(selected)]
144 }
145
146 func update<T>(_ change: (inout DocumentState) throws -> T) rethrows -> T {
147 let before = document.text
148 let defaultsBefore = document.defaults
149 let selected = textView.selectedRange
150 let result = try change(&document)
151 if document.text != before {
152 // A save that merged a change from disk, or a revert: the view shows the new text.
153 shrunk = ShrunkColumns()
154 load(document.text)
155 let length = (document.text as NSString).length
156 textView.selectedRange = NSRange(location: min(selected.location, length), length: 0)
157 textView.undoManager?.removeAllActions()
158 setFolds(fold)
159 } else if document.defaults != defaultsBefore {
160 restyle(0..<(document.text as NSString).length)
161 }
162 return result
163 }
164
165 func perform(_ command: any OrgCommand, now: Date = Date(), answers: [String: String] = [:]) -> CommandStep {
166 let context = EditContext(
167 revision: document.revision, text: document.text, tree: document.tree, selection: selection,
168 now: now, answers: answers, hidden: hidden.all, options: options, knownTags: knownTags
169 )
170 let step = command.run(in: context)
171 switch step {
172 case .commit(let result):
173 guard textView.isEditable || result.edits.isEmpty else {
174 onMessage?("This file is read-only.")
175 return .failed("read-only")
176 }
177 commandEditing = true
178 applyEdits(result.edits)
179 commandEditing = false
180 if let selected = result.selection?.first {
181 unfold(around: selected.lowerBound)
182 textView.selectedRange = NSRange(location: selected.lowerBound, length: selected.count)
183 textView.scrollRangeToVisible(textView.selectedRange)
184 }
185 for effect in result.effects {
186 switch effect {
187 case .message(let text): onMessage?(text)
188 case .fold(let start):
189 var state = fold
190 state.folds.insert(start)
191 setFolds(state)
192 case .refreshSetup: onRefreshSetup?()
193 default: break
194 }
195 }
196 case .failed(let message):
197 onMessage?(message)
198 case .prompt(let prompt):
199 onPrompt?(prompt) { [weak self] answer in
200 guard let self else { return }
201 guard let answer else { return self.onMessage?("Quit") ?? () }
202 _ = self.perform(command, now: now, answers: answers.merging([prompt.key: answer]) { $1 })
203 }
204 case .external(.editBlock(let edit)) where onEditBlock != nil:
205 onEditBlock?(edit)
206 case .external(.babel(let job)) where onBabel != nil:
207 onBabel?(job)
208 case .external(.tangle(let scope)) where onTangle != nil:
209 onTangle?(scope)
210 case .external(.agenda(let start, let count)) where onAgenda != nil:
211 onAgenda?(start, count)
212 case .external(let request):
213 onMessage?(Self.unavailable(request, title: command.title))
214 }
215 return step
216 }
217
218 /// Why a request the app doesn't handle did nothing: only table recalculation needs Emacs.
219 static func unavailable(_ request: ExternalRequest, title: String) -> String {
220 if case .emacsTable(_, _, _, let reason, _) = request { return "This table needs Emacs, which runs on the Mac: \(reason)." }
221 return "\(title) isn't available on iPhone and iPad."
222 }
223
224 // MARK: - Commands by name and key
225
226 /// Runs what `keys` (as `C-c C-t`) is bound to in the Emacs keymap, for the caret's context.
227 func run(keys: String) {
228 guard let chords = KeySequence.parse(keys) else { return }
229 let context = editContext()
230 let binding = keymap.candidates(for: chords).first { binding in
231 (binding.when.map { KeyContext.holds($0, in: context) } ?? true) && applies(binding.command, in: context)
232 }
233 guard let binding else { return onMessage?("Nothing to do here") ?? () }
234 run(binding.command)
235 }
236
237 func run(_ id: String) {
238 switch id {
239 case "org.cycle":
240 if !cycleAtCaret() { onMessage?("Not on a heading, drawer or block") }
241 case "org.cycle-global": cycleGlobal()
242 case "org.link.open": openLinkAtCaret()
243 case "org.toggle-inline-images": toggleImages()
244 case "editor.toggle-truncate-lines":
245 truncatesLines.toggle()
246 onMessage?(truncatesLines ? "Truncate long lines enabled" : "Truncate long lines disabled")
247 case "edit.undo": textView.undoManager?.undo()
248 case "edit.redo": textView.undoManager?.redo()
249 case "org.table.toggle-column-width", "org.table.shrink", "org.table.expand": tableColumnWidth(id)
250 case _ where id.hasPrefix("app.") || Self.linkCommands.contains(id):
251 if let onAppCommand { onAppCommand(id) } else { onMessage?("Not available on iOS yet") }
252 default:
253 if let command = Commands.command(id) {
254 _ = perform(command)
255 } else {
256 onMessage?("Not available on iOS yet")
257 }
258 }
259 }
260
261 /// Link commands that need the stored links or the file, which the screen has.
262 static let linkCommands: Set<String> = ["org.link.store", "org.id.store-link", "org.link.insert"]
263
264 func applies(_ id: String, in context: EditContext) -> Bool {
265 if let command = Commands.command(id) { return command.applies(in: context) }
266 switch id {
267 case "org.cycle":
268 return Presentation.heading(containing: context.caret, in: context.tree) != nil || Wrappers.toggleable(at: context.caret, in: context.tree) != nil
269 case "org.cycle-global", "edit.undo", "edit.redo", "org.toggle-inline-images", "editor.toggle-truncate-lines": return true
270 case "app.clock.in", "app.clock.out", "app.clock.cancel", "app.clock.goto", "app.clock.in-recent", "app.clock.in-last",
271 "app.clock.goto-recent", "app.clock.default", "app.clock.resolve", "app.toggle-markup": return onAppCommand != nil
272 case _ where Self.linkCommands.contains(id): return onAppCommand != nil
273 case "org.link.open": return OpenLinkAtPoint().applies(in: context)
274 case "org.table.toggle-column-width", "org.table.shrink", "org.table.expand":
275 return TableShrink.table(at: context.caret, in: context.text) != nil
276 default: return false
277 }
278 }
279
280 // MARK: - Hardware keyboard
281
282 private lazy var dispatcher = KeyDispatcher(keymap: keymap)
283
284 private static let named: [UIKeyboardHIDUsage: String] = [
285 .keyboardTab: "TAB", .keyboardReturnOrEnter: "RET", .keypadEnter: "RET", .keyboardSpacebar: "SPC",
286 .keyboardEscape: "ESC", .keyboardDeleteOrBackspace: "DEL", .keyboardDeleteForward: "<delete>",
287 .keyboardLeftArrow: "<left>", .keyboardRightArrow: "<right>", .keyboardUpArrow: "<up>", .keyboardDownArrow: "<down>",
288 .keyboardHome: "<home>", .keyboardEnd: "<end>", .keyboardPageUp: "<prior>", .keyboardPageDown: "<next>",
289 ]
290
291 /// A key press as a chord; Option is Meta, as `option-as-meta` makes it on the Mac.
292 static func chord(_ key: UIKey) -> KeyChord? {
293 var modifiers: KeyChord.Modifiers = []
294 let flags = key.modifierFlags
295 if flags.contains(.control) { modifiers.insert(.control) }
296 if flags.contains(.alternate) { modifiers.insert(.meta) }
297 if flags.contains(.command) { modifiers.insert(.command) }
298 if let name = named[key.keyCode] {
299 if flags.contains(.shift) { modifiers.insert(.shift) }
300 return KeyChord(name, modifiers)
301 }
302 var characters = key.charactersIgnoringModifiers
303 if flags.contains(.shift), characters.count == 1, characters.lowercased() == characters { characters = characters.uppercased() }
304 guard characters.count == 1 else { return nil }
305 return KeyChord(characters, modifiers)
306 }
307
308 /// The Emacs keymap's commands on an iPad keyboard. Keys it doesn't bind, Command shortcuts
309 /// and editing keys (C-a, C-e, C-k...) are the text system's.
310 func handleKey(_ key: UIKey) -> Bool {
311 guard let chord = Self.chord(key), !chord.modifiers.contains(.command) else { return false }
312 // Option alone types characters unless it begins a binding.
313 if chord.modifiers == [.meta], dispatcher.pending.isEmpty,
314 keymap.candidates(for: [chord]).isEmpty, !keymap.isPrefix([chord]) { return false }
315 switch dispatcher.feed(chord) {
316 case .pending(let keys):
317 onMessage?(KeySequence.format(keys) + "-")
318 return true
319 case .cancelled:
320 onMessage?("Quit")
321 return true
322 case .undefined(let keys):
323 onMessage?("\(KeySequence.format(keys)) is undefined")
324 return true
325 case .unbound:
326 return false
327 case .complete(let keys, let candidates):
328 let context = editContext()
329 let runnable = candidates.first { binding in
330 (binding.when.map { KeyContext.holds($0, in: context) } ?? true) && applies(binding.command, in: context)
331 }
332 // A sequence runs its command even where it doesn't apply, which says why, as on the Mac.
333 guard let binding = runnable ?? (keys.count > 1 ? candidates.first : nil) else { return false }
334 if keys.count == 1, binding.command.hasPrefix("edit."), !["edit.undo", "edit.redo"].contains(binding.command) { return false }
335 run(binding.command)
336 return true
337 }
338 }
339
340 func editContext() -> EditContext {
341 EditContext(revision: document.revision, text: document.text, tree: document.tree, selection: selection, hidden: hidden.all, options: options, knownTags: knownTags)
342 }
343
344 private func openLinkAtCaret() {
345 let caret = textView.selectedRange.location
346 if let link = Links.link(at: caret, text: document.text, tree: document.tree)?.link {
347 onLink?(link)
348 } else if let days = Links.timestampDays(at: caret, text: document.text) {
349 onAgenda?(days.start, days.count)
350 } else {
351 onMessage?("No link here")
352 }
353 }
354
355 // MARK: - Editing
356
357 /// Applies `edits` (against the current text) through the text view as one undo step.
358 func applyEdits(_ edits: [TextEdit]) {
359 let interval = Perf.begin("editor.applyEdits")
360 defer { interval.end() }
361 guard !edits.isEmpty else { return }
362 applyingEdits = true
363 defer { applyingEdits = false }
364 // Straight into the storage: replacing through text input would take the active
365 // keyboard's substitutions (smart dashes) when another view has the keyboard.
366 let storage = textView.textStorage
367 let old = storage.string as NSString
368 // By lines, so a fold between two changes stays.
369 let ascending = edits.flatMap { splitByLines($0, in: storage.string) }.sorted { $0.range.lowerBound < $1.range.lowerBound }
370 var inverse: [TextEdit] = []
371 var delta = 0
372 for edit in ascending {
373 let start = edit.range.lowerBound + delta
374 let length = (edit.replacement as NSString).length
375 inverse.append(TextEdit(range: start..<start + length, replacement: old.substring(with: NSRange(edit.range))))
376 delta += length - edit.range.count
377 }
378 let caret = textView.selectedRange
379 // One at a time, last first: each is processed alone, so folds between them stay.
380 for edit in ascending.reversed() {
381 storage.replaceCharacters(in: NSRange(edit.range), with: edit.replacement)
382 }
383 textView.undoManager?.registerUndo(withTarget: self) { editor in
384 editor.applyEdits(inverse)
385 editor.textView.selectedRange = caret
386 }
387 }
388
389 /// The storage changed (typing, a command, undo): the document takes the same edit, and
390 /// folds and styles follow.
391 fileprivate func storageEdited(range: NSRange, delta: Int) {
392 let interval = Perf.begin("editor.edit")
393 defer { interval.end() }
394 guard !loading else { return }
395 let old = range.location..<(range.location + range.length - delta)
396 let replacement = (textView.textStorage.string as NSString).substring(with: range)
397 let edit = TextEdit(range: old, replacement: replacement)
398 do {
399 try document.apply([edit], baseRevision: document.revision)
400 } catch {
401 // Out of step: the view's text wins.
402 shrunk = ShrunkColumns()
403 load(textView.textStorage.string)
404 return
405 }
406 for table in shrunk.map(through: edit, in: textView.textStorage.string, command: commandEditing) { scheduleRestyle(table) }
407 fold = FoldState(
408 folds: Self.map(fold.folds, old, delta), bodyFolds: Self.map(fold.bodyFolds, old, delta),
409 wrapperFolds: Self.map(fold.wrapperFolds, old, delta)
410 )
411 scheduleRestyle(range.location..<NSMaxRange(range))
412 onChange?()
413 }
414
415 /// Starts after the edit move with it; ones inside it go.
416 static func map(_ starts: Set<Int>, _ old: Range<Int>, _ delta: Int) -> Set<Int> {
417 Set(starts.compactMap { start in
418 if start >= old.upperBound { return start + delta }
419 return start <= old.lowerBound ? start : nil
420 })
421 }
422
423}
424
425extension MobileEditor: UITextViewDelegate {
426 func textViewDidChangeSelection(_ textView: UITextView) {
427 selectionChanged()
428 }
429
430 /// `electric-pair-mode` for typed brackets and quotes, DEL and RET, from either keyboard.
431 func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
432 guard options.electricPair, !applyingEdits, textView.markedTextRange == nil else { return true }
433 let selected = textView.selectedRange
434 let key: String
435 if text.isEmpty, selected.length == 0, range.length == 1, NSMaxRange(range) == selected.location {
436 key = "DEL"
437 } else if range == selected, text == "\n" {
438 key = "RET"
439 } else if range == selected, ElectricPairKey.characters.contains(text) {
440 key = text
441 } else {
442 return true
443 }
444 let command = ElectricPairKey(key: key)
445 guard command.applies(in: editContext()) else { return true }
446 _ = perform(command)
447 return false
448 }
449}
450
451extension MobileEditor: UIGestureRecognizerDelegate {
452 /// The drawer or block a tap at `point` folds or unfolds: a folded one's `…`, the space after
453 /// its first line, or anywhere on an open drawer's first line.
454 private func foldToggle(at point: CGPoint) -> Int? {
455 guard let manager = textView.textLayoutManager, let content = manager.textContentManager else { return nil }
456 let inContainer = CGPoint(x: point.x - textView.textContainerInset.left, y: point.y - textView.textContainerInset.top)
457 guard let fragment = manager.textLayoutFragment(for: inContainer), let range = fragment.textElement?.elementRange else { return nil }
458 let start = content.offset(from: content.documentRange.location, to: range.location)
459 guard let line = fragment.textLineFragments.first(where: { $0.characterRange.length > 0 }) ?? fragment.textLineFragments.first else { return nil }
460 if hidden.isFolded(start) { return inContainer.x - fragment.layoutFragmentFrame.minX >= line.typographicBounds.maxX ? start : nil }
461 guard Wrappers.starting(at: start, in: document.tree)?.kind == .drawer,
462 inContainer.y - fragment.layoutFragmentFrame.minY < line.typographicBounds.maxY else { return nil }
463 return start
464 }
465
466 /// A tap on a fold's `…` opens it, and one on an open drawer's first line folds it, as TAB
467 /// on the line does.
468 @objc fileprivate func tappedFold(_ tap: UITapGestureRecognizer) {
469 guard let start = foldToggle(at: tap.location(in: textView)),
470 let next = Presentation.cycle(at: start, in: document.tree, fold) else { return }
471 setFolds(next)
472 }
473
474 func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
475 foldToggle(at: gestureRecognizer.location(in: textView)) != nil
476 }
477
478 func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith other: UIGestureRecognizer) -> Bool {
479 true
480 }
481}
482
483extension MobileEditor: NSTextStorageDelegate {
484 nonisolated func textStorage(
485 _ textStorage: NSTextStorage, didProcessEditing editedMask: NSTextStorage.EditActions, range editedRange: NSRange, changeInLength delta: Int
486 ) {
487 guard editedMask.contains(.editedCharacters) else { return }
488 MainActor.assumeIsolated { storageEdited(range: editedRange, delta: delta) }
489 }
490}
491
492extension MobileEditor: NSTextContentStorageDelegate {
493 /// Folded text isn't enumerated, so it isn't laid out or drawn.
494 nonisolated func textContentManager(
495 _ textContentManager: NSTextContentManager, shouldEnumerate textElement: NSTextElement, options: NSTextContentManager.EnumerationOptions = []
496 ) -> Bool {
497 guard let range = textElement.elementRange else { return true }
498 let documentStart = textContentManager.documentRange.location
499 let start = textContentManager.offset(from: documentStart, to: range.location)
500 let end = textContentManager.offset(from: documentStart, to: range.endLocation)
501 return !hidden.covers(start, end)
502 }
503}
504
505extension MobileEditor: NSTextLayoutManagerDelegate {
506 /// Folded headings, drawers and blocks end with `…`; blocks are on a band; image lines
507 /// show their image; pretty entities draw their character.
508 nonisolated func textLayoutManager(
509 _ textLayoutManager: NSTextLayoutManager, textLayoutFragmentFor location: NSTextLocation, in textElement: NSTextElement
510 ) -> NSTextLayoutFragment {
511 let range = textElement.elementRange
512 guard let range, let manager = textLayoutManager.textContentManager else { return NSTextLayoutFragment(textElement: textElement, range: range) }
513 let offset = manager.offset(from: manager.documentRange.location, to: range.location)
514 let folded = hidden.isFolded(offset)
515 let band = shaded.containing(offset) != nil ? fragmentStyle.blockBand : nil
516 let string = (textElement as? NSTextParagraph)?.attributedString
517 let image = string.flatMap(OrgLineFragment.image)
518 let entities = string.map(OrgLineFragment.hasEntities) ?? false
519 guard folded || band != nil || image != nil || entities else { return NSTextLayoutFragment(textElement: textElement, range: range) }
520 let fragment = OrgLineFragment(textElement: textElement, range: range)
521 fragment.folded = folded
522 fragment.band = band
523 if band != nil {
524 fragment.start = offset
525 fragment.style = fragmentStyle
526 }
527 fragment.image = image
528 return fragment
529 }
530}
531#endif