From 54cd21e1bd487276142e3b1d62f1556f05b7f978 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 26 Nov 2026 02:04:56 -0300 Subject: gui, tui, macos, surface, draw: the frontends' colours from the chrome (the themes programme's L2e; DESIGN.md R1, R6, R11, R15, G1'): the window's one null page and text are colors.null_page and null_text (gui.zig's own bg_default and fg_default, the same values written twice, deleted; the tty's trail ink the same constant where it wrote #cccccc again); SGR faint in a window is its ink toward its own ground to the dim floor, 3.5:1 (R15; a terminal's faint on the page's text is the page's dim ink already, L2d's), where it was the ink at 60 % toward black, darker and stronger on a light page; InactiveDim's fade is worked out, not searched: luminance runs straight in linear light, which `blendLinear` mixes in, so the most of the setting that keeps a pair at its own contrast or 4.5 is one division (`fadeToward`, a hair inside the floor for the bytes' rounding), where each frame bisected every distinct (ink, paper) pair eight times into a 32-slot cache made again each frame (A7); the grips (G1', R6): a reading pane's button is ringed in the chrome's mode ink (`grip.mode`: sky, else mint, violet, paper, rose; 3:1 on both tag grounds), two logical pixels as acme's ButtonBorder, outside a pixel of band so its fill never touches it (an unfocused dirty one's gap, now a reading one's too), a held pane's ring the resting `grip.ring` and a focused one's `grip.focus`, dirty `grip.dirty`; the glyph and the mode's bars on a filled button (focused or dirty) in `grip.ink` (held 4.5:1 on every fill), on the band in the tag's own ink: gui.zig's inkOn (black or white past a luminance of 140, not WCAG) deleted; the window's rules: spines, column and stacked-pane rules in `rule` (R11), the topbar's in `rule` unless gui_topbar_pane_border_rgb, the tag rule `tag_rule` (half the tag toward the page in OKLab; acme's own #8888cc) where it was the sRGB average of the tag and the page, `rule_px` and `rail_px` the chrome's; surface.Chrome gains `grip_mode` and `grip_ink`, `tag_rule` is always given (null meant "mix it yourself"), and draw.zig fills them from `p.chrome()`; macOS: the two exports nothing reads, pardes_tagline_bg (the tag's ground, misnamed) and pardes_tag_active_bg, deleted with their header lines and ABI guards; the Mac's sixteen for an index are core/colors.zig's `xterm`, the gui's, where they were Tango (a window is handed a program's sixteen as the theme's own colours now, L2d, so an index under 16 reaches it only from elsewhere: one colour an index in every window); RUN (TEST FIRST): gui.zig "every pixel of a grip column is band, button or ring" asks the button's pixels in the chrome's fills, rings, mode ring and grip ink (it allowed the grid's old box and boxDirty colours and inkOn), over four sizes, focused or not, dirty or not, the first pane reading (Jumps walk): fails on the base by compile (the surface had no mode ring or grip ink), passes now; "InactiveDim fades the unfocused panes' rows alone, never below the text's floor" passes with the fade worked out (#e6e6e6 on black faded toward it, at least 4.5:1); acme's #8888cc tag rule and its 2 px rules and 18 px track as before; PICTURES (the S kit, before = the installed build, after = this tree's Debug gui, 26 px, `Jumps walk`): .scratch/themes/L2cde/png/: the Changes view (dark, neonotte84, orchard, acme), a terminal with `ls --color` and the sixteen, bright, backgrounds, faint, 256 and greys (dark, neonotte84), the grip's four states (held or reading, focused or not; 16 and 26 px; dark, neonotte84), InactiveDim 35 (dark, neonotte84); derived once: every colour these surfaces read is Chrome.of's (colors.zig, at the theme's change: finishThemeInitialization, setThemeIndex, previewTheme, loadThemeFile), handed to the window in surface.Chrome by draw.zig a frame as before; the fades (faint, InactiveDim) are a cell's arithmetic, as the 60 % and the blend were, with no search or cache left; NOT DONE: PDF hits (the PDF addon is handed fg, bg, sel and link through pa_view, the addon ABI 3.3; the theme's hit wants a field there, an ABI 3.4 with a version check: abi/pardes_addon.h, abi/addon.zig, core/Kind.zig, addons/fake, beyond this line's files), so test/image_harness.zig's helix tints are unchanged and not re-pinned; a mark's ink on a button is still pushed 4.5:1 against the fill a frame (it wants a severity ink per grip fill in Chrome: L2a's marks); the grid's frame and empty columns (draw.zig's fills) and the tag grounds the window lays under a tag (tag_bg, tag_focus_bg, tag_reading_bg) stay the old views' until L2a moves the grid; GATES: gui unit-test 1948/1952 (4 skipped; w2base 1947/1951, +1 the dark terminal test of L2d; its one failure the known BaselineHarnessMismatch); macOS: runtime/macos.zig built for this host and its ABI guard run (`unit-test -Dplatform=macos`, "pardes.h declares every export the way it is defined"), the Swift not compiled (no Darwin here); the tui suites on L2c+L2d+L2e: core-test 1123/1296 (173 skipped), shell-test 1344/1347 (3 skipped), pane-test 184/185 (1 skipped), behaviour-test 280/280 and --replay 20 seeds of 70 steps, 0 failures, process-test 0 of 147 failed (3 skipped, no golden moved by L2e), term-test 17/17, kitty-test 45/45; the dump and digest unchanged (no fuzz or soak); load 0.9 to 12.8 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016Y9MNBFhdevVu48bvL9kCE --- dev/gui/gui.zig | 155 ++++++++++++++++++------------------- dev/macos/Sources/PardesView.swift | 16 ++-- dev/tui/tui.zig | 2 +- 3 files changed, 84 insertions(+), 89 deletions(-) (limited to 'dev') diff --git a/dev/gui/gui.zig b/dev/gui/gui.zig index a478db03..f572a7ce 100644 --- a/dev/gui/gui.zig +++ b/dev/gui/gui.zig @@ -45,8 +45,10 @@ const log = std.log.scoped(.gui); const font_ttf = @embedFile("AdwaitaMono-Regular.ttf"); -const bg_default = [3]u8{ 18, 18, 18 }; -const fg_default = [3]u8{ 204, 204, 204 }; +/// The page and text a window draws for a theme that leaves them to the +/// host (`dark`): the chrome's one null page (DESIGN.md R1). +const null_page = pardes.colors.null_page; +const null_text = pardes.colors.null_text; const p9_arrow_clr = [32]u8{ 0xFF, 0xFF, 0x80, 0x01, 0x80, 0x02, 0x80, 0x0C, @@ -4017,7 +4019,7 @@ fn renderFrame( coverFrame(covered, surface.cols, surface.rows, surface.bodyLayers(), surface.tagLayers(), surface.regionList()); try buildDecor(g, gpa, surface, &groups, layout, win_w, win_h, cursors_shown); - const page = chrome.page orelse bg_default; + const page = chrome.page orelse null_page; const background_opacity = backgroundOpacity(g.applied_window_opacity); const clear: c.SDL_FColor = .{ .r = @as(f32, @floatFromInt(page[0])) / 255.0 * background_opacity, @@ -4163,13 +4165,13 @@ const taglineBandOffset = pardes.Layer.taglineBandOffset; /// in `line`, block or bar: shaping breaks around it. fn resolveCell(g: *Gui, line: []const pardes.Cell, at: usize, cursor: ?usize, role: pardes.FontRole, is_cursor: bool, page: [3]u8) ResolvedCell { const cell = &line[at]; - var fg = fg_default; + var fg = null_text; var bg = page; var reverse = is_cursor; if (!cell.default) { const st = cell.style; fg = switch (st.fg) { - .default => fg_default, + .default => null_text, .index => |i| pardes.colors.xterm[i], .rgb => |rgb| rgb, }; @@ -4185,9 +4187,9 @@ fn resolveCell(g: *Gui, line: []const pardes.Cell, at: usize, cursor: ?usize, ro // full opacity would expose text that the terminal concealed, so // cellSlot draws a concealed cell blank. } - if (st.dim) for (&fg) |*ch| { - ch.* = @intCast(@as(u16, ch.*) * 6 / 10); - }; + // SGR faint: the ink toward its ground to the dim floor (DESIGN.md + // R15), so fainter on a light page too, never darkened to black. + if (st.dim) fg = fadeToward(fg, bg, 1, @min(pardes.colors.contrast(fg, bg), pardes.colors.Chrome.dim_floor)); } if (reverse) std.mem.swap([3]u8, &fg, &bg); @@ -4345,13 +4347,14 @@ fn gripButton(g: *const Gui, chrome: *const pardes.Chrome, col: u16, row: u16, l fn gripFill(chrome: *const pardes.Chrome, focus: bool, dirty: bool, reading: bool) [3]u8 { if (dirty) return chrome.grip_dirty; if (focus) return chrome.grip_focus_ring; - // The ring's inside is the tag's ground: a reading pane's tint. + // The ring's inside is the tag's ground. return if (reading) chrome.tag_reading_bg else chrome.tag_bg; } -fn inkOn(bg: [3]u8) [3]u8 { - const lum = (@as(u16, bg[0]) * 3 + @as(u16, bg[1]) * 6 + @as(u16, bg[2])) / 10; - return if (lum > 140) .{ 0x00, 0x00, 0x00 } else .{ 0xff, 0xff, 0xff }; +/// The ink on a pane's button (DESIGN.md R6): the chrome's grip ink on a +/// fill, the tag's own on its ground. +fn gripInk(chrome: *const pardes.Chrome, focus: bool, dirty: bool) [3]u8 { + return if (focus or dirty) chrome.grip_ink else chrome.tag_fg; } /// Cuts an instance's quad to a pixel rectangle (left, top, right, bottom), @@ -4463,8 +4466,8 @@ fn emitSurfaceCell( // or dirty (UX D4). const ink = if (mark) switch (glyph.style.fg) { .rgb => |rgb| pardes.colors.pushAway(rgb, &.{fill}, pardes.colors.Roles.ink_floor), - else => inkOn(fill), - } else if (here.pane_grip) inkOn(fill) else resolved.fg; + else => gripInk(chrome, here.focus, here.dirty), + } else if (here.pane_grip) gripInk(chrome, here.focus, here.dirty) else resolved.fg; instances[next.*].fr = @as(f32, @floatFromInt(ink[0])) / 255; instances[next.*].fg = @as(f32, @floatFromInt(ink[1])) / 255; instances[next.*].fb = @as(f32, @floatFromInt(ink[2])) / 255; @@ -5141,7 +5144,7 @@ fn laneStrip(g: *Gui, gpa: std.mem.Allocator, lane: pardes.Lane, row: i32, ride: /// coloured gutter with a thin track and its thumb, running down through the /// pixels past the last whole row. fn paneDecor(g: *Gui, gpa: std.mem.Allocator, regions: []const pardes.Region, tags: []const pardes.Layer, ticks: []const pardes.RailTick, heat: []const pardes.RailHeat, chrome: *const pardes.Chrome, layout: CellLayout, cols: u16, rows: u16, win_w: f32, win_h: f32) !void { - const page = chrome.page orelse bg_default; + const page = chrome.page orelse null_page; for (regions) |rail| { if (rail.kind != .rail or rail.rect.h == 0) continue; const tag = for (regions) |region| { @@ -5165,7 +5168,7 @@ fn paneDecor(g: *Gui, gpa: std.mem.Allocator, regions: []const pardes.Region, ta if (!tag_bottom and head.rows > 0) tag_end = @max(tag_end, head.viewport.y + head.rows); if (!tag_bottom and band.rows > 0 and band.kind == .band and band.id == rail.owner) tag_end = @max(tag_end, band.viewport.y + band.rows); const rule_y = @as(f32, @floatFromInt(if (tag_bottom) tag.rect.y else tag_end)) * layout.h; - try addDecor(g, gpa, x0, if (tag_bottom) rule_y else rule_y - dp(1), rule_x1, if (tag_bottom) rule_y + dp(1) else rule_y, chrome.tag_rule orelse mixRgb(chrome.tag_bg, page), 1, win_w, win_h); + try addDecor(g, gpa, x0, if (tag_bottom) rule_y else rule_y - dp(1), rule_x1, if (tag_bottom) rule_y + dp(1) else rule_y, chrome.tag_rule, 1, win_w, win_h); // Stacked panes are ruled apart as columns are, where one pane's // body meets the next one's tag (acme's Border). { @@ -5238,9 +5241,6 @@ fn paneDecor(g: *Gui, gpa: std.mem.Allocator, regions: []const pardes.Region, ta } } -/// Halfway between two colours. -const mixRgb = pardes.colors.mix; - /// A rule's width: the theme's own, or one pixel. fn rulePx(chrome: *const pardes.Chrome) f32 { return dp(@floatFromInt(@max(1, chrome.rule_px))); @@ -5270,17 +5270,15 @@ fn updateDisplayScale(window: *c.SDL_Window) void { /// InactiveDim: the unfocused panes' text faded toward its ground by the /// setting's percent, never below the pair's own contrast or 4.5, whichever -/// is lower. The window's alone, from the regions' focus: renderFrame -/// begins it each frame. ponytail: one window per process, as display_scale. +/// is lower (`fadeToward`: worked out, no search, so nothing is kept). The +/// window's alone, from the regions' focus: renderFrame begins it each +/// frame. ponytail: one window per process, as display_scale. var dim: Dim = .{}; const Dim = struct { amount: f32 = 0, /// The pane with the keyboard, from its regions. focused: u16 = pardes.Region.none, - /// The few ink and paper pairs a frame has, each faded once. - keys: [32]?[6]u8 = @splat(null), - values: [32][3]u8 = undefined, fn begin(d: *Dim, percent: u8, regions: []const pardes.Region) void { d.* = .{ .amount = @as(f32, @floatFromInt(@min(percent, 100))) / 100 }; @@ -5297,35 +5295,15 @@ const Dim = struct { } /// A cell instance's ink faded toward its ground. - fn fade(d: *Dim, instance: *CellInstance) void { - const ink = d.faded(byteRgb(.{ instance.fr, instance.fg, instance.fb }), byteRgb(.{ instance.br, instance.bg, instance.bb })); + fn fade(d: *const Dim, instance: *CellInstance) void { + const from = byteRgb(.{ instance.fr, instance.fg, instance.fb }); + const paper = byteRgb(.{ instance.br, instance.bg, instance.bb }); + const ink = fadeToward(from, paper, d.amount, @min(pardes.colors.contrast(from, paper), 4.5)); instance.fr = @as(f32, @floatFromInt(ink[0])) / 255.0; instance.fg = @as(f32, @floatFromInt(ink[1])) / 255.0; instance.fb = @as(f32, @floatFromInt(ink[2])) / 255.0; } - fn faded(d: *Dim, ink: [3]u8, paper: [3]u8) [3]u8 { - const key = ink ++ paper; - const slot = (@as(usize, ink[0]) *% 31 +% @as(usize, ink[1]) *% 7 +% ink[2] +% @as(usize, paper[0]) *% 13 +% @as(usize, paper[1]) *% 3 +% paper[2]) % d.keys.len; - if (d.keys[slot]) |held| if (std.mem.eql(u8, &held, &key)) return d.values[slot]; - // Contrast falls as the ink nears its paper: the most of `amount` - // that keeps the pair at its own contrast or 4.5, whichever is lower. - const floor = @min(pardes.colors.contrast(ink, paper), 4.5); - var t = d.amount; - if (pardes.colors.contrast(blendLinear(ink, paper, t), paper) < floor) { - var lo: f32 = 0; - var hi: f32 = t; - for (0..8) |_| { - const mid = (lo + hi) / 2; - if (pardes.colors.contrast(blendLinear(ink, paper, mid), paper) >= floor) lo = mid else hi = mid; - } - t = lo; - } - d.keys[slot] = key; - d.values[slot] = blendLinear(ink, paper, t); - return d.values[slot]; - } - fn byteRgb(rgb: [3]f32) [3]u8 { var out: [3]u8 = undefined; for (&out, rgb) |*o, v| o.* = @intFromFloat(@round(std.math.clamp(v, 0, 1) * 255)); @@ -5333,6 +5311,19 @@ const Dim = struct { } }; +/// `ink` toward `paper` in linear light, `most` of the way at most and +/// never under `floor`:1 on it. Luminance runs straight in linear light, so +/// the most that keeps the floor is worked out, never searched (a hair +/// inside it, for the bytes' rounding). +fn fadeToward(ink: [3]u8, paper: [3]u8, most: f32, floor: f32) [3]u8 { + const yi = pardes.colors.relativeLuminance(ink); + const yp = pardes.colors.relativeLuminance(paper); + if (@abs(yi - yp) < 1e-6) return ink; + const f = floor * 1.02; + const stop = if (yi > yp) f * (yp + 0.05) - 0.05 else (yp + 0.05) / f - 0.05; + return blendLinear(ink, paper, std.math.clamp((yi - stop) / (yi - yp), 0, most)); +} + /// `t` of the way from one colour to the other in linear light, so a /// coloured ink does not muddy on its way to the paper. fn blendLinear(from: [3]u8, to: [3]u8, t: f32) [3]u8 { @@ -5378,10 +5369,12 @@ fn gripDecor(g: *Gui, gpa: std.mem.Allocator, regions: []const pardes.Region, ce try addDecor(g, gpa, button[2], button[1], right, button[3], band, 1, win_w, win_h); if (grip.kind != .grip) continue; // acme's button ring, two pixels (ButtonBorder) inside the button: - // the focused one's in its own fill. An unfocused dirty one keeps a - // pixel of band inside its ring, so the four states differ in shape - // whatever a theme's colours (a focused dirty one is acme's - // modbutton, filled up to its ring). + // the focused one's in its own fill, a reading pane's in the mode's + // ink (DESIGN.md G1'). An unfocused dirty one and a reading one keep + // a pixel of band inside the ring, so the fill never touches the + // mode's ring and the four states differ in shape whatever a theme's + // colours (a focused dirty held one is acme's modbutton, filled up to + // its ring). { // The rules drawn over the row (paneDecor, after this) cut into // it: the ring runs inside them, from rule to rule. @@ -5401,14 +5394,14 @@ fn gripDecor(g: *Gui, gpa: std.mem.Allocator, regions: []const pardes.Region, ce const x1 = button[2]; const y0 = button[1] + top_rule; const y1 = button[3] - bottom_rule; - const ring = if (grip.active) chrome.grip_focus_ring else chrome.grip_border; + const ring = if (grip.reading) chrome.grip_mode else if (grip.active) chrome.grip_focus_ring else chrome.grip_border; // acme's ButtonBorder: two logical pixels. const b = dp(2); try addDecor(g, gpa, x0, y0, x1, y0 + b, ring, 1, win_w, win_h); try addDecor(g, gpa, x0, y1 - b, x1, y1, ring, 1, win_w, win_h); try addDecor(g, gpa, x0, y0 + b, x0 + b, y1 - b, ring, 1, win_w, win_h); try addDecor(g, gpa, x1 - b, y0 + b, x1, y1 - b, ring, 1, win_w, win_h); - if (grip.dirty and !grip.active) { + if (grip.reading or (grip.dirty and !grip.active)) { const gap = b + dp(1); try addDecor(g, gpa, x0 + b, y0 + b, x1 - b, y0 + gap, band, 1, win_w, win_h); try addDecor(g, gpa, x0 + b, y1 - gap, x1 - b, y1 - b, band, 1, win_w, win_h); @@ -5424,7 +5417,7 @@ fn gripDecor(g: *Gui, gpa: std.mem.Allocator, regions: []const pardes.Region, ce if (x >= cols) continue; const cell = &cells[@as(usize, y) * cols + x]; if (cell.default or cell.printableAscii() != ' ' or boxMark(cells[@as(usize, y) * cols ..][0..cols], x)) continue; - const rgb = inkOn(gripFill(chrome, grip.active, grip.dirty, grip.reading)); + const rgb = gripInk(chrome, grip.active, grip.dirty); const center_x = @floor((button[0] + button[2]) / 2); const center_y = @as(f32, @floatFromInt(y)) * layout.h + @as(f32, @floatFromInt(taglineBandOffset(y, win_h, g.cell_h, g.tagline_height))) + @as(f32, @floatFromInt(g.tagline_height)) / 2; const half_w = @max(dp(1), @min(dp(3), @floor((button[2] - button[0] - 2 * dp(3)) / 2))); @@ -5757,7 +5750,7 @@ fn appendJumpTrail(g: *Gui, on: bool, surface: *const pardes.Surface, now_ns: u6 if (region.kind == .body and cursor.x >= region.rect.x and cursor.x < @as(u32, region.rect.x) + region.rect.w and cursor.y >= region.rect.y and cursor.y < @as(u32, region.rect.y) + region.rect.h) break region.rect; } else return; - const page = surface.chrome.page orelse bg_default; + const page = surface.chrome.page orelse null_page; const w: f32 = @floatFromInt(g.cell_w); const h: f32 = @floatFromInt(g.cell_h); for (lit) |cell| { @@ -5769,7 +5762,7 @@ fn appendJumpTrail(g: *Gui, on: bool, surface: *const pardes.Surface, now_ns: u6 else => page, }; if (!std.mem.eql(u8, &ground, &page)) continue; - var color = overlayRgb(surface.chrome.fg orelse fg_default); + var color = overlayRgb(surface.chrome.fg orelse null_text); color.a = cell.strength; const x0 = @as(f32, @floatFromInt(cell.x)) * w; const y0 = @as(f32, @floatFromInt(cell.y)) * h; @@ -5855,7 +5848,7 @@ fn appendCursorGlide(g: *Gui, surface: *const pardes.Surface, now_ns: u64, build } // Its colour: the cursor the cells would draw nearest the quad. var boxes: [max_cursors]CursorBox = undefined; - var rgb: [3]u8 = chrome.fg orelse fg_default; + var rgb: [3]u8 = chrome.fg orelse null_text; var nearest: f32 = std.math.inf(f32); for (boxes[0..cursorBoxes(g, surface, layout, builder.win_h, &boxes)]) |box| { const dx = (box.x0 + box.x1) / 2 - centre[0]; @@ -6030,7 +6023,7 @@ fn cursorColor(chrome: *const pardes.Chrome, cell: *const pardes.Cell, role: par return if (role == .tagline) switch (cell.style.fg) { .rgb => |rgb| rgb, else => chrome.tag_fg, - } else chrome.fg orelse fg_default; + } else chrome.fg orelse null_text; } test "FreeType and HarfBuzz allocate from the gui allocator and give it all back" { @@ -7170,7 +7163,7 @@ test "a touchpad's fraction over a body whose context rows went (scrolled out of for (&s.body_layers) |*layer| layer.cells = blank[0..layer.cells.len]; @memset(wr.g.scroll_edge, .{}); const held = if (s.facts.pane(id)) |shown| shown.context_rows else 0; - const n = emitScrollRows(&wr.g, instances.ptr, 0, &s, fixedCellLayout(&wr.g), 800, 480, bg_default, held); + const n = emitScrollRows(&wr.g, instances.ptr, 0, &s, fixedCellLayout(&wr.g), 800, 480, null_page, held); // The body's moving rows under the held ones, the layer's // rows past the grid's while there is a layer, and the row // that left. @@ -7197,24 +7190,24 @@ test "a scroll's body taller than its body layer (the pane shrunk under a glide) g.scroll_body_h = 19; var instances: [3 * 40 * 20]CellInstance = undefined; const layout = fixedCellLayout(&g); - try std.testing.expectEqual(@as(u32, 0), emitScrollRows(&g, &instances, 0, &surface, layout, 400, 400, bg_default, 2)); + try std.testing.expectEqual(@as(u32, 0), emitScrollRows(&g, &instances, 0, &surface, layout, 400, 400, null_page, 2)); // As tall as the body, its cells short of its rows: the same. surface.body_layers[0].rows = 21; - try std.testing.expectEqual(@as(u32, 0), emitScrollRows(&g, &instances, 0, &surface, layout, 400, 400, bg_default, 2)); + try std.testing.expectEqual(@as(u32, 0), emitScrollRows(&g, &instances, 0, &surface, layout, 400, 400, null_page, 2)); // Its cells all there: the body's moving rows under the two held, and // the layer's two past the grid's. var whole: [38 * 21]pardes.Cell = @splat(.{}); surface.body_layers[0].cells = &whole; - try std.testing.expectEqual(@as(u32, (19 - 2 + 2) * 38), emitScrollRows(&g, &instances, 0, &surface, layout, 400, 400, bg_default, 2)); + try std.testing.expectEqual(@as(u32, (19 - 2 + 2) * 38), emitScrollRows(&g, &instances, 0, &surface, layout, 400, 400, null_page, 2)); } test "concealed terminal text emits no ink on its ground" { var g = testGui(10, 20, 6, 12); var cell: pardes.Cell = .{ .default = false, .style = .{ .invisible = true, .ul = .single } }; cell.text[0] = 'X'; - const resolved = resolveCell(&g, (&cell)[0..1], 0, null, .body, false, bg_default); + const resolved = resolveCell(&g, (&cell)[0..1], 0, null, .body, false, null_page); try std.testing.expectEqualDeep(g.atlas.space_slot, resolved.slot); - try std.testing.expectEqual(bg_default, resolved.bg); + try std.testing.expectEqual(null_page, resolved.bg); } test "a block cursor's cell is drawn reversed: the cell's ink its ground, its ground its ink" { @@ -7226,8 +7219,8 @@ test "a block cursor's cell is drawn reversed: the cell's ink its ground, its gr .default = false, .style = .{ .fg = .{ .rgb = .{ 10, 20, 30 } }, .bg = .{ .rgb = .{ 200, 210, 220 } } }, }; - const plain = resolveCell(&g, (&cell)[0..1], 0, null, .body, false, bg_default); - const cursor = resolveCell(&g, (&cell)[0..1], 0, 0, .body, true, bg_default); + const plain = resolveCell(&g, (&cell)[0..1], 0, null, .body, false, null_page); + const cursor = resolveCell(&g, (&cell)[0..1], 0, 0, .body, true, null_page); try std.testing.expectEqual([3]u8{ 10, 20, 30 }, plain.fg); try std.testing.expectEqual(plain.fg, cursor.bg); try std.testing.expectEqual(plain.bg, cursor.fg); @@ -7354,7 +7347,7 @@ test "every pixel of a grip column is band, button or ring, and the button sits const row: u16 = grip.rect.y + @as(u16, @intCast(line)); const at = @as(usize, row) * s.cols; var next: u32 = 0; - emitSurfaceCell(&g, &s.chrome, &instances, &next, col, row, layout, win_w, win_h, s.cells[at..][0..s.cols], cover[at..][0..s.cols], col, null, false, bg_default); + emitSurfaceCell(&g, &s.chrome, &instances, &next, col, row, layout, win_w, win_h, s.cells[at..][0..s.cols], cover[at..][0..s.cols], col, null, false, null_page); for (instances[0..next]) |i| paint.quad(pixels, i.x0, i.y0, i.x1, i.y1, .{ i.br, i.bg, i.bb }, win_w, win_h, x_px, y_px, w_px, h_px); }; for (g.decor.items) |i| if (i.fr >= 1 and i.clip_x1 < i.clip_x0) paint.quad(pixels, i.x0, i.y0, i.x1, i.y1, .{ i.br, i.bg, i.bb }, win_w, win_h, x_px, y_px, w_px, h_px); @@ -7370,8 +7363,8 @@ test "every pixel of a grip column is band, button or ring, and the button sits const band = if (pardes.Trail.reading(core, core.panes[0].?)) chrome.tag_reading_bg else if (focus == 0) chrome.tag_focus_bg else chrome.tag_bg; // Band, fills, rings, the rules between stacked panes and under the // tag, and the mode marks' ink (the grip's first cell's). - const ink = inkOn(gripFill(chrome, grip.active, grip.dirty, grip.reading)); - const allowed = [_][3]f32{ rgb(band), rgb(core.chromeTheme().box), rgb(pardes.draw.boxDirty(core)), rgb(chrome.grip_border), rgb(chrome.grip_focus_ring), rgb(chrome.border), rgb(ink), rgb(chrome.tag_rule orelse mixRgb(chrome.tag_bg, chrome.page orelse bg_default)) }; + const ink = gripInk(chrome, grip.active, grip.dirty); + const allowed = [_][3]f32{ rgb(band), rgb(chrome.grip_focus_ring), rgb(chrome.grip_dirty), rgb(chrome.grip_border), rgb(chrome.grip_mode), rgb(chrome.border), rgb(ink), rgb(chrome.tag_rule) }; for (pixels, 0..) |pixel, n| { const got = pixel orelse return error.TestUnpaintedGripPixel; const known = for (allowed) |a| { @@ -7385,7 +7378,7 @@ test "every pixel of a grip column is band, button or ring, and the button sits } // The rule under the tag runs unbroken across the grip column. for (pixels[(h_px - 1) * w_px ..][0..w_px]) |pixel| - try std.testing.expectEqual(rgb(chrome.tag_rule orelse mixRgb(chrome.tag_bg, chrome.page orelse bg_default)), pixel.?); + try std.testing.expectEqual(rgb(chrome.tag_rule), pixel.?); // The button's edges are the scrollbar's. const button = gripButton(&g, chrome, grip.rect.x, grip.rect.y, layout); const column = scrollColumn(&g, chrome, s.region(.rail, 0).?.rect.x, layout); @@ -7403,7 +7396,7 @@ test "small tagline fonts leave no background gutters between adjacent tags" { var next: u32 = 0; for (0..3) |row| { // Column 1: past the anchor's inset edge at the column's left. - emitSurfaceCell(&g, &chrome, &instances, &next, 1, @intCast(row), fixedCellLayout(&g), 800, 480, (&cell)[0..1], &.{.{}}, 0, null, false, bg_default); + emitSurfaceCell(&g, &chrome, &instances, &next, 1, @intCast(row), fixedCellLayout(&g), 800, 480, (&cell)[0..1], &.{.{}}, 0, null, false, null_page); const base = instances[row * 2]; const ink = instances[row * 2 + 1]; try std.testing.expectApproxEqAbs(@as(f32, 20.0 / 480.0 * 2), base.y0 - base.y1, 0.0001); @@ -7416,7 +7409,7 @@ test "small tagline fonts leave no background gutters between adjacent tags" { // Column 0 is an anchor's edge: its ink is inset by the band's margin // (2 px here) and its underlay still covers the whole cell. next = 0; - emitSurfaceCell(&g, &chrome, &instances, &next, 0, 1, fixedCellLayout(&g), 800, 480, (&cell)[0..1], &.{.{ .anchor = true }}, 0, null, false, bg_default); + emitSurfaceCell(&g, &chrome, &instances, &next, 0, 1, fixedCellLayout(&g), 800, 480, (&cell)[0..1], &.{.{ .anchor = true }}, 0, null, false, null_page); try std.testing.expectApproxEqAbs(@as(f32, 10.0 / 800.0 * 2), instances[0].x1 - instances[0].x0, 0.0001); try std.testing.expectApproxEqAbs(@as(f32, 8.0 / 800.0 * 2), instances[1].x1 - instances[1].x0, 0.0001); try std.testing.expectApproxEqAbs(@as(f32, 8) / atlas_w, instances[1].u1 - instances[1].u0, 0.0001); @@ -7427,7 +7420,7 @@ test "block cursor alone overrides transparent cell background" { const cell: pardes.Cell = .{}; var instances: [2]CellInstance = undefined; for ([_]bool{ false, true }, 0..) |cursor, i| { - emitInstance(&g, &instances, @intCast(i), 0, 0, fixedCellLayout(&g), 800, 480, .body, (&cell)[0..1], 0, null, cursor, bg_default); + emitInstance(&g, &instances, @intCast(i), 0, 0, fixedCellLayout(&g), 800, 480, .body, (&cell)[0..1], 0, null, cursor, null_page); try std.testing.expectEqual(cursor, instances[i].effect & opaque_bg_bit != 0); } } @@ -7596,7 +7589,7 @@ test "pane indicator halves are safe on an exhausted atlas" { var instances: [4]CellInstance = undefined; var next: u32 = 0; for (0..2) |col| { - emitSurfaceCell(&g, &chrome, &instances, &next, @intCast(col), 0, fixedCellLayout(&g), 100, 100, cells[0..6], cover[0..6], col, null, false, bg_default); + emitSurfaceCell(&g, &chrome, &instances, &next, @intCast(col), 0, fixedCellLayout(&g), 100, 100, cells[0..6], cover[0..6], col, null, false, null_page); try std.testing.expectEqual(@as(f32, 0), instances[col * 2 + 1].u0); } try std.testing.expectEqual(@as(u32, 4), next); @@ -8037,7 +8030,7 @@ test "compact body layer rendering fills recovered rows and clips the final glyp layer.setContextLines(&.{ 0, 4, 5, 6 }); var instances: [32]CellInstance = undefined; var next: u32 = 0; - emitBodyLayer(&g, &instances, &next, &layer, 200, 200, bg_default, false, .{ 80, 90, 100 }); + emitBodyLayer(&g, &instances, &next, &layer, 200, 200, null_page, false, .{ 80, 90, 100 }); // Four compact header rows (48px), then three body rows: two complete // and a third clipped to the remaining12px of the100px viewport. try std.testing.expectEqual(@as(u32, 20), next); @@ -8052,7 +8045,7 @@ test "compact body layer rendering fills recovered rows and clips the final glyp // A drag preview reserves the last physical column without changing cells. layer.viewport.w = 1; next = 0; - emitBodyLayer(&g, &instances, &next, &layer, 200, 200, bg_default, false, .{ 80, 90, 100 }); + emitBodyLayer(&g, &instances, &next, &layer, 200, 200, null_page, false, .{ 80, 90, 100 }); for (instances[0..next]) |instance| try std.testing.expect(instance.x1 <= -0.6 + 0.0001); } @@ -8062,14 +8055,14 @@ test "compact tag layers fill available width and clip at their physical edge" { const layer: pardes.Layer = .{ .kind = .pane, .id = 0, .serial = 7, .viewport = .{ .x = 2, .y = 3, .w = 3, .h = 1 }, .cols = 6, .rows = 1, .cells = &cells, .bg = .{ 20, 30, 40 } }; var instances: [8]CellInstance = undefined; var next: u32 = 0; - emitTagLayer(&g, &instances, &next, &layer, 100, 100, bg_default, false); + emitTagLayer(&g, &instances, &next, &layer, 100, 100, null_page, false); // Five six-pixel cells fit in the three body-column viewport. try std.testing.expectEqual(@as(u32, 6), next); try std.testing.expectApproxEqAbs(@as(f32, -0.6), instances[1].x0, 0.0001); try std.testing.expectApproxEqAbs(@as(f32, 0), instances[5].x1, 0.0001); g.tagline_width = 8; next = 0; - emitTagLayer(&g, &instances, &next, &layer, 100, 100, bg_default, false); + emitTagLayer(&g, &instances, &next, &layer, 100, 100, null_page, false); try std.testing.expectEqual(@as(u32, 5), next); try std.testing.expectApproxEqAbs(@as(f32, 0), instances[4].x1, 0.0001); try std.testing.expectApproxEqAbs(@as(f32, 6) / atlas_w, instances[4].u1 - instances[4].u0, 0.0001); @@ -8334,7 +8327,7 @@ test "a `│` in a tag layer runs its row's whole height at a tagline smaller th var instances: [8]CellInstance = undefined; var next: u32 = 0; const win_h: f32 = 200; - emitTagLayer(&g, &instances, &next, &layer, 200, win_h, bg_default, false); + emitTagLayer(&g, &instances, &next, &layer, 200, win_h, null_page, false); try std.testing.expectEqual(@as(u32, 3), next); const bh: f32 = @floatFromInt(g.cell_h); // [0] the row's ground, [1] `a` at the tagline's height, [2] `│` the @@ -8402,7 +8395,7 @@ test "a pane's mark is its button's glyph where the mode draws none, in its kind defer g.decor.deinit(gpa); var instances: [4]CellInstance = undefined; var next: u32 = 0; - for (0..2) |col| emitSurfaceCell(&g, &chrome, &instances, &next, @intCast(col), 0, fixedCellLayout(&g), 100, 100, cells[0..6], cover[0..6], col, null, false, bg_default); + for (0..2) |col| emitSurfaceCell(&g, &chrome, &instances, &next, @intCast(col), 0, fixedCellLayout(&g), 100, 100, cells[0..6], cover[0..6], col, null, false, null_page); try std.testing.expectEqual(@as(u32, 4), next); // Each of the box's two cells draws its slice of the mark's glyph, in // the err ink pushed off the focused button's fill. diff --git a/dev/macos/Sources/PardesView.swift b/dev/macos/Sources/PardesView.swift index 11818e10..8dbaea0e 100644 --- a/dev/macos/Sources/PardesView.swift +++ b/dev/macos/Sources/PardesView.swift @@ -96,14 +96,16 @@ private let sRGB: CGColorSpace = CGColorSpace(name: CGColorSpace.sRGB) ?? CGColo // a CTFont instead of being bridged to NSFont on the way in. private let fontAttribute = NSAttributedString.Key(kCTFontAttributeName as String) -// The named sixteen, then xterm's 6x6x6 cube, then the 24-step grey ramp. These -// sixteen are app.mjs's, not gui.zig's: gui.zig borrows ghostty's palette -// because it already links it, and the two disagree on the base colors. +// The named sixteen, then xterm's 6x6x6 cube, then the 24-step grey ramp. A +// window is handed a program's sixteen as the theme's own colours (the core's +// terminal paint, colors.Chrome's ansi), so an index under 16 reaches it only +// from elsewhere; these are core/colors.zig's `xterm`, the gui's, so an index +// is one colour in every window. private let ansi16: [UInt32] = [ - 0x00_00_00, 0xCC_00_00, 0x4E_9A_06, 0xC4_A0_00, - 0x34_65_A4, 0x75_50_7B, 0x06_98_9A, 0xD3_D7_CF, - 0x55_57_53, 0xEF_29_29, 0x8A_E2_34, 0xFC_E9_4F, - 0x72_9F_CF, 0xAD_7F_A8, 0x34_E2_E2, 0xEE_EE_EC, + 0x1D_1F_21, 0xCC_66_66, 0xB5_BD_68, 0xF0_C6_74, + 0x81_A2_BE, 0xB2_94_BB, 0x8A_BE_B7, 0xC5_C8_C6, + 0x66_66_66, 0xD5_4E_53, 0xB9_CA_4A, 0xE7_C5_47, + 0x7A_A6_DA, 0xC3_97_D8, 0x70_C0_B1, 0xEA_EA_EA, ] private func paletteColor(_ index: UInt8) -> UInt32 { diff --git a/dev/tui/tui.zig b/dev/tui/tui.zig index aa1f8849..835fda6d 100644 --- a/dev/tui/tui.zig +++ b/dev/tui/tui.zig @@ -2236,7 +2236,7 @@ fn trailCells(arena: std.mem.Allocator, shown: *const pardes.Surface, trail: *Ju if (region.kind == .body and cursor.x >= region.rect.x and cursor.x < @as(u32, region.rect.x) + region.rect.w and cursor.y >= region.rect.y and cursor.y < @as(u32, region.rect.y) + region.rect.h) break region.rect; } else return shown; - const ink = shown.chrome.fg orelse .{ 0xcc, 0xcc, 0xcc }; + const ink = shown.chrome.fg orelse pardes.colors.null_text; const page = shown.chrome.page orelse pardes.colors.null_page; const out = try arena.create(pardes.Surface); out.* = shown.*; -- cgit v1.3 From 8393c24f76675f182055149645c10af3102b739e Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 26 Nov 2026 02:49:36 -0300 Subject: lsp_client, Output, lspmock, syntax, Pick, Query, docs: the Symbols builtin (a language server's documentSymbol) gives the Symbols picker's marks and order (UX DESIGN N, binding: "The builtin `Symbols` keeps reading the server but gets the same mark, order and qualified names, from `SymbolKind`"): walkSymbols keeps each symbol's SymbolKind, mapped onto N2's kinds (5 Class, 10 Enum, 11 Interface, 23 Struct, 26 TypeParameter a type; 6 Method, 9 Constructor, 12 Function, 25 Operator a function; 7 Property, 8 Field, 22 EnumMember a field; 14 Constant a const; 13 Variable, 15 to 21 and 24 a var; 1 File to 4 Package a module; any other the other), and names each in the ones it is in (a DocumentSymbol's nesting, a SymbolInformation's `containerName`): a row is `shapes.rs:5:5-8 m Shape.side`, the rows types, functions, fields, then the rest, each in the server's order; the +Search keeps that order: a file's symbols are neither sorted by their places (Output.sortResults) nor laid out as Locations, which put a file's rows in their lines' order (Output.usesLocationsConfig): a row each, as the picker lists them; the walk's list picker (`Jumps walk`, Ask's) takes them in that order (tty `lsp` with zls: `f helper`, `f main`, `c std`, was `std`, `helper`, `main`); an index's Symbols (SCIP, dev/lsp/Scip.zig) keep their rows unmarked, one row each now too; the mock answers documentSymbol with a nested list in no kind's order (a const, a function, a struct with a field and a method, an enum with a member, a module); docs/typ guide's `Symbols name` and the reference's Symbols say the marks and the order; and three faults of the change before's rows, which its pictures showed (each TEST FIRST: the syntax.zig and Pick.zig tests failed with them first; the pattern guard came with its JavaScript case, not before it): a test whose name is longer than 200 bytes was no symbol, so its body was no scope and its local structs and functions were listed as types and functions (Pick.zig's own tests: `t typeIn = struct`): a name that long is cut, on a character, and a test's body lists nothing (370 rows of core/Pick.zig to 247); a name field is taken whole when it is one line (C++'s `namespace v8::internal::torque` named `v8`, now whole; a value binding's must still be a name, never a pattern: `const { x, y } = a`, OCaml's `let () =`); the qualifier dimmed in a row ran to the name's last `.`, a test's sentence's (`(SPEC §6.3, §7.3)` dimmed most of it): it is the candidate's `base` now, the qualifier's length from the gather, which also gives the scorer its basename bonus on the name; core/root.zig's import of syntax.zig (the change before) says what it does: without it a -Dtest-filter run compiles none of syntax.zig's tests, while a whole run has them (core-test 1135/1308 with it or without it; the change before said they ran nowhere: wrong); RUN (TEST FIRST): test/behaviour/language_servers.zig "language-servers: a server's Symbols are the Symbols picker's rows ..." opens shapes.rs with no index (the server asked) and asks the +Search's rows in that order: with walkSymbols' marks alone they came in their lines' order (`c LIMIT`, `f main`, `t Shape`, ...: the sort and the Locations layout), passes now; the index's Symbols test asks one row each (`lib.rs:1:11-15 Shape`); test/snapshots/lsp.golden re-recorded: only its symbols snap's three rows (marked and grouped) and the preview landing on their first, `helper`'s line 3; GATES on this stack (the change before under it): core-test 1135/1308 (173 skipped; base 1127/1301 with the base's one failure, a CPU-time test under load: colors' "the whole ring resolves in 150 ms"), shell-test 1356/1359 (3 skipped), pane-test 183/184 (1 skipped), behaviour-test 281/281 and --replay 281/281, process-test 1 of 147 failed (tty editing: lsp, its golden: re-recorded, the ten `tty editing: lsp` cases 0 of 10 failed), term-test 17/17, kitty-test 45/45; the dump fuzz (Names.Cand.group, Stream.Batch.symbols) at 40,000 join seeds twice and 1,779 image seeds 13/13; the soak `replicas -- --clients 5 --rtt 30,80,207`: diverged 0, unequal 0, quiet checks 421/0 415/0 590/0, unlisted stops 0, the corpus 22 of 22 scenes the same, no leak; the gui unit-test 1960/1964 (4 skipped; its one failure the perf check's BaselineHarnessMismatch, every base's); core-test, shell-test, pane-test and behaviour-test again after the three faults: the same counts; the pictures (the S kit at 26 px, neonotte84, 100x30, typed through the pty; .scratch/walkui/W6/png): today's install (install74) beside this tree's Debug gui, SPC s s on core/Pick.zig (today 127 rows of declarations, `pub fn deinit(...` first; here 247, `t Pick = @This()` first, the types, then the functions ...) and on V8's torque-parser.cc (today 132, here 273 under `v8::internal::torque.`), and `count` typed (today the cursor on `count`, then `paneCount` and every row whose signature holds c-o-u-n-t, `[]const u8` among them; here `f count` current, `f paneCount`, `c counts_zig`, then the tests whose sentences match); no frame or perf gate (the user's rule of 2026-11-26); load 3.0 to 14.2 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016Y9MNBFhdevVu48bvL9kCE --- core/Output.zig | 9 +++++-- core/Pick.zig | 10 ++++---- core/Query.zig | 7 ++++-- core/root.zig | 2 +- core/syntax.zig | 48 +++++++++++++++++++++++++++---------- dev/lsp/lsp_client.zig | 39 +++++++++++++++++++++++++----- docs/typ/guide.typ | 2 +- docs/typ/reference.typ | 3 ++- test/behaviour/language_servers.zig | 25 ++++++++++++++++++- test/lspmock.zig | 11 +++++++-- test/snapshots/lsp.golden | 12 +++++----- 11 files changed, 130 insertions(+), 38 deletions(-) (limited to 'dev') diff --git a/core/Output.zig b/core/Output.zig index fe1543fe..e55ff4a3 100644 --- a/core/Output.zig +++ b/core/Output.zig @@ -198,11 +198,15 @@ pub fn traits(o: Origin) Traits { }; } +/// A list laid out as Locations (each place's lines from its file, in +/// their order): not a file's symbols, a row each in their own order (UX +/// DESIGN N: types, functions, fields, the rest). pub fn usesLocationsConfig(from: Origin) bool { const tr = traits(from); return tr.steps and !tr.commands and from != .kind and !std.meta.eql(from, Origin{ .query = .completion }) and - !std.meta.eql(from, Origin{ .query = .callstack }); + !std.meta.eql(from, Origin{ .query = .callstack }) and + !std.meta.eql(from, Origin{ .query = .document_symbols }); } pub fn fileTraits(out: ?State) Traits { @@ -244,6 +248,8 @@ pub fn isResultRow(file: *const File.State, row: usize) bool { return !locations.isContextLine(modal.lineSlice(file.content, row)); } +/// A language server's places in the order of their places; a file's +/// symbols stay in theirs (lsp_client: types, functions, fields, the rest). fn sortResults(arena: std.mem.Allocator, from: Origin, content: []u8, anchor: ?usize) !?usize { switch (from) { .search => {}, @@ -258,7 +264,6 @@ fn sortResults(arena: std.mem.Allocator, from: Origin, content: []u8, anchor: ?u .outgoing_calls, .supertypes, .subtypes, - .document_symbols, .workspace_symbols, .diagnostics, .workspace_diagnostics, diff --git a/core/Pick.zig b/core/Pick.zig index 2b5714cb..dcb838f3 100644 --- a/core/Pick.zig +++ b/core/Pick.zig @@ -677,10 +677,9 @@ fn rowAt(p: *Pardes, pk: *const Pick, arena: std.mem.Allocator, i: usize) std.me for (marks_in, row.marks) |*m, at| m.* = at -| line; row.marks = marks_in; const name_at = cand.key - line; - const dot = std.mem.lastIndexOfScalar(u8, row.text[name_at .. name_at + cand.key_len], '.'); row.kind = @intCast(name_at - 1); row.pre = @intCast(name_at); - row.faint = @intCast(if (dot) |at| at + 1 else 0); + row.faint = cand.base; if (name_at + cand.key_len < row.text.len) row.quiet = .{ @intCast(name_at + cand.key_len), @intCast(row.text.len) }; const owner = p.panes[p.paneBySerial(pk.owner) orelse return row] orelse return row; const f = owner.file orelse return row; @@ -3357,7 +3356,7 @@ const counts_zig = \\pub fn count(text: []const u8) Counts { \\ return .{ .lines = text.len }; \\} - \\test "count" {} + \\test "count.add" {} \\ ; @@ -3381,9 +3380,12 @@ test "Symbols (UX DESIGN N): a Zig file's rows types, functions, fields, then th \\ 1 n std = @import("std") \\ 5 c Counts.zero : Counts = .{} \\12 v hits : u32 = 0 - \\16 · "count" + \\16 · "count.add" \\ , try rowLines(p, a)); + // The qualifier dim, `Counts.`; a name holding a `.` none of it. + try std.testing.expectEqual(@as(u16, "Counts.".len), (try rowAt(p, live(p).?, a, 4)).faint); + try std.testing.expectEqual(@as(u16, 0), (try rowAt(p, live(p).?, a, 11)).faint); // Drawn: `m Counts.lines : usize = 0` (not the cursor's row). const pane = p.panes[p.paneBySerial(live(p).?.landing).?].?; _ = try p.render(a); diff --git a/core/Query.zig b/core/Query.zig index 743e9540..a5926e23 100644 --- a/core/Query.zig +++ b/core/Query.zig @@ -785,7 +785,8 @@ pub fn gather(p: *Pardes, names: *Names, source: Source, dir: []const u8, self: // line, its mark, its name qualified by the ones it is in, then // what its first line says after the name; types, functions, // fields, then the rest, each in the text's order (UX DESIGN N). - // The name alone is matched. + // The qualified name alone is matched, its own name the + // basename. for (0..4) |group| for (symbols) |sym| { if (sym.kind.group() != group or sym.kind == .scope or sym.end > text.len) continue; var buf: [512]u8 = undefined; @@ -793,13 +794,15 @@ pub fn gather(p: *Pardes, names: *Names, source: Source, dir: []const u8, self: row.print("{d: >6} {s} ", .{ sym.line + 1, sym.kind.mark() }) catch continue; const key_at = row.end; qualify(&row, symbols, text, sym.parent, 4) catch continue; + // The name its basename: the qualifier dim (Pick.rowAt). + const base = row.end - key_at; row.writeAll(text[sym.name_start..sym.name_end]) catch continue; const key_len = row.end - key_at; const rest = text[sym.name_end..@max(sym.name_end, sym.end)]; var detail = std.mem.trim(u8, rest[0 .. std.mem.indexOfScalar(u8, rest, '\n') orelse rest.len], " \t\r"); detail = std.mem.trimEnd(u8, std.mem.trimEnd(u8, detail, "{,;"), " \t"); if (detail.len > 0) row.print(" {s}", .{detail[0..@min(detail.len, buf.len - row.end -| 2)]}) catch {}; - names.add(gpa, row.buffered(), key_at, key_len, 0, sym.line + 1) catch break; + names.add(gpa, row.buffered(), key_at, key_len, @intCast(base), sym.line + 1) catch break; names.cands.items[names.cands.items.len - 1].group = @intCast(group); }; }, diff --git a/core/root.zig b/core/root.zig index 86ca62e0..a9c95a96 100644 --- a/core/root.zig +++ b/core/root.zig @@ -461,7 +461,7 @@ test { _ = @import("FrameStats.zig"); _ = @import("Query.zig"); _ = @import("Names.zig"); - _ = @import("syntax.zig"); // its tests ran nowhere before + _ = @import("syntax.zig"); // without it a -Dtest-filter run compiles none of its tests (a whole run has them) _ = @import("Stream.zig"); _ = @import("Tables.zig"); _ = @import("Handover.zig"); diff --git a/core/syntax.zig b/core/syntax.zig index 5cdc2ff3..9fbad3cf 100644 --- a/core/syntax.zig +++ b/core/syntax.zig @@ -1135,6 +1135,9 @@ const SymbolWalk = struct { fn visit(w: *SymbolWalk, node: ts.Node) !void { while (w.depth > 0 and w.scopes[w.depth - 1].end <= node.startByte()) w.depth -= 1; const in: Scope = if (w.depth > 0) w.scopes[w.depth - 1] else .{ .end = 0, .kind = .module, .symbol = 0 }; + // A test's body (a macro's) lists nothing: its types are its + // locals' (a test's `const Find = struct`). + if (in.kind == .other) return; const kind_name = node.kind(); const rule = for (w.rules) |r| { if (std.mem.eql(u8, r.node, kind_name)) break r; @@ -1145,11 +1148,17 @@ const SymbolWalk = struct { if (local and (found.kind == .constant or found.kind == .variable)) return; var named = in.symbol; if (found.name) |name| { + // A longer name is cut (a test's sentence), on a character. + var end = name.endByte(); + if (end - name.startByte() > max_name) { + end = name.startByte() + max_name; + while (end > name.startByte() and w.source[end] & 0xc0 == 0x80) end -= 1; + } try w.out.append(w.gpa, .{ .kind = found.kind, .line = name.startPoint().row, .name_start = name.startByte(), - .name_end = name.endByte(), + .name_end = end, .end = found.end, .parent = in.symbol, }); @@ -1190,7 +1199,10 @@ fn symbolOf(rule: Rule, node: ts.Node, source: []const u8, in: SymbolKind) ?stru if (kind == .variable and constant(source, node.startByte(), name orelse return null)) kind = .constant; }, .value => { + // Named by a name, never a pattern (`const { a, b } = ...`, + // OCaml's `let () = ...`). name = nameOf(node, rule.name); + if (name) |n| if (!nameLike(n.kind())) return null; kind = valueKind(node, source) orelse kind; // JavaScript's keyword is its declaration's (`const a = 1, b`). const from = if (std.mem.eql(u8, rule.node, "variable_declarator")) (node.parent() orelse node).startByte() else node.startByte(); @@ -1228,20 +1240,24 @@ fn symbolOf(rule: Rule, node: ts.Node, source: []const u8, in: SymbolKind) ?stru if (childOfKind(node, "Block")) |block| end = block.startByte(); } if (name == null and kind != .scope) return null; - if (name) |n| if (n.endByte() <= n.startByte() or n.endByte() - n.startByte() > max_name) return null; + if (name) |n| if (n.endByte() <= n.startByte()) return null; return .{ .kind = kind, .name = name, .end = end }; } -/// The longest name a symbol has: a longer one is no name. +/// The longest name a symbol has: a longer one is cut. const max_name = 200; -/// The node naming `node`: its field `field`; without one, its declarator's -/// (C's `int *f(void)`: `f`); else the first name under it, past its -/// type, value, body and parameters (Kotlin's, Fortran's). +/// The node naming `node`: its field `field`, whole on its line (C++'s +/// `namespace v8::internal`, Rust's `impl Vec`); without one, its +/// declarator's (C's `int *f(void)`: `f`); else the first name under it, +/// past its type, value, body and parameters (Kotlin's, Fortran's). fn nameOf(node: ts.Node, field: []const u8) ?ts.Node { if (field.len == 0) return null; var n = node; - if (node.childByFieldName(field)) |f| n = f else while (n.childByFieldName("declarator")) |d| n = d; + if (node.childByFieldName(field)) |f| { + if (f.startPoint().row == f.endPoint().row) return f; + n = f; + } else while (n.childByFieldName("declarator")) |d| n = d; if (nameLike(n.kind())) return n; if (n.childByFieldName("name")) |f| if (nameLike(f.kind())) return f; return firstName(n, 3); @@ -2786,12 +2802,20 @@ test "syntax symbols: a Zig file's types, functions, fields and the rest by thei \\fn List(comptime T: type) type { \\ return struct { items: []T }; \\} - \\test "count" {} + \\test "count" { + \\ const Local = struct { + \\ fn helper() void {} + \\ }; + \\ _ = Local; + \\} \\test {} \\extern fn tick() void; \\ ; - const lines = try symbolLines(gpa, "a.zig", source); + // A test's name longer than a row's room is cut, its body still none. + const xs: [250]u8 = @splat('x'); + const long = "test \"" ++ xs ++ "\" {\n const Inner = struct {};\n _ = Inner;\n}\n"; + const lines = try symbolLines(gpa, "a.zig", source ++ long); defer gpa.free(lines); try std.testing.expectEqualStrings( \\n std @@ -2810,7 +2834,7 @@ test "syntax symbols: a Zig file's types, functions, fields and the rest by thei \\· "count" \\f tick \\ - , lines); + ++ "· \"" ++ xs[0 .. max_name - 1].* ++ "\n", lines); } test "syntax symbols: C, C++, Rust, Go, Python and JavaScript by their kind tables, members named in their types, an impl's in its type, locals none" { @@ -2820,11 +2844,11 @@ test "syntax symbols: C, C++, Rust, Go, Python and JavaScript by their kind tabl defer stop(); const cases = [_]struct { path: []const u8, source: []const u8, want: []const u8 }{ .{ .path = "a.c", .source = "#define LIMIT 4\nstruct point { int x; int *y; };\ntypedef struct { int a; } pair;\nenum color { RED };\nstatic int counter = 0;\nconst int limit = 4;\nint add(int a) { int local = a; return local; }\nint later(void);\nstruct point p;\n", .want = "· LIMIT\nt point\nm point.x\nm point.y\nt pair\nm pair.a\nt color\nm color.RED\nv counter\nc limit\nf add\nf later\nv p\n" }, - .{ .path = "a.cc", .source = "namespace torque {\nclass Parser : public Base {\n public:\n Parser();\n int Parse(int depth) const { return depth; }\n int depth_;\n};\nint Parser::Run(int n) { int local = n; return local; }\nusing Alias = int;\n}\n", .want = "n torque\nt torque.Parser\nf torque.Parser.Parser\nf torque.Parser.Parse\nm torque.Parser.depth_\nf torque.Parser::Run\nt torque.Alias\n" }, + .{ .path = "a.cc", .source = "namespace torque {\nclass Parser : public Base {\n public:\n Parser();\n int Parse(int depth) const { return depth; }\n int depth_;\n};\nint Parser::Run(int n) { int local = n; return local; }\nusing Alias = int;\n}\nnamespace v8::internal {\nint flags;\n}\n", .want = "n torque\nt torque.Parser\nf torque.Parser.Parser\nf torque.Parser.Parse\nm torque.Parser.depth_\nf torque.Parser::Run\nt torque.Alias\nn v8::internal\nv v8::internal.flags\n" }, .{ .path = "a.rs", .source = "mod m {\npub struct S { pub a: u32 }\nenum E { A, B(u32) }\ntrait T { fn f(&self); }\nimpl S { pub fn new() -> Self { let x = 1; S { a: x } } }\nconst C: u32 = 1;\nstatic G: u32 = 2;\nmacro_rules! mac { () => {} }\n}\n", .want = "n m\nt m.S\nm m.S.a\nt m.E\nm m.E.A\nm m.E.B\nt m.T\nf m.T.f\nf m.S.new\nc m.C\nv m.G\n· m.mac\n" }, .{ .path = "a.go", .source = "package main\ntype S struct { A int }\ntype I interface { M() }\nconst C = 1\nvar V = 2\nfunc F() { var x = 1; _ = x }\nfunc (s *S) M() {}\n", .want = "t S\nm S.A\nt I\nf I.M\nc C\nv V\nf F\nf M\n" }, .{ .path = "a.py", .source = "X = 1\nclass C:\n attr = 2\n def m(self):\n y = 3\n self.z = 4\ndef f():\n pass\n", .want = "v X\nt C\nm C.attr\nf C.m\nf f\n" }, - .{ .path = "a.js", .source = "const A = 1;\nlet b = 2;\nfunction f() { const local = 1; }\nclass K { field = 1; m() {} }\nconst arrow = () => 1;\nconst Klass = class {};\n", .want = "c A\nv b\nf f\nt K\nm K.field\nf K.m\nf arrow\nt Klass\n" }, + .{ .path = "a.js", .source = "const A = 1;\nlet b = 2;\nfunction f() { const local = 1; }\nclass K { field = 1; m() {} }\nconst arrow = () => 1;\nconst Klass = class {};\nconst { x, y } = A;\n", .want = "c A\nv b\nf f\nt K\nm K.field\nf K.m\nf arrow\nt Klass\n" }, }; for (cases) |case| { const lines = try symbolLines(gpa, case.path, case.source); diff --git a/dev/lsp/lsp_client.zig b/dev/lsp/lsp_client.zig index a53ff57f..b76be78c 100644 --- a/dev/lsp/lsp_client.zig +++ b/dev/lsp/lsp_client.zig @@ -50,6 +50,7 @@ const std = @import("std"); const builtin = @import("builtin"); const libc = std.c; const lsp = @import("core").lsp; +const SymbolKind = @import("core").syntax.SymbolKind; const Scip = @import("Scip.zig"); extern "c" fn execv(path: [*:0]const u8, argv: [*:null]const ?[*:0]const u8) c_int; @@ -1002,7 +1003,11 @@ fn run(c: *Conn, io: std.Io, si: usize, arena: std.mem.Allocator, req: lsp.Req, .document_symbols => { const b = try docParams(arena, uri.items); const result = (try call(c, io, arena, "textDocument/documentSymbol", b.items, deadline)) orelse return; - try walkSymbols(&cx, c.caps.enc, uri.items, result, 0); + // Types, functions, fields, then the rest, each in the + // server's order (UX DESIGN N, the Symbols picker's). + var found: std.ArrayList(Symbol) = .empty; + try walkSymbols(arena, &found, uri.items, result, "", 0); + for (0..4) |group| for (found.items) |sym| if (sym.kind.group() == group) try emitRange(&cx, c.caps.enc, sym.uri, sym.range, sym.note); }, .workspace_symbols => { var b: std.ArrayList(u8) = .empty; @@ -1106,20 +1111,42 @@ fn locations(cx: *Cx, enc: Enc, result: std.json.Value) Err!void { } } -/// DocumentSymbol[] nests (`children`), SymbolInformation[] is flat. -fn walkSymbols(cx: *Cx, enc: Enc, uri: []const u8, node: std.json.Value, depth: u8) Err!void { +/// A symbol a server listed: its row's place and words, `t Shape.area`. +const Symbol = struct { kind: SymbolKind, uri: []const u8, range: ?std.json.Value, note: []const u8 }; + +/// DocumentSymbol[] nests (`children`), SymbolInformation[] is flat: each +/// its kind's mark and its name qualified by the ones it is in (the +/// nesting, or SymbolInformation's `containerName`), into `out`. +fn walkSymbols(arena: std.mem.Allocator, out: *std.ArrayList(Symbol), uri: []const u8, node: std.json.Value, qualifier: []const u8, depth: u8) Err!void { if (depth > 8) return; for (items(node)) |sym| { const name = str(get(sym, "name")) orelse continue; + const kind = symbolKind(num(get(sym, "kind")) orelse 0); + const container = if (qualifier.len > 0) qualifier else str(get(sym, "containerName")) orelse ""; + const qualified = if (container.len > 0) try std.fmt.allocPrint(arena, "{s}.{s}", .{ container, name }) else name; + const note = try std.fmt.allocPrint(arena, "{s} {s}", .{ kind.mark(), qualified }); if (get(get(sym, "location"), "range")) |r| { - try emitRange(cx, enc, str(get(get(sym, "location"), "uri")) orelse uri, r, name); + try out.append(arena, .{ .kind = kind, .uri = str(get(get(sym, "location"), "uri")) orelse uri, .range = r, .note = note }); } else { - try emitRange(cx, enc, uri, get(sym, "selectionRange") orelse get(sym, "range"), name); + try out.append(arena, .{ .kind = kind, .uri = uri, .range = get(sym, "selectionRange") orelse get(sym, "range"), .note = note }); } - if (get(sym, "children")) |kids| try walkSymbols(cx, enc, uri, kids, depth + 1); + if (get(sym, "children")) |kids| try walkSymbols(arena, out, uri, kids, qualified, depth + 1); } } +/// LSP's SymbolKind as the Symbols picker's (UX DESIGN N2). +fn symbolKind(lsp_kind: i64) SymbolKind { + return switch (lsp_kind) { + 5, 10, 11, 23, 26 => .type, + 6, 9, 12, 25 => .function, + 7, 8, 22 => .field, + 14 => .constant, + 13, 15...21, 24 => .variable, + 1...4 => .module, + else => .other, + }; +} + /// Pull when the server does (LSP 3.17), the push store otherwise. The store /// path waits briefly for a publish that postdates the didChange we just /// sent, so `]d` right after an edit sees the new truth, not the old one. diff --git a/docs/typ/guide.typ b/docs/typ/guide.typ index 66d3bb00..d80302c5 100644 --- a/docs/typ/guide.typ +++ b/docs/typ/guide.typ @@ -207,7 +207,7 @@ Line 1's first word names what it searches, and editing the word changes it: [`Grep text`], [the lines of those files holding `text`, literally (#key("SPC f g"), #word("Grep")); past 2000 lines #word("More") goes on], [`Recent name`], [the files opened lately, in any window (#key("SPC f r"), #word("Recent"))], [`Panes name`], [the open panes, then the ones closed this session, `(closed)` and dimmer: #key("Enter") (or a #word("Look") at its `@pN`) brings one back where it was, its text with it (#key("SPC b b"), #word("Panes"))], - [`Symbols name`], [the text's declarations (#key("SPC s s"))], + [`Symbols name`], [the text's symbols, a row each: its kind's mark (`t` type, `f` function, `m` field, `c` const, `v` var, `n` module, `·` other), its name in the ones it is in (`Counts.lines`), what its line says after the name; types, functions, fields, then the rest, each in the text's order, and so while typed, the best match current (#key("SPC s s"))], [`All pat`], [every open pane's text, its rows under each pane (#key("SPC /"))], [`Refs`, `Def`, `Impl`, `Diagnostics`], [the language server's lists (#key("g r"), #key("g d"), #key("g i"), #key("SPC l d")): one answer is a jump, none a message; several open the list with the keyboard on its current row in normal mode (#keys("j", "k", "n", "N") step it, #key("Enter") lands, #key("Esc") goes back), the diagnostics' keeping it in the text for `]d`; their places in the text tinted as a `/`'s are], ) diff --git a/docs/typ/reference.typ b/docs/typ/reference.typ index 42b44fc9..035625cf 100644 --- a/docs/typ/reference.typ +++ b/docs/typ/reference.typ @@ -290,7 +290,8 @@ A line written to #file("exec") is #word("Exec"): runtime depth (1–64, default 8) for subsequent queries. #word("Callers") and #word("Callees") keep their short lists and single-result jumps. - #word("Diagnostics") and #word("Symbols") list the file's in `+Search`; + #word("Diagnostics") and #word("Symbols") list the file's in `+Search` + (its symbols marked and in the order #key("SPC s s") lists them); #word("Lspinfo") fills `+Lsp`, the pane its write answers, with the index the file asks (`scip: , , , , indexed , files newer`, or `scip: no index.scip above ; diff --git a/test/behaviour/language_servers.zig b/test/behaviour/language_servers.zig index 13e42fa6..80d1cb1e 100644 --- a/test/behaviour/language_servers.zig +++ b/test/behaviour/language_servers.zig @@ -206,7 +206,7 @@ test "language-servers: Symbols lists the file's definitions by name, a local's try s.write(s.at("/pane/{d}/look", .{main}), s.at("{s}/lib.rs\n", .{std.fs.path.dirname(std.mem.trimEnd(u8, try s.read(s.at("/pane/{d}/name", .{main})), "\n")).?})); try s.write(s.at("/pane/{d}/ctl", .{try s.focused()}), "Symbols\n"); const rows = try bodyOf(&s, "+Search"); - for ([_][]const u8{ "lib.rs:1:11-15\nShape\n", "lib.rs:2:8-11\narea\n", "lib.rs:5:8-10\nadd\n", "lib.rs:8:12-17\nSquare\n", "lib.rs:10:8-11\narea\n" }) |row| + for ([_][]const u8{ "lib.rs:1:11-15 Shape\n", "lib.rs:2:8-11 area\n", "lib.rs:5:8-10 add\n", "lib.rs:8:12-17 Square\n", "lib.rs:10:8-11 area\n" }) |row| try std.testing.expect(has(rows, row)); try std.testing.expect(!has(rows, "lib.rs:5:12")); } @@ -323,3 +323,26 @@ test "language-servers: SPC l a lists the server's code actions in the pane's ta try s.keys("u"); try s.expect(body, before); } + +test "language-servers: a server's Symbols are the Symbols picker's rows: types, functions, fields, then the rest, each its kind's mark and its name in the ones it is in (UX DESIGN N)" { + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var s = try Session.initLanguage(std.testing.allocator); + defer s.deinit(); + try s.write("/ctl", "Jumps new-pane\n"); + // No index: the server is asked. + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "shapes.rs", .data = "const LIMIT: u32 = 4;\n\nfn main() {}\npub struct Shape {\n side: u32,\n fn area() {}\n}\nenum Kind {\n Round,\n}\nmod lib;\n" }); + var buf: [4096]u8 = undefined; + const dir = buf[0..try tmp.dir.realPath(std.testing.io, &buf)]; + const shapes = try s.lookFile(s.at("{s}/shapes.rs:1:1", .{dir})); + try s.write(s.at("/pane/{d}/ctl", .{shapes}), "Symbols\n"); + const rows = try bodyOf(&s, "+Search"); + var at: usize = 0; + for ([_][]const u8{ "shapes.rs:4:12-16 t Shape\n", "shapes.rs:8:6-9 t Kind\n", "shapes.rs:3:4-7 f main\n", "shapes.rs:6:8-11 f Shape.area\n", "shapes.rs:5:5-8 m Shape.side\n", "shapes.rs:9:5-9 m Kind.Round\n", "shapes.rs:1:7-11 c LIMIT\n", "shapes.rs:11:5-7 n lib\n" }) |row| { + const found = std.mem.indexOfPos(u8, rows, at, row) orelse { + std.debug.print("{s} not after {d} in\n{s}\n", .{ row, at, rows }); + return error.TestUnexpectedResult; + }; + at = found + row.len; + } +} diff --git a/test/lspmock.zig b/test/lspmock.zig index 0fd34677..6f52f568 100644 --- a/test/lspmock.zig +++ b/test/lspmock.zig @@ -257,8 +257,15 @@ fn handle(a: std.mem.Allocator, raw: []const u8) void { } else if (std.mem.eql(u8, method, "textDocument/hover")) { reply(a, rid, "{{\"contents\":{{\"kind\":\"markdown\",\"value\":\"mock hover: pub fn add\"}}}}", .{}); } else if (std.mem.eql(u8, method, "textDocument/documentSymbol")) { - reply(a, rid, "[{{\"name\":\"main\",\"kind\":12,\"range\":{s},\"selectionRange\":{s}}}]", .{ - range(a, 2, 0, 11), range(a, 2, 3, 7), + // Nested and in no kind's order: a const, a function, a struct + // with a field and a method, an enum with a member, a module. + reply(a, rid, "[{{\"name\":\"LIMIT\",\"kind\":14,\"range\":{s},\"selectionRange\":{s}}},{{\"name\":\"main\",\"kind\":12,\"range\":{s},\"selectionRange\":{s}}}," ++ + "{{\"name\":\"Shape\",\"kind\":23,\"range\":{s},\"selectionRange\":{s},\"children\":[{{\"name\":\"side\",\"kind\":8,\"range\":{s},\"selectionRange\":{s}}},{{\"name\":\"area\",\"kind\":6,\"range\":{s},\"selectionRange\":{s}}}]}}," ++ + "{{\"name\":\"Kind\",\"kind\":10,\"range\":{s},\"selectionRange\":{s},\"children\":[{{\"name\":\"Round\",\"kind\":22,\"range\":{s},\"selectionRange\":{s}}}]}},{{\"name\":\"lib\",\"kind\":2,\"range\":{s},\"selectionRange\":{s}}}]", .{ + range(a, 0, 0, 21), range(a, 0, 6, 11), range(a, 2, 0, 11), range(a, 2, 3, 7), + range(a, 3, 0, 18), range(a, 3, 11, 16), range(a, 4, 4, 14), range(a, 4, 4, 8), + range(a, 5, 4, 16), range(a, 5, 7, 11), range(a, 7, 0, 11), range(a, 7, 5, 9), + range(a, 8, 4, 10), range(a, 8, 4, 9), range(a, 10, 0, 8), range(a, 10, 4, 7), }); } else if (std.mem.eql(u8, method, "workspace/symbol")) { const q = str(get(params, "query")) orelse ""; diff --git a/test/snapshots/lsp.golden b/test/snapshots/lsp.golden index c680700d..0db3b21e 100644 --- a/test/snapshots/lsp.golden +++ b/test/snapshots/lsp.golden @@ -59,13 +59,13 @@ == snap symbols grid=120x41 cursor=24,2 |2: ^ a.zig:8 › ␣ l Symbols 1/3 |3: │ │ Walk Look Split Newcol Grep Edit Copy Keep Drop | Find Grep Recent Panes Symbols All Jumplist -|4: │ │ ▶ a.zig:1:7-9 std -|5: │ │ a.zig:3:4-9 helper -|6: │ │ a.zig:7:8-11 main +|4: │ │ ▶ a.zig:3:4-9 f helper +|5: │ │ a.zig:7:8-11 f main +|6: │ │ a.zig:1:7-9 c std |7: │ │ -|8: 1▸const std = @import("std"); +|8: 1 const std = @import("std"); |9: 2 -|10: 3 fn helper(x: u32) u32 { +|10: 3▸fn helper(x: u32) u32 { |11: fn helper(x: u32) u32 |12: (fn (u32) u32) |13: 4 return x + 1; @@ -81,6 +81,6 @@ |4: │ │ nothing matches |5: │ │ |6: │ │ -|8: 1 const std = @import("std"); +|10: 3 fn helper(x: u32) u32 { == snap nothing grid=120x41 cursor=29,2 |2: ^ a.zig:8 › ␣ l Symbols jngd 0 -- cgit v1.3 From 02b64ff90ae2f82fb83a604f6d4ded3459a84620 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 26 Nov 2026 04:54:39 -0300 Subject: Lsp, lsp_client, File, dump: a file of a language a server speaks, opened in a pane (a Look, a landing, a walk step, the boot's file, a restored session's), starts that server and tells it of the file on a worker of its own, so the file's first question finds it ready (agent V4's find for the comparison video, VIDEO2/STORY.md §4.1 and §10.2: pardes's first `gd` cost about 2.5 s where Helix's, LazyVim's and Doom's cost 0.05 s; the user was asked, the default yes); THE CAUSE: dev/lsp/lsp_client.zig spawned a server on the first query that needed it (its header's lifecycle), and that query paid the spawn, the handshake and the server's first parse of the file; THE FIX: an effect `lsp_open`, emitted beside the file's watch by File.open (look.open, Trail's step, the boot document) and dump.revivePane (a restored or upgraded session), performed through a Host entry `lsp_open` (tui, gui and macOS: Inbox.openLsp; not held for `threads_ok`: the boot's file and a restored session's are opened before the loop's threads start); dev/Lsp.zig `open` asks nothing for a file no spec speaks for (lsp.speaks, on the loop), else copies the pane's file (`snapshot`) and hands it to a worker of its own (`Opener`, one at a time: a file opened while one is under way is let go and told at its first query, syncDoc; one done is awaited, at once, before the next), which calls lsp_client.open: a spec disabled asks nothing, a binary not found disables the spec without a word (its first query says `language server for .py not found`, not every file opened), else `ensure` (the server started as a query starts it, `starting` and `ready` narrated as before, one per spec) and `syncDoc` (didOpen); nothing in the query log; not through Lsp.start (its cancel and join of the query in flight waits out a protected handshake, up to init_ms = 8 s, on the loop) nor `work` (the queries' one fixed region, memory.takeLspQuery); a picker's preview (Pick.preview, no pane) and a 9P `ctl get` (ninep/ctl.zig getFile, no File.open) start none; Lspinfo says `not started yet (a file of its opened starts it)`; docs/typ/setup.typ and reference.typ say when a server starts; THE HARNESSES (the coordinator's ruling: no test starts a server of this machine's): PARDES_LSP_OPEN=off starts none and is the process harnesses' default (test/process.zig's child environment, test/tty.zig, and test/fs.py, selfmount.py and daemon.py's base_env), so the `lsp` tty cases' zls is started by their first query as before; a test binary (builtin.is_test) starts none unless it says `on`, as the behaviour harness's language sessions do (Session.initLanguage, every spec the mock or off, `.lsp_open` drained as a host performs it, awaited); RUN (TEST FIRST): behaviour/language_servers.zig "a file of a server's language opened in a pane starts that server and tells it of the file, with no query asked; a picker's preview of one starts none, a second file no second server, and a server not installed is found silently" previews a.zig in Find's picker (Lspinfo: zls `not started yet`), opens it (zls `ready`, `docs 1`, the query count unchanged), opens b.zig (`docs 2`: the same server), and opens c.py and d.py with PARDES_LSP_PY naming no binary (pyright `disabled`, no query, nothing on the screen): fails on the base at language_servers.zig:367 (zls not started by the open), passes now; lsp_client.zig "a file opened whose server is not installed disables it without a word ..." opens two .py files with a status sink set: the spec disabled, no word posted, a query then `not found`; MEASURED (.scratch/walkui/T23/measure-v8.sh: VIDEO's probe.py, the screen polled every 50 ms, this change's Debug tui, a reflink copy of VIDEO2's V8 tree with clangd and its 27-file compile database, torque-parser.cc opened, `743ggfI` then `gd` 4 s after the start, until utils.h's `bool IsUpperCamelCase` shows): with PARDES_LSP_OPEN=off (the base's way) 1.97, 1.98, 1.97 s; started at the open 0.05, 0.05, 0.05 s; on VIDEO's tally with zls (measure.sh) both ways 0.05-0.10 s (zls starts and answers within one poll there); a user hit it on the first question of every file of a session's languages, about 2 s with clangd over a real project; NEW HOT PATHS: none per key or frame; per file opened, one effect more and on the loop lsp.speaks (the spec table's extensions); for a file a spec speaks for, a copy of its text (the snapshot a query makes) and a worker started; GATES: core-test 1130/1304 (174 skipped: +1), shell-test 1352/1355 (3 skipped: +1), pane-test 183/184, behaviour-test 286/286 (+1) and --replay 20 seeds of 70 steps, 0 failures, process-test 0 of 147 failed (3 skipped), term-test 17/17, kitty-test 45/45; the wire's semantics move (a Host entry, tape.shape); no dump change (effects are local, not dumped); the soak `replicas -- --clients 5 --rtt 30,80,207` dies on the base too (5dab435d7262, run here: `allocator leaks detected` at seed 0 rtt 80, MuPDF's allocations of documents a picker previewed, Pick.showKind), so run without the pdf addon (its binary, `--addon` image and life): diverged 0, unequal 0, quiet checks 468/0 251/0 657/0, stops not on may_wait 0, the corpus 22 of 22 scenes the same, no leak (a first run had one key stop at `spawn` at seed 3 rtt 80, exec.zig's rerun of a command pane, which emits a spawn with no `open a terminal` stop; the base's run and a second run had none); the gui unit-test run once, on T3's change over this one (its description); no frame or perf gate (the user's rule of 2026-11-26); load 1.1 to 9.1 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016Y9MNBFhdevVu48bvL9kCE --- core/Effect.zig | 6 +++ core/File.zig | 8 +++- core/dump.zig | 6 ++- core/lsp/lsp.zig | 6 +++ dev/Host.zig | 3 ++ dev/Inbox.zig | 11 +++++ dev/Lsp.zig | 40 +++++++++++++++++ dev/gui/gui.zig | 8 ++++ dev/lsp/lsp_client.zig | 88 ++++++++++++++++++++++++++++++++++--- dev/tui/tui.zig | 8 ++++ docs/typ/reference.typ | 2 +- docs/typ/setup.typ | 6 ++- runtime/macos.zig | 6 +++ test/behaviour/language_servers.zig | 57 ++++++++++++++++++++++++ test/daemon.py | 3 ++ test/fs.py | 2 + test/process.zig | 5 ++- test/selfmount.py | 2 + test/session.zig | 19 +++++++- test/tty.zig | 5 ++- 20 files changed, 274 insertions(+), 17 deletions(-) (limited to 'dev') diff --git a/core/Effect.zig b/core/Effect.zig index 3bca04c9..72244f2b 100644 --- a/core/Effect.zig +++ b/core/Effect.zig @@ -64,6 +64,10 @@ pub const Effect = union(enum) { /// `arg` up to 128 bytes, or for `explain` the query it explains, /// ` `. lsp: struct { id: u32, kind: lsp.Kind, pane: Pane.Id, offset: u32, arg: Buf(160) }, + /// A file opened in pane `pane` (File.open, a session's revived pane): + /// the server its language speaks to started and told of it, off the + /// loop (dev/Lsp.zig open), so its first query finds it ready. + lsp_open: struct { pane: Pane.Id }, /// Snapshot the matching request with pipeRequest(id), then run it away /// from the UI/event loop and answer with pipe_resp. pipe: struct { id: u32 }, @@ -216,6 +220,8 @@ fn performInner(p: *Pardes, e: Effect) void { }, .lsp => |q| p.tape.host(p, .lsp, .{.{ .id = q.id, .kind = q.kind, .pane = q.pane, .offset = q.offset, .arg = q.arg.slice() }}) orelse p.update(.{ .lsp_resp = .{ .id = q.id, .rows = "" } }), + // No workers here (a test, a board): no server starts before a query. + .lsp_open => |o| _ = p.tape.host(p, .lsp_open, .{o.pane}), .pipe => |q| p.tape.host(p, .pipe, .{q.id}) orelse p.update(.{ .pipe_resp = .{ .id = q.id, .success = false, .outputs = &.{} } }), // No workers here (a test, a board): it runs on the loop. diff --git a/core/File.zig b/core/File.zig index 0f9178ac..d16b0c73 100644 --- a/core/File.zig +++ b/core/File.zig @@ -922,7 +922,13 @@ pub fn open(p: *Pardes, id: usize, path: []const u8, line: usize) !*Pane { pane.body.cur_pinned = true; pane.body.cur_row = @intCast(scroll); p.installPane(id, pane); - if (filesystem.localPath(path) != null) p.emit(.{ .watch = .{ .pane = .at(id), .on = true } }); + if (filesystem.localPath(path) != null) { + p.emit(.{ .watch = .{ .pane = .at(id), .on = true } }); + // Its language's server started now, off the loop: the first + // question asked of it finds it ready. Not a picker's preview's, + // which opens no pane (Pick.preview). + p.emit(.{ .lsp_open = .{ .pane = .at(id) } }); + } return pane; } diff --git a/core/dump.zig b/core/dump.zig index 2dde9c8c..d7c44b71 100644 --- a/core/dump.zig +++ b/core/dump.zig @@ -718,8 +718,9 @@ fn reviveSession(p: *Pardes, previous: ?*Pardes, resumed: bool) !void { } /// A loaded pane given to this host: a terminal a new shell in its old -/// one's directory under its history, a file watched again (one changed on -/// disk since comes back as it is now, one unsaved is marked changed), a +/// one's directory under its history, a file watched again and its +/// language's server started (one changed on disk since comes back as it +/// is now, one unsaved is marked changed), a /// kind's pane opened again (a PDF a build before the pdf addon dumped, as /// the addon's). fn revivePane(p: *Pardes, id: usize, pane: *pardes.panes.Pane, was_on_disk: bool) void { @@ -762,6 +763,7 @@ fn revivePane(p: *Pardes, id: usize, pane: *pardes.panes.Pane, was_on_disk: bool } else |_| {} } p.emit(.{ .watch = .{ .pane = .at(id), .on = true } }); + p.emit(.{ .lsp_open = .{ .pane = .at(id) } }); // Its file gone from disk since the dump: its text is nowhere else, so // it is said deleted, and Del, Exit and Restore ask first. One never on // disk (a name not yet saved) comes back as it was. diff --git a/core/lsp/lsp.zig b/core/lsp/lsp.zig index 7a636f72..00ffc98b 100644 --- a/core/lsp/lsp.zig +++ b/core/lsp/lsp.zig @@ -96,6 +96,12 @@ pub fn query(io: std.Io, arena: std.mem.Allocator, req: Req, out: *std.Io.Writer return client.query(io, arena, req, out); } +/// A file opened in a pane: its language's server started and told of it +/// (lsp_client.open), on a host's worker. +pub fn open(io: std.Io, arena: std.mem.Allocator, req: Req) !void { + return client.open(io, arena, req); +} + /// The one line the client answers with when it cannot answer at all, and /// why: the core says it rather than "nothing found". pub fn none(out: *std.Io.Writer, comptime fmt: []const u8, args: anytype) std.Io.Writer.Error!void { diff --git a/dev/Host.zig b/dev/Host.zig index 52205518..0a175754 100644 --- a/dev/Host.zig +++ b/dev/Host.zig @@ -54,6 +54,9 @@ pub const VTable = struct { /// startDetached. Null once it runs, else why not. start: ?*const fn (ctx: ?*anyopaque, line: []const u8, why: []u8) ?[]const u8 = null, lsp: ?*const fn (ctx: ?*anyopaque, req: Lsp.Request) void = null, + /// Start the language server of the file `pane` opened, and tell it of + /// the file, on a worker (Lsp.open). + lsp_open: ?*const fn (ctx: ?*anyopaque, pane: pardes.Pane.Id) void = null, pipe: ?*const fn (ctx: ?*anyopaque, id: u32) void = null, /// Start the streaming search of this generation on a worker /// (pardes.Stream.start); absent, it runs on the loop. diff --git a/dev/Inbox.zig b/dev/Inbox.zig index bc7c7e8a..a0b9494d 100644 --- a/dev/Inbox.zig +++ b/dev/Inbox.zig @@ -67,6 +67,9 @@ gpa: std.mem.Allocator, lsp_allocator: std.mem.Allocator, /// The query in flight; the UI thread's alone (spawnLsp, teardown). lsp_task: ?Lsp.Task = null, +/// The server start a file's opening asked for (openLsp); the UI +/// thread's alone. +lsp_opener: Lsp.Opener = .{}, /// The `|` pipes' and the addons' jobs' and draws' workers in flight, each /// posting its answer here (`pushPipe`, `pushJob`); the loop's thread's /// alone: joined as their answers land (`land`), canceled at the end. @@ -290,6 +293,8 @@ pub fn deinit(q: *Inbox) void { // The workers in flight end first: what they still deliver is dropped. if (q.lsp_task) |*t| t.future.cancel(q.io); q.lsp_task = null; + if (q.lsp_opener.future) |*f| f.cancel(q.io); + q.lsp_opener.future = null; q.pipe_tasks.cancelAll(q.io); q.job_tasks.cancelAll(q.io); q.close(); @@ -343,6 +348,12 @@ pub fn startLsp(q: *Inbox, core: *pardes.Pardes, e: Lsp.Request) void { Lsp.start(q.io, q.lsp_allocator, core, &q.lsp_task, e, q, pushLspRows); } +/// The language server of the file `pane` opened started, on a worker of +/// its own (Lsp.open). +pub fn openLsp(q: *Inbox, core: *const pardes.Pardes, pane: pardes.Pane.Id) void { + Lsp.open(q.io, q.lsp_allocator, core, &q.lsp_opener, pane); +} + /// A worker's answer taken off the queue, to the core (whichever frontend /// took it), its worker joined: a language server's answer or status line, /// a pipe's, a search's rows, an addon's job or draw, a handover's end. diff --git a/dev/Lsp.zig b/dev/Lsp.zig index b799c9f6..d7638c83 100644 --- a/dev/Lsp.zig +++ b/dev/Lsp.zig @@ -138,6 +138,46 @@ pub fn start(io: std.Io, gpa: std.mem.Allocator, core: *pardes.Pardes, task: *?T task.* = .{ .id = req.id, .future = future }; } +/// The server start a file's opening asks for (`open`), one at a time: +/// `busy` while its worker runs. +pub const Opener = struct { + future: ?std.Io.Future(void) = null, + busy: std.atomic.Value(bool) = .init(false), +}; + +/// Pane `pane`'s file just opened: the server of its language started and +/// told of it (lsp_client.open) on a worker of its own, so its first query +/// finds both done (that query paid a spawn and a handshake, 2.5 s of zls's +/// over the comparison video's project). Not through `start`, whose cancel +/// of the query in flight waits out a handshake on the loop, nor `work`, +/// whose fixed region is the queries'. One at a time: a file opened while +/// one is under way is let go, and told at its first query (syncDoc); one +/// done is awaited (at once) before the next. +pub fn open(io: std.Io, gpa: std.mem.Allocator, core: *const pardes.Pardes, opener: *Opener, pane: pardes.Pane.Id) void { + if (opener.busy.load(.acquire)) return; + if (opener.future) |*f| f.await(io); + opener.future = null; + const p = core.panes[pane.index()] orelse return; + const f = p.file orelse return; + if (!pardes.lsp.speaks(f.path)) return; + const job = snapshot(gpa, core, .{ .id = 0, .kind = .definition, .pane = pane, .offset = 0, .arg = "" }) catch return; + opener.busy.store(true, .release); + opener.future = io.concurrent(tell, .{ io, gpa, job, &opener.busy }) catch { + opener.busy.store(false, .release); + return job.free(gpa); + }; +} + +fn tell(io: std.Io, gpa: std.mem.Allocator, job: *Job, busy: *std.atomic.Value(bool)) void { + defer busy.store(false, .release); + defer job.free(gpa); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + // A server that failed to start says so itself (`ensure`); one not + // started for want of memory is started by the file's first query. + pardes.lsp.open(io, arena.allocator(), .{ .kind = job.kind, .path = job.path, .source = job.source, .offset = 0, .root = job.root }) catch {}; +} + pub fn work(io: std.Io, gpa: std.mem.Allocator, job: *Job, ctx: ?*anyopaque, deliver: Deliver) void { defer job.free(gpa); // The query's memory is the fixed region memory.zig reserved at diff --git a/dev/gui/gui.zig b/dev/gui/gui.zig index a478db03..7a87c110 100644 --- a/dev/gui/gui.zig +++ b/dev/gui/gui.zig @@ -2648,6 +2648,7 @@ const Shell = struct { .open_link = openLink, .start = host_io.startDetached, .lsp = lsp, + .lsp_open = lspOpen, .pipe = pipe, .search = search, .hand_over = handOver, @@ -3223,6 +3224,13 @@ fn lsp(ctx: ?*anyopaque, req: host_io.Lsp.Request) void { s.core.reportError(req.pane, "lsp", error.WorkersUnavailable); } +/// Not held for `threads_ok`: the boot's file and a restored session's are +/// opened before `start`. +fn lspOpen(ctx: ?*anyopaque, pane: pardes.Pane.Id) void { + const s = shellOf(ctx); + s.queue.openLsp(s.core, pane); +} + fn pipe(ctx: ?*anyopaque, id: u32) void { const s = shellOf(ctx); if (s.threads_ok) return selection_pipe.start(s.io, s.gpa, s.core, &s.queue.pipe_tasks, id, s.queue, Queue.pushPipe); diff --git a/dev/lsp/lsp_client.zig b/dev/lsp/lsp_client.zig index a53ff57f..be5069ae 100644 --- a/dev/lsp/lsp_client.zig +++ b/dev/lsp/lsp_client.zig @@ -6,9 +6,10 @@ //! //! THE PROCESS LIFECYCLE IS THE DESIGN. `lsp.query` is a synchronous call on a //! worker thread, and a language server costs tens of milliseconds to start -//! and MINUTES to index a large workspace. So a server is spawned lazily on -//! the first query that needs it, kept for the life of the editor, and each -//! spec gets at most one — `conns[i]` guards itself with an `Io.Mutex` +//! and MINUTES to index a large workspace. So a server is spawned when a +//! file of its language opens in a pane (`open`, on a worker of its own) or +//! by the first query that needs it, kept for the life of the editor, and +//! each spec gets at most one — `conns[i]` guards itself with an `Io.Mutex` //! because a canceled query can still be inside `run` when the next arrives. //! Every wait is an `Io` cancelation point: a shell cancels the worker of a //! query it no longer wants, and the worker stops there. @@ -40,7 +41,8 @@ //! (ignoring SIGPIPE process-wide would be inherited by every pty shell we //! fork and would change what `yes | head` does in a pane), //! - a binary missing from PATH costs one cached probe, disables the spec -//! for the session, and says so ONCE on the message row. +//! for the session, and says so ONCE on the message row (a query's; a +//! file opened says nothing). //! //! Position encoding is negotiated to utf-8 and the SERVER'S ANSWER is //! believed, not our request; the utf-16 conversion is implemented in both @@ -478,8 +480,8 @@ fn status(io: std.Io, path: []const u8, out: *std.Io.Writer) !void { const thier = c.caps.type_hier; c.mu.unlock(io); const env_v = if (libc.getenv(s.env)) |v| std.mem.span(v) else null; - // Never spawned is not off: the first query of its files starts it. - try out.print(" {s:<28} {s}", .{ s.name, if (state == .off) "not started yet (its first query starts it)" else @tagName(state) }); + // Never spawned is not off: a file of its opened starts it. + try out.print(" {s:<28} {s}", .{ s.name, if (state == .off) "not started yet (a file of its opened starts it)" else @tagName(state) }); if (state == .ready or state == .starting) { try out.print(" root {s} {s}", .{ root, @tagName(enc) }); if (pull) try out.print(" pull-diags", .{}); @@ -757,6 +759,36 @@ pub fn query(io: std.Io, arena: std.mem.Allocator, asked: lsp.Req, out: *std.Io. try out.writeAll(scratch.buffered()); } +/// A file opened in a pane (dev/Lsp.zig open): the server of its language +/// started as its first query would start it (`ensure`, which says +/// `starting` and `ready` on the message row) and told of the file +/// (didOpen), so that query finds both done. A server not installed is +/// disabled without a word: the file's first query says it is not found, +/// not every file opened. Nothing in the query log: none was asked. +/// PARDES_LSP_OPEN=off starts none (the process harnesses' default), and a +/// test binary starts none unless it says `on` (the behaviour harness's +/// language sessions, their servers the mock): no test starts a server of +/// this machine's by opening a file. +pub fn open(io: std.Io, arena: std.mem.Allocator, req: lsp.Req) Err!void { + const said = if (libc.getenv("PARDES_LSP_OPEN")) |v| std.mem.span(v) else ""; + if (std.mem.eql(u8, said, "off") or (builtin.is_test and !std.mem.eql(u8, said, "on"))) return; + const si = specFor(req.path) orelse return; + const c = &conns[si]; + try c.mu.lock(io); + defer c.mu.unlock(io); + if (c.state == .disabled) return; + var exe_buf: [4096:0]u8 = undefined; + if (!c.alive() and binOf(&specs[si], &exe_buf) == null) { + c.state = .disabled; + return; + } + var tr: Trace = .{}; + _ = try ensure(c, io, si, arena, req, &tr); + var uri: std.ArrayList(u8) = .empty; + try uriOf(&uri, arena, req.path); + try syncDoc(c, io, si, arena, uri.items, req.source); +} + fn traceOut(tr: *const Trace, req: lsp.Req, out: *std.Io.Writer, rows: usize, us: u64) std.Io.Writer.Error!void { if (req.kind != .explain) return; try out.print("lsp explain — the {s} query at byte {d} of {s}\n\n", .{ @@ -3162,11 +3194,53 @@ test "a language with no server to start says so, not that it did not answer" { try std.testing.expectEqualStrings("@none language server for .py not found\n", out.buffered()); } +test "a file opened whose server is not installed disables it without a word, at every file's open; a query of it then says it is not found" { + const host_io = @import("../host_io.zig"); + const io = std.testing.io; + const si = specFor("/x/a.py") orelse return; + const c = &conns[si]; + const was_state = c.state; + defer c.state = was_state; + // A test binary's files start servers only where it says so. + const names = [_][*:0]const u8{ "PARDES_LSP_PY", "PARDES_LSP_OPEN" }; + var was_buf: [names.len][4096:0]u8 = undefined; + var was: [names.len]?[:0]const u8 = undefined; + for (names, &was, &was_buf) |name, *w, *b| w.* = if (libc.getenv(name)) |v| try std.fmt.bufPrintSentinel(b, "{s}", .{std.mem.span(v)}, 0) else null; + defer for (names, was) |name, w| { + _ = if (w) |v| host_io.Shell.setenv(name, v.ptr, 1) else host_io.testUnsetenv(name); + }; + _ = host_io.Shell.setenv("PARDES_LSP_PY", "/nonexistent/pyright-langserver", 1); + _ = host_io.Shell.setenv("PARDES_LSP_OPEN", "on", 1); + const Said = struct { + var n: usize = 0; + fn post(_: ?*anyopaque, _: []const u8) void { + n += 1; + } + }; + Said.n = 0; + // A word said before is never said twice in a row (`post`): forgotten. + sink_last_len[si] = 0; + setStatusSink(null, Said.post); + defer setStatusSink(null, null); + c.state = .off; + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + for ([_][]const u8{ "/x/a.py", "/x/b.py" }) |path| { + try open(io, arena.allocator(), .{ .kind = .definition, .path = path, .source = "", .offset = 0, .root = "/x" }); + try std.testing.expectEqual(State.disabled, c.state); + } + try std.testing.expectEqual(@as(usize, 0), Said.n); + var buf: [256]u8 = undefined; + var out: std.Io.Writer = .fixed(&buf); + try query(io, arena.allocator(), .{ .kind = .hover, .path = "/x/a.py", .source = "", .offset = 0 }, &out); + try std.testing.expectEqualStrings("@none language server for .py not found\n", out.buffered()); +} + test "Lspinfo before any query says a server is not started yet, not off" { var out: std.Io.Writer.Allocating = .init(std.testing.allocator); defer out.deinit(); try status(std.testing.io, "/x/notes.txt", &out.writer); - try std.testing.expect(std.mem.indexOf(u8, out.written(), "not started yet (its first query starts it)") != null); + try std.testing.expect(std.mem.indexOf(u8, out.written(), "not started yet (a file of its opened starts it)") != null); } test "a server that failed a moment ago is said to have failed, and when it is tried again, not to be missing" { diff --git a/dev/tui/tui.zig b/dev/tui/tui.zig index aa1f8849..f7b9cae8 100644 --- a/dev/tui/tui.zig +++ b/dev/tui/tui.zig @@ -1328,6 +1328,7 @@ const Shell = struct { .open_link = openLink, .start = host_io.startDetached, .lsp = lsp, + .lsp_open = lspOpen, .pipe = pipe, .search = search, .job = job, @@ -2047,6 +2048,13 @@ const Shell = struct { s.core.reportError(req.pane, "lsp", error.WorkersUnavailable); } + /// Not held for `threads_ok`: the boot's file and a restored + /// session's are opened before `start`. + fn lspOpen(ctx: ?*anyopaque, pane: pardes.Pane.Id) void { + const s = of(ctx); + s.ptys.queue.openLsp(s.core, pane); + } + fn pipe(ctx: ?*anyopaque, id: u32) void { const s = of(ctx); if (!s.threads_ok) { diff --git a/docs/typ/reference.typ b/docs/typ/reference.typ index 42b44fc9..a08d3acc 100644 --- a/docs/typ/reference.typ +++ b/docs/typ/reference.typ @@ -295,7 +295,7 @@ A line written to #file("exec") is #word("Exec"): index the file asks (`scip: , , , , indexed , files newer`, or `scip: no index.scip above ; Index runs `), which server serves it and its state (`not - started yet` until its first query starts it, ` failed recently; + started yet` until a file of its opened starts it, ` failed recently; retry in Ns` while it backs off), and what answered each query lately (`scip`, or the server); #word("Lspwhy") narrates the last query step by step (in `+Lsp`). The diff --git a/docs/typ/setup.typ b/docs/typ/setup.typ index c9556c61..3ef67da5 100644 --- a/docs/typ/setup.typ +++ b/docs/typ/setup.typ @@ -119,8 +119,10 @@ script on that `PATH` is a word you can click. = Language servers -pardes starts a language server for a file it knows, searching `PATH` first -and then `~/.local/bin` (desktop launchers may leave it out of `PATH`): +pardes starts a language server when a file it knows opens in a pane (a +picker's preview starts none), searching `PATH` first and then +`~/.local/bin` (desktop launchers may leave it out of `PATH`), so the +file's first question finds it ready: #pairs( [`.zig`], [`zls` (`PARDES_LSP_ZIG`)], diff --git a/runtime/macos.zig b/runtime/macos.zig index 7e0f50e7..6a6d39a2 100644 --- a/runtime/macos.zig +++ b/runtime/macos.zig @@ -1628,6 +1628,7 @@ const vtable: pardes.Host.VTable = .{ .open_link = openLink, .start = host_io.startDetached, .lsp = lspRequest, + .lsp_open = lspOpen, .pipe = pipeRequest, }; @@ -1640,6 +1641,11 @@ fn lspRequest(ctx: ?*anyopaque, req: host_io.Lsp.Request) void { st.inbox.startLsp(st.core, req); } +fn lspOpen(ctx: ?*anyopaque, pane: pardes.Pane.Id) void { + const st = hostState(ctx); + st.inbox.openLsp(st.core, pane); +} + fn pipeRequest(ctx: ?*anyopaque, id: u32) void { const st = hostState(ctx); selection_pipe.start(st.io, st.gpa, st.core, &st.pipe_tasks, id, &st.inbox, Inbox.pushPipe); diff --git a/test/behaviour/language_servers.zig b/test/behaviour/language_servers.zig index 13e42fa6..79b556f4 100644 --- a/test/behaviour/language_servers.zig +++ b/test/behaviour/language_servers.zig @@ -323,3 +323,60 @@ test "language-servers: SPC l a lists the server's code actions in the pane's ta try s.keys("u"); try s.expect(body, before); } + +extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int; + +/// The row of Lspinfo's report on the server `name` (`zls`), asked of the +/// pane with the keyboard, and how many queries its client has answered. +fn serverRow(s: *Session, name: []const u8) !struct { []const u8, []const u8 } { + try s.write(s.at("/pane/{d}/ctl", .{try s.focused()}), "Lspinfo\n"); + const info = try bodyOf(s, "+Lsp"); + const at = (std.mem.indexOf(u8, info, s.at("\n {s} ", .{name})) orelse return error.NoSuchServer) + 1; + const row = info[at .. std.mem.indexOfScalarPos(u8, info, at, '\n') orelse info.len]; + const log = std.mem.indexOf(u8, info, "client queries (") orelse return error.NoQueryLog; + return .{ row, info[log .. std.mem.indexOfPos(u8, info, log, " total") orelse return error.NoQueryLog] }; +} + +test "language-servers: a file of a server's language opened in a pane starts that server and tells it of the file, with no query asked; a picker's preview of one starts none, a second file no second server, and a server not installed is found silently" { + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + // A work tree of its own: Find searches it, not the one the test runs in. + try tmp.dir.createDir(io, ".git", .default_dir); + try tmp.dir.writeFile(io, .{ .sub_path = "a.zig", .data = "const a = 1;\n" }); + try tmp.dir.writeFile(io, .{ .sub_path = "b.zig", .data = "const b = 2;\n" }); + try tmp.dir.writeFile(io, .{ .sub_path = "c.py", .data = "c = 3\n" }); + try tmp.dir.writeFile(io, .{ .sub_path = "d.py", .data = "d = 4\n" }); + try tmp.dir.writeFile(io, .{ .sub_path = "notes.txt", .data = "the notes\n" }); + var buf: [4096]u8 = undefined; + const dir = buf[0..try tmp.dir.realPath(io, &buf)]; + var s = try Session.initLanguage(std.testing.allocator); + defer s.deinit(); + _ = try s.lookFile(s.at("{s}/notes.txt", .{dir})); + // a.zig previewed by Find's picker (the session's jumps walk): its text + // shown, its server (the scripted one, the session's zls) not started. + try s.keys(" ffa.zig"); + s.tick(); + try std.testing.expect(has(try s.screen(), "const a = 1;")); + try s.keys("\x1b"); + const before, const asked = try serverRow(&s, "zls"); + try std.testing.expect(has(before, "not started yet")); + // Opened: started and told of a.zig, no query asked of it. + _ = try s.lookFile(s.at("{s}/a.zig", .{dir})); + const opened, const asked_open = try serverRow(&s, "zls"); + try std.testing.expect(has(opened, "ready") and has(opened, "docs 1")); + try std.testing.expectEqualStrings(asked, asked_open); + // A second file: the same server told of it too (a second would know one). + _ = try s.lookFile(s.at("{s}/b.zig", .{dir})); + const second, _ = try serverRow(&s, "zls"); + try std.testing.expect(has(second, "ready") and has(second, "docs 2")); + // Not installed: the language's server disabled at the first file's + // open, with no word at either (its first query says it is not found). + _ = setenv("PARDES_LSP_PY", "/nonexistent/pyright-langserver", 1); + _ = try s.lookFile(s.at("{s}/c.py", .{dir})); + _ = try s.lookFile(s.at("{s}/d.py", .{dir})); + const missing, const asked_missing = try serverRow(&s, "pyright"); + try std.testing.expect(has(missing, "disabled")); + try std.testing.expectEqualStrings(asked, asked_missing); + try std.testing.expect(!has(try s.screen(), "not found")); +} diff --git a/test/daemon.py b/test/daemon.py index 3dfb0710..95a4da75 100644 --- a/test/daemon.py +++ b/test/daemon.py @@ -92,6 +92,9 @@ def base_env(): of the user's) or a pager; under `--with-pair`, PARDES_PAIR set in it, as for a user who exported it: every mode run with the variable.""" env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k} + # No language server starts at a file's open (lsp_client.open): none of + # this machine's. + env['PARDES_LSP_OPEN'] = 'off' if WITH_PAIR: env['PARDES_PAIR'] = '1' return env diff --git a/test/fs.py b/test/fs.py index a2b67cbc..abf9f1b6 100644 --- a/test/fs.py +++ b/test/fs.py @@ -32,6 +32,8 @@ def session(binary, root, name, *options, socket_name=None, file=None, tty=False env.update(inherited or {}) for language in ['RS', 'C', 'GO', 'TS', 'PY']: env['PARDES_LSP_' + language] = '' + # No server starts at a file's open (lsp_client.open): none of this machine's. + env['PARDES_LSP_OPEN'] = 'off' fixture = root / (name + '.txt') fixture.write_bytes(b'initial\n') address = root / ('pardes-9p-' + (socket_name or name) + '.sock') diff --git a/test/process.zig b/test/process.zig index 791a5b8e..fe5d97f0 100644 --- a/test/process.zig +++ b/test/process.zig @@ -960,9 +960,12 @@ pub const Child = struct { // never the user's: the dumps a test makes there would push the // user's out. if (root_z != null) _ = unsetenv("XDG_DATA_HOME"); + // No language server starts at a file's open (lsp_client.open): + // the `lsp` cases' zls is this machine's, started by their + // first query as before. for ([_][2][*:0]const u8{ .{ "PARDES_DAEMON", "off" }, .{ "PARDES_LSP_RS", "" }, .{ "PARDES_LSP_C", "" }, .{ "PARDES_LSP_GO", "" }, - .{ "PARDES_LSP_TS", "" }, .{ "PARDES_LSP_PY", "" }, + .{ "PARDES_LSP_TS", "" }, .{ "PARDES_LSP_PY", "" }, .{ "PARDES_LSP_OPEN", "off" }, }) |kv| if (setenv(kv[0], kv[1], 1) != 0) _exit(126); if (opts.pty != null and setenv("TERM", "xterm-256color", 1) != 0) _exit(126); // No test reaches the user's display: a window any of them diff --git a/test/selfmount.py b/test/selfmount.py index 61d32523..aa4540b0 100644 --- a/test/selfmount.py +++ b/test/selfmount.py @@ -81,6 +81,8 @@ def run(binary): env.update(PARDES_NOTIME='1', TERM='xterm-256color', PARDES_DUMP=f'/tmp/{name}.dump.zon') for language in ['RS', 'C', 'GO', 'TS', 'PY']: env['PARDES_LSP_' + language] = '' + # No server starts at a file's open (lsp_client.open): none of this machine's. + env['PARDES_LSP_OPEN'] = 'off' pid, master = pty.fork() if pid == 0: os.execve(ns, ['9ns', '--mntgen', '--', binary, '--tty', '--9p=' + name, str(fixture)], env) diff --git a/test/session.zig b/test/session.zig index 13798753..9285c13b 100644 --- a/test/session.zig +++ b/test/session.zig @@ -38,6 +38,8 @@ pub const Session = struct { /// What the language words' questions are asked of their servers /// through (initLanguage); none, and they go unanswered. languages: ?std.Io = null, + /// The server start a file's opening asks for (`languages`'s). + opener: pardes.host_io.Lsp.Opener = .{}, /// Kinds' jobs taken as a host's worker takes them and held, not run, /// until `releaseJobs`: a job under way across what a test does /// meanwhile (a reload). @@ -62,12 +64,19 @@ pub const Session = struct { } /// A session showing one scratch pane that asks language servers as a - /// host does, a `.rs` file's the scripted one (test/lspmock.zig, which - /// answers over a main.rs and the lib.rs beside it). + /// host does, a `.rs` and a `.zig` file's the scripted one + /// (test/lspmock.zig, which answers over a main.rs and the lib.rs beside + /// it), every other language's none: no test starts a server of this + /// machine's. pub fn initLanguage(gpa: std.mem.Allocator) !Session { var s = try initFile(gpa, "x\n"); const mock = try std.Io.Dir.cwd().realPathFileAlloc(std.testing.io, @import("session_options").lspmock, s.arena.allocator()); _ = setenv("PARDES_LSP_RS", mock, 1); + _ = setenv("PARDES_LSP_ZIG", mock, 1); + for ([_][*:0]const u8{ "PARDES_LSP_C", "PARDES_LSP_GO", "PARDES_LSP_TS", "PARDES_LSP_PY" }) |v| _ = setenv(v, "", 1); + // A test binary's opened files start their servers where it says + // so (lsp_client.open): here, the mock. + _ = setenv("PARDES_LSP_OPEN", "on", 1); s.languages = std.testing.io; return s; } @@ -295,6 +304,12 @@ pub const Session = struct { // held while a test holds them (`hold_jobs`). .job => |j| if (!s.hold_jobs) pardesOf(s).perform(e) else if (pardes.host_io.KindJob.take(pardesOf(s), j.pane.index(), j.serial, j.token)) |taken| s.held.append(pardesOf(s).gpa, taken) catch taken.drop(), .lsp => |q| if (s.languages) |io| s.askServer(io, .{ .id = q.id, .kind = q.kind, .pane = q.pane, .offset = q.offset, .arg = q.arg.slice() }), + // A file's server started as a host starts it, and waited for. + .lsp_open => |o| if (s.languages) |io| { + pardes.host_io.Lsp.open(io, pardesOf(s).gpa, pardesOf(s), &s.opener, o.pane); + if (s.opener.future) |*f| f.await(io); + s.opener.future = null; + }, .watch => |w| { if (s.watch_fd < 0) s.watch_fd = pardes.file_watch.init(true); if (s.watch_fd >= 0) _ = pardes.file_watch.applyEffect(pardesOf(s), std.Io.Threaded.global_single_threaded.io(), s.watch_fd, &s.watches, w.pane.index(), w.on, w.mode); diff --git a/test/tty.zig b/test/tty.zig index 97b64b7c..cbb4e446 100644 --- a/test/tty.zig +++ b/test/tty.zig @@ -128,9 +128,12 @@ pub const Tty = struct { _ = setenv("PARDES_NOTIME", "1", 1); _ = setenv("PARDES_TEST_CLOCK", "1", 1); // Hermetic language clients: `.rs` speaks to the mock, every other - // spec is off, so a stray `.c` never spawns this machine's clangd. + // spec but zls is off, so a stray `.c` never spawns this machine's + // clangd, and no server starts at a file's open (lsp_client.open): + // the `lsp` cases' zls is started by their first query. _ = setenv("PARDES_LSP_RS", try arena.dupeSentinel(u8, lspmock, 0), 1); for ([_][*:0]const u8{ "PARDES_LSP_C", "PARDES_LSP_GO", "PARDES_LSP_TS", "PARDES_LSP_PY" }) |v| _ = setenv(v, "", 1); + _ = setenv("PARDES_LSP_OPEN", "off", 1); const dump = try std.fmt.allocPrintSentinel(arena, "{s}/dump.zon", .{base}, 0); _ = setenv("PARDES_DUMP", dump, 1); if (replay) { -- cgit v1.3