// // ProseList.swift // Museion // // #115 (S5): prose-list model — pure, UTF-16-safe scan and structural // edits over the ONE plain buffer (ADR-0010 mode B: no secondary model). // A list "item" is its marker line plus wrapped lines and nested list // lines (indent > the item's). Tab/⇧Tab re-indent, ⌥↑/⌥↓ swap with an // adjacent sibling — each ONE range replacement, one undo step. Honest // v1: indent unit = the previous sibling's content column (never a // blind 2); moves are sibling-adjacent; fences end a block. // import Foundation nonisolated enum ProseList { // MARK: Scan struct Line { let range: NSRange // content + terminator let content: NSRange let text: String let indent: Int // leading whitespace columns (tab = 2) let isList: Bool let isBlank: Bool var end: Int { range.location + range.length } } struct Item: Equatable { /// The marker line incl. terminator — its `location` is the fold key. let markerLine: NSRange /// End of the marker line's content (caret park when its subtree folds). let markerEnd: Int let contentOffset: Int // UTF-16 offset of the first content column /// Marker line through the last subtree line's terminator. let block: NSRange /// The fold-hidden range; nil = no children. let foldScope: NSRange? let hiddenLineCount: Int let indent: Int } /// One scan into lines, fence-aware via the presenter's classifier /// (list lines inside a fence are never .listMarker). static func lines(in text: String) -> [Line] { let buffer = text as NSString var out: [Line] = [] var loc = 0 let total = buffer.length var inFence = false while loc < total { let full = buffer.lineRange(for: NSRange(location: loc, length: 0)) if full.length == 0 { break } var len = full.length while len > 0 { let unit = buffer.character(at: full.location + len - 1) if unit == 0x0A || unit == 0x0D { len -= 1 } else { break } } let content = NSRange(location: full.location, length: len) let lineText = len > 0 ? buffer.substring(with: content) : "" let kind = ProsePresenter.classify(lineText, inFence: inFence) if kind == .fence { inFence.toggle() } out.append(Line( range: full, content: content, text: lineText, indent: leadingColumns(lineText), isList: kind == .listMarker, isBlank: kind == .blank, )) loc = full.location + full.length } return out } static func item(at caret: Int, in text: String) -> Item? { let buffer = text as NSString guard buffer.length > 0 else { return nil } let scanned = lines(in: text) let caretLoc = min(max(0, caret), buffer.length - 1) guard let idx = scanned.firstIndex(where: { NSLocationInRange(caretLoc, $0.range) }), scanned[idx].isList else { return nil } let indent = scanned[idx].indent let bounds = blockBounds(scanned, from: idx, indent: indent) let blockEnd = scanned[bounds.end].end let block = NSRange(location: scanned[idx].range.location, length: blockEnd - scanned[idx].range.location) let scope: NSRange? var hidden = 0 if let foldStart = bounds.foldStart, let scopeStartIdx = bounds.scopeStartIdx { scope = NSRange(location: foldStart, length: blockEnd - foldStart) hidden = bounds.end - scopeStartIdx + 1 } else { scope = nil } return Item( markerLine: scanned[idx].range, markerEnd: scanned[idx].content.location + scanned[idx].content.length, contentOffset: contentOffset(of: scanned[idx]), block: block, foldScope: scope, hiddenLineCount: hidden, indent: indent, ) } /// Every list line that has children (the fold chevron targets). struct ParentHint: Equatable { let markerLine: NSRange let markerEnd: Int let contentOffset: Int let foldScope: NSRange let hiddenLineCount: Int } static func parents(in text: String) -> [ParentHint] { let scanned = lines(in: text) var out: [ParentHint] = [] for (idx, line) in scanned.enumerated() where line.isList { let bounds = blockBounds(scanned, from: idx, indent: line.indent) guard let foldStart = bounds.foldStart, let scopeStartIdx = bounds.scopeStartIdx else { continue } let blockEnd = scanned[bounds.end].end out.append(ParentHint( markerLine: line.range, markerEnd: line.content.location + line.content.length, contentOffset: contentOffset(of: line), foldScope: NSRange(location: foldStart, length: blockEnd - foldStart), hiddenLineCount: bounds.end - scopeStartIdx + 1, )) } return out } } nonisolated extension ProseList { // MARK: Edits (one range replacement each — one undo step) struct Edit: Equatable { let range: NSRange let replacement: String let caret: Int } /// Tab: nest under the previous sibling — delta = its content column /// minus our indent. No previous sibling → nil (boundary no-op). static func indent(_ item: Item, caret: Int, in text: String) -> Edit? { let scanned = lines(in: text) guard let idx = lineIndex(of: item.markerLine.location, in: scanned), let sibIdx = adjacentSiblingLine(scanned, from: idx, through: idx, indent: item.indent, direction: -1) else { return nil } let delta = contentColumn(scanned[sibIdx].text) - item.indent guard delta > 0 else { return nil } let body = blockBody(text, item.block) let terminated = body.terminated let shifted = body.lines.map { $0.isEmpty ? $0 : String(repeating: " ", count: delta) + $0 }.joined(separator: "\n") + (terminated ? "\n" : "") return Edit(range: item.block, replacement: shifted, caret: caret + delta) } /// ⇧Tab: remove up to 2 columns from every line of the block. The caret /// rides its line's shift (parks at the new line start inside it). static func outdent(_ item: Item, caret: Int, in text: String) -> Edit? { guard item.indent > 0 else { return nil } let stripWidth = min(2, item.indent) let body = blockBody(text, item.block) var outLines: [String] = [] var lineStart = item.block.location // utf16 start of this line in the OLD text var caretShift = 0 var found = false for line in body.lines { let (removed, rest) = stripLeading(line, columns: stripWidth) let into = caret - lineStart if !found, into >= 0, into <= line.utf16.count { caretShift = -min(removed.utf16.count, max(0, into)) found = true } outLines.append(rest) lineStart += line.utf16.count + 1 // +1 for the joined \n } let replacement = outLines.joined(separator: "\n") + (body.terminated ? "\n" : "") let newCaret = max(item.block.location, caret + caretShift) return Edit(range: item.block, replacement: replacement, caret: newCaret) } /// ⌥↑/⌥↓: swap the item's block with the adjacent sibling's BLOCK /// (children and continuations ride WITH their own item — a marker-line /// swap would steal the sibling's subtree, #115 audit); the text between /// rides unchanged. Boundary or paragraph-interrupted → nil. static func move(_ item: Item, caret: Int, direction: Int, in text: String) -> Edit? { let scanned = lines(in: text) guard let idx = lineIndex(of: item.markerLine.location, in: scanned) else { return nil } let bounds = blockBounds(scanned, from: idx, indent: item.indent) guard let sibIdx = adjacentSiblingLine(scanned, from: idx, through: bounds.end, indent: item.indent, direction: direction) else { return nil } let sibStart = scanned[sibIdx].range.location let sibEnd = NSMaxRange(scanned[blockBounds(scanned, from: sibIdx, indent: item.indent).end].range) let sib = NSRange(location: sibStart, length: sibEnd - sibStart) let itemText = substring(text, item.block) let sibText = substring(text, sib) if direction > 0 { let range = NSRange(location: item.block.location, length: NSMaxRange(sib) - item.block.location) let between = substring(text, NSRange(location: NSMaxRange(item.block), length: sib.location - NSMaxRange(item.block))) let replacement = sibText + between + itemText // the item lands after the sibling + the between-text let newCaret = range.location + sibText.utf16.count + between.utf16.count + (caret - item.block.location) return Edit(range: range, replacement: replacement, caret: newCaret) } else { let range = NSRange(location: sib.location, length: NSMaxRange(item.block) - sib.location) let between = substring(text, NSRange(location: NSMaxRange(sib), length: item.block.location - NSMaxRange(sib))) let replacement = itemText + between + sibText let newCaret = sib.location + (caret - item.block.location) return Edit(range: range, replacement: replacement, caret: newCaret) } } // MARK: Block geometry /// blockBounds result: last belonging line, fold-scope start (nil = no /// children), and the scope-start line's index. private struct BlockBounds { let end: Int let foldStart: Int? let scopeStartIdx: Int? } /// Block walk from the marker line: lines belong while deeper (any /// kind) or a lazy continuation (prose, no blank between); blanks ride /// inside only when a belonging line follows. private static func blockBounds(_ scanned: [Line], from idx: Int, indent: Int) -> BlockBounds { var end = idx var pendingBlanks = 0 var scanIndex = idx + 1 while scanIndex < scanned.count { let candidate = scanned[scanIndex] if candidate.isBlank { pendingBlanks += 1 scanIndex += 1 continue } let deep = candidate.indent > indent // ponytail: lazy continuation treats ANY non-list line as item content — // CommonMark restricts it to paragraphs, so a heading/fence after an // item rides its block; exclude those kinds if fidelity bites. let lazy = !candidate.isList && pendingBlanks == 0 if deep || lazy { end = scanIndex pendingBlanks = 0 scanIndex += 1 } else { break } } var foldStart: Int? var scopeStartIdx: Int? var probeIndex = idx + 1 while probeIndex <= end { if scanned[probeIndex].indent > indent { var source = probeIndex while source - 1 > idx, scanned[source - 1].isBlank { source -= 1 } // blanks before the first child hide too foldStart = scanned[source].range.location scopeStartIdx = source break } probeIndex += 1 } return BlockBounds(end: end, foldStart: foldStart, scopeStartIdx: scopeStartIdx) } // MARK: Sibling searches /// Adjacent sibling LINE INDEX at the same indent (direction -1 = previous, /// +1 = next), or nil at any boundary. Backward: skip blanks, deeper /// list lines (the sibling's subtree), and lazy prose; a standalone /// paragraph or a shallower list line is a boundary. Forward: prose /// always ends the walk (adjacent prose would be inside the block). private static func adjacentSiblingLine(_ scanned: [Line], from idx: Int, through end: Int, indent: Int, direction: Int) -> Int? { if direction < 0 { var pendingBlanks = 0 var probeIndex = idx - 1 while probeIndex >= 0 { let candidate = scanned[probeIndex] if candidate.isBlank { pendingBlanks += 1; probeIndex -= 1; continue } if candidate.isList { if candidate.indent == indent { return probeIndex } if candidate.indent < indent { return nil } probeIndex -= 1 // deeper: subtree of the sibling, keep walking continue } if pendingBlanks > 0 || (probeIndex - 1 >= 0 && scanned[probeIndex - 1].isBlank) { return nil } probeIndex -= 1 } return nil } var probeIndex = end + 1 while probeIndex < scanned.count { let candidate = scanned[probeIndex] if candidate.isBlank { probeIndex += 1; continue } if candidate.isList, candidate.indent == indent { return probeIndex } return nil // prose, or a list at another indent: boundary } return nil } // MARK: Helpers private static func lineIndex(of location: Int, in scanned: [Line]) -> Int? { scanned.firstIndex { $0.range.location == location } } /// Leading whitespace columns (space = 1, tab = 2 — OutlineTree's rule). private static func leadingColumns(_ source: String) -> Int { var cols = 0 for unit in source { if unit == " " { cols += 1 } else if unit == "\t" { cols += 2 } else { break } } return cols } /// Content column of a list line: indent + marker + following whitespace. /// CommonMark's nesting anchor ("1. " → 3, "10. " → 4). private static func contentColumn(_ source: String) -> Int { var cols = 0 var scanIndex = source.startIndex while scanIndex < source.endIndex, source[scanIndex] == " " || source[scanIndex] == "\t" { cols += source[scanIndex] == "\t" ? 2 : 1 scanIndex = source.index(after: scanIndex) } while scanIndex < source.endIndex, source[scanIndex] != " ", source[scanIndex] != "\t" { cols += 1 scanIndex = source.index(after: scanIndex) } while scanIndex < source.endIndex, source[scanIndex] == " " || source[scanIndex] == "\t" { cols += source[scanIndex] == "\t" ? 2 : 1 scanIndex = source.index(after: scanIndex) } return cols } /// UTF-16 offset of the first content character (after "\source*marker\source+"). private static func contentOffset(of line: Line) -> Int { guard let match = line.text.firstMatch(of: ProsePresenter.listMarkerPattern) else { return line.range.location } let utf16 = match.range.utf16Range(in: line.text) return line.range.location + min(utf16.upperBound, line.content.length) } private static func substring(_ text: String, _ range: NSRange) -> String { (text as NSString).substring(with: range) } /// Block text split into lines; `terminated` = block ends with \n. private static func blockBody(_ text: String, _ block: NSRange) -> (lines: [String], terminated: Bool) { let raw = substring(text, block) let terminated = raw.hasSuffix("\n") let body = terminated ? String(raw.dropLast()) : raw let lines = body.split(separator: "\n", omittingEmptySubsequences: false).map(String.init) return (lines, terminated) } /// Remove up to `columns` of leading whitespace (tab = 2, consumed /// whole). Returns (removed prefix, rest). private static func stripLeading(_ line: String, columns: Int) -> (removed: Substring, rest: String) { var removed = 0 var scanIndex = line.startIndex while scanIndex < line.endIndex, removed < columns { let unit = line[scanIndex] if unit == " " { removed += 1 } else if unit == "\t" { removed += 2 } else { break } scanIndex = line.index(after: scanIndex) } return (line[..