summaryrefslogtreecommitdiff
path: root/src/File.zig
diff options
context:
space:
mode:
Diffstat (limited to 'src/File.zig')
-rw-r--r--src/File.zig118
1 files changed, 96 insertions, 22 deletions
diff --git a/src/File.zig b/src/File.zig
index dc7b4cf8..5150f1cd 100644
--- a/src/File.zig
+++ b/src/File.zig
@@ -2,7 +2,7 @@
//! index, syntax highlights and the body it fills.
const panes = @import("panes.zig");
const std = @import("std");
-const vaxis = @import("vaxis");
+const uucode = @import("uucode");
const builtin = @import("builtin");
const pardes = @import("pardes.zig");
const config = @import("config.zig");
@@ -59,12 +59,31 @@ pub const History = struct {
}
};
+/// Owned syntax results. Excluded from dumps as State.context is derived.
+pub const ContextCache = struct {
+ allocator: ?std.mem.Allocator = null,
+ declarations: []syntax.ContextDeclaration = &.{},
+ revision: ?u32 = null,
+
+ pub fn deinit(self: *ContextCache) void {
+ if (self.allocator) |gpa| gpa.free(self.declarations);
+ self.* = .{};
+ }
+
+ /// Takes ownership of declarations allocated by gpa.
+ pub fn replace(self: *ContextCache, gpa: std.mem.Allocator, declarations: []syntax.ContextDeclaration, revision: u32) void {
+ self.deinit();
+ self.* = .{ .allocator = gpa, .declarations = declarations, .revision = revision };
+ }
+};
+
/// A file pane's backing: owned content, its derived caches, and undo history.
pub const State = struct {
/// What the replay digest leaves out (src/walk.zig): what is made again
/// from the text whenever it is wanted.
+ // Syntax caches must not load through the dump loader's core allocator.
pub const replica = .{
- .derived = .{ "cap", "line_starts", "line_cap", "highlights", "highlight_start", "syntax_dirty", "node_tree", "node_tree_revision", "node_tree_edits", "node_history", "tables" },
+ .derived = .{ "cap", "line_starts", "line_cap", "highlights", "highlight_start", "syntax_dirty", "context", "node_tree", "node_tree_revision", "node_tree_edits", "node_history", "tables" },
// Big texts, dumped and sent by their hash (src/walk.zig). The
// text is written in place by `replace`, but never while a join
// sends it (memory.zig `pin`): then an edit puts a new buffer in
@@ -136,8 +155,7 @@ pub const State = struct {
highlight_start: usize = 0,
syntax_dirty: bool = true,
tree_context: bool = false,
- context_declarations: []syntax.ContextDeclaration = &.{},
- context_revision: ?u32 = null,
+ context: ContextCache = .{},
/// The whole file's parse for the keys that walk its nodes (Alt-o and
/// kin), made on the first of them after an edit and kept until the next
/// one: `syntax.parseTree`'s, opaque here.
@@ -168,10 +186,8 @@ pub const NodeStep = struct { ranges: []modal.Selection, primary: usize };
pub fn graphemeDisplayWidth(grapheme: []const u8) usize {
if (std.mem.eql(u8, grapheme, "\t")) return config.tab_now;
if (grapheme.len == 1 and grapheme[0] >= 0x20 and grapheme[0] < 0x7f) return 1;
- if (std.unicode.utf8ValidateSlice(grapheme)) return @max(1, @as(usize, vaxis.gwidth.gwidth(grapheme, .unicode)));
- // vaxis's gwidth counts back a replacement rune's 3 bytes over the one
- // invalid byte it stood for (`\xee` before `e\u{301}` overflowed it):
- // each invalid byte is a cell, as surface.zig draws it, and each valid
+ if (std.unicode.utf8ValidateSlice(grapheme)) return @max(1, @as(usize, utf8Width(grapheme)));
+ // Each invalid byte is a cell, as surface.zig draws it, and each valid
// run between is measured alone.
var width: usize = 0;
var run: usize = 0;
@@ -182,15 +198,60 @@ pub fn graphemeDisplayWidth(grapheme: []const u8) usize {
i += n;
continue;
}
- if (run < i) width += vaxis.gwidth.gwidth(grapheme[run..i], .unicode);
+ if (run < i) width += utf8Width(grapheme[run..i]);
width += 1;
i += 1;
run = i;
}
- if (run < grapheme.len) width += vaxis.gwidth.gwidth(grapheme[run..], .unicode);
+ if (run < grapheme.len) width += utf8Width(grapheme[run..]);
return @max(1, width);
}
+/// The cells valid UTF-8 takes, summed over its graphemes: a grapheme is
+/// as wide as its widest code point (a control, a nonspacing or enclosing
+/// mark and the joiners, selectors and other format characters below add
+/// none; East Asian wide and fullwidth two, the rest one), then at least
+/// one under the text selector U+FE0E, else at least two under the emoji
+/// selector U+FE0F, with an emoji-presentation code point, or as a flag's
+/// two regional indicators. It is libvaxis's `gwidth(.unicode)` over the
+/// same uucode tables, which the tui renders with in mode 2027.
+pub fn utf8Width(valid: []const u8) u16 {
+ var total: u16 = 0;
+ var widest: u16 = 0;
+ var text_vs = false;
+ var emoji = false;
+ var flags: u8 = 0;
+ var it = uucode.grapheme.utf8Iterator(valid);
+ while (it.nextCodePoint()) |r| {
+ const cp = r.code_point;
+ if (cp == 0xfe0e) {
+ text_vs = true;
+ } else if (cp == 0xfe0f) {
+ emoji = true;
+ } else {
+ if (uucode.get(.is_emoji_presentation, cp)) emoji = true;
+ if (cp >= 0x1f1e6 and cp <= 0x1f1ff) flags += 1;
+ widest = @max(widest, @as(u16, switch (cp) {
+ 0...0x1f, 0x7f...0x9f, 0xad, 0x34f, 0x180b...0x180d, 0x200b...0x200d, 0x2060, 0xfe00...0xfe0d, 0xfeff, 0xe0100...0xe01ef => 0,
+ else => switch (uucode.get(.general_category, cp)) {
+ .mark_nonspacing, .mark_enclosing => 0,
+ else => switch (uucode.get(.east_asian_width, cp)) {
+ .fullwidth, .wide => 2,
+ else => 1,
+ },
+ },
+ }));
+ }
+ if (!r.is_break) continue;
+ total += if (text_vs) @max(1, widest) else if (emoji or flags == 2) @max(2, widest) else widest;
+ widest = 0;
+ text_vs = false;
+ emoji = false;
+ flags = 0;
+ }
+ return total;
+}
+
pub fn displayWidth(text: []const u8) usize {
var width: usize = 0;
var at: usize = 0;
@@ -576,7 +637,7 @@ pub fn deinit(p: *Pardes, pane: *Pane, file: *State) void {
if (file.highlights.len > 0) p.tree_sitter_gpa.free(file.highlights);
p.gpa.free(file.pager_spans);
locations.freeRows(p.gpa, file.location_rows);
- if (file.context_declarations.len > 0) p.tree_sitter_gpa.free(file.context_declarations);
+ file.context.deinit();
if (file.node_tree) |tree| syntax.freeTree(tree);
for (file.node_history.items) |step| p.gpa.free(step.ranges);
file.node_history.deinit(p.gpa);
@@ -1463,11 +1524,9 @@ pub fn changed(p: *Pardes, id: u8, bytes: []const u8) void {
/// its text as it is now: found in the step (Pardes.sync), never only by a
/// render, since the view's geometry is made of them (`geometry`).
pub fn refreshContext(p: *Pardes, pane: *Pane, f: *State) void {
- if (!f.tree_context or !supportsContext(pane) or f.context_revision == f.revision) return;
+ if (!f.tree_context or !supportsContext(pane) or f.context.revision == f.revision) return;
const declarations = syntax.contextDeclarations(p.tree_sitter_gpa, f.path, f.content) catch return;
- if (f.context_declarations.len > 0) p.tree_sitter_gpa.free(f.context_declarations);
- f.context_declarations = declarations;
- f.context_revision = f.revision;
+ f.context.replace(p.tree_sitter_gpa, declarations, f.revision);
}
pub fn refreshHighlights(p: *Pardes) void {
@@ -1585,7 +1644,7 @@ fn prepareContextRows(pane: *Pane, file: *State) void {
pane.context_rows = 0;
if (!file.tree_context or !supportsContext(pane) or pane.rows > pane.wrap_line.len) return;
const capacity = @min(pane.rows -| 1, pane.context_row_limit orelse std.math.maxInt(u16)); // retain an ordinary body row
- for (file.context_declarations) |declaration| {
+ for (file.context.declarations) |declaration| {
if (declaration.start_line >= file.scroll) break;
if (declaration.end_line < file.scroll) continue;
var row = declaration.start_line;
@@ -1676,8 +1735,8 @@ fn geometryKey(pane: *const Pane, f: *const State) u64 {
f.revision, f.content.len, f.scroll, pane.hscroll,
pane.rows, pane.cols, pane.tag_rows, pane.collapsed,
pane.query != null, f.pager, f.mini != null, f.output != null,
- if (f.output) |o| pardes.walk.digest(Output.Origin, &o.from) else 0, std.hash.Wyhash.hash(0, f.path), f.tree_context, f.context_revision orelse 0,
- f.context_declarations.len, f.line_starts.len, t.revision orelse 0, t.list.items.len,
+ if (f.output) |o| pardes.walk.digest(Output.Origin, &o.from) else 0, std.hash.Wyhash.hash(0, f.path), f.tree_context, f.context.revision orelse 0,
+ f.context.declarations.len, f.line_starts.len, t.revision orelse 0, t.list.items.len,
if (t.pending) |r| r.at else std.math.maxInt(usize), pane.view.wrap, pane.view.layered, pane.view.body_h,
pane.view.tagline_h, pane.view.rect_h,
};
@@ -2190,7 +2249,7 @@ pub fn paintWordSelection(
}
}
-test "an invalid byte in a grapheme is one cell, and never reaches vaxis's width" {
+test "an invalid byte in a grapheme is one cell, and never reaches utf8Width" {
try std.testing.expectEqual(@as(usize, 2), graphemeDisplayWidth("\xeee\xcc\x81"));
try std.testing.expectEqual(@as(usize, 3), graphemeDisplayWidth("\xee\xffe"));
try std.testing.expectEqual(@as(usize, 3), graphemeDisplayWidth("\u{4e16}\x80"));
@@ -2229,11 +2288,11 @@ test "indexed source rows match uncached scans across content changes" {
}
}
-test "the ASCII arm of graphemeDisplayWidth matches the gwidth it skips" {
+test "the ASCII arm of graphemeDisplayWidth matches the utf8Width it skips" {
const ref = struct {
fn width(grapheme: []const u8) usize {
if (std.mem.eql(u8, grapheme, "\t")) return config.tab_now;
- return @max(1, @as(usize, vaxis.gwidth.gwidth(grapheme, .unicode)));
+ return @max(1, @as(usize, utf8Width(grapheme)));
}
}.width;
@@ -2248,7 +2307,7 @@ test "the ASCII arm of graphemeDisplayWidth matches the gwidth it skips" {
"\u{1f642}", "\u{1f1e6}\u{1f1e7}", "\xff",
}) |g| try std.testing.expectEqual(ref(g), graphemeDisplayWidth(g));
// Two invalid bytes are two cells, as surface.zig draws them, where
- // vaxis's own count gives the pair one.
+ // one U+FFFD for the pair would give one.
try std.testing.expectEqual(@as(usize, 2), graphemeDisplayWidth("\xe4\xb8"));
}
@@ -2640,3 +2699,18 @@ test "undo keeps its steps within a byte bound, the newest always" {
try std.testing.expect(std.mem.allEqual(u8, f.content[step / 2 ..][0..step], f.content[step / 2]));
}
}
+
+test "context cache frees each allocation with its original allocator" {
+ var first: std.heap.DebugAllocator(.{}) = .init;
+ defer std.testing.expect(first.deinit() == .ok) catch @panic("first allocator leaked");
+ var second: std.heap.DebugAllocator(.{}) = .init;
+ defer std.testing.expect(second.deinit() == .ok) catch @panic("second allocator leaked");
+ var cache: ContextCache = .{};
+ defer cache.deinit();
+ cache.replace(first.allocator(), try first.allocator().alloc(syntax.ContextDeclaration, 1), 1);
+ cache.replace(second.allocator(), try second.allocator().alloc(syntax.ContextDeclaration, 2), 2);
+ try std.testing.expectEqual(@as(?u32, 2), cache.revision);
+ cache.deinit();
+ try std.testing.expect(cache.allocator == null);
+ try std.testing.expectEqual(@as(usize, 0), cache.declarations.len);
+}