SPB Git

Repository Public

InlineCommands.swift 6.9 KB 136 lines swift

1// SP Notes Core2// File: Sources/SPNotesDocument/InlineCommands.swift3// Description: Inline editing commands: text replacement, inline atoms, mark toggling and links, with the mark4//              queries an editor toolbar needs. Offsets are UTF-16 units; an atom counts as 1.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation910extension NoteDocument {11    private func textRuns(_ line: Int) -> [InlineRun]? {12        guard lines.indices.contains(line), case .inline(let runs) = lines[line].content else { return nil }13        return runs14    }1516    /// Whether marks are allowed in the line (not in a code block).17    private func allowsMarks(_ line: Int) -> Bool { lines[line].type != NodeType.codeBlock }1819    /// Whether the line accepts inline atoms (code blocks and details summaries hold text only).20    private func allowsAtoms(_ line: Int) -> Bool {21        lines[line].type != NodeType.codeBlock && lines[line].type != NodeType.detailsSummary22    }2324    private mutating func setRuns(_ runs: [InlineRun], _ line: Int) -> Bool {25        let new = LineContent.inline(InlineTools.normalized(runs))26        guard new != lines[line].content else { return false }27        lines[line].content = new28        return true29    }3031    /// The marks typed text takes at a caret: those of the text before it (a link is not continued past its end),32    /// or of the text after it at the start of the line.33    public func marks(at offset: Int, line: Int) -> [PMMark] {34        guard let runs = textRuns(line), allowsMarks(line) else { return [] }35        var pos = 036        for (n, run) in runs.enumerated() {37            let end = pos + run.length38            if offset > pos, offset <= end, case .text(_, let marks) = run {39                if offset == end {40                    let next = n + 1 < runs.count ? runs[n + 1].marks : []41                    return marks.filter { $0.type != "link" || next.contains($0) }42                }43                return marks44            }45            pos = end46        }47        if offset <= 0, case .text(_, let marks)? = runs.first { return marks.filter { $0.type != "link" } }48        return []49    }5051    /// Replaces an inline range of a text line by plain text (typing, deleting, pasting). `marks` nil inherits the52    /// marks at the start of the range. Line feeds become hard breaks, except in a code block where they stay text.53    @discardableResult54    public mutating func replaceText(in range: Range<Int>, at line: Int, with text: String, marks: [PMMark]? = nil) -> Bool {55        guard let runs = textRuns(line) else { return false }56        let (before, _, after) = InlineTools.split(runs, range: range)57        var inserted: [InlineRun] = []58        if !text.isEmpty {59            if !allowsMarks(line) {60                inserted = [.text(text, marks: [])]61            } else {62                let m = InlineTools.validMarks(marks ?? self.marks(at: InlineTools.length(before), line: line))63                inserted = allowsAtoms(line) ? InlineTools.runs(plain: text, marks: m) : [.text(JS.replacing(text, "\n", with: " "), marks: m)]64            }65        }66        return setRuns(before + inserted + after, line)67    }6869    /// Inserts an inline atom (mention, inline math, hard break, footnote reference) at an offset of a text line.70    @discardableResult71    public mutating func insertInlineAtom(_ node: PMNode, at offset: Int, line: Int) -> Bool {72        guard let runs = textRuns(line), allowsAtoms(line), node.text == nil else { return false }73        let (left, right) = InlineTools.split(runs, at: offset)74        return setRuns(left + [.atom(node)] + right, line)75    }7677    private func markable(_ run: InlineRun, _ type: String) -> Bool {78        guard case .text(_, let marks) = run else { return false }79        return type == "code" || !marks.contains { $0.type == "code" }80    }8182    /// Whether all the text of the range that can take the mark has it (false for an empty range).83    public func hasMark(_ kind: MarkKind, in range: Range<Int>, at line: Int) -> Bool {84        guard let runs = textRuns(line), allowsMarks(line) else { return false }85        let inside = InlineTools.split(runs, range: range).inside.filter { markable($0, kind.rawValue) }86        return !inside.isEmpty && inside.allSatisfy { $0.marks.contains { $0.type == kind.rawValue } }87    }8889    /// Toggles a mark on the text of an inline range: removed when all of it has the mark, added otherwise.90    /// `code` removes every other mark; other marks are not added to text marked `code`. Atoms are left as they are.91    @discardableResult92    public mutating func toggleMark(_ kind: MarkKind, in range: Range<Int>, at line: Int) -> Bool {93        guard let runs = textRuns(line), allowsMarks(line) else { return false }94        let remove = hasMark(kind, in: range, at: line)95        return mapMarks(runs, range, line) { remove ? InlineTools.removing(kind.rawValue, from: $0) : InlineTools.adding(.mark(kind), to: $0) }96    }9798    /// Links the text of an inline range (replacing any link there). Text marked `code` cannot be linked.99    @discardableResult100    public mutating func setLink(href: String, in range: Range<Int>, at line: Int) -> Bool {101        guard let runs = textRuns(line), allowsMarks(line) else { return false }102        return mapMarks(runs, range, line) { InlineTools.adding(.link(href: href), to: InlineTools.removing("link", from: $0)) }103    }104105    /// Removes the link from the text of an inline range.106    @discardableResult107    public mutating func removeLink(in range: Range<Int>, at line: Int) -> Bool {108        guard let runs = textRuns(line) else { return false }109        return mapMarks(runs, range, line) { InlineTools.removing("link", from: $0) }110    }111112    private mutating func mapMarks(_ runs: [InlineRun], _ range: Range<Int>, _ line: Int, _ body: ([PMMark]) -> [PMMark]) -> Bool {113        let (before, inside, after) = InlineTools.split(runs, range: range)114        let mapped = inside.map { run -> InlineRun in115            if case .text(let s, let m) = run { return .text(s, marks: body(m)) }116            return run117        }118        return setRuns(before + mapped + after, line)119    }120121    /// The extent of the link at or just before a caret, nil when there is none.122    public func linkRange(at offset: Int, line: Int) -> Range<Int>? {123        guard let runs = textRuns(line) else { return nil }124        var starts: [Int] = []125        var pos = 0126        for run in runs { starts.append(pos); pos += run.length }127        func link(_ n: Int) -> PMMark? { runs[n].marks.first { $0.type == "link" } }128        guard let n = runs.indices.first(where: { starts[$0] <= offset && offset <= starts[$0] + runs[$0].length && link($0) != nil }),129              let mark = link(n) else { return nil }130        var a = n, b = n131        while a > 0, link(a - 1) == mark { a -= 1 }132        while b + 1 < runs.count, link(b + 1) == mark { b += 1 }133        return starts[a]..<(starts[b] + runs[b].length)134    }135}136
Files main
Menu

Theme