Something went wrong. Try again.
Ron's Dynamic EDitor
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851package ded
import hm "core:container/handle_map"import "core:log"import "core:mem"import vmem "core:mem/virtual"import "core:slice"import "core:strings"import "core:testing"import "core:unicode/utf8"
Buffer_Handle :: distinct hm.Handle64
Buffer :: struct { handle: Buffer_Handle, name: string, path: Maybe(string), // FIXME: `path` should be a buffer-local thing, not part of coree options: Buffer_Options,
// internal version: u64, allocator: mem.Allocator, arena: vmem.Arena, buf: []byte, gap_start, gap_end: int, line_starts: [dynamic]int,}
Buffer_Options :: struct { tab_width: int,}
DEFAULT_BUFFER_OPTIONS :: Buffer_Options { tab_width = 4,}
buffer_init :: proc( b: ^Buffer, name: string, path: Maybe(string) = nil, options: Buffer_Options = DEFAULT_BUFFER_OPTIONS, allocator := context.allocator,) -> ( err: mem.Allocator_Error,) { defer if err != nil { log.debugf("buffer init failed: {}", err) buffer_destroy(b) }
b.allocator = allocator b.name = strings.clone(name, allocator) or_return if p, ok := path.?; ok { b.path = strings.clone(p, allocator) or_return } b.options = options
vmem.arena_init_static(&b.arena) or_return b.line_starts = make([dynamic]int, 0, mem.Kilobyte, allocator) or_return append(&b.line_starts, 0)
log.debug("buffer: initialized")
return}
buffer_destroy :: proc(b: ^Buffer) { log.debugf("buffer: destroyed ({} bytes)", buffer_len(b)) vmem.arena_destroy(&b.arena) delete(b.line_starts) delete(b.name, b.allocator) if path, ok := b.path.?; ok { delete(path, b.allocator) } b^ = {}}
// Replaces the bytes in the exclusive range of [from, to) with `text`.// Empty `text` means remove, and an empty range means insert.@(private = "file")buffer_replace :: proc(b: ^Buffer, from, to: int, text: string) { old_len := buffer_len(b) lo, hi := clamp(from, 0, old_len), clamp(to, 0, old_len) if lo > hi {lo, hi = hi, lo} if lo != from || hi != to { log.debugf("[{}, {}), normalized to [{}, {})", from, to, lo, hi) }
removed := hi - lo if removed == 0 && len(text) == 0 {return}
when ODIN_DEBUG { log.assertf(is_valid_offset(b, lo), "offset `lo` {} is not a rune boundary (len {})", lo, old_len) log.assertf(is_valid_offset(b, hi), "offset `hi` {} is not a rune boundary (len {})", hi, old_len) }
buffer_shift(b, lo)
b.gap_end += removed reserve_gap(b, len(text))
copy(b.buf[b.gap_start:], text) b.gap_start += len(text)
log.debugf("replaced [{}, {}) with {}B (len {} -> {})", lo, hi, len(text), old_len, buffer_len(b)) return}
@(private = "file")buffer_chunks :: proc(b: ^Buffer, from, to: int) -> (left, right: string) { l, r := string(b.buf[:b.gap_start]), string(b.buf[b.gap_end:]) if to <= b.gap_start { return l[from:to], "" } else if from >= b.gap_start { return r[from - b.gap_start:to - b.gap_start], "" } else { return l[from:], r[:to - b.gap_start] }}
@(private = "file")reindex_line_starts :: proc(b: ^Buffer, first_off: int) { row := buffer_offset_to_line(b, first_off) err := resize(&b.line_starts, row + 1) log.assertf(err == nil, "allocator error: {}", err) start := clamp(first_off, b.line_starts[row], buffer_len(b))
append_line_starts :: proc(b: ^Buffer, text: string, base: int) { for i in 0 ..< len(text) { if text[i] == '\n' { _, err := append(&b.line_starts, base + i + 1) log.assert(err == nil, "allocator error") } } }
a, c := buffer_chunks(b, start, buffer_len(b)) append_line_starts(b, a, start) append_line_starts(b, c, b.gap_start) // empty when the range doesn't cross the gap}
// Incrementally updates the line index after the range `[from, to)` was replaced with text that is// `delta` bytes longer, so `to + delta` is the end of the replacement in the new buffer.//// Unlike `reindex_line_starts`, this only looks at the bytes of the edit and then shifts the line// starts that follow it, instead of rescanning the rest of the buffer.@(private = "file")reindex_line_starts_range :: proc(b: ^Buffer, from, to, delta: int) { // Starts at or before `from` are untouched by the edit. lo := search_line_index(b, from) + 1 // Starts in `(from, to]` pointed at text that the edit removed. hi := lo for hi < len(b.line_starts) && b.line_starts[hi] <= to { hi += 1 }
log.assertf( to + delta <= buffer_len(b) && from <= to + delta, "range [{}, {}) + delta {} is outside the buffer (len {}), gap [{}, {})", from, to, delta, buffer_len(b), b.gap_start, b.gap_end, ) x, y := buffer_chunks(b, from, to + delta) inserted := strings.count(x, "\n") + strings.count(y, "\n")
old_count := len(b.line_starts) target := lo + inserted + (old_count - hi) if target > old_count { err := resize(&b.line_starts, target) log.assertf(err == nil, "allocator error: {}", err) }
// The untouched suffix keeps its contents, but its offsets move with the edit. When the index // shrinks, move the suffix before truncating so its old indices are still valid. copy(b.line_starts[lo + inserted:], b.line_starts[hi:old_count]) if target < old_count { err := resize(&b.line_starts, target) log.assertf(err == nil, "allocator error: {}", err) } for i in lo + inserted ..< target { b.line_starts[i] += delta }
// Fill in the starts created by the replacement. `y` begins at the gap, which is a text offset. i := lo for c, off in x { if c == '\n' { b.line_starts[i] = from + off + 1 i += 1 } } for c, off in y { if c == '\n' { b.line_starts[i] = b.gap_start + off + 1 i += 1 } } log.assertf(i == lo + inserted, "wrote {} line starts, found {} newlines", i - lo, inserted)}
buffer_offset_to_line :: proc(b: ^Buffer, off: int) -> int { if off < 0 || off > buffer_len(b) { log.debugf("offset_to_point: offset {} out of range 0..={}", off, buffer_len(b)) }
clamped := clamp(off, 0, buffer_len(b)) return search_line_index(b, clamped)}
buffer_offset_to_point :: proc(b: ^Buffer, off: int) -> Point { clamped := clamp(off, 0, buffer_len(b)) row := buffer_offset_to_line(b, off) return {row = row, col = line_display_col(b, row, clamped)}}
buffer_point_to_offset :: proc(b: ^Buffer, p: Point) -> int { row := clamp(p.row, 0, buffer_line_count(b) - 1) line_start := b.line_starts[row] line_end := buffer_line_end(b, row) if p.col <= 0 {return line_start}
col := 0 it := buffer_iterator(b, line_start) for g, off in buffer_iterate(&it) { if off >= line_end {break} if is_nl(g.text) {break}
width := display_width(g, col, b.options.tab_width) if col + width > p.col {return off} if col + width == p.col {return off + len(g.text)} col += width }
return line_end}
@(private = "file")line_display_col :: proc(b: ^Buffer, row, off: int) -> int { target := clamp(off, buffer_line_start(b, row), buffer_line_end(b, row)) col := 0
it := buffer_iterator(b, buffer_line_start(b, row)) for g, g_off in buffer_iterate(&it) { if g_off >= target {break} if is_nl(g.text) {break} col += display_width(g, col, b.options.tab_width) }
return col}
@(private = "file")search_line_index :: proc(b: ^Buffer, off: int) -> int { i, found := slice.binary_search(b.line_starts[:], off) return max(i if found else i - 1, 0)}
Buffer_Iterator :: struct { b: ^Buffer, data: string, // Contiguous view of the buffer's contents. off: int, // The offset that the next iteration starts from.}
// The buffer must never be invalidated during iteration.buffer_iterator :: proc(b: ^Buffer, off := 0) -> Buffer_Iterator { buffer_shift_contiguous(b) return {b = b, data = buffer_text(b), off = clamp(off, 0, buffer_len(b))}}
buffer_iterate :: proc(it: ^Buffer_Iterator) -> (grapheme: utf8.Grapheme, off: int, ok: bool) { if it.off >= len(it.data) {return} git := utf8.decode_grapheme_iterator_make(it.data[it.off:]) _, grapheme, ok = utf8.decode_grapheme_iterate(&git) off = it.off it.off += len(grapheme.text) return}
buffer_iterate_back :: proc(it: ^Buffer_Iterator) -> (grapheme: utf8.Grapheme, off: int, ok: bool) { if it.off <= 0 {return} lo := buffer_line_start(it.b, search_line_index(it.b, it.off - 1))
// Walk back to a certain grapheme boundary, then segment forward up to it.off. b, n := utf8.decode_last_rune_in_string(it.data[lo:it.off]) off = it.off - n for off > lo { a, m := utf8.decode_last_rune_in_string(it.data[lo:off]) if is_boundary_between(a, b) {break} off -= m b = a } git := utf8.decode_grapheme_iterator_make(it.data[off:it.off]) for _, g in utf8.decode_grapheme_iterate(&git) {grapheme = g} off += grapheme.byte_index grapheme.byte_index = 0 it.off = off return grapheme, off, true}
@(private = "file")buffer_shift :: proc(b: ^Buffer, off: int) { if off < 0 || off > buffer_len(b) { log.errorf("buffer_shift: offset {} out of range 0..={}", off, buffer_len(b)) return }
if off == b.gap_start {return}
gap := gap_len(b) if off < b.gap_start { n := b.gap_start - off copy(b.buf[b.gap_end - n:], b.buf[off:b.gap_start]) } else if off > b.gap_start { n := off - b.gap_start copy(b.buf[b.gap_start:], b.buf[b.gap_end:b.gap_end + n]) }
b.gap_start = off b.gap_end = off + gap}
@(private = "file")buffer_shift_contiguous :: proc(b: ^Buffer) { dist_start, dist_end := b.gap_start, len(b.buf) - b.gap_end if dist_start == 0 || dist_end == 0 {return} if dist_start < dist_end { buffer_shift(b, 0) } else { buffer_shift(b, buffer_len(b)) }}
@(private = "file")buffer_text :: proc(b: ^Buffer) -> string { if b.gap_start == 0 { return string(b.buf[b.gap_end:]) } else if b.gap_start == buffer_len(b) { return string(b.buf[:b.gap_start]) } else { log.panic("buffer contents are not contiguous") }}
buffer_clear :: proc(b: ^Buffer) { log.debugf("buffer cleared ({} bytes)", buffer_len(b)) b.gap_start = 0 b.gap_end = len(b.buf) clear(&b.line_starts) append(&b.line_starts, 0)}
buffer_len :: proc(b: ^Buffer) -> int {return len(b.buf) - gap_len(b)}buffer_line_count :: proc(b: ^Buffer) -> int {return len(b.line_starts)}buffer_line_start :: proc(b: ^Buffer, row: int) -> int {return b.line_starts[row]}buffer_line_end :: proc(b: ^Buffer, row: int) -> int { if row + 1 < len(b.line_starts) { return b.line_starts[row + 1] - 1 } return buffer_len(b)}
// Checks whether byte offset `off` is a rune boundary, meaning that it's// not pointing to an invalid character (like in the middle of a rune).@(private = "file")is_valid_offset :: proc(b: ^Buffer, off: int) -> bool { if off <= 0 || off >= buffer_len(b) {return true}
index := off if off >= b.gap_start { gap_size := b.gap_end - b.gap_start index = off + gap_size }
return b.buf[index] & 0xC0 != 0x80}
@(private = "file")reserve_gap :: proc(b: ^Buffer, needed: int) { if gap_len(b) >= needed {return}
old_cap := len(b.buf) min_cap := buffer_len(b) + needed new_cap := max(old_cap + min(old_cap, 64 * mem.Megabyte), min_cap, 64) allocator := vmem.arena_allocator(&b.arena) new_buf, resize_err := mem.resize_bytes(b.buf, new_cap, allocator = allocator) if resize_err == .Out_Of_Memory && new_cap > min_cap { new_cap = min_cap new_buf, resize_err = mem.resize_bytes(b.buf, new_cap, allocator = allocator) } log.assertf(resize_err == nil, "allocator error: {}", resize_err) when ODIN_DEBUG { log.assert( old_cap == 0 || raw_data(new_buf) == raw_data(b.buf), "reserve_gap: buf moved, but something else allocated from the arena", ) }
after := old_cap - b.gap_end copy(new_buf[new_cap - after:], b.buf[b.gap_end:old_cap]) b.buf = new_buf b.gap_end = new_cap - after
return}
@(private = "file")gap_len :: proc(b: ^Buffer) -> int {return b.gap_end - b.gap_start}
// Very much inspired by Helix's design, although simplifiedChange :: struct { from, to: int, // byte offsets in buffer text: string, // replacement text. "" means delete // TODO: _removed: string, // filled when change is applied. used for change inversion}
// An ordered and disjoint set of changes to a buffer.Change_Set :: struct { changes: [dynamic]Change,}
// Appends a change. Asserts the changeset stays ordered and disjoint.@(private)change_set_append :: proc(cs: ^Change_Set, c: Change) { when ODIN_DEBUG { if n := len(cs.changes); n > 0 { last := cs.changes[n - 1] log.assertf(c.from >= last.to, "change starts at {}, but the previous change ends at {}", c.from, last.to) } log.assertf(c.from <= c.to, "change from {} > to {}", c.from, c.to) }
_, err := append(&cs.changes, c) log.assertf(err == nil, "allocation error: {}", err)}
// Applies the changes and rebuilds the line index.// Returns false when the changeset doesn't fit the buffer.change_set_apply :: proc(cs: ^Change_Set, b: ^Buffer) -> bool { if len(cs.changes) == 0 {return true} if cs.changes[len(cs.changes) - 1].to > buffer_len(b) {return false}
delta := 0 for c in cs.changes { from, to := c.from + delta, c.to + delta buffer_replace(b, from, to, c.text) delta += len(c.text) - (to - from) }
reindex_line_starts_range(b, cs.changes[0].from, cs.changes[len(cs.changes) - 1].to, delta)
return true}
Change_Assoc :: enum { Before, // bias towards the start of the change After, // bias towards the end of the change}
// Map an offset through a changeset.@(private)change_set_map_off :: proc(cs: ^Change_Set, off: int, assoc: Change_Assoc) -> int { delta := 0 for c in cs.changes { if off < c.from {break}
inserted, removed := len(c.text), c.to - c.from
if off > c.to { delta += inserted - removed continue } else if off == c.from { // `.Before` maps to start of the change, `.After` maps to after inserted text return c.from + delta + (assoc == .After ? inserted : 0) } else if off == c.to { return c.from + delta + inserted // after changed text } else { // strictly inside replaced or deleted text return c.from + delta + (assoc == .After ? inserted : 0) } }
return off + delta}
Transaction :: struct { change_set: Change_Set,}
transaction_destroy :: proc(tx: ^Transaction) { delete(tx.change_set.changes) tx^ = {}}
transaction_change :: proc(tx: ^Transaction, from, to: int, text: string) { change_set_append(&tx.change_set, {from = from, to = to, text = text})}
transaction_delete :: proc(tx: ^Transaction, from, to: int) { change_set_append(&tx.change_set, {from = from, to = to})}
transaction_insert :: proc(tx: ^Transaction, off: int, text: string) { transaction_change(tx, off, off, text)}
@(private = "file")test_expect_contents :: proc(t: ^testing.T, b: ^Buffer, args: ..string, loc := #caller_location) { left, right := buffer_chunks(b, 0, buffer_len(b)) s := strings.concatenate({left, right}) defer delete(s)
if len(args) == 0 { testing.expect_value(t, s, "", loc = loc) return } if len(args) == 1 { testing.expect_value(t, s, args[0], loc = loc) return } expected := strings.concatenate(args) defer delete(expected) testing.expect_value(t, s, expected, loc = loc)}
@(private = "file")test_buffer_with_gap :: proc(t: ^testing.T, b: ^Buffer, head, tail: string) { buffer_clear(b) buffer_replace(b, 0, 0, tail) buffer_replace(b, 0, 0, head) reindex_line_starts(b, 0) testing.expect_value(t, b.gap_start, len(head))}
// Checks `line_starts` against the buffer contents, so a replace that adds, removes or merges line// endings is caught even when the text itself looks right.@(private)test_expect_line_starts :: proc(t: ^testing.T, b: ^Buffer, loc := #caller_location) { left, right := buffer_chunks(b, 0, buffer_len(b)) text := strings.concatenate({left, right}) defer delete(text)
want := make([dynamic]int, 0, 16, context.temp_allocator) append(&want, 0) for c, i in text { if c == '\n' {append(&want, i + 1)} }
testing.expectf( t, slice.equal(b.line_starts[:], want[:]), "line starts {:v}, want {:v}", b.line_starts[:], want[:], loc = loc, )}
@(test)test_replace :: proc(t: ^testing.T) { b := Buffer{} buffer_init(&b, "test") defer buffer_destroy(&b)
// an empty buffer, and out of range bounds, do nothing buffer_replace(&b, 100, 200, "") test_expect_contents(t, &b) test_expect_line_starts(t, &b)
// one case per branch, each starting from `head` + `tail` with the gap sitting after `head` cases := []struct { head, tail: string, from, to: int, text, want: string, } {
// replacing, one per gap branch {"foo", "bar", 2, 4, "XX", "foXXar"}, // same length {"foo", "bar", 0, 3, "hello", "hellobar"}, // grows {"foo", "bar", 3, 4, "X", "fooXar"}, // at the gap {"foo", "bar", 1, 5, "oob", "foobr"}, // spanning it
// inserting, an empty range {"foo", "bar", 0, 0, "oh ", "oh foobar"}, // at the start {"foo", "bar", 6, 6, "!", "foobar!"}, // at the end {"foo", "bar", 3, 3, "-", "foo-bar"}, {"foo", "bar", 3, 3, "😀", "foo😀bar"}, // a whole rune
// removing, one per gap branch {"foo", "bar", 1, 2, "", "fobar"}, // before it {"foo", "bar", 1, 3, "", "fbar"}, // ending at it {"foo", "bar", 3, 5, "", "foor"}, // starting at it {"foo", "bar", 2, 5, "", "for"}, // spanning it
// bounds {"foo", "bar", 5, 1, "", "fr"}, // either order {"foo", "bar", -10, 1_000, "x", "x"}, // clamped
// line endings added, removed and merged {"a\n", "bc", 1, 3, "", "ac"}, {"a\n", "bc", 2, 2, "\n", "a\n\nbc"}, {"a\n", "bc", 0, 0, "x\n", "x\na\nbc"}, {"a\n", "bc", 1, 4, "", "a"}, {"a\n", "bc", 3, 3, "\n", "a\nb\nc"}, {"a\n", "bc", 4, 4, "\nc\nd", "a\nbc\nc\nd"}, } for c in cases { test_buffer_with_gap(t, &b, c.head, c.tail) buffer_replace(&b, c.from, c.to, c.text) test_expect_contents(t, &b, c.want) reindex_line_starts(&b, c.from) test_expect_line_starts(t, &b) }
// a replacement longer than the gap grows the buffer, and shrinking it back still works big := strings.repeat("0123456789", 100) defer delete(big) buffer_clear(&b) buffer_replace(&b, 0, 0, big) test_expect_contents(t, &b, big) reindex_line_starts(&b, 0) test_expect_line_starts(t, &b) buffer_replace(&b, 0, buffer_len(&b), "short") test_expect_contents(t, &b, "short") reindex_line_starts(&b, 0) test_expect_line_starts(t, &b)
// a same size replacement moves the gap to its end and leaves the gap as large as it was, so the // bytes after the replacement never move { test_buffer_with_gap(t, &b, "foo", "bar") gap := gap_len(&b) buffer_replace(&b, 2, 4, "XX") testing.expect_value(t, b.gap_start, 2 + len("XX")) testing.expect_value(t, gap_len(&b), gap) test_expect_contents(t, &b, "foXXar") }}
@(test)test_iterator :: proc(t: ^testing.T) { TEXT :: "a😀e\u0301b"
b := Buffer{} buffer_init(&b, "test") defer buffer_destroy(&b)
// empty buffer: both directions are exhausted { it := buffer_iterator(&b, 0) _, _, ok := buffer_iterate(&it) testing.expect(t, !ok, "next on an empty buffer should be exhausted") _, _, ok = buffer_iterate_back(&it) testing.expect(t, !ok, "prev on an empty buffer should be exhausted") }
// positions are clamped to len(text) { buffer_replace(&b, 0, 0, TEXT)
it := buffer_iterator(&b, -10) testing.expect_value(t, it.off, 0) it = buffer_iterator(&b, 1_000_000) testing.expect_value(t, it.off, buffer_len(&b)) }
// forward iteration yields grapheme clusters with byte offsets; the gap // sits in front of the "e\u0301" cluster, so the loop crosses it clusters := []struct { text: string, off: int, }{{text = "a", off = 0}, {text = "😀", off = 1}, {text = "e\u0301", off = 5}, {text = "b", off = 8}} test_buffer_with_gap(t, &b, "a😀", "e\u0301b") testing.expect_value(t, buffer_len(&b), len(TEXT)) { it := buffer_iterator(&b, 0) for want in clusters { g, off, ok := buffer_iterate(&it) testing.expect(t, ok, "next ran out early") testing.expect_value(t, g.text, want.text) testing.expect_value(t, off, want.off) } _, _, ok := buffer_iterate(&it) testing.expect(t, !ok, "next should be exhausted at the end") }
// backward iteration rescans from the line start, so check a line boundary // too; the gap sits after the "\n" { test_buffer_with_gap(t, &b, "a😀\n", "e\u0301b") // a@0, 😀@1, \n@5, e\u0301@6, b@9
it := buffer_iterator(&b, buffer_len(&b)) g, off, ok := buffer_iterate_back(&it) testing.expect(t, ok, "prev b") testing.expect_value(t, g.text, "b") testing.expect_value(t, g.width, 1) testing.expect_value(t, off, 9) g, off, ok = buffer_iterate_back(&it) testing.expect(t, ok, "prev e") testing.expect_value(t, g.text, "e\u0301") testing.expect_value(t, g.width, 1) testing.expect_value(t, off, 6) g, off, ok = buffer_iterate_back(&it) testing.expect(t, ok, "prev newline") testing.expect_value(t, g.text, "\n") testing.expect_value(t, off, 5) }}
@(test)test_offset_point_conversion :: proc(t: ^testing.T) { b := Buffer{} buffer_init(&b, "test") defer buffer_destroy(&b)
// "a😀e\u0301b" is 5 cells wide and 9 bytes long. // "世x" is 3 cells wide and 4 bytes long. TEXT :: "a😀e\u0301b\n世x" test_buffer_with_gap(t, &b, "a😀e\u0301", "b\n世x") testing.expect_value(t, buffer_len(&b), len(TEXT))
// byte offsets are converted to display columns, so wide graphemes and // combining marks don't advance the column by their byte count points := []struct { off: int, want: Point, } { {off = 0, want = {row = 0, col = 0}}, {off = 1, want = {row = 0, col = 1}}, // before 😀 {off = 5, want = {row = 0, col = 3}}, // after 😀 {off = 8, want = {row = 0, col = 4}}, // after e + combining mark {off = 9, want = {row = 0, col = 5}}, // end of the first line {off = 10, want = {row = 1, col = 0}}, // after \n {off = 13, want = {row = 1, col = 2}}, // after 世 {off = 14, want = {row = 1, col = 3}}, // end of the buffer } for p in points { testing.expect_value(t, buffer_offset_to_point(&b, p.off), p.want)
// display columns map back to the same offset when they're on a // grapheme boundary testing.expect_value(t, buffer_point_to_offset(&b, p.want), p.off) }
// converting a display column never lands in the middle of a grapheme; // columns past the end of a line clamp to the end of its contents offsets := []struct { p: Point, want: int, } { {p = {row = 0, col = 0}, want = 0}, {p = {row = 0, col = 1}, want = 1}, {p = {row = 0, col = 2}, want = 1}, // inside 😀, snap left {p = {row = 0, col = 3}, want = 5}, {p = {row = 0, col = 4}, want = 8}, {p = {row = 0, col = 5}, want = 9}, {p = {row = 0, col = 100}, want = 9}, {p = {row = 1, col = 0}, want = 10}, {p = {row = 1, col = 1}, want = 10}, // inside 世, snap left {p = {row = 1, col = 2}, want = 13}, {p = {row = 1, col = 3}, want = 14}, {p = {row = 1, col = 100}, want = 14}, {p = {row = -1, col = 0}, want = 0}, {p = {row = 100, col = 0}, want = 10}, } for o in offsets { testing.expect_value(t, buffer_point_to_offset(&b, o.p), o.want) }
// inserting an emoji advances the cursor offset by its byte count, but its // display column by its cell width buffer_clear(&b) EMOJI :: "😀" buffer_replace(&b, 0, 0, EMOJI) testing.expect_value(t, buffer_offset_to_point(&b, len(EMOJI)), Point{row = 0, col = 2})}
@(test)test_reindex_line_starts :: proc(t: ^testing.T) { b := Buffer{} buffer_init(&b, "test") defer buffer_destroy(&b)
// a stale tail is rebuilt from the row before it, without moving the gap buffer_clear(&b) buffer_replace(&b, 0, 0, "a\nbc\nd") reindex_line_starts(&b, 0) resize(&b.line_starts, 2) gap_start, gap_end := b.gap_start, b.gap_end reindex_line_starts(&b, buffer_line_start(&b, 1)) test_expect_line_starts(t, &b) testing.expect_value(t, b.gap_start, gap_start) testing.expect_value(t, b.gap_end, gap_end)}
@(test)test_transaction_apply :: proc(t: ^testing.T) { b := Buffer{} buffer_init(&b, "test") defer buffer_destroy(&b)
// a set that does not fit is refused and leaves the buffer alone { buffer_replace(&b, 0, 0, "hello")
tx: Transaction defer transaction_destroy(&tx) transaction_change(&tx, 0, 6, "x")
testing.expect(t, !change_set_apply(&tx.change_set, &b), "apply should refuse a set that does not fit") test_expect_contents(t, &b, "hello") }
// every change lands in one pass { buffer_clear(&b) buffer_replace(&b, 0, 0, "hello world")
tx: Transaction defer transaction_destroy(&tx) transaction_change(&tx, 0, 5, "hi") transaction_change(&tx, 6, 11, "there")
testing.expect(t, change_set_apply(&tx.change_set, &b), "apply should succeed") test_expect_contents(t, &b, "hi there") test_expect_line_starts(t, &b) testing.expect_value(t, b.gap_start, len("hi there")) }
// later changes are shifted by the size difference of earlier ones { buffer_clear(&b) buffer_replace(&b, 0, 0, "a\nbc\nd") reindex_line_starts(&b, 0)
tx: Transaction defer transaction_destroy(&tx) transaction_change(&tx, 1, 4, "X\nY") transaction_insert(&tx, 6, "Z")
testing.expect(t, change_set_apply(&tx.change_set, &b), "apply should succeed") test_expect_contents(t, &b, "aX\nY\ndZ") test_expect_line_starts(t, &b) }}