Sources/OrgstarMobile/MobileEditor.swift
532 lines · 25722 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 "app.refile": return onAppCommand != nil && Presentation.heading(containing: context.caret, in: context.tree) != nil
273 case _ where Self.linkCommands.contains(id): return onAppCommand != nil
274 case "org.link.open": return OpenLinkAtPoint().applies(in: context)
275 case "org.table.toggle-column-width", "org.table.shrink", "org.table.expand":
276 return TableShrink.table(at: context.caret, in: context.text) != nil
277 default: return false
278 }
279 }
280
281 // MARK: - Hardware keyboard
282
283 private lazy var dispatcher = KeyDispatcher(keymap: keymap)
284
285 private static let named: [UIKeyboardHIDUsage: String] = [
286 .keyboardTab: "TAB", .keyboardReturnOrEnter: "RET", .keypadEnter: "RET", .keyboardSpacebar: "SPC",
287 .keyboardEscape: "ESC", .keyboardDeleteOrBackspace: "DEL", .keyboardDeleteForward: "<delete>",
288 .keyboardLeftArrow: "<left>", .keyboardRightArrow: "<right>", .keyboardUpArrow: "<up>", .keyboardDownArrow: "<down>",
289 .keyboardHome: "<home>", .keyboardEnd: "<end>", .keyboardPageUp: "<prior>", .keyboardPageDown: "<next>",
290 ]
291
292 /// A key press as a chord; Option is Meta, as `option-as-meta` makes it on the Mac.
293 static func chord(_ key: UIKey) -> KeyChord? {
294 var modifiers: KeyChord.Modifiers = []
295 let flags = key.modifierFlags
296 if flags.contains(.control) { modifiers.insert(.control) }
297 if flags.contains(.alternate) { modifiers.insert(.meta) }
298 if flags.contains(.command) { modifiers.insert(.command) }
299 if let name = named[key.keyCode] {
300 if flags.contains(.shift) { modifiers.insert(.shift) }
301 return KeyChord(name, modifiers)
302 }
303 var characters = key.charactersIgnoringModifiers
304 if flags.contains(.shift), characters.count == 1, characters.lowercased() == characters { characters = characters.uppercased() }
305 guard characters.count == 1 else { return nil }
306 return KeyChord(characters, modifiers)
307 }
308
309 /// The Emacs keymap's commands on an iPad keyboard. Keys it doesn't bind, Command shortcuts
310 /// and editing keys (C-a, C-e, C-k...) are the text system's.
311 func handleKey(_ key: UIKey) -> Bool {
312 guard let chord = Self.chord(key), !chord.modifiers.contains(.command) else { return false }
313 // Option alone types characters unless it begins a binding.
314 if chord.modifiers == [.meta], dispatcher.pending.isEmpty,
315 keymap.candidates(for: [chord]).isEmpty, !keymap.isPrefix([chord]) { return false }
316 switch dispatcher.feed(chord) {
317 case .pending(let keys):
318 onMessage?(KeySequence.format(keys) + "-")
319 return true
320 case .cancelled:
321 onMessage?("Quit")
322 return true
323 case .undefined(let keys):
324 onMessage?("\(KeySequence.format(keys)) is undefined")
325 return true
326 case .unbound:
327 return false
328 case .complete(let keys, let candidates):
329 let context = editContext()
330 let runnable = candidates.first { binding in
331 (binding.when.map { KeyContext.holds($0, in: context) } ?? true) && applies(binding.command, in: context)
332 }
333 // A sequence runs its command even where it doesn't apply, which says why, as on the Mac.
334 guard let binding = runnable ?? (keys.count > 1 ? candidates.first : nil) else { return false }
335 if keys.count == 1, binding.command.hasPrefix("edit."), !["edit.undo", "edit.redo"].contains(binding.command) { return false }
336 run(binding.command)
337 return true
338 }
339 }
340
341 func editContext() -> EditContext {
342 EditContext(revision: document.revision, text: document.text, tree: document.tree, selection: selection, hidden: hidden.all, options: options, knownTags: knownTags)
343 }
344
345 private func openLinkAtCaret() {
346 let caret = textView.selectedRange.location
347 if let link = Links.link(at: caret, text: document.text, tree: document.tree)?.link {
348 onLink?(link)
349 } else if let days = Links.timestampDays(at: caret, text: document.text) {
350 onAgenda?(days.start, days.count)
351 } else {
352 onMessage?("No link here")
353 }
354 }
355
356 // MARK: - Editing
357
358 /// Applies `edits` (against the current text) through the text view as one undo step.
359 func applyEdits(_ edits: [TextEdit]) {
360 let interval = Perf.begin("editor.applyEdits")
361 defer { interval.end() }
362 guard !edits.isEmpty else { return }
363 applyingEdits = true
364 defer { applyingEdits = false }
365 // Straight into the storage: replacing through text input would take the active
366 // keyboard's substitutions (smart dashes) when another view has the keyboard.
367 let storage = textView.textStorage
368 let old = storage.string as NSString
369 // By lines, so a fold between two changes stays.
370 let ascending = edits.flatMap { splitByLines($0, in: storage.string) }.sorted { $0.range.lowerBound < $1.range.lowerBound }
371 var inverse: [TextEdit] = []
372 var delta = 0
373 for edit in ascending {
374 let start = edit.range.lowerBound + delta
375 let length = (edit.replacement as NSString).length
376 inverse.append(TextEdit(range: start..<start + length, replacement: old.substring(with: NSRange(edit.range))))
377 delta += length - edit.range.count
378 }
379 let caret = textView.selectedRange
380 // One at a time, last first: each is processed alone, so folds between them stay.
381 for edit in ascending.reversed() {
382 storage.replaceCharacters(in: NSRange(edit.range), with: edit.replacement)
383 }
384 textView.undoManager?.registerUndo(withTarget: self) { editor in
385 editor.applyEdits(inverse)
386 editor.textView.selectedRange = caret
387 }
388 }
389
390 /// The storage changed (typing, a command, undo): the document takes the same edit, and
391 /// folds and styles follow.
392 fileprivate func storageEdited(range: NSRange, delta: Int) {
393 let interval = Perf.begin("editor.edit")
394 defer { interval.end() }
395 guard !loading else { return }
396 let old = range.location..<(range.location + range.length - delta)
397 let replacement = (textView.textStorage.string as NSString).substring(with: range)
398 let edit = TextEdit(range: old, replacement: replacement)
399 do {
400 try document.apply([edit], baseRevision: document.revision)
401 } catch {
402 // Out of step: the view's text wins.
403 shrunk = ShrunkColumns()
404 load(textView.textStorage.string)
405 return
406 }
407 for table in shrunk.map(through: edit, in: textView.textStorage.string, command: commandEditing) { scheduleRestyle(table) }
408 fold = FoldState(
409 folds: Self.map(fold.folds, old, delta), bodyFolds: Self.map(fold.bodyFolds, old, delta),
410 wrapperFolds: Self.map(fold.wrapperFolds, old, delta)
411 )
412 scheduleRestyle(range.location..<NSMaxRange(range))
413 onChange?()
414 }
415
416 /// Starts after the edit move with it; ones inside it go.
417 static func map(_ starts: Set<Int>, _ old: Range<Int>, _ delta: Int) -> Set<Int> {
418 Set(starts.compactMap { start in
419 if start >= old.upperBound { return start + delta }
420 return start <= old.lowerBound ? start : nil
421 })
422 }
423
424}
425
426extension MobileEditor: UITextViewDelegate {
427 func textViewDidChangeSelection(_ textView: UITextView) {
428 selectionChanged()
429 }
430
431 /// `electric-pair-mode` for typed brackets and quotes, DEL and RET, from either keyboard.
432 func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
433 guard options.electricPair, !applyingEdits, textView.markedTextRange == nil else { return true }
434 let selected = textView.selectedRange
435 let key: String
436 if text.isEmpty, selected.length == 0, range.length == 1, NSMaxRange(range) == selected.location {
437 key = "DEL"
438 } else if range == selected, text == "\n" {
439 key = "RET"
440 } else if range == selected, ElectricPairKey.characters.contains(text) {
441 key = text
442 } else {
443 return true
444 }
445 let command = ElectricPairKey(key: key)
446 guard command.applies(in: editContext()) else { return true }
447 _ = perform(command)
448 return false
449 }
450}
451
452extension MobileEditor: UIGestureRecognizerDelegate {
453 /// The drawer or block a tap at `point` folds or unfolds: a folded one's `…`, the space after
454 /// its first line, or anywhere on an open drawer's first line.
455 private func foldToggle(at point: CGPoint) -> Int? {
456 guard let manager = textView.textLayoutManager, let content = manager.textContentManager else { return nil }
457 let inContainer = CGPoint(x: point.x - textView.textContainerInset.left, y: point.y - textView.textContainerInset.top)
458 guard let fragment = manager.textLayoutFragment(for: inContainer), let range = fragment.textElement?.elementRange else { return nil }
459 let start = content.offset(from: content.documentRange.location, to: range.location)
460 guard let line = fragment.textLineFragments.first(where: { $0.characterRange.length > 0 }) ?? fragment.textLineFragments.first else { return nil }
461 if hidden.isFolded(start) { return inContainer.x - fragment.layoutFragmentFrame.minX >= line.typographicBounds.maxX ? start : nil }
462 guard Wrappers.starting(at: start, in: document.tree)?.kind == .drawer,
463 inContainer.y - fragment.layoutFragmentFrame.minY < line.typographicBounds.maxY else { return nil }
464 return start
465 }
466
467 /// A tap on a fold's `…` opens it, and one on an open drawer's first line folds it, as TAB
468 /// on the line does.
469 @objc fileprivate func tappedFold(_ tap: UITapGestureRecognizer) {
470 guard let start = foldToggle(at: tap.location(in: textView)),
471 let next = Presentation.cycle(at: start, in: document.tree, fold) else { return }
472 setFolds(next)
473 }
474
475 func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
476 foldToggle(at: gestureRecognizer.location(in: textView)) != nil
477 }
478
479 func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith other: UIGestureRecognizer) -> Bool {
480 true
481 }
482}
483
484extension MobileEditor: NSTextStorageDelegate {
485 nonisolated func textStorage(
486 _ textStorage: NSTextStorage, didProcessEditing editedMask: NSTextStorage.EditActions, range editedRange: NSRange, changeInLength delta: Int
487 ) {
488 guard editedMask.contains(.editedCharacters) else { return }
489 MainActor.assumeIsolated { storageEdited(range: editedRange, delta: delta) }
490 }
491}
492
493extension MobileEditor: NSTextContentStorageDelegate {
494 /// Folded text isn't enumerated, so it isn't laid out or drawn.
495 nonisolated func textContentManager(
496 _ textContentManager: NSTextContentManager, shouldEnumerate textElement: NSTextElement, options: NSTextContentManager.EnumerationOptions = []
497 ) -> Bool {
498 guard let range = textElement.elementRange else { return true }
499 let documentStart = textContentManager.documentRange.location
500 let start = textContentManager.offset(from: documentStart, to: range.location)
501 let end = textContentManager.offset(from: documentStart, to: range.endLocation)
502 return !hidden.covers(start, end)
503 }
504}
505
506extension MobileEditor: NSTextLayoutManagerDelegate {
507 /// Folded headings, drawers and blocks end with `…`; blocks are on a band; image lines
508 /// show their image; pretty entities draw their character.
509 nonisolated func textLayoutManager(
510 _ textLayoutManager: NSTextLayoutManager, textLayoutFragmentFor location: NSTextLocation, in textElement: NSTextElement
511 ) -> NSTextLayoutFragment {
512 let range = textElement.elementRange
513 guard let range, let manager = textLayoutManager.textContentManager else { return NSTextLayoutFragment(textElement: textElement, range: range) }
514 let offset = manager.offset(from: manager.documentRange.location, to: range.location)
515 let folded = hidden.isFolded(offset)
516 let band = shaded.containing(offset) != nil ? fragmentStyle.blockBand : nil
517 let string = (textElement as? NSTextParagraph)?.attributedString
518 let image = string.flatMap(OrgLineFragment.image)
519 let entities = string.map(OrgLineFragment.hasEntities) ?? false
520 guard folded || band != nil || image != nil || entities else { return NSTextLayoutFragment(textElement: textElement, range: range) }
521 let fragment = OrgLineFragment(textElement: textElement, range: range)
522 fragment.folded = folded
523 fragment.band = band
524 if band != nil {
525 fragment.start = offset
526 fragment.style = fragmentStyle
527 }
528 fragment.image = image
529 return fragment
530 }
531}
532#endif