Repository Public
1// ORIX Docs2// File: Packages/ORIXDocsKit/Sources/DocModel/Editor.swift3// Description: The editing engine: a document plus a selection, and every text operation on them (typing, deleting, splitting and joining4// paragraphs, formatting, lists, inline objects, fragments for copy and paste). Change tracking is applied here.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation910public extension String {11 private static let wordCharacters: CharacterSet = {12 var s = CharacterSet.alphanumerics13 s.insert(charactersIn: "'’_")14 return s15 }()1617 private func isWordUnit(_ ns: NSString, _ i: Int) -> Bool {18 guard let scalar = UnicodeScalar(ns.character(at: i)) else { return true } // surrogate halves belong to words (emoji, CJK ext.)19 return String.wordCharacters.contains(scalar)20 }2122 /// Offset of the start of the word before `offset` (Option-Left).23 func wordBoundary(before offset: Int) -> Int {24 let ns = self as NSString25 var i = Swift.max(0, Swift.min(ns.length, offset))26 while i > 0, !isWordUnit(ns, i - 1) { i -= 1 }27 while i > 0, isWordUnit(ns, i - 1) { i -= 1 }28 return composedBoundary(atOrBefore: i)29 }3031 /// Offset of the end of the word after `offset` (Option-Right).32 func wordBoundary(after offset: Int) -> Int {33 let ns = self as NSString34 var i = Swift.max(0, Swift.min(ns.length, offset))35 while i < ns.length, !isWordUnit(ns, i) { i += 1 }36 while i < ns.length, isWordUnit(ns, i) { i += 1 }37 return i >= ns.length ? ns.length : composedBoundary(atOrBefore: i)38 }3940 /// The word surrounding `offset` (double-click selection).41 func wordRange(at offset: Int) -> Range<Int> {42 let ns = self as NSString43 guard ns.length > 0 else { return 0..<0 }44 let i = Swift.max(0, Swift.min(ns.length - 1, offset))45 let word = isWordUnit(ns, i)46 var lo = i, hi = i + 147 while lo > 0, isWordUnit(ns, lo - 1) == word, ns.character(at: lo - 1) != 0xFFFC { lo -= 1 }48 while hi < ns.length, isWordUnit(ns, hi) == word, ns.character(at: hi) != 0xFFFC { hi += 1 }49 return composedBoundary(atOrBefore: lo)..<hi50 }51}5253/// A piece of document carried by copy and paste: blocks plus the notes, assets and list definitions they reference.54public struct DocumentFragment: Codable, Hashable, Sendable {55 public var blocks: [Block]56 public var notes: [String: Note]57 public var lists: [ListDefinition]58 public var assetData: [String: Data]59 public var assetTypes: [String: String]60 public init(blocks: [Block], notes: [String: Note] = [:], lists: [ListDefinition] = [], assets: [String: Asset] = [:]) {61 self.blocks = blocks; self.notes = notes; self.lists = lists62 self.assetData = assets.mapValues(\.data); self.assetTypes = assets.mapValues(\.mimeType)63 }64 public var plainText: String {65 var lines: [String] = []66 DocumentModel.forEachParagraph(in: blocks) { p, _ in lines.append(p.visibleText) }67 return lines.joined(separator: "\n")68 }69 /// True when the fragment is a single paragraph (pasted inline).70 public var isInline: Bool { blocks.count == 1 && blocks[0].paragraph != nil }71}7273/// What a selection designates once resolved against the blocks.74public enum SelectionTarget: Hashable, Sendable {75 case caret(Position)76 /// A text range whose two ends live in the same container (the story itself, or one table cell).77 case range(Position, Position)78 /// A rectangle of table cells: rows and grid columns.79 case cells(block: Int, rows: ClosedRange<Int>, columns: ClosedRange<Int>)80}8182public struct DocumentEditor: Sendable {83 public var doc: DocumentModel84 public var selection: Selection85 /// Reviewer name recorded on tracked changes and comments (entered locally by the user).86 public var author: String87 /// Formatting chosen at the caret before typing (e.g. ⌘B with no selection). Cleared when the caret moves.88 public var typingOverride: CharProps?89 /// Clock used for revisions; injectable for tests.90 public var now: @Sendable () -> Date = { Date() }9192 public init(doc: DocumentModel, selection: Selection = .documentStart, author: String = "Author") {93 self.doc = doc; self.selection = selection; self.author = author94 sanitizeSelection()95 }9697 public var tracking: Bool { doc.settings.trackChanges }9899 public var blocks: [Block] {100 get { doc.blocks(in: selection.story) }101 set { doc.setBlocks(newValue, in: selection.story) }102 }103104 // MARK: - Containers (the story, or one table cell)105106 static func container(_ blocks: [Block], _ path: ParaPath) -> [Block] {107 guard let c = path.cell, let t = blocks[path.block].table else { return blocks }108 return t.rows[c.row].cells[c.cell].paragraphs.map { .paragraph($0) }109 }110111 static func setContainer(_ container: [Block], in blocks: inout [Block], _ path: ParaPath) {112 guard let c = path.cell, var t = blocks[path.block].table else { blocks = container.isEmpty ? [.paragraph(Paragraph())] : container; return }113 var paras: [Paragraph] = []114 for b in container {115 switch b {116 case .paragraph(let p): paras.append(p)117 case .table(let tt): for r in tt.rows { for cell in r.cells { paras.append(contentsOf: cell.paragraphs) } } // no nested tables118 default: break119 }120 }121 if paras.isEmpty { paras = [Paragraph(style: StyleID.tableText)] }122 t.rows[c.row].cells[c.cell].paragraphs = paras123 blocks[path.block] = .table(t)124 }125126 static func local(_ path: ParaPath) -> Int { path.cell?.paragraph ?? path.block }127128 static func path(like path: ParaPath, local: Int) -> ParaPath {129 if var c = path.cell { c.paragraph = local; return ParaPath(block: path.block, cell: c) }130 return ParaPath(block: local)131 }132133 // MARK: - Caret stops134135 public static func firstPosition(inBlock i: Int, _ blocks: [Block]) -> Position {136 if case .table = blocks[i] { return Position(path: ParaPath(block: i, cell: CellPath(row: 0, cell: 0, paragraph: 0)), offset: 0) }137 return Position(block: i, offset: 0)138 }139140 public static func lastPosition(inBlock i: Int, _ blocks: [Block]) -> Position {141 switch blocks[i] {142 case .paragraph(let p): return Position(block: i, offset: p.length)143 case .table(let t):144 let r = t.rows.count - 1, c = t.rows[r].cells.count - 1, p = t.rows[r].cells[c].paragraphs.count - 1145 return Position(path: ParaPath(block: i, cell: CellPath(row: r, cell: c, paragraph: p)), offset: t.rows[r].cells[c].paragraphs[p].length)146 default: return Position(block: i, offset: 0)147 }148 }149150 public static func documentEnd(_ blocks: [Block]) -> Position { lastPosition(inBlock: blocks.count - 1, blocks) }151152 /// The next caret stop after `p` (one composed character forward), or nil at the end of the story.153 public static func position(after p: Position, in blocks: [Block]) -> Position? {154 if let para = blocks.paragraph(at: p.path), p.offset < para.length {155 return Position(path: p.path, offset: para.plainText.composedBoundary(after: p.offset))156 }157 if let c = p.path.cell, let t = blocks[p.path.block].table {158 if c.paragraph + 1 < t.rows[c.row].cells[c.cell].paragraphs.count {159 return Position(path: ParaPath(block: p.path.block, cell: CellPath(row: c.row, cell: c.cell, paragraph: c.paragraph + 1)), offset: 0)160 }161 if c.cell + 1 < t.rows[c.row].cells.count { return Position(path: ParaPath(block: p.path.block, cell: CellPath(row: c.row, cell: c.cell + 1)), offset: 0) }162 if c.row + 1 < t.rows.count { return Position(path: ParaPath(block: p.path.block, cell: CellPath(row: c.row + 1, cell: 0)), offset: 0) }163 }164 return p.path.block + 1 < blocks.count ? firstPosition(inBlock: p.path.block + 1, blocks) : nil165 }166167 /// The previous caret stop before `p`, or nil at the start of the story.168 public static func position(before p: Position, in blocks: [Block]) -> Position? {169 if let para = blocks.paragraph(at: p.path), p.offset > 0 {170 return Position(path: p.path, offset: para.plainText.composedBoundary(before: p.offset))171 }172 if let c = p.path.cell, let t = blocks[p.path.block].table {173 func end(_ r: Int, _ ci: Int, _ pi: Int) -> Position {174 Position(path: ParaPath(block: p.path.block, cell: CellPath(row: r, cell: ci, paragraph: pi)), offset: t.rows[r].cells[ci].paragraphs[pi].length)175 }176 if c.paragraph > 0 { return end(c.row, c.cell, c.paragraph - 1) }177 if c.cell > 0 { return end(c.row, c.cell - 1, t.rows[c.row].cells[c.cell - 1].paragraphs.count - 1) }178 if c.row > 0 { let ci = t.rows[c.row - 1].cells.count - 1; return end(c.row - 1, ci, t.rows[c.row - 1].cells[ci].paragraphs.count - 1) }179 }180 return p.path.block > 0 ? lastPosition(inBlock: p.path.block - 1, blocks) : nil181 }182183 /// Clamps a position onto a valid caret stop.184 public static func clamp(_ p: Position, in blocks: [Block], preferEnd: Bool = false) -> Position {185 let bi = max(0, min(blocks.count - 1, p.path.block))186 switch blocks[bi] {187 case .paragraph(let para):188 guard bi == p.path.block, p.path.cell == nil else { return preferEnd ? lastPosition(inBlock: bi, blocks) : firstPosition(inBlock: bi, blocks) }189 return Position(block: bi, offset: para.plainText.composedBoundary(atOrBefore: max(0, min(para.length, p.offset))))190 case .table(let t):191 guard bi == p.path.block, var c = p.path.cell else {192 return (p.offset >= 1 || preferEnd) && bi == p.path.block ? lastPosition(inBlock: bi, blocks) : firstPosition(inBlock: bi, blocks)193 }194 c.row = max(0, min(t.rows.count - 1, c.row))195 c.cell = max(0, min(t.rows[c.row].cells.count - 1, c.cell))196 let paras = t.rows[c.row].cells[c.cell].paragraphs197 c.paragraph = max(0, min(paras.count - 1, c.paragraph))198 let para = paras[c.paragraph]199 return Position(path: ParaPath(block: bi, cell: c), offset: para.plainText.composedBoundary(atOrBefore: max(0, min(para.length, p.offset))))200 default:201 return Position(block: bi, offset: 0)202 }203 }204205 public mutating func sanitizeSelection() {206 let b = blocks207 if b.isEmpty { selection = Selection(story: .body, caret: Position(block: 0, offset: 0)); return }208 let forward = selection.anchor <= selection.head209 if selection.isCaret {210 let p = DocumentEditor.clamp(selection.head, in: b)211 selection.anchor = p; selection.head = p212 } else {213 selection.anchor = DocumentEditor.clamp(selection.anchor, in: b, preferEnd: !forward)214 selection.head = DocumentEditor.clamp(selection.head, in: b, preferEnd: forward)215 }216 }217218 // MARK: - Selection resolution219220 public static func gridStart(_ row: TableRow, cell: Int) -> Int { row.cells[..<min(cell, row.cells.count)].reduce(0) { $0 + $1.colSpan } }221222 /// Indexes of the cells of `row` that intersect the grid column range.223 public static func cells(in row: TableRow, columns: ClosedRange<Int>) -> [Int] {224 var out: [Int] = []225 var g = 0226 for (i, c) in row.cells.enumerated() {227 if g <= columns.upperBound && g + c.colSpan - 1 >= columns.lowerBound { out.append(i) }228 g += c.colSpan229 }230 return out231 }232233 public var target: SelectionTarget { DocumentEditor.resolve(selection, blocks) }234235 public static func resolve(_ sel: Selection, _ blocks: [Block]) -> SelectionTarget {236 if sel.isCaret { return .caret(sel.head) }237 var s = sel.start, e = sel.end238 if let sc = s.path.cell, let ec = e.path.cell, s.path.block == e.path.block, let t = blocks[s.path.block].table {239 if sc.row == ec.row && sc.cell == ec.cell { return .range(s, e) }240 let g1 = gridStart(t.rows[sc.row], cell: sc.cell), g2 = gridStart(t.rows[ec.row], cell: ec.cell)241 let w1 = t.rows[sc.row].cells[sc.cell].colSpan, w2 = t.rows[ec.row].cells[ec.cell].colSpan242 return .cells(block: s.path.block, rows: min(sc.row, ec.row)...max(sc.row, ec.row), columns: min(g1, g2)...max(g1 + w1 - 1, g2 + w2 - 1))243 }244 // One end inside a table and the other outside: the whole table is selected.245 if s.path.cell != nil { s = Position(block: s.path.block, offset: 0) }246 if e.path.cell != nil { e = Position(block: e.path.block, offset: 1) }247 return .range(s, e)248 }249250 /// Paths of every paragraph touched by the selection, with the UTF-16 range selected in each (the whole paragraph for a caret).251 public func selectedParagraphs() -> [(path: ParaPath, range: Range<Int>)] {252 let b = blocks253 switch target {254 case .caret(let p):255 guard let para = b.paragraph(at: p.path) else { return [] }256 return [(p.path, 0..<para.length)]257 case .cells(let bi, let rows, let cols):258 guard let t = b[bi].table else { return [] }259 var out: [(ParaPath, Range<Int>)] = []260 for r in rows {261 for ci in DocumentEditor.cells(in: t.rows[r], columns: cols) {262 for (pi, p) in t.rows[r].cells[ci].paragraphs.enumerated() { out.append((ParaPath(block: bi, cell: CellPath(row: r, cell: ci, paragraph: pi)), 0..<p.length)) }263 }264 }265 return out266 case .range(let s, let e):267 var out: [(ParaPath, Range<Int>)] = []268 if let c = s.path.cell {269 for pi in c.paragraph...(e.path.cell?.paragraph ?? c.paragraph) {270 let path = ParaPath(block: s.path.block, cell: CellPath(row: c.row, cell: c.cell, paragraph: pi))271 guard let p = b.paragraph(at: path) else { continue }272 out.append((path, (pi == c.paragraph ? s.offset : 0)..<(pi == e.path.cell?.paragraph ? e.offset : p.length)))273 }274 return out275 }276 for bi in s.path.block...e.path.block {277 switch b[bi] {278 case .paragraph(let p):279 out.append((ParaPath(block: bi), (bi == s.path.block ? min(s.offset, p.length) : 0)..<(bi == e.path.block ? min(e.offset, p.length) : p.length)))280 case .table(let t):281 if (bi == s.path.block && s.offset >= 1) || (bi == e.path.block && e.offset == 0) { continue }282 for (r, row) in t.rows.enumerated() { for (ci, cell) in row.cells.enumerated() { for (pi, p) in cell.paragraphs.enumerated() {283 out.append((ParaPath(block: bi, cell: CellPath(row: r, cell: ci, paragraph: pi)), 0..<p.length))284 } } }285 default: break286 }287 }288 return out289 }290 }291292 public var selectedText: String { copyFragment()?.plainText ?? "" }293294 // MARK: - Typing295296 /// Inserts text at the caret, replacing the selection. Newlines create paragraphs.297 public mutating func insertText(_ text: String) {298 if !selection.isCaret { deleteSelection(caretAtEnd: true) }299 let normalized = text.replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n").replacingOccurrences(of: "\u{2029}", with: "\n")300 let parts = normalized.components(separatedBy: "\n")301 for (i, part) in parts.enumerated() {302 if i > 0 { insertParagraphBreak() }303 if !part.isEmpty { insertRuns([Run(part)], inheritAttributes: true) }304 }305 }306307 /// Makes sure the caret sits in a paragraph (a caret on an atomic block gets a new empty paragraph before the block).308 mutating func ensureCaretInParagraph() {309 var b = blocks310 let p = selection.head311 if b.paragraph(at: p.path) != nil { return }312 b.insert(.paragraph(Paragraph()), at: max(0, min(b.count, p.path.block)))313 blocks = b314 selection = Selection(story: selection.story, caret: Position(block: max(0, min(b.count - 1, p.path.block)), offset: 0))315 }316317 func insertionRevision(in p: Paragraph, at offset: Int) -> Revision {318 var pos = 0319 for r in p.runs {320 let end = pos + r.length321 if (end == offset || pos == offset), let rev = r.revision, rev.kind == .insertion, rev.author == author { return rev }322 pos = end323 }324 return Revision(kind: .insertion, author: author, date: now())325 }326327 /// Inserts runs at the caret. With `inheritAttributes` plain runs take the formatting in effect at the caret.328 public mutating func insertRuns(_ runs: [Run], inheritAttributes: Bool = false) {329 if !selection.isCaret { deleteSelection(caretAtEnd: true) }330 ensureCaretInParagraph()331 var b = blocks332 let pos = selection.head333 guard var p = b.paragraph(at: pos.path) else { return }334 let ta = p.typingAttributes(at: pos.offset)335 let rev: Revision? = tracking ? insertionRevision(in: p, at: pos.offset) : nil336 var total = 0337 let prepared: [Run] = runs.map { r in338 var r = r339 if inheritAttributes {340 r.props = typingOverride ?? ta.props341 r.charStyle = ta.charStyle342 if r.inline == nil { r.comments = ta.comments }343 }344 r.revision = rev345 r.formatRevision = nil346 total += r.length347 return r348 }349 p.insert(prepared, at: pos.offset)350 b.setParagraph(p, at: pos.path)351 blocks = b352 selection = Selection(story: selection.story, caret: Position(path: pos.path, offset: pos.offset + total))353 }354355 public mutating func insertInline(_ inline: Inline) {356 insertRuns([Run(inline: inline)], inheritAttributes: true)357 }358359 /// Return: splits the paragraph at the caret.360 public mutating func insertParagraphBreak() {361 if !selection.isCaret { deleteSelection(caretAtEnd: true) }362 ensureCaretInParagraph()363 var b = blocks364 let pos = selection.head365 guard let p = b.paragraph(at: pos.path) else { return }366 // Return on an empty list item leaves the list.367 if p.isEmpty, p.list != nil {368 var q = p369 if let l = q.list, l.level > 0 { q.list = ListItem(listID: l.listID, level: l.level - 1) } else { q.list = nil }370 b.setParagraph(q, at: pos.path)371 blocks = b372 return373 }374 let next = pos.offset >= p.length ? doc.styles.style(p.style)?.next : nil375 var (first, second) = p.split(at: pos.offset, nextStyle: next)376 if tracking { first.markRevision = Revision(kind: .insertion, author: author, date: now()) }377 // Splitting at the very start keeps the content (and its id, which cross-references target) in the second paragraph.378 if pos.offset == 0, !p.isEmpty { swap(&first.id, &second.id) }379 var cont = DocumentEditor.container(b, pos.path)380 let li = DocumentEditor.local(pos.path)381 cont[li] = .paragraph(first)382 cont.insert(.paragraph(second), at: li + 1)383 DocumentEditor.setContainer(cont, in: &b, pos.path)384 blocks = b385 selection = Selection(story: selection.story, caret: Position(path: DocumentEditor.path(like: pos.path, local: li + 1), offset: 0))386 }387388 /// Shift-Return: a line break inside the paragraph.389 public mutating func insertLineBreak() { insertRuns([Run(lineSeparatorCharacter)], inheritAttributes: true) }390391 // MARK: - Deleting392393 /// Marks `range` of `p` as deleted for the tracking author. Text the author had inserted (still pending) disappears for good.394 /// Returns the number of UTF-16 units that remain in the paragraph for the range.395 static func trackDelete(_ p: inout Paragraph, _ range: Range<Int>, author: String, date: Date) -> Int {396 let lo = max(0, min(p.length, range.lowerBound)), hi = max(lo, min(p.length, range.upperBound))397 guard hi > lo else { return 0 }398 let a = p.splitRun(at: lo)399 let b = p.splitRun(at: hi)400 var revision = Revision(kind: .deletion, author: author, date: date)401 if a > 0, let r = p.runs[a - 1].revision, r.kind == .deletion, r.author == author { revision = r }402 else if b < p.runs.count, let r = p.runs[b].revision, r.kind == .deletion, r.author == author { revision = r }403 var kept = 0404 var out: [Run] = []405 for i in a..<b {406 var r = p.runs[i]407 if let rev = r.revision, rev.kind == .insertion, rev.author == author { continue }408 if !r.isDeleted { r.revision = revision }409 kept += r.length410 out.append(r)411 }412 p.runs.replaceSubrange(a..<b, with: out)413 p.normalize()414 return kept415 }416417 /// Deletes from `lo` to `hi` (index, offset) inside one container. Returns the caret positions at the start and at the end of what remains.418 static func deleteRange(_ c: inout [Block], _ lo: (Int, Int), _ hi: (Int, Int), track: Bool, author: String, date: Date) -> (lo: (Int, Int), hi: (Int, Int)) {419 func ensureNonEmpty() { if c.isEmpty { c = [.paragraph(Paragraph())] } }420 if lo.0 == hi.0 {421 switch c[lo.0] {422 case .paragraph(var p):423 if track {424 let kept = trackDelete(&p, lo.1..<hi.1, author: author, date: date)425 c[lo.0] = .paragraph(p)426 return (lo, (lo.0, lo.1 + kept))427 }428 p.delete(lo.1..<hi.1)429 c[lo.0] = .paragraph(p)430 return (lo, lo)431 default:432 if lo.1 == 0 && hi.1 >= 1 {433 c.remove(at: lo.0)434 ensureNonEmpty()435 let i = min(lo.0, c.count - 1)436 let pos = lo.0 < c.count ? (i, 0) : (i, c[i].paragraph?.length ?? 0)437 return (pos, pos)438 }439 return (lo, hi)440 }441 }442 if track {443 var removed: [Int] = []444 var ownBreaks = Set<Int>() // paragraphs whose break this author had inserted: the break simply disappears445 var endPos = hi446 for i in lo.0...hi.0 {447 switch c[i] {448 case .paragraph(var p):449 let from = i == lo.0 ? lo.1 : 0, to = i == hi.0 ? hi.1 : p.length450 let kept = trackDelete(&p, from..<to, author: author, date: date)451 if i < hi.0 {452 if let m = p.markRevision, m.kind == .insertion, m.author == author { ownBreaks.insert(i) }453 else { p.markRevision = Revision(kind: .deletion, author: author, date: date) }454 } else {455 endPos = (i, from + kept)456 }457 c[i] = .paragraph(p)458 default:459 let wholly = (i > lo.0 || lo.1 == 0) && (i < hi.0 || hi.1 >= 1)460 if wholly { removed.append(i) }461 }462 }463 for i in stride(from: hi.0, through: lo.0, by: -1) {464 if removed.contains(i) {465 c.remove(at: i)466 if i < endPos.0 { endPos.0 -= 1 } else if i == endPos.0 { endPos = (i, 0) }467 } else if ownBreaks.contains(i), i + 1 < c.count, case .paragraph(var p) = c[i], case .paragraph(let next) = c[i + 1] {468 let joinAt = p.length469 p.runs.append(contentsOf: next.runs)470 p.markRevision = next.markRevision471 p.normalize()472 c[i] = .paragraph(p)473 c.remove(at: i + 1)474 if endPos.0 == i + 1 { endPos = (i, endPos.1 + joinAt) } else if endPos.0 > i + 1 { endPos.0 -= 1 }475 }476 }477 ensureNonEmpty()478 let start = (min(lo.0, c.count - 1), lo.1)479 return (start, (min(endPos.0, c.count - 1), endPos.1))480 }481 var head: Block?482 var tail: Block?483 var caret = (lo.0, 0)484 switch c[lo.0] {485 case .paragraph(var p): p.delete(lo.1..<p.length); head = .paragraph(p); caret = (lo.0, lo.1)486 default: if lo.1 >= 1 { head = c[lo.0]; caret = (lo.0 + 1, 0) }487 }488 switch c[hi.0] {489 case .paragraph(var p): p.delete(0..<hi.1); tail = .paragraph(p)490 default: if hi.1 == 0 { tail = c[hi.0] }491 }492 var middle: [Block] = []493 if case .paragraph(var hp)? = head, case .paragraph(let tp)? = tail {494 if hp.isEmpty && !tp.isEmpty && lo.1 == 0 {495 // An emptied paragraph adopts the formatting of the text that follows.496 var merged = tp497 merged.id = hp.id498 middle = [.paragraph(merged)]499 } else {500 hp.append(contentsOf: tp)501 middle = [.paragraph(hp)]502 }503 } else {504 if let h = head { middle.append(h) }505 if let t = tail { middle.append(t) }506 }507 c.replaceSubrange(lo.0...hi.0, with: middle)508 ensureNonEmpty()509 caret.0 = min(caret.0, c.count - 1)510 if c[caret.0].paragraph == nil { caret.1 = 0 }511 return (caret, caret)512 }513514 /// Deletes the selection. Under change tracking the text is marked instead; `caretAtEnd` then leaves the caret after it.515 public mutating func deleteSelection(caretAtEnd: Bool = false) {516 var b = blocks517 switch target {518 case .caret: return519 case .cells(let bi, let rows, let cols):520 guard var t = b[bi].table else { return }521 var first: CellPath?522 for r in rows {523 for ci in DocumentEditor.cells(in: t.rows[r], columns: cols) {524 let style = t.rows[r].cells[ci].paragraphs.first?.style ?? StyleID.tableText525 t.rows[r].cells[ci].paragraphs = [Paragraph(style: style)]526 t.rows[r].cells[ci].formula = nil527 if first == nil { first = CellPath(row: r, cell: ci) }528 }529 }530 b[bi] = .table(t)531 blocks = b532 selection = Selection(story: selection.story, caret: Position(path: ParaPath(block: bi, cell: first), offset: 0))533 case .range(let s, let e):534 var cont = DocumentEditor.container(b, s.path)535 let r = DocumentEditor.deleteRange(&cont, (DocumentEditor.local(s.path), s.offset), (DocumentEditor.local(e.path), e.offset), track: tracking, author: author, date: now())536 DocumentEditor.setContainer(cont, in: &b, s.path)537 blocks = b538 let pick = caretAtEnd ? r.hi : r.lo539 selection = Selection(story: selection.story, caret: Position(path: DocumentEditor.path(like: s.path, local: pick.0), offset: pick.1))540 }541 sanitizeSelection()542 pruneOrphans()543 }544545 public enum DeleteUnit: Sendable { case character, word }546547 public mutating func deleteBackward(_ unit: DeleteUnit = .character) {548 guard selection.isCaret else { deleteSelection(); return }549 var b = blocks550 let pos = selection.head551 guard var p = b.paragraph(at: pos.path) else {552 // Caret on an atomic block: Backspace acts on what precedes it.553 if let prev = DocumentEditor.position(before: pos, in: b) { selection = Selection(story: selection.story, caret: prev) }554 return555 }556 if pos.offset > 0 {557 let text = p.plainText558 let from = unit == .word ? text.wordBoundary(before: pos.offset) : text.composedBoundary(before: pos.offset)559 if tracking { _ = DocumentEditor.trackDelete(&p, from..<pos.offset, author: author, date: now()) } else { p.delete(from..<pos.offset) }560 b.setParagraph(p, at: pos.path)561 blocks = b562 selection = Selection(story: selection.story, caret: Position(path: pos.path, offset: from))563 pruneOrphans()564 return565 }566 if p.list != nil {567 p.list = nil568 b.setParagraph(p, at: pos.path)569 blocks = b570 return571 }572 var cont = DocumentEditor.container(b, pos.path)573 let li = DocumentEditor.local(pos.path)574 guard li > 0 else { return }575 switch cont[li - 1] {576 case .paragraph(var q):577 let joinOffset = q.length578 if tracking && !(q.markRevision?.kind == .insertion && q.markRevision?.author == author) {579 q.markRevision = Revision(kind: .deletion, author: author, date: now())580 cont[li - 1] = .paragraph(q)581 } else if q.isEmpty && !p.isEmpty {582 cont.remove(at: li - 1)583 } else {584 q.append(contentsOf: p)585 cont[li - 1] = .paragraph(q)586 cont.remove(at: li)587 }588 DocumentEditor.setContainer(cont, in: &b, pos.path)589 blocks = b590 selection = Selection(story: selection.story, caret: Position(path: DocumentEditor.path(like: pos.path, local: li - 1), offset: joinOffset))591 case .table:592 selection = Selection(story: selection.story, caret: DocumentEditor.lastPosition(inBlock: li - 1, b))593 default:594 cont.remove(at: li - 1)595 DocumentEditor.setContainer(cont, in: &b, pos.path)596 blocks = b597 selection = Selection(story: selection.story, caret: Position(path: DocumentEditor.path(like: pos.path, local: li - 1), offset: 0))598 }599 pruneOrphans()600 }601602 public mutating func deleteForward(_ unit: DeleteUnit = .character) {603 guard selection.isCaret else { deleteSelection(); return }604 var b = blocks605 let pos = selection.head606 guard var p = b.paragraph(at: pos.path) else {607 // Caret on an atomic block: Delete removes it.608 if b[pos.path.block].isAtomic {609 b.remove(at: pos.path.block)610 if b.isEmpty { b = [.paragraph(Paragraph())] }611 blocks = b612 sanitizeSelection()613 }614 return615 }616 if pos.offset < p.length {617 let text = p.plainText618 let to = unit == .word ? text.wordBoundary(after: pos.offset) : text.composedBoundary(after: pos.offset)619 var caret = pos.offset620 if tracking { caret += DocumentEditor.trackDelete(&p, pos.offset..<to, author: author, date: now()) } else { p.delete(pos.offset..<to) }621 b.setParagraph(p, at: pos.path)622 blocks = b623 selection = Selection(story: selection.story, caret: Position(path: pos.path, offset: caret))624 pruneOrphans()625 return626 }627 var cont = DocumentEditor.container(b, pos.path)628 let li = DocumentEditor.local(pos.path)629 guard li + 1 < cont.count else { return }630 switch cont[li + 1] {631 case .paragraph(let q):632 if tracking && !(p.markRevision?.kind == .insertion && p.markRevision?.author == author) {633 p.markRevision = Revision(kind: .deletion, author: author, date: now())634 cont[li] = .paragraph(p)635 DocumentEditor.setContainer(cont, in: &b, pos.path)636 blocks = b637 selection = Selection(story: selection.story, caret: Position(path: DocumentEditor.path(like: pos.path, local: li + 1), offset: 0))638 return639 }640 if p.isEmpty && !q.isEmpty {641 cont.remove(at: li)642 } else {643 p.append(contentsOf: q)644 cont[li] = .paragraph(p)645 cont.remove(at: li + 1)646 }647 case .table: return648 default: cont.remove(at: li + 1)649 }650 DocumentEditor.setContainer(cont, in: &b, pos.path)651 blocks = b652 pruneOrphans()653 }654655 /// Removes notes whose reference is gone and comments that no longer have an anchor.656 public mutating func pruneOrphans() {657 guard !doc.notes.isEmpty || !doc.comments.isEmpty else { return }658 var noteIDs = Set<String>(), commentIDs = Set<String>()659 doc.forEachParagraphEverywhere { p, _, _ in660 for r in p.runs {661 if case .note(let ref)? = r.inline { noteIDs.insert(ref.id) }662 for c in r.comments { commentIDs.insert(c) }663 }664 }665 if case .note(let current) = selection.story, !noteIDs.contains(current) {666 selection = .documentStart667 }668 if doc.notes.count != noteIDs.count { doc.notes = doc.notes.filter { noteIDs.contains($0.key) } }669 if doc.comments.contains(where: { !commentIDs.contains($0.id) }) { doc.comments.removeAll { !commentIDs.contains($0.id) } }670 }671672 // MARK: - Character formatting673674 /// Applies a change to every run of the selection. With a caret, the change becomes the typing formatting.675 public mutating func formatCharacters(_ change: (inout CharProps) -> Void) {676 if selection.isCaret {677 guard let p = blocks.paragraph(at: selection.head.path) else { return }678 var props = typingOverride ?? p.typingAttributes(at: selection.head.offset).props679 change(&props)680 typingOverride = props681 return682 }683 var b = blocks684 let stamp = now()685 for (path, range) in selectedParagraphs() where !range.isEmpty {686 guard var p = b.paragraph(at: path) else { continue }687 p.transform(range) { r in688 let before = r.props689 change(&r.props)690 if tracking, r.props != before, r.formatRevision == nil, !r.isInserted {691 r.formatRevision = FormatRevision(author: author, date: stamp, previous: before, previousCharStyle: r.charStyle)692 }693 }694 b.setParagraph(p, at: path)695 }696 blocks = b697 }698699 public mutating func setCharacterStyle(_ id: String?) {700 guard !selection.isCaret else { return }701 var b = blocks702 for (path, range) in selectedParagraphs() where !range.isEmpty {703 guard var p = b.paragraph(at: path) else { continue }704 p.transform(range) { $0.charStyle = id }705 b.setParagraph(p, at: path)706 }707 blocks = b708 }709710 /// Removes direct character formatting from the selection (links and comments are kept).711 public mutating func clearCharacterFormatting() {712 formatCharacters { p in p = CharProps(link: p.link, language: p.language) }713 if !selection.isCaret { setCharacterStyle(nil) }714 }715716 /// Resolved character formatting at the caret or at the start of the selection (drives the toolbar state).717 public func currentCharacterFormat() -> ResolvedChar {718 let b = blocks719 let pos = selection.start720 guard let p = b.paragraph(at: pos.path) else { return ResolvedChar(doc.styles.defaultChar) }721 if selection.isCaret {722 let ta = p.typingAttributes(at: pos.offset)723 return doc.styles.charProps(paraStyle: p.style, charStyle: ta.charStyle, direct: typingOverride ?? ta.props)724 }725 let r = p.run(containing: pos.offset) ?? p.runs.last726 return doc.styles.charProps(paraStyle: p.style, charStyle: r?.charStyle, direct: r?.props ?? .none)727 }728729 public enum Toggle: Sendable { case bold, italic, underline, strikethrough, superscript, `subscript`, smallCaps }730731 public mutating func toggle(_ t: Toggle) {732 let cur = currentCharacterFormat()733 formatCharacters { p in734 switch t {735 case .bold: p.bold = !cur.isBold; p.weight = nil736 case .italic: p.italic = !cur.italic737 case .underline: p.underline = !cur.underline738 case .strikethrough: p.strikethrough = !cur.strikethrough739 case .superscript: p.vertical = cur.vertical == .superscript ? .baseline : .superscript740 case .subscript: p.vertical = cur.vertical == .subscript ? .baseline : .subscript741 case .smallCaps: p.smallCaps = !cur.smallCaps742 }743 }744 }745746 // MARK: - Paragraph formatting747748 public mutating func formatParagraphs(_ change: (inout Paragraph) -> Void) {749 var b = blocks750 for (path, _) in selectedParagraphs() {751 guard var p = b.paragraph(at: path) else { continue }752 change(&p)753 b.setParagraph(p, at: path)754 }755 blocks = b756 }757758 /// Applies a paragraph style. Direct paragraph formatting is reset so the style shows as designed; list membership is kept.759 public mutating func setParagraphStyle(_ id: String) {760 guard doc.styles.style(id)?.kind == .paragraph else { return }761 formatParagraphs { p in762 p.style = id763 p.props = ParaProps(pageBreakBefore: p.props.pageBreakBefore)764 }765 }766767 public func currentParagraph() -> Paragraph? { blocks.paragraph(at: selection.start.path) }768769 public func currentParagraphFormat() -> ResolvedPara {770 guard let p = currentParagraph() else { return ResolvedPara(doc.styles.defaultPara) }771 return doc.styles.paraProps(style: p.style, direct: p.props)772 }773774 /// Redefines a style from the formatting of the current paragraph ("Update style to match selection").775 public mutating func updateStyleFromSelection(_ id: String) {776 guard var style = doc.styles.style(id), let p = currentParagraph() else { return }777 if style.kind == .paragraph { style.para.apply(p.props) }778 if let r = p.run(containing: selection.start.offset) ?? p.runs.first { style.char.apply(r.props); style.char.link = nil }779 doc.styles.upsert(style)780 // Paragraphs of that style drop the direct formatting that is now part of the style.781 doc.mutateEveryParagraph { q in if q.style == id { q.props = ParaProps(pageBreakBefore: q.props.pageBreakBefore, outlineLevel: q.props.outlineLevel) } }782 }783784 // MARK: - Lists785786 public enum ListKind: Sendable { case bulleted, numbered, multilevel }787788 public mutating func toggleList(_ kind: ListKind) {789 let b = blocks790 let paths = selectedParagraphs().map(\.path)791 guard let firstPath = paths.first else { return }792 func flavour(_ p: Paragraph?) -> ListKind? {793 guard let li = p?.list, let def = doc.list(li.listID) else { return nil }794 if def.isBulleted { return .bulleted }795 return (def.levels.first?.pattern.contains("%1") ?? false) && def.levels.count > 1 && def.levels[1].pattern.contains("%1") ? .multilevel : .numbered796 }797 let allSame = paths.allSatisfy { flavour(b.paragraph(at: $0)) == kind }798 if allSame {799 formatParagraphs { $0.list = nil }800 return801 }802 var listID: String803 switch kind {804 case .bulleted: listID = doc.ensureList(bulleted: true)805 case .numbered, .multilevel:806 // Continue the numbered list of the paragraph just above; otherwise start a new one (numbering restarts at 1).807 let li = DocumentEditor.local(firstPath)808 let prev = li > 0 ? DocumentEditor.container(b, firstPath)[li - 1].paragraph : nil809 if flavour(prev) == kind, let id = prev?.list?.listID { listID = id } else {810 let def = kind == .numbered ? ListDefinition.numbered() : ListDefinition.multilevel()811 doc.lists.append(def)812 listID = def.id813 }814 }815 formatParagraphs { p in p.list = ListItem(listID: listID, level: p.list?.level ?? 0) }816 }817818 /// Tab / Shift-Tab in a list. Returns false when the paragraph is not a list item.819 @discardableResult820 public mutating func changeListLevel(by delta: Int) -> Bool {821 guard currentParagraph()?.list != nil else { return false }822 formatParagraphs { p in823 guard let l = p.list else { return }824 let lvl = l.level + delta825 if lvl < 0 { p.list = nil } else { p.list = ListItem(listID: l.listID, level: min(8, lvl)) }826 }827 return true828 }829830 // MARK: - Blocks and fragments831832 /// Inserts a block (table, break, generated list) at the caret, splitting the paragraph if needed. The caret ends after the block.833 public mutating func insertBlock(_ block: Block) {834 if !selection.isCaret { deleteSelection(caretAtEnd: true) }835 ensureCaretInParagraph()836 var b = blocks837 let pos = selection.head838 guard pos.path.cell == nil, selection.story == .body || block.paragraph != nil else { return } // tables and breaks live in the body only839 guard let p = b.paragraph(at: pos.path) else { return }840 let bi = pos.path.block841 var insertAt = bi + 1842 if p.isEmpty {843 insertAt = bi844 } else if pos.offset == 0 {845 insertAt = bi846 } else if pos.offset < p.length {847 let (first, second) = p.split(at: pos.offset)848 b[bi] = .paragraph(first)849 b.insert(.paragraph(second), at: bi + 1)850 }851 b.insert(block, at: insertAt)852 if insertAt + 1 >= b.count { b.append(.paragraph(Paragraph())) }853 if case .table = block, b[insertAt + 1].paragraph == nil { b.insert(.paragraph(Paragraph()), at: insertAt + 1) }854 blocks = b855 if case .table = block {856 selection = Selection(story: selection.story, caret: DocumentEditor.firstPosition(inBlock: insertAt, b))857 } else {858 selection = Selection(story: selection.story, caret: DocumentEditor.firstPosition(inBlock: insertAt + 1, b))859 }860 }861862 /// The selection as a fragment, or nil for a caret.863 public func copyFragment() -> DocumentFragment? {864 let b = blocks865 var out: [Block] = []866 switch target {867 case .caret: return nil868 case .cells(let bi, let rows, let cols):869 guard let t = b[bi].table else { return nil }870 var newRows: [TableRow] = []871 var widths: [Points] = []872 for r in rows {873 let idx = DocumentEditor.cells(in: t.rows[r], columns: cols)874 var row = t.rows[r]875 row.cells = idx.map { var c = t.rows[r].cells[$0]; c.vMerge = .none; return c }876 newRows.append(row)877 }878 let n = newRows.map { $0.cells.reduce(0) { $0 + $1.colSpan } }.max() ?? 1879 widths = (0..<n).map { cols.lowerBound + $0 < t.columnWidths.count ? t.columnWidths[cols.lowerBound + $0] : 72 }880 out = [.table(Table(columnWidths: widths, rows: newRows, style: t.style, alignment: t.alignment))]881 case .range(let s, let e):882 let cont = DocumentEditor.container(b, s.path)883 let lo = DocumentEditor.local(s.path), hi = DocumentEditor.local(e.path)884 for i in lo...hi {885 switch cont[i] {886 case .paragraph(var p):887 let from = i == lo ? s.offset : 0, to = i == hi ? e.offset : p.length888 p.runs = p.slice(from..<to).filter { !$0.isDeleted }.map { var r = $0; r.revision = nil; r.formatRevision = nil; r.comments = []; return r }889 p.markRevision = nil890 out.append(.paragraph(p))891 default:892 let wholly = (i > lo || s.offset == 0) && (i < hi || e.offset >= 1)893 if wholly { out.append(cont[i]) }894 }895 }896 }897 guard !out.isEmpty else { return nil }898 var notes: [String: Note] = [:], assets: [String: Asset] = [:], listIDs = Set<String>()899 DocumentModel.forEachParagraph(in: out) { p, _ in900 if let l = p.list { listIDs.insert(l.listID) }901 for r in p.runs {902 switch r.inline {903 case .note(let ref): notes[ref.id] = doc.notes[ref.id]904 case .image(let img): assets[img.asset] = doc.assets[img.asset]905 default: break906 }907 }908 }909 return DocumentFragment(blocks: out, notes: notes, lists: doc.lists.filter { listIDs.contains($0.id) }, assets: assets)910 }911912 /// Pastes a fragment at the caret (replacing the selection). Ids are regenerated so pasted content never clashes with existing content.913 public mutating func insertFragment(_ fragment: DocumentFragment) {914 guard !fragment.blocks.isEmpty else { return }915 if !selection.isCaret { deleteSelection(caretAtEnd: true) }916 // Bring over what the fragment references.917 for (id, data) in fragment.assetData where doc.assets[id] == nil { doc.assets[id] = Asset(id: id, mimeType: fragment.assetTypes[id] ?? "image/png", data: data) }918 for l in fragment.lists where doc.list(l.id) == nil { doc.lists.append(l) }919 var noteMap: [String: String] = [:]920 for (id, note) in fragment.notes {921 let newID = DocID.make()922 var n = note923 n.id = newID924 n.paragraphs = n.paragraphs.map { var p = $0; p.id = DocID.make(); return p }925 doc.notes[newID] = n926 noteMap[id] = newID927 }928 var incoming = fragment.blocks929 DocumentModel.mutateParagraphs(in: &incoming) { p in930 p.id = DocID.make()931 p.markRevision = nil932 for i in p.runs.indices {933 if case .note(var ref)? = p.runs[i].inline, let n = noteMap[ref.id] { ref.id = n; p.runs[i].inline = .note(ref) }934 }935 if doc.styles.style(p.style) == nil { p.style = StyleID.normal }936 }937 incoming = incoming.map { b in938 switch b {939 case .table(var t): t.id = DocID.make(); return .table(t)940 case .pageBreak(var x): x.id = DocID.make(); return .pageBreak(x)941 case .sectionBreak(var x): x.id = DocID.make(); return .sectionBreak(x)942 case .toc(var x): x.id = DocID.make(); return .toc(x)943 case .bibliography(var x): x.id = DocID.make(); return .bibliography(x)944 default: return b945 }946 }947 ensureCaretInParagraph()948 let inCellOrNote = selection.head.path.cell != nil || selection.story != .body949 if inCellOrNote {950 // Only paragraphs can live here: tables are flattened to their text, breaks are dropped.951 var paras: [Block] = []952 for blk in incoming {953 switch blk {954 case .paragraph: paras.append(blk)955 case .table(let t): for r in t.rows { for c in r.cells { paras.append(contentsOf: c.paragraphs.map { .paragraph($0) }) } }956 default: break957 }958 }959 incoming = paras960 guard !incoming.isEmpty else { return }961 }962 if incoming.count == 1, let p = incoming[0].paragraph {963 insertRuns(p.runs)964 return965 }966 var b = blocks967 let pos = selection.head968 guard let cur = b.paragraph(at: pos.path) else { return }969 var cont = DocumentEditor.container(b, pos.path)970 let li = DocumentEditor.local(pos.path)971 let rev: Revision? = tracking ? Revision(kind: .insertion, author: author, date: now()) : nil972 if let rev {973 DocumentModel.mutateParagraphs(in: &incoming) { p in974 for i in p.runs.indices { p.runs[i].revision = rev }975 p.markRevision = rev976 }977 }978 var (head, tail) = cur.split(at: pos.offset)979 var middle = incoming980 var caretLocal = li, caretOffset = 0981 // First pasted paragraph flows into the text before the caret.982 if case .paragraph(let fp)? = middle.first {983 if head.isEmpty { var adopted = fp; adopted.id = head.id; head = adopted } else { head.runs.append(contentsOf: fp.runs); head.normalize() }984 if let rev { head.markRevision = rev }985 middle.removeFirst()986 }987 var result: [Block] = [.paragraph(head)] + middle988 // Text after the caret follows the last pasted paragraph.989 if case .paragraph(var lp)? = result.last, result.count > 1 {990 caretOffset = lp.length991 lp.runs.append(contentsOf: tail.runs)992 lp.markRevision = tail.markRevision993 lp.normalize()994 result[result.count - 1] = .paragraph(lp)995 caretLocal = li + result.count - 1996 } else {997 result.append(.paragraph(tail))998 caretLocal = li + result.count - 1999 caretOffset = 01000 }1001 cont.replaceSubrange(li...li, with: result)1002 DocumentEditor.setContainer(cont, in: &b, pos.path)1003 blocks = b1004 selection = Selection(story: selection.story, caret: Position(path: DocumentEditor.path(like: pos.path, local: caretLocal), offset: caretOffset))1005 sanitizeSelection()1006 }10071008 // MARK: - Notes, images, links10091010 /// Inserts a footnote or endnote reference at the caret and moves the caret into the new note.1011 @discardableResult1012 public mutating func insertNote(_ kind: NoteRef.Kind) -> String? {1013 guard selection.story == .body else { return nil }1014 let note = Note(kind: kind, paragraphs: [Paragraph(style: StyleID.footnoteText)])1015 doc.notes[note.id] = note1016 insertInline(.note(NoteRef(kind: kind, id: note.id)))1017 return note.id1018 }10191020 /// Stores image data as an asset and inserts it at the caret.1021 @discardableResult1022 public mutating func insertImage(data: Data, mimeType: String, width: Points, height: Points, altText: String = "", placement: Placement = .inline) -> String {1023 let asset = Asset(mimeType: mimeType, data: data)1024 doc.assets[asset.id] = asset1025 insertInline(.image(ImageObject(asset: asset.id, width: width, height: height, altText: altText, placement: placement)))1026 return asset.id1027 }10281029 /// Sets or removes the hyperlink of the selection.1030 public mutating func setLink(_ url: String?) {1031 guard !selection.isCaret else { return }1032 let hasStyle = doc.styles.style(StyleID.hyperlink) != nil1033 var b = blocks1034 for (path, range) in selectedParagraphs() where !range.isEmpty {1035 guard var p = b.paragraph(at: path) else { continue }1036 p.transform(range) { r in1037 r.props.link = url1038 if hasStyle { r.charStyle = url == nil ? (r.charStyle == StyleID.hyperlink ? nil : r.charStyle) : StyleID.hyperlink }1039 }1040 b.setParagraph(p, at: path)1041 }1042 blocks = b1043 }10441045 /// Replaces the inline object at a position (image resize, equation edit …).1046 public mutating func updateInline(at pos: Position, in story: StoryID, _ change: (inout Inline) -> Void) {1047 var b = doc.blocks(in: story)1048 guard var p = b.paragraph(at: pos.path) else { return }1049 var offset = 01050 for i in p.runs.indices {1051 if offset == pos.offset, var inline = p.runs[i].inline {1052 change(&inline)1053 p.runs[i].inline = inline1054 b.setParagraph(p, at: pos.path)1055 doc.setBlocks(b, in: story)1056 return1057 }1058 offset += p.runs[i].length1059 }1060 }10611062 /// The inline object right after `pos`, if any.1063 public func inline(at pos: Position, in story: StoryID) -> Inline? {1064 doc.blocks(in: story).paragraph(at: pos.path)?.run(containing: pos.offset)?.inline1065 }10661067 // MARK: - Structure10681069 /// Moves a heading and everything under it (up to the next heading of the same or a higher level) before the block at `destination`.1070 /// Cross-references follow because they target paragraph ids.1071 public mutating func moveSection(startingAt blockIndex: Int, before destination: Int) {1072 guard doc.body.indices.contains(blockIndex), let head = doc.body[blockIndex].paragraph else { return }1073 func level(_ p: Paragraph) -> Int { p.props.outlineLevel ?? doc.styles.styleProps(p.style).para.outlineLevel ?? 0 }1074 let lvl = level(head)1075 guard lvl > 0 else { return }1076 var end = blockIndex + 11077 while end < doc.body.count {1078 if let p = doc.body[end].paragraph, level(p) > 0, level(p) <= lvl { break }1079 if case .sectionBreak = doc.body[end] { break }1080 end += 11081 }1082 guard destination < blockIndex || destination >= end else { return }1083 let moved = Array(doc.body[blockIndex..<end])1084 doc.body.removeSubrange(blockIndex..<end)1085 let dest = destination >= end ? destination - moved.count : destination1086 doc.body.insert(contentsOf: moved, at: max(0, min(doc.body.count, dest)))1087 if doc.body.last?.paragraph == nil { doc.body.append(.paragraph(Paragraph())) }1088 selection = Selection(caret: Position(block: max(0, min(doc.body.count - 1, dest)), offset: 0))1089 sanitizeSelection()1090 }10911092 /// Keeps the structural invariants: a non-empty body that ends with a paragraph.1093 public mutating func sanitizeDocument() {1094 if doc.body.isEmpty || doc.body.last?.paragraph == nil { doc.body.append(.paragraph(Paragraph())) }1095 sanitizeSelection()1096 }1097}1098