Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-ui

Source of release 0.19.5

0.19.5 / src / text / editing.lucb

## Editing commands operate on scalar offsets. Pixel coordinates, key bindings and
## focus are deliberately absent, so the same commands work in other text controls.
import interop
import memory
from luce_std import collections
from text.cells import grid
from text.document import Document
from text.style import Swatch, swatch_span

pub func move(document: Document*, position: usize, extend: bool) -> !:
    try document.select(document.anchor() if extend else position, position)

pub func word_left(document: const Document*, position: usize) -> usize:
    var index = position
    while index > 0 and whitespace(document.scalar(index - 1)):
        index -= 1
    if index == 0:
        return 0
    let letters = word_character(document.scalar(index - 1))
    while index > 0 and not whitespace(document.scalar(index - 1)) and word_character(document.scalar(index - 1)) == letters:
        index -= 1
    return index

pub func word_right(document: const Document*, position: usize) -> usize:
    var index = position
    if index < document.length():
        let letters = word_character(document.scalar(index))
        while index < document.length() and not whitespace(document.scalar(index)) and word_character(document.scalar(index)) == letters:
            index += 1
    while index < document.length() and whitespace(document.scalar(index)):
        index += 1
    return index

## Select the run at `position` for a double-click: a word of letters, or a run of
## whitespace, or a run of punctuation, whichever the position sits on.
pub func select_word(document: Document*, position: usize) -> !:
    let length = document.length()
    if length == 0:
        try document.select(0, 0)
        return
    let pivot = position if position < length else length - 1
    let target = document.scalar(pivot)
    var start = pivot
    var end = pivot + 1
    if whitespace(target):
        while start > 0 and whitespace(document.scalar(start - 1)):
            start -= 1
        while end < length and whitespace(document.scalar(end)):
            end += 1
    else:
        let letters = word_character(target)
        while start > 0 and not whitespace(document.scalar(start - 1)) and word_character(document.scalar(start - 1)) == letters:
            start -= 1
        while end < length and not whitespace(document.scalar(end)) and word_character(document.scalar(end)) == letters:
            end += 1
    try document.select(start, end)

pub func erase(document: Document*, backwards: bool, word: bool = false) -> !:
    if document.first() == document.last():
        let caret = document.caret()
        if backwards:
            if caret == 0:
                return
            try document.replace(word_left(document, caret) if word else caret - 1, caret, "")
        else:
            if caret == document.length():
                return
            try document.replace(caret, word_right(document, caret) if word else caret + 1, "")
    else:
        try document.insert("")

pub func newline(document: Document*) -> !:
    let position = document.first()
    let start = document.line_start(position)
    var end = start
    while end < position and (document.scalar(end) == 32 or document.scalar(end) == 9):
        end += 1
    let indentation = try document.text(start, end)
    defer indentation.release()
    with memory.heap:
        var value: collections.Buffer
        defer value.destroy()
        try value.put_text("\n")
        try value.put_text(indentation.value)
        if position > start and document.scalar(position - 1) == 58:
            try value.put_text("    ")
        try document.insert(value.text())

pub func indent(document: Document*, backwards: bool) -> !:
    let selected = document.first() != document.last()
    if not selected and not backwards:
        var no_chips: Swatch[]
        let width = 4 - column(document, document.caret(), no_chips) % 4
        let spaces = "    "
        try document.insert((str)spaces.bytes[..<width])
        return
    let start = document.line_start(document.first())
    var end = document.line_end(document.last())
    if selected and document.last() > start and document.line_start(document.last()) == document.last():
        end = document.last() - 1
    let original_anchor = document.anchor()
    let original_caret = document.caret()
    with memory.heap:
        var value: collections.Buffer
        defer value.destroy()
        var row = start
        var first_removed: usize = 0
        while row <= end:
            let finish = document.line_end(row)
            var content = row
            if backwards:
                if content < finish and document.scalar(content) == 9:
                    content += 1
                else:
                    while content < finish and content - row < 4 and document.scalar(content) == 32:
                        content += 1
                if row == start:
                    first_removed = content - row
            else:
                try value.put_text("    ")
            let line = try document.text(content, finish)
            defer line.release()
            try value.put_text(line.value)
            if finish >= end:
                break
            try value.put_text("\n")
            row = finish + 1
        try document.replace(start, end, value.text())
        let replacement_end = document.caret()
        if selected:
            try document.complete_selection(start, replacement_end)
        else:
            let anchor = original_anchor - first_removed if original_anchor >= start + first_removed else start
            let caret = original_caret - first_removed if original_caret >= start + first_removed else start
            try document.complete_selection(anchor, caret)

## The display column of `position`. `swatches` are the color chips that reserve
## `swatch_span` cells each before their offset (empty when soft-wrap is on, so the
## chips do not shift text); a chip at `position` itself sits left of the caret.
pub func column(document: const Document*, position: usize, swatches: const Swatch[]) -> usize:
    var width: usize = 0
    for index in document.line_start(position)..<position:
        if has_swatch(swatches, index):
            width += swatch_span
        width += grid(document.scalar(index), width)
    if has_swatch(swatches, position):
        width += swatch_span
    return width

## The offset on the line starting at `start` whose caret sits at or before display column `requested`:
## a wide scalar the column falls inside keeps the caret before it, and zero-width
## marks are passed over with their base. Vertical moves keep their column this way.
pub func at_column(document: const Document*, start: usize, requested: usize, swatches: const Swatch[]) -> usize:
    return locate(document, start, (f64)requested, false, swatches)

## The offset on the line starting at `start` whose caret boundary is nearest the
## fractional display column `x`: a click past a scalar's middle (a wide one's
## included) lands after it. Callers pass the start the projection keeps, so a
## drag or hover never counts lines from the top of the document.
pub func at_x(document: const Document*, start: usize, x: f64, swatches: const Swatch[]) -> usize:
    return locate(document, start, x, true, swatches)

## Walk the line starting at `start` to `requested` columns: with `nearest`, to the
## closest boundary, otherwise to the last one not past it. Shared so both agree
## with `column`.
func locate(document: const Document*, start: usize, requested: f64, nearest: bool, swatches: const Swatch[]) -> usize:
    var index = start
    var width: usize = 0
    while index < document.length() and document.scalar(index) != 10:
        var before = width
        if has_swatch(swatches, index):
            before += swatch_span
            if not nearest and (f64)before > requested:
                break
        let cells = grid(document.scalar(index), before)
        if nearest:
            if cells > 0 and requested < (f64)before + (f64)cells * 0.5:
                break
        elif (f64)(before + cells) > requested:
            break
        width = before + cells
        index += 1
    return index

## Whether a chip sits at `offset`. Swatches are ordered by ascending offset; the
## lists are short (a handful of colors per view), so a linear scan is ample.
func has_swatch(swatches: const Swatch[], offset: usize) -> bool:
    for swatch in swatches:
        if swatch.offset == (i64)offset:
            return true
        if swatch.offset > (i64)offset:
            return false
    return false

pub func normalize_lines(text: str) -> interop.Owned[str]!:
    with memory.heap:
        var value: collections.Buffer
        defer value.destroy()
        var index: usize = 0
        while index < text.length:
            if text.bytes[index] == 13:
                try value.put_text("\n")
                if index + 1 < text.length and text.bytes[index + 1] == 10:
                    index += 1
            else:
                _ = try value.write(text.bytes[index..<index + 1])
            index += 1
        return try interop.copy_text(value.text())

func whitespace(scalar: u32) -> bool:
    return scalar == 32 or scalar == 9 or scalar == 10 or scalar == 13

## Whether `scalar` belongs to a word: ASCII letters and digits, `_`, and any
## non-ASCII scalar. Completion and hover use the same words.
pub func word_character(scalar: u32) -> bool:
    return ((scalar >= 65 and scalar <= 90) or (scalar >= 97 and scalar <= 122) or (scalar >= 48 and scalar <= 57) or scalar == 95 or scalar >= 128)

test "indentation and deletion restore selections on undo":
    var document = try Document("alpha\n    beta\ngamma")
    defer document.close()
    try document.select(0, 15)
    try indent(&document, false)
    let indented = try document.text()
    defer indented.release()
    assert(indented.value == "    alpha\n        beta\ngamma")
    assert(try document.undo())
    assert(document.anchor() == 0 and document.caret() == 15)
    assert(try document.redo())
    try indent(&document, true)
    let restored = try document.text()
    defer restored.release()
    assert(restored.value == "alpha\n    beta\ngamma")
    try document.select(1, 1)
    try erase(&document, true)
    assert(try document.undo())
    assert(document.anchor() == 1 and document.caret() == 1)

test "newline and Unicode word commands preserve scalar boundaries":
    var document = try Document("    if ready:")
    defer document.close()
    try document.select(document.length(), document.length())
    try newline(&document)
    let text = try document.text()
    defer text.release()
    assert(text.value == "    if ready:\n        ")
    try document.set_text("héllo 世界")
    assert(word_left(&document, document.length()) == 6)
    assert(word_right(&document, 0) == 6)
    let normalized = try normalize_lines("one\r\ntwo\rthree\n")
    defer normalized.release()
    assert(normalized.value == "one\ntwo\nthree\n")

test "select_word spans a word, a run of spaces, or punctuation":
    var document = try Document("hi  there(x)")
    defer document.close()
    try select_word(&document, 1)
    let word = try document.text(document.first(), document.last())
    defer word.release()
    assert(word.value == "hi")
    try select_word(&document, 3)
    let spaces = try document.text(document.first(), document.last())
    defer spaces.release()
    assert(spaces.value == "  ")
    try select_word(&document, 5)
    let other = try document.text(document.first(), document.last())
    defer other.release()
    assert(other.value == "there")
    try select_word(&document, 9)
    let punctuation = try document.text(document.first(), document.last())
    defer punctuation.release()
    assert(punctuation.value == "(")