// CottonWriting (notes-new-ios, 19 Nov 2026): the writing surface any Cotton// app drops in — Notes first, then Journal, Story and the rest. It knows// nothing of notes. Its host hands it a `WritingRules` (the core's// `cotton-rules::writing`, through the host's own methods) and draws what it// answers: each line's block, each run's style and how it looks (text, dim,// hidden, a glyph), the tables as grids, what a key does to the text, which// tags to offer. The surface never reads Markdown itself.//// The shapes are `cotton-rules::writing`'s own (`style::Styled`,// `format::Edited`, `table::Table`). Offsets are UTF-16 code units, end// exclusive — the units UIKit's NSString and Android's String count in.importCoreGraphicsimportFoundation/// A text styled for a cursor (`style::Styled`).publicstructWritingStyled: Decodable, Hashable, Sendable {publicvar blocks: [WritingBlock]publicvar spans: [WritingSpan]publicvar tables: [WritingTable]/// Where the text folds (`folds::Fold`): each heading and each list item with deeper items.publicvar folds: [WritingFold]/// The `[[note links]]` written, each with the note it opens when the host's core resolved it.publicvar links: [WritingNoteLink]publicinit(blocks: [WritingBlock] = [], spans: [WritingSpan] = [], tables: [WritingTable] = [], folds: [WritingFold] = [], links: [WritingNoteLink] = []) {self.blocks = blocksself.spans = spansself.tables = tablesself.folds = foldsself.links = links }enumCodingKeys: String, CodingKey { case blocks, spans, tables, folds, links }publicinit(from decoder: Decoder) throws {let c = try decoder.container(keyedBy: CodingKeys.self) blocks = try c.decodeIfPresent([WritingBlock].self, forKey: .blocks) ?? [] spans = try c.decodeIfPresent([WritingSpan].self, forKey: .spans) ?? [] tables = try c.decodeIfPresent([WritingTable].self, forKey: .tables) ?? [] folds = try c.decodeIfPresent([WritingFold].self, forKey: .folds) ?? [] links = try c.decodeIfPresent([WritingNoteLink].self, forKey: .links) ?? [] }}/// A line that folds (`folds::Fold`): where it starts, and the range folding hides.publicstructWritingFold: Decodable, Hashable, Sendable {/// `heading` or `list`.publicvar kind: Stringpublicvar line: Intpublicvar start: Intpublicvar end: Intpublicvar level: Int?publicinit(kind: String = "heading", line: Int, start: Int, end: Int, level: Int? = nil) {self.kind = kindself.line = lineself.start = startself.end = endself.level = level }}/// A `[[note link]]` as written: its run, its target, and the note it opens (nil: none has that title, or not resolved).publicstructWritingNoteLink: Decodable, Hashable, Sendable {publicvar start: Intpublicvar end: Intpublicvar target: Stringpublicvar heading: String?publicvar note: String?publicinit(start: Int, end: Int, target: String, heading: String? = nil, note: String? = nil) {self.start = startself.end = endself.target = targetself.heading = headingself.note = note }}/// The notes a `[[` being typed may name (the host's `notes.links`): what to replace, and each offer.publicstructWritingLinkOffers: Hashable, Sendable {publicstructOffer: Hashable, Sendable, Identifiable {publicvar id: Stringpublicvar title: String/// What is written in place of `replace`, and where the cursor then stands.publicvar with: Stringpublicvar cursor: Intpublicinit(id: String, title: String, with: String, cursor: Int) {self.id = idself.title = titleself.with = withself.cursor = cursor } }publicvar replace: NSRangepublicvar offers: [Offer]/// The words said when nothing matches.publicvar none: String?publicinit(replace: NSRange, offers: [Offer], none: String? = nil) {self.replace = replaceself.offers = offersself.none = none }}/// One line and what it is (`style::Block`).publicstructWritingBlock: Decodable, Hashable, Sendable {publicvar start: Intpublicvar end: Int/// `paragraph`, `blank`, `heading`, `bullet`, `numbered`, `check`, `quote`,/// `divider`, `fence`, `code`, `table`, `table_rule`, `picture`.publicvar kind: String/// Where the line's words start, after its marker and indent.publicvar content: Int/// Indent level, 0 at the margin.publicvar depth: Intpublicvar level: Int?publicvar checked: Bool?publicvar number: Int?/// The note's title line.publicvar title: Bool/// A picture line's address, as written.publicvar src: String?/// A picture line's width: `small`, `medium` or `full` (nil: full).publicvar width: String?enumCodingKeys: String, CodingKey { case start, end, kind, content, depth, level, checked, number, title, src, width }publicinit(start: Int, end: Int, kind: String, content: Int? = nil, depth: Int = 0, level: Int? = nil, checked: Bool? = nil, number: Int? = nil, title: Bool = false, src: String? = nil, width: String? = nil) {self.width = widthself.start = startself.end = endself.kind = kindself.content = content ?? startself.depth = depthself.level = levelself.checked = checkedself.number = numberself.title = titleself.src = src }publicinit(from decoder: Decoder) throws {let c = try decoder.container(keyedBy: CodingKeys.self) start = try c.decode(Int.self, forKey: .start) end = try c.decode(Int.self, forKey: .end) kind = try c.decode(String.self, forKey: .kind) content = try c.decodeIfPresent(Int.self, forKey: .content) ?? start depth = try c.decodeIfPresent(Int.self, forKey: .depth) ?? 0 level = try c.decodeIfPresent(Int.self, forKey: .level) checked = try c.decodeIfPresent(Bool.self, forKey: .checked) number = try c.decodeIfPresent(Int.self, forKey: .number) title = try c.decodeIfPresent(Bool.self, forKey: .title) ?? false src = try c.decodeIfPresent(String.self, forKey: .src) width = try c.decodeIfPresent(String.self, forKey: .width) }/// The share of the column a picture line stands at: small 0.4, medium 0.7, full 1.publicvar pictureShare: CGFloat {switch width {case"small": 0.4case"medium": 0.7default: 1 } }publicvar range: NSRange { NSRange(location: start, length: max(0, end - start)) }}/// One run of the text and how it is drawn (`style::Span`).publicstructWritingSpan: Decodable, Hashable, Sendable {publicvar start: Intpublicvar end: Int/// `title`, `heading`, `bold`, `italic`, `underline`, `strike`,/// `highlight`, `code`, `code_block`, `link`, `image`, `tag`, `quote`,/// `number`, `done`, `mark`, `indent`. A style this build does not know/// is drawn as plain text.publicvar style: String/// `text`, `dim` (a mark the cursor is in), `hidden` (a mark away from/// it), `glyph` (drawn as `glyph` instead of its characters).publicvar look: Stringpublicvar level: Int?/// `bullet`, `box`, `ticked`, `rule`.publicvar glyph: String?/// A link's or a picture's address.publicvar url: String?publicinit(start: Int, end: Int, style: String, look: String = "text", level: Int? = nil, glyph: String? = nil, url: String? = nil) {self.start = startself.end = endself.style = styleself.look = lookself.level = levelself.glyph = glyphself.url = url }publicvar range: NSRange { NSRange(location: start, length: max(0, end - start)) }}/// A pipe table's rows and cells (`table::Table`): the header row first,/// the delimiter line no row.publicstructWritingTable: Decodable, Hashable, Sendable {publicvar start: Intpublicvar end: Int/// Per column: `none`, `left`, `center`, `right`.publicvar align: [String]publicvar rows: [[WritingCell]]publicinit(start: Int, end: Int, align: [String] = [], rows: [[WritingCell]]) {self.start = startself.end = endself.align = alignself.rows = rows }publicvar columns: Int { rows.map(\.count).max() ?? 0 }publicvar range: NSRange { NSRange(location: start, length: max(0, end - start)) }/// The cells' words alone, for a grid that redraws only when they change.publicvar words: [[String]] { rows.map { $0.map(\.text) } }}/// One cell: where its words are (an empty cell is an empty range where words/// would go) and the words.publicstructWritingCell: Decodable, Hashable, Sendable {publicvar start: Intpublicvar end: Intpublicvar text: Stringpublicinit(start: Int, end: Int, text: String) {self.start = startself.end = endself.text = text }}/// One value in an action: words, a number or a yes/no.publicenumWritingValue: Codable, Hashable, Sendable {case text(String)case number(Double)case flag(Bool)publicinit(from decoder: Decoder) throws {let c = try decoder.singleValueContainer()iflet flag = try? c.decode(Bool.self) { self = .flag(flag) }elseiflet number = try? c.decode(Double.self) { self = .number(number) }else { self = .text(try c.decode(String.self)) } }publicfunc encode(to encoder: Encoder) throws {var c = encoder.singleValueContainer()switchself {case .text(let s): try c.encode(s)case .number(let n): if n.rounded() == n, abs(n) < 1e15 { try c.encode(Int(n)) } else { try c.encode(n) }case .flag(let b): try c.encode(b) } }publicvar text: String? { ifcase .text(let s) = self { s } else { nil } }publicvar number: Double? { ifcase .number(let n) = self { n } else { nil } }}/// What a key does, in the writing rule's own words (`format::Action`):/// `{"action": "heading", "level": 2}`, `{"action": "table_cell", "row": 1,/// "column": 0, "text": "…"}`. The surface sends it as it was given; it/// names only the few it presses itself (Return, a tick, a table's edits).publicstructWritingAction: Codable, Hashable, Sendable {publicvar fields: [String: WritingValue]publicinit(_ name: String, _ more: [String: WritingValue] = [:]) { fields = more.merging(["action": .text(name)]) { _, new in new } }publicinit(from decoder: Decoder) throws { fields = try decoder.singleValueContainer().decode([String: WritingValue].self) }publicfunc encode(to encoder: Encoder) throws {var c = encoder.singleValueContainer()try c.encode(fields) }/// The action's name: `bold`, `heading`, `return`.publicvar name: String { fields["action"]?.text ?? "" }}/// A key pressed on a text: what it does, the whole text and the selection.publicstructWritingAsk: Hashable, Sendable {publicvar action: WritingActionpublicvar text: Stringpublicvar start: Intpublicvar end: Intpublicinit(action: WritingAction, text: String, start: Int, end: Int) {self.action = actionself.text = textself.start = startself.end = end }publicinit(action: WritingAction, text: String, selection: NSRange) {self.init(action: action, text: text, start: selection.location, end: NSMaxRange(selection)) }}publicstructWritingSelection: Codable, Hashable, Sendable {publicvar start: Intpublicvar end: Intpublicinit(start: Int, end: Int) {self.start = startself.end = end }publicinit(_ range: NSRange) {self.init(start: range.location, end: NSMaxRange(range)) }publicvar range: NSRange {let low = min(start, end)return NSRange(location: low, length: abs(end - start)) }}/// One replacement in the old text (`format::Replace`).publicstructWritingReplace: Codable, Hashable, Sendable {publicvar start: Intpublicvar end: Intpublicvar with: Stringpublicinit(start: Int, end: Int, with: String) {self.start = startself.end = endself.with = with }}/// The core's answer to a key (`format::Edited`): the whole new text, the one/// replacement that makes it, and the selection. Empty: the key does nothing/// here. The surface writes back only the replacement, so Undo takes back/// exactly the key.publicstructWritingChange: Decodable, Hashable, Sendable {publicvar text: String?publicvar replace: WritingReplace?publicvar selection: WritingSelection?publicinit(text: String?, replace: WritingReplace? = nil, selection: WritingSelection?) {self.text = textself.replace = replaceself.selection = selection }publicstaticlet nothing = WritingChange(text: nil, selection: nil)}/// A tag the core offers while one is typed.publicstructWritingTagOffer: Decodable, Hashable, Sendable, Identifiable {publicvar tag: Stringpublicvar label: Stringpublicvar count: Int?publicvar id: String { tag }publicinit(tag: String, label: String, count: Int? = nil) {self.tag = tagself.label = labelself.count = count }}/// A key on the bar or the formatting panel, as the core names it: what it/// is, what it does (`action`, sent back as it came), the words VoiceOver says, and what it/// wears — `glyph` (a few letters, "H1", "B", drawn in `style`) or `icon`/// (a symbol's name). `delete`, `space` and `return` are typed as the/// keyboard types them (Return through the core: it continues a list).publicstructWritingKey: Decodable, Hashable, Sendable, Identifiable {publicvar id: Stringpublicvar label: Stringpublicvar glyph: String?publicvar icon: String?/// `bold`, `italic`, `underline`, `strike`, `mono`: how a glyph is drawn.publicvar style: String?/// The panel's row it sits in.publicvar group: String?/// What it does to the text; nil for the surface's own keys (undo,/// redo, tag, picture, hide, the panel, delete, space, return, copy, paste).publicvar action: WritingAction?/// An editing key, drawn darker than the marks (the grid's left column, delete, space, return).publicvar grey: Bool?/// What the key offers when held (H2 and H3 behind H1, the camera behind the picture); a corner triangle says so.publicvar hold: [WritingKey]?publicinit(id: String, label: String, glyph: String? = nil, icon: String? = nil, style: String? = nil, group: String? = nil, action: WritingAction? = nil, grey: Bool? = nil, hold: [WritingKey]? = nil) {self.id = idself.action = actionself.grey = greyself.hold = holdself.label = labelself.glyph = glyphself.icon = iconself.style = styleself.group = group }}/// A hardware keyboard's shortcut: the key, its modifiers, and the key it presses.publicstructWritingShortcut: Decodable, Hashable, Sendable {publicvar key: Stringpublicvar ctrl: Boolpublicvar shift: Boolpublicvar alt: Boolpublicvar does: StringenumCodingKeys: String, CodingKey { case key, ctrl, shift, alt, does }publicinit(key: String, ctrl: Bool = true, shift: Bool = false, alt: Bool = false, does: String) {self.key = keyself.ctrl = ctrlself.shift = shiftself.alt = altself.does = does }publicinit(from decoder: Decoder) throws {let c = try decoder.container(keyedBy: CodingKeys.self) key = try c.decode(String.self, forKey: .key) ctrl = try c.decodeIfPresent(Bool.self, forKey: .ctrl) ?? false shift = try c.decodeIfPresent(Bool.self, forKey: .shift) ?? false alt = try c.decodeIfPresent(Bool.self, forKey: .alt) ?? false does = try c.decode(String.self, forKey: .does) }}/// The surface's keys and words, as the core says them (`notes.keys`): the/// bar above the keyboard and the formatting panel's keys in order, the/// hardware shortcuts, and the words (`hint`, `add_row`, `add_column`,/// `remove_row`, `remove_column`, `cell` "Row {row}, column {column}").publicstructWritingWords: Decodable, Hashable, Sendable {publicvar bar: [WritingKey]publicvar panel: [WritingKey]publicvar shortcuts: [WritingShortcut]publicvar words: [String: String]/// The formatting keys as a grid in the keyboard's place, row by row (six across, four down); empty: `panel` in rows.publicvar grid: [[WritingKey]]/// The slim row under the grid: copy at the left, paste at the right.publicvar foot: [WritingKey]enumCodingKeys: String, CodingKey { case bar, panel, shortcuts, words, grid, foot }publicinit(bar: [WritingKey], panel: [WritingKey], shortcuts: [WritingShortcut] = [], words: [String: String] = [:], grid: [[WritingKey]] = [], foot: [WritingKey] = []) {self.bar = barself.panel = panelself.grid = gridself.foot = footself.shortcuts = shortcutsself.words = words }publicinit(from decoder: Decoder) throws {let c = try decoder.container(keyedBy: CodingKeys.self) bar = try c.decode([WritingKey].self, forKey: .bar) panel = try c.decode([WritingKey].self, forKey: .panel) shortcuts = try c.decodeIfPresent([WritingShortcut].self, forKey: .shortcuts) ?? [] words = try c.decodeIfPresent([String: String].self, forKey: .words) ?? [:] grid = try c.decodeIfPresent([[WritingKey]].self, forKey: .grid) ?? [] foot = try c.decodeIfPresent([WritingKey].self, forKey: .foot) ?? [] }publicfunc bar(_ id: String) -> WritingKey? { bar.first { $0.id == id } }publicfunc key(_ id: String) -> WritingKey? {let every = panel + grid.flatMap { $0 } + foot + barreturn every.first { $0.id == id } ?? every.flatMap { $0.hold ?? [] }.first { $0.id == id } }/// A word by its name; the name itself when the core said none, so a/// missing word is seen, never invented.publicfunc word(_ name: String) -> String { words[name] ?? name }func cell(_ row: Int, _ column: Int) -> String { word("cell").replacingOccurrences(of: "{row}", with: String(row)).replacingOccurrences(of: "{column}", with: String(column)) }}/// What the surface asks of its host's core. Every answer is the core's.publicprotocolWritingRules: Sendable {/// The text styled for the cursor (nil: reading, every mark hidden).func style(_ text: String, cursor: Int?) asyncthrows -> WritingStyled/// What a key does to the text.func press(_ ask: WritingAsk) asyncthrows -> WritingChange/// The tags to offer for the tag typed so far, `#` left off.func tags(_ prefix: String) asyncthrows -> [WritingTagOffer]/// A tag as it is written in the text: `#work`, `#two words#`.func written(_ tag: String) -> String}#if canImport(UIKit)import UIKit/// Where the surface's pictures come from and go to: the host's own store.publicprotocolWritingMedia: Sendable {/// The picture an address names, at most `width` points wide.func image(_ src: String, width: CGFloat) async -> UIImage?/// Keeps a picture's file with the document and places it in the text at/// the selection: the core's answer, as for a key.func add(_ file: URL, text: String, selection: NSRange) asyncthrows -> WritingChange}#endif