interactive shell navigation and history
Something went wrong. Try again.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017const std = @import("std");const builtin = @import("builtin");const assert = std.debug.assert;const zf = @import("zf");const vaxis = @import("vaxis");const vxfw = vaxis.vxfw;const config = @import("config.zig");const input_output = @import("input_output.zig");const walker = @import("walker.zig");
pub const max_grep_lines: usize = 10_000;pub const max_grep_file_bytes: usize = 1 * 1024 * 1024;pub const max_grep_corpus_bytes: usize = 256 * 1024 * 1024;/// Ceiling on the number of files kept in memory. Trees with millions of/// files would otherwise cost hours of stat and read calls even when the/// byte budget already matches.pub const max_grep_files: usize = 50_000;const min_terminal_columns: u16 = 20;const min_terminal_rows: u16 = 8;pub const excerpt_context_before: usize = 5;pub const excerpt_context_after: usize = 15;const binary_probe_bytes: usize = 8192;/// One background loading step inspects at most this many tree entries/// before it hands control back to the event loop.const grep_slice_entries: usize = 512;/// One background loading step runs at most this long before it hands/// control back to the event loop, keeping typing responsive.const grep_slice_time_ns: i96 = 12 * std.time.ns_per_ms;/// A query tracks its words in a u64 bitmask, so words past the 64th are/// ignored rather than overflowing the shift.const max_grep_words: usize = 64;
fn hasUppercase(text: []const u8) bool { for (text) |byte| { if (std.ascii.isUpper(byte)) { return true; } } return false;}
fn checkTerminalSize(input_output_handle: std.Io) !void { if (input_output.getenv("TERM")) |term| { if (std.mem.eql(u8, term, "dumb")) { input_output.warn("dumb terminal cannot run picker\n", .{}); return error.NoTerminal; } } if (builtin.os.tag != .linux) { return; } const tty = std.Io.Dir.openFileAbsolute(input_output_handle, "/dev/tty", .{ .mode = .read_only, .allow_directory = false, .path_only = false, }) catch |err| { input_output.warn("cannot open terminal for picker: {}\n", .{err}); return error.NoTerminal; }; defer tty.close(input_output_handle); var size: std.posix.winsize = .{ .row = 0, .col = 0, .xpixel = 0, .ypixel = 0 }; const ioctl_rc = std.os.linux.ioctl(tty.handle, std.os.linux.T.IOCGWINSZ, @intFromPtr(&size)); if (ioctl_rc != 0) { input_output.warn("cannot query terminal size for picker: {d}\n", .{ioctl_rc}); return error.NoTerminal; } if (size.col < min_terminal_columns) { input_output.warn( "terminal too narrow for picker: {d} columns, need {d}\n", .{ size.col, min_terminal_columns }, ); return error.TerminalTooSmall; } if (size.row < min_terminal_rows) { input_output.warn( "terminal too short for picker: {d} rows, need {d}\n", .{ size.row, min_terminal_rows }, ); return error.TerminalTooSmall; }}
pub const ResolvedTheme = struct { prompt: vaxis.Style, match: vaxis.Style, cursor_row: vaxis.Style, status: vaxis.Style, preview_current: vaxis.Style, bg: vaxis.Color, fg: vaxis.Color,};
fn defaultTheme() ResolvedTheme { return .{ .prompt = .{ .fg = .{ .index = 4 } }, .match = .{ .fg = .{ .index = 4 }, .reverse = true }, .cursor_row = .{ .bg = .{ .index = 8 } }, .status = .{ .fg = .{ .index = 8 } }, .preview_current = .{ .fg = .{ .index = 4 } }, .bg = .default, .fg = .default, };}
comptime { // The default theme is the reference the theme tests compare against. const theme = defaultTheme(); assert(theme.prompt.fg.index == 4); assert(theme.match.reverse); assert(theme.cursor_row.bg.index == 8);}
pub fn parseThemeColor(text: []const u8) !vaxis.Color { if (std.mem.eql(u8, text, "default")) { return .default; } if (text.len == 0) { return error.InvalidColor; } if (text[0] == '#') { return parseHexColor(text); } const index = std.fmt.parseInt(u16, text, 10) catch { return error.InvalidColor; }; if (index > 255) { return error.InvalidColor; } assert(index <= 255); return .{ .index = @intCast(index) };}
fn parseHexColor(text: []const u8) !vaxis.Color { assert(text.len > 0); if (text[0] != '#') { return error.InvalidColor; } if (text.len != 7) { return error.InvalidColor; } var rgb: [3]u8 = undefined; var channel: usize = 0; while (channel < 3) { assert(channel < 3); const pair = text[1 + channel * 2 ..][0..2]; assert(pair.len == 2); rgb[channel] = std.fmt.parseUnsigned(u8, pair, 16) catch { return error.InvalidColor; }; channel += 1; } assert(channel == 3); return .{ .rgb = rgb };}
fn noColorSet() bool { const raw = std.c.getenv("NO_COLOR") orelse return false; return std.mem.span(raw).len > 0;}
fn resolveRoleColor( input_output_handle: std.Io, role: []const u8, maybe_text: ?[]const u8, fallback: vaxis.Color,) vaxis.Color { assert(role.len > 0); const text = maybe_text orelse return fallback; return parseThemeColor(text) catch { warn(input_output_handle, "invalid theme color for '{s}': '{s}', using default\n", .{ role, text, }); return fallback; };}
pub fn resolveTheme(input_output_handle: std.Io, app_config: config.Config) ResolvedTheme { if (noColorSet()) { return .{ .prompt = .{}, .match = .{}, .cursor_row = .{}, .status = .{}, .preview_current = .{}, .bg = .default, .fg = .default, }; } const defaults = defaultTheme(); const theme = app_config.theme; const prompt_fg = resolveRoleColor( input_output_handle, "prompt", theme.prompt, defaults.prompt.fg, ); const match_fg = resolveRoleColor(input_output_handle, "match", theme.match, defaults.match.fg); const cursor_bg = resolveRoleColor( input_output_handle, "cursor_row", theme.cursor_row, defaults.cursor_row.bg, ); const status_fg = resolveRoleColor( input_output_handle, "status", theme.status, defaults.status.fg, ); const marker_fg = resolveRoleColor( input_output_handle, "preview_current", theme.preview_current, defaults.preview_current.fg, ); const bg_color = resolveRoleColor( input_output_handle, "bg", theme.bg, defaults.bg, ); const fg_color = resolveRoleColor( input_output_handle, "fg", theme.fg, defaults.fg, ); const resolved: ResolvedTheme = .{ .prompt = .{ .fg = prompt_fg }, .match = .{ .fg = match_fg, .reverse = true }, .cursor_row = .{ .bg = cursor_bg }, .status = .{ .fg = status_fg }, .preview_current = .{ .fg = marker_fg }, .bg = bg_color, .fg = fg_color, }; return resolved;}
pub const RankedItem = struct { index: usize, score: f64, length: usize, tail_offset: usize, matches: []const usize,};
pub fn rankItems( arena: std.mem.Allocator, items: []const []const u8, query: []const u8,) ![]RankedItem { var ranked = std.ArrayListUnmanaged(RankedItem).empty; if (query.len == 0) { return unrankedItems(arena, items); }
const case_sensitive = hasUppercase(query); var needles = std.ArrayListUnmanaged([]const u8).empty; defer needles.deinit(arena); var split = std.mem.splitScalar(u8, query, ' '); while (split.next()) |part| { if (part.len == 0) continue; try needles.append(arena, part); } if (needles.items.len == 0) { return unrankedItems(arena, items); }
const total_needle_len = blk: { var sum: usize = 0; for (needles.items) |n| sum += n.len; break :blk sum; };
for (items, 0..) |item, index| { if (item.len == 0) continue; const score = zf.rank( item, needles.items, .{ .case_sensitive = case_sensitive }, ) orelse continue; const matches_buf = try arena.alloc(usize, total_needle_len); const matches = zf.highlight( item, needles.items, matches_buf, .{ .case_sensitive = case_sensitive }, ); try ranked.append(arena, .{ .index = index, .score = @floatCast(score), .length = item.len, .tail_offset = 0, .matches = matches, }); } std.mem.sortUnstable(RankedItem, ranked.items, {}, compareRankedItem); return ranked.toOwnedSlice(arena);}
/// Returns every non-empty item with a score of zero. Used when the query has/// no words.fn unrankedItems(arena: std.mem.Allocator, items: []const []const u8) ![]RankedItem { var ranked = std.ArrayListUnmanaged(RankedItem).empty; for (items, 0..) |item, index| { if (item.len == 0) continue; try ranked.append(arena, .{ .index = index, .score = 0, .length = item.len, .tail_offset = 0, .matches = &.{}, }); } std.mem.sortUnstable(RankedItem, ranked.items, {}, compareRankedItem); return ranked.toOwnedSlice(arena);}
fn compareRankedItem(_: void, left: RankedItem, right: RankedItem) bool { if (left.score != right.score) { return left.score < right.score; } // zf scores are always positive, because scanToEnd starts at rank 1. A // score of zero means the query was empty, so keep the original order. // When 2 real scores tie, prefer the shorter item so shallow paths come // before deep ones. if (left.score != 0 and left.length != right.length) { return left.length < right.length; } return left.index < right.index;}
pub fn appendHighlightSpans( spans: *std.ArrayListUnmanaged(vxfw.RichText.TextSpan), arena: std.mem.Allocator, text: []const u8, matches: []const usize, match_style: vaxis.Style,) !void { assert(text.len > 0); const start_len = spans.items.len; var cursor: usize = 0; var match_index: usize = 0; while (match_index < matches.len) { assert(match_index < matches.len); const position = matches[match_index]; assert(position < text.len); var run_end = position + 1; while (match_index + 1 < matches.len) { if (matches[match_index + 1] != run_end) { break; } match_index += 1; run_end += 1; } assert(run_end <= text.len); if (position > cursor) { try appendDisplaySafeText(spans, arena, text[cursor..position], .{}); } try appendDisplaySafeText(spans, arena, text[position..run_end], match_style); cursor = run_end; match_index += 1; } if (cursor < text.len) { try appendDisplaySafeText(spans, arena, text[cursor..], .{}); } assert(spans.items.len >= start_len);}
pub fn sanitizeDisplayText(allocator: std.mem.Allocator, text: []const u8) ![]u8 { var out = std.ArrayListUnmanaged(u8).empty; errdefer out.deinit(allocator); const replacement = [_]u8{ 0xEF, 0xBF, 0xBD }; var i: usize = 0; var col: usize = 0; while (i < text.len) { const b = text[i]; if (b == '\n') { try out.append(allocator, '\n'); i += 1; col = 0; continue; } if (b == '\t') { const width = 8 - (col % 8); assert(width >= 1 and width <= 8); try out.appendNTimes(allocator, ' ', width); col += width; i += 1; continue; } if (b == 0x1B) { i = skipAnsiEscape(text, i); continue; } if (b < 0x20 or b == 0x7F) { try out.append(allocator, ' '); col += 1; i += 1; continue; } if (b < 0x80) { try out.append(allocator, b); col += 1; i += 1; continue; } const seq_len = std.unicode.utf8ByteSequenceLength(b) catch { try out.appendSlice(allocator, &replacement); col += 1; i += 1; continue; }; if (i + seq_len > text.len) { try out.appendSlice(allocator, &replacement); col += 1; i += 1; continue; } const codepoint = std.unicode.utf8Decode(text[i..][0..seq_len]) catch { try out.appendSlice(allocator, &replacement); col += 1; i += 1; continue; }; if (codepoint < 0x20 or (codepoint >= 0x7F and codepoint <= 0x9F)) { try out.append(allocator, ' '); } else { try out.appendSlice(allocator, text[i..][0..seq_len]); } col += 1; i += seq_len; } return out.toOwnedSlice(allocator);}
fn skipAnsiEscape(text: []const u8, index: usize) usize { assert(text[index] == 0x1B); var j = index + 1; if (j >= text.len) { return j; } const kind = text[j]; if (kind == '[') { j += 1; while (j < text.len) : (j += 1) { if (text[j] >= 0x40 and text[j] <= 0x7E) { return j + 1; } } return j; } if (kind == ']') { j += 1; while (j < text.len) : (j += 1) { if (text[j] == 0x07) { return j + 1; } if (text[j] == 0x1B and j + 1 < text.len and text[j + 1] == '\\') { return j + 2; } } return j; } if (kind == 'P' or kind == 'X' or kind == '^' or kind == '_') { j += 1; while (j < text.len) : (j += 1) { if (text[j] == 0x1B and j + 1 < text.len and text[j + 1] == '\\') { return j + 2; } } return j; } return j + 1;}
pub fn appendDisplaySafeText( spans: *std.ArrayListUnmanaged(vxfw.RichText.TextSpan), arena: std.mem.Allocator, text: []const u8, style: vaxis.Style,) !void { assert(text.len > 0); const start_len = spans.items.len; const clean = try sanitizeDisplayText(arena, text); if (clean.len == 0) { try spans.append(arena, .{ .text = try arena.dupe(u8, " "), .style = style }); } else { try spans.append(arena, .{ .text = clean, .style = style }); } assert(spans.items.len > start_len);}
pub fn appendCursorSpans( spans: *std.ArrayListUnmanaged(vxfw.RichText.TextSpan), arena: std.mem.Allocator, source: []const vxfw.RichText.TextSpan, cursor_row: vaxis.Style,) !void { assert(source.len > 0); const start_len = spans.items.len; for (source) |span| { assert(span.text.len > 0); var styled = span; styled.style.bg = cursor_row.bg; try spans.append(arena, styled); } assert(spans.items.len == start_len + source.len);}
pub fn appendPreviewSpans( spans: *std.ArrayListUnmanaged(vxfw.RichText.TextSpan), arena: std.mem.Allocator, excerpt: []const u8, column_one_based: usize, query_len: usize, theme: ResolvedTheme,) !void { assert(excerpt.len > 0); const start_len = spans.items.len; var split = std.mem.splitScalar(u8, excerpt, '\n'); while (split.next()) |line| { if (line.len == 0) { continue; } if (isTargetLine(line)) { try appendTargetLineSpans(spans, arena, line, column_one_based, query_len, theme); continue; } try appendDisplaySafeText(spans, arena, line, .{}); try spans.append(arena, .{ .text = "\n" }); } assert(spans.items.len > start_len);}
fn isTargetLine(line: []const u8) bool { return std.mem.startsWith(u8, line, "> ");}
const PreviewRegion = struct { start: usize, end: usize,};
fn appendTargetLineSpans( spans: *std.ArrayListUnmanaged(vxfw.RichText.TextSpan), arena: std.mem.Allocator, line: []const u8, column_one_based: usize, query_len: usize, theme: ResolvedTheme,) !void { assert(line.len >= 2); try spans.append(arena, .{ .text = line[0..2], .style = theme.preview_current }); const content = line[2..]; assert(content.len <= line.len); const region = previewMatchRegion(content, column_one_based, query_len); if (region) |match| { assert(match.start <= content.len); assert(match.end <= content.len); if (match.start > 0) { try appendDisplaySafeText(spans, arena, content[0..match.start], .{}); } try appendDisplaySafeText(spans, arena, content[match.start..match.end], theme.match); if (match.end < content.len) { try appendDisplaySafeText(spans, arena, content[match.end..], .{}); } try spans.append(arena, .{ .text = "\n" }); return; } if (content.len > 0) { try appendDisplaySafeText(spans, arena, content, .{}); } try spans.append(arena, .{ .text = "\n" });}
fn previewMatchRegion( content: []const u8, column_one_based: usize, query_len: usize,) ?PreviewRegion { if (column_one_based == 0 or query_len == 0 or content.len == 0) { return null; } const start = column_one_based - 1; if (start >= content.len) { return null; } const end = @min(start + query_len, content.len); if (end <= start) { return null; } return .{ .start = start, .end = end };}
fn rowConstraints(ctx: vxfw.DrawContext, width: u16, height: u16) vxfw.DrawContext { const constrained = ctx.withConstraints(ctx.min, .{ .width = width, .height = height }); assert(constrained.max.width != null); assert(constrained.max.height != null); return constrained;}
/// What a key press does in either picker.const KeyAction = enum { quit, previous, next, preview_page_down, preview_page_up, preview_lines_down, preview_lines_up,};
const KeyBinding = struct { codepoint: u21, mods: vaxis.Key.Modifiers = .{}, action: KeyAction,};
const key_bindings = [_]KeyBinding{ .{ .codepoint = vaxis.Key.escape, .action = .quit }, .{ .codepoint = 'c', .mods = .{ .ctrl = true }, .action = .quit }, .{ .codepoint = 'd', .mods = .{ .ctrl = true }, .action = .quit }, .{ .codepoint = 'g', .mods = .{ .ctrl = true }, .action = .quit }, .{ .codepoint = vaxis.Key.up, .action = .previous }, .{ .codepoint = 'p', .mods = .{ .ctrl = true }, .action = .previous }, .{ .codepoint = vaxis.Key.down, .action = .next }, .{ .codepoint = 'n', .mods = .{ .ctrl = true }, .action = .next }, .{ .codepoint = vaxis.Key.page_down, .action = .preview_page_down }, .{ .codepoint = 'j', .mods = .{ .alt = true }, .action = .preview_lines_down }, .{ .codepoint = vaxis.Key.page_up, .action = .preview_page_up }, .{ .codepoint = 'k', .mods = .{ .alt = true }, .action = .preview_lines_up },};
fn keyAction(key: vaxis.Key) ?KeyAction { for (key_bindings) |binding| { if (key.matches(binding.codepoint, binding.mods)) { return binding.action; } } return null;}
/// Handles the actions both pickers share: quitting and moving the cursor./// Returns false for preview actions. Only the list picker supports those.fn handleListAction(model: anytype, ctx: *vxfw.EventContext, action: KeyAction) bool { switch (action) { .quit => { ctx.quit = true; }, .previous => { model.list_view.prevItem(ctx); model.refreshPreview(); }, .next => { model.list_view.nextItem(ctx); model.refreshPreview(); }, .preview_page_down, .preview_page_up, .preview_lines_down, .preview_lines_up, => return false, } return true;}
/// Handles the events both pickers share. Each picker handles ticks itself:/// it loads its items on the first tick, after the empty frame is drawn.fn handleCommonEvent(model: anytype, ctx: *vxfw.EventContext, event: vxfw.Event) !void { switch (event) { .init => { try ctx.tick(0, model.widget()); return ctx.requestFocus(model.text_field.widget()); }, .focus_in => { return ctx.requestFocus(model.text_field.widget()); }, .key_press => |key| { const action = keyAction(key) orelse return; _ = handleListAction(model, ctx, action); }, else => {}, }}
/// Connects the list and prompt of a new model to the model's callbacks.fn connectModel(model: anytype) void { const Model = @TypeOf(model.*); model.list_view.children = .{ .builder = .{ .userdata = model, .buildFn = Model.widgetBuilder, } }; model.list_view.item_count = 0; model.text_field.userdata = model; model.text_field.onChange = Model.onChange; model.text_field.onSubmit = Model.onSubmit; assert(model.text_field.userdata != null);}
/// Draws the picker. The prompt and query fill the first row and the status/// fills the second. The list takes the rest. An optional preview pane takes/// 3/5 of the width.fn drawPicker( ctx: vxfw.DrawContext, owner: vxfw.Widget, theme: ResolvedTheme, text_field: *vxfw.TextField, list_view: *vxfw.ListView, status_text: []const u8, preview: ?vxfw.Widget,) std.mem.Allocator.Error!vxfw.Surface { const max_size = ctx.max.size(); assert(max_size.width > 0); assert(max_size.height > 0);
const status: vxfw.Text = .{ .text = status_text, .style = theme.status }; const prompt: vxfw.Text = .{ .text = ">", .style = theme.prompt };
const total_width: u32 = max_size.width; const preview_width: u16 = if (preview != null) @intCast(total_width * 3 / 5) else 0; const list_width: u16 = @intCast(total_width - preview_width); const list_height = max_size.height -| 2; const child_count: usize = if (preview != null) 5 else 4; const children = try ctx.arena.alloc(vxfw.SubSurface, child_count); children[0] = .{ .origin = .{ .row = 0, .col = 0 }, .surface = try prompt.draw(rowConstraints(ctx, 2, 1)), }; children[1] = .{ .origin = .{ .row = 0, .col = 2 }, .surface = try text_field.draw(rowConstraints(ctx, max_size.width -| 2, 1)), }; children[2] = .{ .origin = .{ .row = 1, .col = 2 }, .surface = try status.draw(rowConstraints(ctx, max_size.width -| 2, 1)), }; children[3] = .{ .origin = .{ .row = 2, .col = 0 }, .surface = try list_view.draw(rowConstraints(ctx, list_width, list_height)), }; if (preview) |preview_widget| { children[4] = .{ .origin = .{ .row = 2, .col = list_width }, .surface = try preview_widget.draw(rowConstraints(ctx, preview_width, list_height)), }; }
const bg_style: vaxis.Style = .{ .bg = theme.bg, .fg = theme.fg }; const buffer = try ctx.arena.alloc(vaxis.Cell, max_size.width * max_size.height); @memset(buffer, .{ .style = bg_style });
return .{ .size = max_size, .widget = owner, .buffer = buffer, .children = children, };}
/// Builds list row index. The row under the cursor uses its highlighted/// version from cursor_rows.fn rowWidget( rows: []const vxfw.RichText, cursor_rows: []const vxfw.RichText, index: usize, cursor: usize,) ?vxfw.Widget { assert(cursor_rows.len == rows.len); if (index >= rows.len) { return null; } if (index == cursor) { return cursor_rows[index].widget(); } return rows[index].widget();}
/// Returns a copy of spans styled for the cursor row. The copy uses/// allocator.fn cursorRowSpans( allocator: std.mem.Allocator, spans: []const vxfw.RichText.TextSpan, cursor_style: vaxis.Style,) ![]vxfw.RichText.TextSpan { var cursor_spans = std.ArrayListUnmanaged(vxfw.RichText.TextSpan).empty; errdefer cursor_spans.deinit(allocator); try appendCursorSpans(&cursor_spans, allocator, spans, cursor_style); const owned = try cursor_spans.toOwnedSlice(allocator); assert(owned.len == spans.len); return owned;}
/// Resets the list to show count new rows, with the cursor on the first.fn resetListView(list_view: *vxfw.ListView, count: usize) void { assert(count <= std.math.maxInt(u32)); list_view.cursor = 0; list_view.scroll.top = 0; list_view.scroll.offset = 0; list_view.item_count = @intCast(count);}
/// Runs the terminal UI until the root widget quits.fn runApp(allocator: std.mem.Allocator, root: vxfw.Widget) !void { var app_buffer: [4096]u8 = undefined; var app: vxfw.App = try .init( input_output.runtime(), allocator, input_output.environMap(), &app_buffer, ); defer app.deinit(); try app.run(root, .{});}
/// Loads previews on demand. The picker calls load with the index of the/// highlighted item and shows the returned text in the side pane. Each/// refresh gets a new arena for all allocations, so load never frees memory.pub const PreviewSource = struct { ctx: ?*anyopaque, load: *const fn (ctx: ?*anyopaque, arena: std.mem.Allocator, index: usize) anyerror!?[]const u8,};
const ListModel = struct { allocator: std.mem.Allocator, items: []const []const u8, preview_source: ?PreviewSource, theme: ResolvedTheme, arena: std.heap.ArenaAllocator, preview_arena: std.heap.ArenaAllocator, preview_lines: []const vxfw.RichText = &no_preview_lines, preview_scroll: vxfw.ScrollView, ranked: []RankedItem = &.{}, filtered: std.ArrayListUnmanaged(vxfw.RichText) = .empty, filtered_cursor: std.ArrayListUnmanaged(vxfw.RichText) = .empty, list_view: vxfw.ListView, text_field: vxfw.TextField, selected: ?usize = null, loaded: bool = false,
fn init( allocator: std.mem.Allocator, items: []const []const u8, preview_source: ?PreviewSource, theme: ResolvedTheme, ) !*ListModel { assert(items.len > 0); assert(items.len <= std.math.maxInt(u32)); const self = try allocator.create(ListModel); self.* = .{ .allocator = allocator, .items = items, .preview_source = preview_source, .theme = theme, .arena = std.heap.ArenaAllocator.init(allocator), .preview_arena = std.heap.ArenaAllocator.init(allocator), .preview_scroll = .{ // SAFETY: init replaces this placeholder before it returns. .children = .{ .builder = undefined }, }, .list_view = .{ // SAFETY: init replaces this placeholder before it returns. .children = .{ .builder = undefined }, }, .text_field = vxfw.TextField.init(allocator), }; connectModel(self); self.preview_scroll.children = .{ .builder = .{ .userdata = self, .buildFn = ListModel.previewBuilder, } }; self.preview_scroll.item_count = @intCast(self.preview_lines.len); return self; }
fn deinit(self: *ListModel) void { const allocator = self.allocator; self.arena.deinit(); self.preview_arena.deinit(); self.text_field.deinit(); allocator.destroy(self); }
fn widget(self: *ListModel) vxfw.Widget { const result: vxfw.Widget = .{ .userdata = self, .eventHandler = ListModel.typeErasedEventHandler, .drawFn = ListModel.typeErasedDrawFn, }; assert(result.userdata == @as(*anyopaque, @ptrCast(self))); return result; }
fn typeErasedEventHandler( ptr: *anyopaque, ctx: *vxfw.EventContext, event: vxfw.Event, ) anyerror!void { const self: *ListModel = @ptrCast(@alignCast(ptr)); switch (event) { .tick => { if (!self.loaded) { self.loaded = true; const query = try self.text_field.buf.dupe(); defer self.text_field.buf.allocator.free(query); try self.refilter(query); ctx.redraw = true; } }, .key_press => |key| { const action = keyAction(key) orelse return; if (handleListAction(self, ctx, action)) { return; } const scroll = &self.preview_scroll.scroll; const moved = switch (action) { .preview_page_down => scroll.linesDown(self.previewPageLines()), .preview_page_up => scroll.linesUp(self.previewPageLines()), .preview_lines_down => scroll.linesDown(preview_scroll_lines), .preview_lines_up => scroll.linesUp(preview_scroll_lines), else => unreachable, }; if (moved) { ctx.redraw = true; } }, .mouse => { // Pass wheel events to the preview pane, so it scrolls even // while the text field has focus. if (self.preview_source != null) { try self.preview_scroll.handleEvent(ctx, event); } }, else => try handleCommonEvent(self, ctx, event), } }
fn typeErasedDrawFn( ptr: *anyopaque, ctx: vxfw.DrawContext, ) std.mem.Allocator.Error!vxfw.Surface { const self: *ListModel = @ptrCast(@alignCast(ptr)); const status_text = try std.fmt.allocPrint( ctx.arena, "{d}/{d}", .{ self.filtered.items.len, self.items.len }, ); const preview: ?vxfw.Widget = if (self.preview_source != null) self.preview_scroll.widget() else null; return drawPicker( ctx, self.widget(), self.theme, &self.text_field, &self.list_view, status_text, preview, ); }
fn previewBuilder(ptr: *const anyopaque, index: usize, _: usize) ?vxfw.Widget { const self: *const ListModel = @ptrCast(@alignCast(ptr)); if (self.preview_source == null) { return null; } if (index >= self.preview_lines.len) { return null; } return self.preview_lines[index].widget(); }
fn previewPageLines(self: *const ListModel) u8 { const height = self.preview_scroll.last_height; return if (height > 0) height else 10; }
fn widgetBuilder(ptr: *const anyopaque, index: usize, cursor: usize) ?vxfw.Widget { const self: *const ListModel = @ptrCast(@alignCast(ptr)); return rowWidget(self.filtered.items, self.filtered_cursor.items, index, cursor); }
fn onChange(maybe_ptr: ?*anyopaque, _: *vxfw.EventContext, query: []const u8) anyerror!void { const ptr = maybe_ptr orelse return; const self: *ListModel = @ptrCast(@alignCast(ptr)); try self.refilter(query); }
fn refilter(self: *ListModel, query: []const u8) !void { _ = self.arena.reset(.free_all); const arena = self.arena.allocator(); const display = try arena.alloc([]const u8, self.items.len); for (self.items, 0..) |item, index| { if (item.len == 0) { display[index] = item; continue; } const clean = try sanitizeDisplayText(arena, item); display[index] = if (clean.len == 0) " " else clean; } self.ranked = try rankItems(arena, display, query); self.filtered = .empty; self.filtered_cursor = .empty; for (self.ranked) |ranked_item| { var spans = std.ArrayListUnmanaged(vxfw.RichText.TextSpan).empty; try appendHighlightSpans( &spans, arena, display[ranked_item.index], ranked_item.matches, self.theme.match, ); const owned = try spans.toOwnedSlice(arena); assert(owned.len > 0); try self.filtered.append(arena, .{ .text = owned }); const owned_cursor = try cursorRowSpans(arena, owned, self.theme.cursor_row); try self.filtered_cursor.append(arena, .{ .text = owned_cursor }); } assert(self.filtered.items.len == self.ranked.len); assert(self.filtered_cursor.items.len == self.ranked.len); resetListView(&self.list_view, self.filtered.items.len); self.refreshPreview(); }
fn refreshPreview(self: *ListModel) void { _ = self.preview_arena.reset(.free_all); self.preview_lines = &no_preview_lines; self.preview_scroll.item_count = no_preview_lines.len; self.preview_scroll.scroll = .{}; const source = self.preview_source orelse return; if (self.list_view.cursor >= self.ranked.len) { return; } const arena = self.preview_arena.allocator(); const index = self.ranked[self.list_view.cursor].index; const text = source.load(source.ctx, arena, index) catch return orelse return; if (text.len == 0) { return; } const lines = buildDiffLines(arena, text) catch return; if (lines.len == 0) { return; } self.preview_lines = lines; self.preview_scroll.item_count = @intCast(lines.len); }
fn onSubmit(maybe_ptr: ?*anyopaque, ctx: *vxfw.EventContext, _: []const u8) anyerror!void { const ptr = maybe_ptr orelse return; const self: *ListModel = @ptrCast(@alignCast(ptr)); if (self.list_view.cursor < self.ranked.len) { self.selected = self.ranked[self.list_view.cursor].index; } ctx.quit = true; assert(ctx.quit); }};
const diff_add_style: vaxis.Style = .{ .fg = .{ .index = 2 } };const diff_delete_style: vaxis.Style = .{ .fg = .{ .index = 1 } };const diff_hunk_style: vaxis.Style = .{ .fg = .{ .index = 6 } };const preview_scroll_lines: u8 = 3;// vaxis sizes surfaces as u16 width * u16 height, so a wrapped line must stay// well under 65,536 cells. 2,048 bytes expand to at most 16,384 cells, because// a tab expands to 8 cells.const max_preview_line_bytes: usize = 2048;
comptime { assert(preview_scroll_lines > 0); assert(max_preview_line_bytes * 8 * 2 < std.math.maxInt(u16));}
/// Splits diff text into one RichText per line. Additions are green,/// deletions are red and hunk headers are cyan. Other lines use the default/// style. With one widget per line, the preview ScrollView draws only the/// visible lines. A single RichText for the whole diff would overflow the/// u16 surface size in vaxis.pub fn buildDiffLines(arena: std.mem.Allocator, diff: []const u8) ![]vxfw.RichText { assert(diff.len > 0); // Follow the NO_COLOR convention: if the variable is set and not empty, // use plain styles. const color = !noColorSet(); var lines = std.ArrayListUnmanaged(vxfw.RichText).empty; var split = std.mem.splitScalar(u8, diff, '\n'); while (split.next()) |line| { if (line.len == 0 and split.peek() == null) { break; } var spans = std.ArrayListUnmanaged(vxfw.RichText.TextSpan).empty; if (line.len == 0) { // An empty RichText takes up zero rows. Use a space so blank lines // stay visible. try spans.append(arena, .{ .text = " " }); } else { const style: vaxis.Style = if (!color) .{} else switch (line[0]) { '+' => diff_add_style, '-' => diff_delete_style, '@' => diff_hunk_style, else => .{}, }; try appendDisplaySafeText(&spans, arena, clipPreviewLine(line), style); } assert(spans.items.len > 0); try lines.append(arena, .{ .text = spans.items }); } return lines.items;}
/// Cuts line to max_preview_line_bytes without splitting a UTF-8 sequence.fn clipPreviewLine(line: []const u8) []const u8 { assert(line.len > 0); if (line.len <= max_preview_line_bytes) { return line; } var end = max_preview_line_bytes; while (end > 0 and (line[end] & 0xC0) == 0x80) { end -= 1; } return if (end > 0) line[0..end] else line[0..max_preview_line_bytes];}
pub fn pickFromList( allocator: std.mem.Allocator, items: []const []const u8, theme: ResolvedTheme,) ![]u8 { return pickFromListWithPreview(allocator, items, theme, null);}
/// Works like pickFromList, and also shows a preview of the highlighted item/// in a side pane. The preview loads on demand.pub fn pickFromListWithPreview( allocator: std.mem.Allocator, items: []const []const u8, theme: ResolvedTheme, preview_source: ?PreviewSource,) ![]u8 { try checkTerminalSize(input_output.runtime()); for (items) |item| { if (item.len > 0) { break; } } else { return error.UserAbort; } const model = try ListModel.init(allocator, items, preview_source, theme); defer model.deinit(); try runApp(allocator, model.widget()); const selected = model.selected orelse return error.UserAbort; assert(selected < items.len); const result = try allocator.dupe(u8, items[selected]); assert(result.len == items[selected].len); return result;}
/// A file held in memory for the grep picker. The content is the raw file/// bytes; case-insensitive matching scans it directly instead of keeping a/// second lowered copy around.pub const GrepFile = struct { path: []const u8, content: []const u8, /// Lowercase file copy for case-insensitive AC scans. Built once /// when the file enters the corpus; freed on deinit. lower: ?[]const u8 = null,
fn deinit(self: *const GrepFile, allocator: std.mem.Allocator) void { allocator.free(self.path); allocator.free(self.content); if (self.lower) |lower| { allocator.free(lower); } }};
pub fn isBinaryContent(content: []const u8) bool { const probe = content[0..@min(content.len, binary_probe_bytes)]; return std.mem.indexOfScalar(u8, probe, 0) != null;}
/// Real Aho-Corasick automaton. Scans a byte stream for all patterns/// at once, then groups hits by line.const Hit = struct { byte_index: usize, pattern_idx: usize,};
const AcNode = struct { fail: usize, next: std.AutoHashMap(u8, usize), output: std.ArrayListUnmanaged(usize),};
const AhoCorasick = struct { nodes: std.ArrayListUnmanaged(AcNode), allocator: std.mem.Allocator,
fn init(allocator: std.mem.Allocator) !AhoCorasick { var nodes = std.ArrayListUnmanaged(AcNode).empty; errdefer nodes.deinit(allocator); try nodes.append(allocator, .{ .fail = 0, .next = std.AutoHashMap(u8, usize).init(allocator), .output = std.ArrayListUnmanaged(usize).empty, }); return .{ .nodes = nodes, .allocator = allocator }; }
fn deinit(self: *AhoCorasick) void { for (self.nodes.items) |*node| { node.next.deinit(); node.output.deinit(self.allocator); } self.nodes.deinit(self.allocator); }
fn addPattern(self: *AhoCorasick, pattern: []const u8, pattern_idx: usize) !void { var state: usize = 0; for (pattern) |byte| { const child = self.nodes.items[state].next.get(byte) orelse blk: { const new_state = self.nodes.items.len; try self.nodes.append(self.allocator, .{ .fail = 0, .next = std.AutoHashMap(u8, usize).init(self.allocator), .output = std.ArrayListUnmanaged(usize).empty, }); try self.nodes.items[state].next.put(byte, new_state); break :blk new_state; }; state = child; } try self.nodes.items[state].output.append(self.allocator, pattern_idx); }
fn buildFail(self: *AhoCorasick) !void { var queue_items = std.ArrayListUnmanaged(usize).empty; defer queue_items.deinit(self.allocator); // Initialize depth-1 nodes var it = self.nodes.items[0].next.iterator(); while (it.next()) |entry| { const child = entry.value_ptr.*; self.nodes.items[child].fail = 0; try queue_items.append(self.allocator, child); } var read_idx: usize = 0; while (read_idx < queue_items.items.len) { const state_idx = queue_items.items[read_idx]; read_idx += 1; var it2 = self.nodes.items[state_idx].next.iterator(); while (it2.next()) |entry| { const byte = entry.key_ptr.*; const child_idx = entry.value_ptr.*; // Set the failure link for this transition. var fail_state = self.nodes.items[state_idx].fail; while (fail_state != 0) { if (self.nodes.items[fail_state].next.get(byte)) |fs_child| { fail_state = fs_child; break; } fail_state = self.nodes.items[fail_state].fail; } if (self.nodes.items[fail_state].next.get(byte)) |fs_child| { self.nodes.items[child_idx].fail = fs_child; } else { self.nodes.items[child_idx].fail = 0; } // Merge output patterns from the failure link. const fail_node_idx = self.nodes.items[child_idx].fail; const fail_outputs = self.nodes.items[fail_node_idx].output.items; try self.nodes.items[child_idx].output.appendSlice(self.allocator, fail_outputs); try queue_items.append(self.allocator, child_idx); } } }
fn search( self: *const AhoCorasick, haystack: []const u8, allocator: std.mem.Allocator, hits: *std.ArrayListUnmanaged(Hit), ) !void { var state: usize = 0; for (haystack, 0..) |byte, i| { while (true) { if (self.nodes.items[state].next.get(byte)) |child| { state = child; break; } if (state == 0) { break; } state = self.nodes.items[state].fail; } for (self.nodes.items[state].output.items) |pattern_idx| { try hits.append(allocator, .{ .byte_index = i, .pattern_idx = pattern_idx }); } } }};
/// Returns true when the row list hits max_grep_lines. Appends a/// 'path:line:column:text' row for each line that contains all words.pub fn grepFiles( allocator: std.mem.Allocator, lines: *std.ArrayListUnmanaged([]const u8), files: []GrepFile, query: []const u8,) !bool { const case_sensitive = hasUppercase(query); var needles = std.ArrayListUnmanaged([]const u8).empty; defer { for (needles.items) |needle| { allocator.free(needle); } needles.deinit(allocator); } var words = std.mem.splitScalar(u8, query, ' '); while (words.next()) |word| { if (word.len == 0) { continue; } // A query's words fill a u64 bitmask per line, so extra words are // dropped instead of overflowing the mask. if (needles.items.len == max_grep_words) { break; } const needle = if (case_sensitive) try allocator.dupe(u8, word) else try std.ascii.allocLowerString(allocator, word); try needles.append(allocator, needle); } if (needles.items.len == 0) { return false; } for (files) |file| { const truncated = try grepOneFile(allocator, lines, file, needles.items, case_sensitive); if (lines.items.len >= max_grep_lines) { return true; } if (truncated) { return true; } } return false;}
fn grepOneFile( allocator: std.mem.Allocator, lines: *std.ArrayListUnmanaged([]const u8), file: GrepFile, needles: []const []const u8, case_sensitive: bool,) !bool { assert(file.path.len > 0); assert(needles.len > 0); assert(needles.len <= max_grep_words); var lower_copy: ?[]u8 = null; defer if (lower_copy) |copy| allocator.free(copy); var haystack = file.content; if (!case_sensitive) { if (file.lower) |existing| { haystack = existing; } else { const copy = try std.ascii.allocLowerString(allocator, file.content); lower_copy = copy; haystack = copy; } }
var ac = try AhoCorasick.init(allocator); defer ac.deinit(); for (needles, 0..) |needle, idx| { try ac.addPattern(needle, idx); } try ac.buildFail();
var hits = std.ArrayListUnmanaged(Hit).empty; defer hits.deinit(allocator); try ac.search(haystack, allocator, &hits);
if (hits.items.len == 0) return false;
const sorted = try allocator.alloc(Hit, hits.items.len); defer allocator.free(sorted); @memcpy(sorted, hits.items); std.mem.sort(Hit, sorted, {}, struct { fn lessThan(_: void, a: Hit, b: Hit) bool { return a.byte_index < b.byte_index; } }.lessThan);
// Group hits by line (line start = index after previous newline, or 0). var i: usize = 0; while (i < sorted.len) { const first_byte = sorted[i].byte_index; // Find line start var line_start: usize = 0; if (first_byte > 0) { var s = first_byte; while (s > 0) : (s -= 1) { if (haystack[s - 1] == '\n') { line_start = s; break; } } } // Find line end (next newline or end of haystack) var line_end = haystack.len; var s = first_byte; while (s < haystack.len) : (s += 1) { if (haystack[s] == '\n') { line_end = s; break; } } // Count unique patterns on this line. var found: u64 = 0; const needle_len_first = needles[sorted[i].pattern_idx].len; var earliest_start: usize = sorted[i].byte_index - (needle_len_first - 1); var j = i; while (j < sorted.len) { const hit_byte = sorted[j].byte_index; // Compute line start for hit_byte var hit_line_start: usize = 0; if (hit_byte > 0) { var hs = hit_byte; while (hs > 0) : (hs -= 1) { if (haystack[hs - 1] == '\n') { hit_line_start = hs; break; } } } if (hit_line_start != line_start) break; const needle_len = needles[sorted[j].pattern_idx].len; const start_index = hit_byte - (needle_len - 1); found |= @as(u64, 1) << @intCast(sorted[j].pattern_idx); if (start_index < earliest_start) earliest_start = start_index; j += 1; } i = j; const full_mask = ~@as(u64, 0) >> @as(u6, @intCast(max_grep_words - needles.len)); if (found == full_mask) { const line_slice = haystack[line_start..line_end]; // Compute line number by counting newlines before line_start. var ln: usize = 1; if (line_start > 0) { ln = std.mem.count(u8, haystack[0..line_start], "\n") + 1; } const row = try std.fmt.allocPrint(allocator, "{s}:{d}:{d}:{s}", .{ file.path, ln, earliest_start - line_start + 1, line_slice, }); try lines.append(allocator, row); if (lines.items.len >= max_grep_lines) { return true; } } } return false;}
/// Frees every line and leaves the list empty.fn freeLines(allocator: std.mem.Allocator, lines: *std.ArrayListUnmanaged([]const u8)) void { for (lines.items) |line| { allocator.free(line); } lines.deinit(allocator); lines.* = .empty;}
pub const GrepTarget = struct { file: []const u8, line: usize, column: usize,};
pub fn splitGrepLine(selected: []const u8) GrepTarget { assert(selected.len > 0); var fields = std.mem.splitScalar(u8, selected, ':'); if (fields.next()) |file| { const line = if (fields.next()) |text| parseGrepNumber(text) else 0; const column = if (fields.next()) |text| parseGrepNumber(text) else 0; return .{ .file = file, .line = line, .column = column }; } return .{ .file = selected, .line = 0, .column = 0 };}
fn parseGrepNumber(text: []const u8) usize { const number = std.fmt.parseInt(usize, text, 10) catch return 0; return number;}
/// Returns the lines of content around line_one_based. The target line/// starts with "> " and the others start with 2 spaces.pub fn excerptFromContent( allocator: std.mem.Allocator, content: []const u8, line_one_based: usize,) ![]u8 { assert(line_one_based > 0); const first = excerptFirstLine(line_one_based); const last = first + excerpt_context_before + excerpt_context_after; assert(first >= 1); assert(last >= first); var out = std.ArrayListUnmanaged(u8).empty; errdefer out.deinit(allocator); var number: usize = 0; var split = std.mem.splitScalar(u8, content, '\n'); while (split.next()) |text| { number += 1; if (number < first) { continue; } if (number > last) { break; } if (number == line_one_based) { try out.appendSlice(allocator, "> "); } else { try out.appendSlice(allocator, " "); } try out.appendSlice(allocator, text); try out.append(allocator, '\n'); } return out.toOwnedSlice(allocator);}
fn excerptFirstLine(line_one_based: usize) usize { assert(line_one_based > 0); if (line_one_based > excerpt_context_before) { const first = line_one_based - excerpt_context_before; assert(first < line_one_based); assert(first >= 1); return first; } return 1;}
const no_preview_text = "[no preview]";
const no_preview_spans = [_]vxfw.RichText.TextSpan{ .{ .text = no_preview_text },};
const no_preview_lines = [_]vxfw.RichText{ .{ .text = &no_preview_spans },};
/// Writes picker warnings to stderr. Tests skip them, because there they are/// only noise.fn warn(input_output_handle: std.Io, comptime fmt: []const u8, arguments: anytype) void { if (builtin.is_test) { return; } input_output.warnTo(input_output_handle, fmt, arguments);}
/// What the file walk is doing right now. The corpus loads in small steps/// from tick events, so the picker always keeps accepting input while a/// directory walk is still running.const GrepState = enum { /// The walk has not started yet. pending, /// The walk is running in bounded steps. loading, /// The walk is parked because the current query already filled the row /// list. A new query resumes it, because narrower queries may fit. paused, /// A stop reason fired (too many files or bytes) and the walk ended /// early. The corpus is final. capped, /// The whole tree was walked. The corpus is final. done, /// The walk or a read failed partway. The corpus keeps what loaded. failed,};
/// The tree walk that feeds the corpus, kept across loading steps.const GrepLoader = struct { tree_walker: walker.TreeWalker, /// The same directory the tree walker holds; reads go through it. root: std.Io.Dir, corpus_bytes: usize = 0,};
const GrepModel = struct { input_output_handle: std.Io, allocator: std.mem.Allocator, patterns: []const []const u8, theme: ResolvedTheme, corpus: std.ArrayListUnmanaged(GrepFile) = .empty, state: GrepState = .pending, loader: ?GrepLoader = null, /// Number of corpus files that the current query already searched. Files /// are searched once per query; each loading step fills the gap between /// this count and the corpus length. searched_files: usize = 0, truncated: bool = false, lines: std.ArrayListUnmanaged([]const u8) = .empty, query_len: usize = 0, preview_arena: std.heap.ArenaAllocator, preview_text: []const u8 = &.{}, preview_spans: []const vxfw.RichText.TextSpan = &.{}, preview: vxfw.RichText = .{ .text = &no_preview_spans }, /// Holds the styled spans of the rows built for the frame being drawn. /// Rows are built on demand from `lines` for the rows on screen only, /// which keeps typing cheap even when a query matches thousands of lines. row_arena: std.heap.ArenaAllocator, list_view: vxfw.ListView, text_field: vxfw.TextField, selected: ?usize = null,
fn init( input_output_handle: std.Io, allocator: std.mem.Allocator, patterns: []const []const u8, theme: ResolvedTheme, ) !*GrepModel { const self = try allocator.create(GrepModel); self.* = .{ .input_output_handle = input_output_handle, .allocator = allocator, .patterns = patterns, .theme = theme, .preview_arena = std.heap.ArenaAllocator.init(allocator), .row_arena = std.heap.ArenaAllocator.init(allocator), .list_view = .{ // SAFETY: init replaces this placeholder before it returns. .children = .{ .builder = undefined }, }, .text_field = vxfw.TextField.init(allocator), }; connectModel(self); return self; }
fn deinit(self: *GrepModel) void { const allocator = self.allocator; self.clearResults(); self.freeCorpus(); self.dropLoader(null); self.row_arena.deinit(); self.preview_arena.deinit(); self.text_field.deinit(); allocator.destroy(self); }
fn freeCorpus(self: *GrepModel) void { assert(self.searched_files <= self.corpus.items.len); for (self.corpus.items) |*file| { file.deinit(self.allocator); } self.corpus.deinit(self.allocator); self.corpus = .empty; self.searched_files = 0; assert(self.corpus.items.len == 0); assert(self.searched_files == 0); }
/// Starts the walk from the current directory. Runs on the first tick. fn startLoading(self: *GrepModel) void { assert(self.state == .pending); const root = walker.openWalkRoot() catch { self.state = .failed; return; }; self.openLoader(root); }
/// Takes a directory that was already opened with walker access. Used /// by tests and by startLoading after opening the root itself. fn openLoader(self: *GrepModel, root: std.Io.Dir) void { assert(self.state == .pending); const tree_walker = walker.TreeWalker.init( self.input_output_handle, self.allocator, root, self.patterns, walker.max_supported_depth, // The walk runs while the picker is on screen. Walk failures are // skipped silently; a stderr write would garble the drawing. true, ) catch { // TreeWalker.init closes the root when it fails. self.state = .failed; return; }; self.loader = .{ .tree_walker = tree_walker, .root = root }; self.state = .loading; }
/// Ends the walk and keeps the corpus loaded so far. Without an /// argument the state stays untouched; deinit uses that to free things. fn dropLoader(self: *GrepModel, end_state: ?GrepState) void { if (end_state) |target| { assert(target != .loading and target != .pending); self.state = target; } if (self.loader) |*loader| { loader.tree_walker.deinit(); self.loader = null; } }
/// Loads the entire corpus from root in one pass, without giving control /// back to an event loop. The UI loads in bounded steps through /// handleTick instead. Tests use this to simulate a finished walk. fn loadCorpus(self: *GrepModel, root: std.Io.Dir) !void { if (self.state != .pending) { return; } self.openLoader(root); while (self.state == .loading) { _ = try self.loadCorpusStep( std.math.maxInt(usize), std.math.maxInt(i96), max_grep_files, ); } }
/// Inspects at most max_entries tree entries, staying within the time /// budget and the file cap. Binary files are detected with a cheap probe /// before a full read. Returns true when the walk wants to continue. fn loadCorpusStep( self: *GrepModel, max_entries: usize, time_budget_ns: i96, file_cap: usize, ) !bool { assert(self.state == .loading); assert(max_entries > 0); assert(time_budget_ns > 0); assert(file_cap > 0); const loader = &(self.loader orelse { // Only .loading steps reach here and .loading implies a loader; // treat a missing one as an ended walk, not a crash. self.dropLoader(.done); return false; }); const started = std.Io.Timestamp.now(self.input_output_handle, .awake); var examined: usize = 0; while (examined < max_entries) : (examined += 1) { const now = std.Io.Timestamp.now(self.input_output_handle, .awake); assert(now.nanoseconds >= started.nanoseconds); if (started.durationTo(now).nanoseconds > time_budget_ns) { break; } const item = try loader.tree_walker.next(); if (item == null) { self.dropLoader(.done); return false; } const entry = item.?; defer self.allocator.free(entry.path); assert(entry.path.len > 0); if (entry.stat_kind != .file) { continue; } // Empty files can never match and files above the single-file // ceiling are not worth reading. The walker already stat'ed the // file, so there is no second stat here; files that grow between // this check and the read hit the StreamTooLong backstop below. if (entry.size_bytes == 0 or entry.size_bytes > max_grep_file_bytes) { continue; } if (self.corpus.items.len >= file_cap) { self.dropLoader(.capped); return false; } // A short probe goes first, so binary blobs are detected before // the file is fully read. A probe that ends early carries the // whole file, and reading the rest is saved. var probe: [binary_probe_bytes]u8 = undefined; const got = self.readGrepProbe(loader.root, entry.path, &probe) orelse continue; if (isBinaryContent(probe[0..got])) { continue; } const content = if (got < probe.len) try self.allocator.dupe(u8, probe[0..got]) else (try self.readGrepFile(loader.root, entry.path)) orelse continue; if (loader.corpus_bytes + content.len > max_grep_corpus_bytes) { self.allocator.free(content); self.dropLoader(.capped); return false; } loader.corpus_bytes += content.len; const owned_path = try self.allocator.dupe(u8, entry.path); const lower_content = try std.ascii.allocLowerString(self.allocator, content); self.corpus.append(self.allocator, .{ .path = owned_path, .content = content, .lower = lower_content, }) catch |err| { self.allocator.free(owned_path); self.allocator.free(lower_content); return err; }; } assert(self.state == .loading); return true; }
/// Reads the first bytes of a file into probe. Returns null when the /// file cannot be opened or read; unreadable files are simply not /// searched. fn readGrepProbe( self: *GrepModel, root: std.Io.Dir, path: []const u8, probe: []u8, ) ?usize { var file = root.openFile(self.input_output_handle, path, .{ .mode = .read_only, .allow_directory = false, }) catch return null; defer file.close(self.input_output_handle); var file_reader = file.reader(self.input_output_handle, &.{}); return file_reader.interface.readSliceShort(probe) catch return null; }
/// Reads a whole file that already passed the probe check. Returns null /// when the file cannot be read; only out of memory propagates. fn readGrepFile(self: *GrepModel, root: std.Io.Dir, path: []const u8) !?[]u8 { const content = root.readFileAlloc( self.input_output_handle, path, self.allocator, .limited(max_grep_file_bytes), ) catch |err| { // The file grew past the single-file ceiling between the stat // and this read, or it vanished, or it is not readable. Skip it. if (err == error.OutOfMemory) { return err; } return null; }; if (isBinaryContent(content)) { self.allocator.free(content); return null; } assert(content.len <= max_grep_file_bytes); return content; }
fn widget(self: *GrepModel) vxfw.Widget { const result: vxfw.Widget = .{ .userdata = self, .eventHandler = GrepModel.typeErasedEventHandler, .drawFn = GrepModel.typeErasedDrawFn, }; assert(result.userdata == @as(*anyopaque, @ptrCast(self))); return result; }
/// Handles one loading tick: walk a bounded slice of the tree, search /// the newly loaded files, and ask for another tick while there is more /// work. The bounded slices keep every step short, so picking or typing /// stays responsive even in huge trees. fn handleTick(self: *GrepModel, ctx: *vxfw.EventContext) !void { if (self.state == .pending) { self.startLoading(); } ctx.redraw = true; if (self.state == .loading) { _ = self.loadCorpusStep(grep_slice_entries, grep_slice_time_ns, max_grep_files) catch { self.dropLoader(.failed); }; } // Search the files this step loaded, even when the walk just // reached its end; cap hits only park a walk that still runs. if (self.searched_files < self.corpus.items.len) { const query = try self.text_field.buf.dupe(); defer self.text_field.buf.allocator.free(query); self.query_len = query.len; const truncated = try self.appendMatches(query); if (truncated and self.state == .loading) { self.state = .paused; } self.updateListView(false); self.refreshPreview(); } if (self.state == .loading) { try ctx.tick(0, self.widget()); } }
fn typeErasedEventHandler( ptr: *anyopaque, ctx: *vxfw.EventContext, event: vxfw.Event, ) anyerror!void { const self: *GrepModel = @ptrCast(@alignCast(ptr)); switch (event) { .tick => try self.handleTick(ctx), else => try handleCommonEvent(self, ctx, event), } }
fn statusText(self: *GrepModel, allocator: std.mem.Allocator) ![]const u8 { const matches = self.lines.items.len; if (self.truncated or self.state == .paused) { return "too many matches, keep typing to narrow"; } return switch (self.state) { .pending, .loading => std.fmt.allocPrint( allocator, "{d} matches, scanning {d} files", .{ matches, self.corpus.items.len }, ), .capped => std.fmt.allocPrint( allocator, "{d} matches in {d} files, list capped", .{ matches, self.corpus.items.len }, ), .done => std.fmt.allocPrint(allocator, "{d} matches", .{matches}), .failed => std.fmt.allocPrint( allocator, "{d} matches, directory read failed", .{matches}, ), .paused => unreachable, }; }
fn typeErasedDrawFn( ptr: *anyopaque, ctx: vxfw.DrawContext, ) std.mem.Allocator.Error!vxfw.Surface { const self: *GrepModel = @ptrCast(@alignCast(ptr)); // Rows are built into the row arena on demand, and nothing built // for the previous frame is needed anymore. _ = self.row_arena.reset(.free_all); const status_text = try self.statusText(ctx.arena); return drawPicker( ctx, self.widget(), self.theme, &self.text_field, &self.list_view, status_text, self.preview.widget(), ); }
fn widgetBuilder(ptr: *const anyopaque, index: usize, cursor: usize) ?vxfw.Widget { // SAFETY: the ListView hands its builders a const pointer, but rows // are scratch built into the row arena for the frame being drawn, // so the model must stay mutable here. const self: *GrepModel = @ptrCast(@alignCast(@constCast(ptr))); return self.rowWidget(index, cursor); }
/// Builds the styled spans for one result row. Only called for rows on /// the screen, so a search that matches thousands of lines costs no more /// styling work than the visible window. fn rowWidget(self: *GrepModel, index: usize, cursor: usize) ?vxfw.Widget { assert(cursor <= self.lines.items.len); if (index >= self.lines.items.len) { return null; } const arena = self.row_arena.allocator(); const line = self.lines.items[index]; assert(line.len > 0); var spans = std.ArrayListUnmanaged(vxfw.RichText.TextSpan).empty; appendDisplaySafeText(&spans, arena, line, .{}) catch return null; const normal = spans.toOwnedSlice(arena) catch return null; assert(normal.len > 0); const shown = if (index == cursor) cursorRowSpans(arena, normal, self.theme.cursor_row) catch return null else normal; const rich = arena.create(vxfw.RichText) catch return null; rich.* = .{ .text = shown }; return rich.widget(); }
fn onChange(maybe_ptr: ?*anyopaque, ctx: *vxfw.EventContext, query: []const u8) anyerror!void { const ptr = maybe_ptr orelse return; const self: *GrepModel = @ptrCast(@alignCast(ptr)); _ = try self.runSearch(query); if (self.state == .paused) { // The query narrowed, so files skipped while the row list was // full get searched while the walk resumes. self.state = .loading; try ctx.tick(0, self.widget()); } }
/// Runs a full search over the loaded corpus with the new query. fn runSearch(self: *GrepModel, query: []const u8) !bool { self.clearResults(); self.query_len = query.len; self.searched_files = 0; const truncated = try self.appendMatches(query); resetListView(&self.list_view, self.lines.items.len); self.refreshPreview(); return truncated; }
/// Greps the corpus files that this query has not seen yet and appends /// rows for their matches. Files are searched at most once per query. fn appendMatches(self: *GrepModel, query: []const u8) !bool { assert(self.searched_files <= self.corpus.items.len); const truncated = try grepFiles( self.allocator, &self.lines, self.corpus.items[self.searched_files..], query, ); self.searched_files = self.corpus.items.len; if (truncated) { self.truncated = true; } return truncated; }
fn updateListView(self: *GrepModel, reset: bool) void { if (reset) { resetListView(&self.list_view, self.lines.items.len); return; } // Rows only get appended, so the cursor stays where it is while the // corpus loads. It is pulled back when the list shrank below it. self.list_view.item_count = @intCast(self.lines.items.len); if (self.list_view.cursor >= self.lines.items.len) { self.list_view.cursor = 0; self.list_view.scroll = .{}; } }
fn clearResults(self: *GrepModel) void { freeLines(self.allocator, &self.lines); self.truncated = false; assert(self.lines.items.len == 0); }
fn refreshPreview(self: *GrepModel) void { _ = self.preview_arena.reset(.free_all); self.preview_text = &.{}; self.preview_spans = &.{}; self.preview = .{ .text = &no_preview_spans }; const cursor = self.list_view.cursor; if (cursor >= self.lines.items.len) { return; } const target = splitGrepLine(self.lines.items[cursor]); if (target.file.len == 0) { return; } if (target.line == 0) { return; } self.loadPreview(target) catch return; }
fn loadPreview(self: *GrepModel, target: GrepTarget) !void { assert(target.file.len > 0); assert(target.line > 0); for (self.corpus.items) |file| { if (!std.mem.eql(u8, file.path, target.file)) { continue; } const excerpt = try excerptFromContent( self.preview_arena.allocator(), file.content, target.line, ); if (excerpt.len == 0) { return; } assert(excerpt.len > 0); var spans = std.ArrayListUnmanaged(vxfw.RichText.TextSpan).empty; defer spans.deinit(self.preview_arena.allocator()); try appendPreviewSpans( &spans, self.preview_arena.allocator(), excerpt, target.column, self.query_len, self.theme, ); self.preview_text = excerpt; self.preview_spans = try spans.toOwnedSlice(self.preview_arena.allocator()); assert(self.preview_spans.len > 0); self.preview = .{ .text = self.preview_spans }; assert(self.preview.text.len > 0); return; } }
fn onSubmit(maybe_ptr: ?*anyopaque, ctx: *vxfw.EventContext, _: []const u8) anyerror!void { const ptr = maybe_ptr orelse return; const self: *GrepModel = @ptrCast(@alignCast(ptr)); if (self.list_view.cursor < self.lines.items.len) { self.selected = self.list_view.cursor; } ctx.quit = true; assert(ctx.quit); }};
pub fn pickGrepLine( allocator: std.mem.Allocator, ignored_patterns: []const []const u8, theme: ResolvedTheme, initial_query: ?[]const u8,) ![]u8 { try checkTerminalSize(input_output.runtime()); const model = try GrepModel.init( input_output.runtime(), allocator, ignored_patterns, theme, ); defer model.deinit(); // The prompt is the single source of the query. Every loading step // searches with whatever the prompt holds, including an initial query // that was filled in here before the first tick. if (initial_query) |query| { if (query.len > 0) { try model.text_field.insertSliceAtCursor(query); } } try runApp(allocator, model.widget()); const selected = model.selected orelse return error.UserAbort; assert(selected < model.lines.items.len); const result = try allocator.dupe(u8, model.lines.items[selected]); assert(result.len == model.lines.items[selected].len); return result;}
const testing = std.testing;
test "rankItems: filename match beats non-matches" { const items = [_][]const u8{ "src/main.zig", "README.md" }; var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const ranked = try rankItems(arena.allocator(), &items, "main"); try testing.expectEqual(@as(usize, 1), ranked.len); try testing.expectEqual(@as(usize, 0), ranked[0].index);}
test "rankItems: empty query keeps original order" { const items = [_][]const u8{ "b.txt", "a.txt", "c.txt" }; var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const ranked = try rankItems(arena.allocator(), &items, ""); try testing.expectEqual(@as(usize, 3), ranked.len); try testing.expectEqual(@as(usize, 0), ranked[0].index); try testing.expectEqual(@as(usize, 1), ranked[1].index); try testing.expectEqual(@as(usize, 2), ranked[2].index);}
test "rankItems: score ties prefer the shortest path" { const items = [_][]const u8{ "extensions/browser/README.md", "deprecated/extensions/filechanges/README.md", "README.md", }; var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const ranked = try rankItems(arena.allocator(), &items, "README"); try testing.expectEqual(@as(usize, 3), ranked.len); try testing.expectEqual(@as(usize, 2), ranked[0].index); try testing.expectEqual(@as(usize, 0), ranked[1].index); try testing.expectEqual(@as(usize, 1), ranked[2].index);}
test "rankItems: empty query keeps original order for mixed lengths" { const items = [_][]const u8{ "bbbb", "a", "cc" }; var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const ranked = try rankItems(arena.allocator(), &items, ""); try testing.expectEqual(@as(usize, 3), ranked.len); try testing.expectEqual(@as(usize, 0), ranked[0].index); try testing.expectEqual(@as(usize, 1), ranked[1].index); try testing.expectEqual(@as(usize, 2), ranked[2].index);}
test "rankItems: no match yields nothing" { const items = [_][]const u8{"src/main.zig"}; var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const ranked = try rankItems(arena.allocator(), &items, "zzz"); try testing.expectEqual(@as(usize, 0), ranked.len);}
test "rankItems: uppercase query matches case-sensitively" { const items = [_][]const u8{ "src/main.zig", "src/MAIN.zig" }; var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const lower = try rankItems(arena.allocator(), &items, "main"); try testing.expectEqual(@as(usize, 2), lower.len); const upper = try rankItems(arena.allocator(), &items, "MAIN"); try testing.expectEqual(@as(usize, 1), upper.len); try testing.expectEqual(@as(usize, 1), upper[0].index);}
test "rankItems: results are deterministic across runs" { const items = [_][]const u8{ "src/main.zig", "src/picker.zig", "README.md" }; var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const first = try rankItems(arena.allocator(), &items, "z"); const second = try rankItems(arena.allocator(), &items, "z"); try testing.expectEqual(first.len, second.len); for (first, second) |left, right| { try testing.expectEqual(left.index, right.index); try testing.expectEqual(left.score, right.score); }}
test "rankItems: space matches path separator like slash" { const items = [_][]const u8{ "hosts/impish/overlays/config/magdalena", "hosts/impish/overlays/config/MangoHud", }; var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const slashed = try rankItems(arena.allocator(), &items, "impish/mag"); const spaced = try rankItems(arena.allocator(), &items, "impish mag"); try testing.expectEqual(slashed.len, spaced.len); try testing.expect(spaced.len > 0); for (slashed, spaced) |left, right| { try testing.expectEqual(left.index, right.index); }}
test "rankItems: literal space content still matches" { const items = [_][]const u8{ "foo bar", "foo/bar" }; var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const ranked = try rankItems(arena.allocator(), &items, "foo bar"); try testing.expectEqual(@as(usize, 2), ranked.len); try testing.expectEqual(@as(usize, 0), ranked[0].index);}
test "appendHighlightSpans: text rebuilds and matches glow" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const text = "src/main.zig"; const matches = [_]usize{ 4, 5, 6, 7 }; var spans = std.ArrayListUnmanaged(vxfw.RichText.TextSpan).empty; try appendHighlightSpans(&spans, arena.allocator(), text, &matches, defaultTheme().match); var rebuilt = std.ArrayListUnmanaged(u8).empty; defer rebuilt.deinit(testing.allocator); var highlighted: ?[]const u8 = null; for (spans.items) |span| { try rebuilt.appendSlice(testing.allocator, span.text); if (span.style.reverse) { highlighted = span.text; } } try testing.expectEqualStrings(text, rebuilt.items); try testing.expectEqualStrings("main", highlighted.?);}
test "appendHighlightSpans: no matches leaves plain text" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); var spans = std.ArrayListUnmanaged(vxfw.RichText.TextSpan).empty; try appendHighlightSpans(&spans, arena.allocator(), "abc", &.{}, defaultTheme().match); try testing.expectEqual(@as(usize, 1), spans.items.len); try testing.expectEqualStrings("abc", spans.items[0].text); try testing.expect(!spans.items[0].style.reverse);}
test "splitGrepLine: file with line and column" { const target = splitGrepLine("src/main.zig:12:4:needle"); try testing.expectEqualStrings("src/main.zig", target.file); try testing.expectEqual(@as(usize, 12), target.line);}
test "splitGrepLine: missing line yields zero" { const target = splitGrepLine("README.md"); try testing.expectEqualStrings("README.md", target.file); try testing.expectEqual(@as(usize, 0), target.line);}
test "splitGrepLine: malformed line yields zero" { const target = splitGrepLine("src/main.zig:deep:4:x"); try testing.expectEqualStrings("src/main.zig", target.file); try testing.expectEqual(@as(usize, 0), target.line);}
extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int;
test "GrepModel: prompt prefills and drives the background search" { var temp_directory = testing.tmpDir(.{ .iterate = true }); defer temp_directory.cleanup(); const test_input_output = testing.io; try input_output.writeFile( test_input_output, temp_directory.dir, "notes.txt", "hello\nfind the needle\n", 0o644, );
var model = try GrepModel.init(test_input_output, testing.allocator, &.{}, defaultTheme()); defer model.deinit(); try model.text_field.insertSliceAtCursor("needle"); const inserted = try model.text_field.buf.dupe(); defer model.text_field.buf.allocator.free(inserted); try testing.expectEqualStrings("needle", inserted);
// Drive the loading the same way tick events do: bounded steps that // search with whatever the prompt holds. const root = try walker.openWalkDir(test_input_output, temp_directory.dir); model.openLoader(root); var ctx: vxfw.EventContext = .{ .io = test_input_output, .alloc = testing.allocator, .cmds = .empty, }; defer ctx.cmds.deinit(testing.allocator); while (model.state == .loading) { try model.handleTick(&ctx); } try testing.expectEqual(GrepState.done, model.state); try testing.expectEqual(@as(usize, 1), model.lines.items.len); const target = splitGrepLine(model.lines.items[0]); try testing.expectEqualStrings("notes.txt", target.file); try testing.expectEqual(@as(usize, 2), target.line); // The whole tree loaded in one step, so no follow-up tick was needed. try testing.expectEqual(@as(usize, 0), ctx.cmds.items.len);}
test "parseThemeColor: default keyword" { const color = try parseThemeColor("default"); try testing.expect(color == .default);}
test "parseThemeColor: palette bounds" { const zero = try parseThemeColor("0"); try testing.expectEqual(@as(u8, 0), zero.index); const top = try parseThemeColor("255"); try testing.expectEqual(@as(u8, 255), top.index); try testing.expectError(error.InvalidColor, parseThemeColor("256")); try testing.expectError(error.InvalidColor, parseThemeColor("-1"));}
test "parseThemeColor: hex triple" { const color = try parseThemeColor("#ff0080"); try testing.expectEqual([3]u8{ 255, 0, 128 }, color.rgb); const black = try parseThemeColor("#000000"); try testing.expectEqual([3]u8{ 0, 0, 0 }, black.rgb);}
test "parseThemeColor: malformed input errors" { try testing.expectError(error.InvalidColor, parseThemeColor("")); try testing.expectError(error.InvalidColor, parseThemeColor("blue")); try testing.expectError(error.InvalidColor, parseThemeColor("red")); try testing.expectError(error.InvalidColor, parseThemeColor("#xyz")); try testing.expectError(error.InvalidColor, parseThemeColor("#12345")); try testing.expectError(error.InvalidColor, parseThemeColor("#1234567")); try testing.expectError(error.InvalidColor, parseThemeColor("#zzzzzz"));}
test "resolveTheme: empty config yields defaults" { const theme = resolveTheme(testing.io, config.Config{}); try testing.expectEqual(@as(u8, 4), theme.prompt.fg.index); try testing.expect(!theme.prompt.reverse); try testing.expectEqual(@as(u8, 4), theme.match.fg.index); try testing.expect(theme.match.reverse); try testing.expectEqual(@as(u8, 8), theme.cursor_row.bg.index); try testing.expectEqual(@as(u8, 8), theme.status.fg.index); try testing.expectEqual(@as(u8, 4), theme.preview_current.fg.index);}
test "resolveTheme: partial theme fills only set roles" { const app_config = config.Config{ .theme = .{ .prompt = "9" } }; const theme = resolveTheme(testing.io, app_config); try testing.expectEqual(@as(u8, 9), theme.prompt.fg.index); try testing.expectEqual(@as(u8, 4), theme.match.fg.index); try testing.expectEqual(@as(u8, 8), theme.status.fg.index);}
test "resolveTheme: invalid role warns and defaults that role" { const app_config = config.Config{ .theme = .{ .match = "not-a-color" } }; const theme = resolveTheme(testing.io, app_config); try testing.expectEqual(@as(u8, 4), theme.match.fg.index); try testing.expect(theme.match.reverse); try testing.expectEqual(@as(u8, 4), theme.prompt.fg.index);}
test "resolveTheme: NO_COLOR convention" { const old_value = if (std.c.getenv("NO_COLOR")) |existing| try testing.allocator.dupeSentinel(u8, std.mem.span(existing), 0) else null; defer { if (old_value) |saved| { defer testing.allocator.free(saved); _ = setenv("NO_COLOR", saved.ptr, 1); } else { _ = setenv("NO_COLOR", "", 1); } } assert(setenv("NO_COLOR", "1", 1) == 0); const app_config = config.Config{ .theme = .{ .prompt = "9" } }; const blank = resolveTheme(testing.io, app_config); try testing.expect(blank.prompt.fg == .default); try testing.expect(blank.match.fg == .default); try testing.expect(!blank.match.reverse); try testing.expect(blank.cursor_row.bg == .default); try testing.expect(blank.status.fg == .default); try testing.expect(blank.preview_current.fg == .default); assert(setenv("NO_COLOR", "", 1) == 0); const kept = resolveTheme(testing.io, config.Config{}); try testing.expectEqual(@as(u8, 4), kept.prompt.fg.index); try testing.expect(kept.match.reverse);}
test "appendPreviewSpans: marker styled and match highlighted" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const excerpt = " line one\n> needle here\n line three\n"; var spans = std.ArrayListUnmanaged(vxfw.RichText.TextSpan).empty; try appendPreviewSpans(&spans, arena.allocator(), excerpt, 1, 6, defaultTheme()); var rebuilt = std.ArrayListUnmanaged(u8).empty; defer rebuilt.deinit(testing.allocator); var marker_style: ?vaxis.Style = null; var match_text: ?[]const u8 = null; for (spans.items) |span| { try rebuilt.appendSlice(testing.allocator, span.text); if (std.mem.eql(u8, span.text, "> ")) { marker_style = span.style; } if (span.style.reverse) { match_text = span.text; } } try testing.expectEqualStrings(excerpt, rebuilt.items); try testing.expectEqual(@as(u8, 4), marker_style.?.fg.index); try testing.expectEqualStrings("needle", match_text.?);}
test "appendPreviewSpans: other lines stay plain" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const excerpt = " plain one\n> needle here\n plain two\n"; var spans = std.ArrayListUnmanaged(vxfw.RichText.TextSpan).empty; try appendPreviewSpans(&spans, arena.allocator(), excerpt, 1, 6, defaultTheme()); for (spans.items) |span| { if (std.mem.eql(u8, span.text, "> ")) { continue; } if (std.mem.eql(u8, span.text, "needle")) { continue; } try testing.expect(span.style.fg == .default); try testing.expect(!span.style.reverse); }}
test "appendPreviewSpans: past-the-end column leaves plain text" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const excerpt = "> short\n"; var spans = std.ArrayListUnmanaged(vxfw.RichText.TextSpan).empty; try appendPreviewSpans(&spans, arena.allocator(), excerpt, 99, 3, defaultTheme()); var rebuilt = std.ArrayListUnmanaged(u8).empty; defer rebuilt.deinit(testing.allocator); for (spans.items) |span| { try rebuilt.appendSlice(testing.allocator, span.text); try testing.expect(!span.style.reverse); } try testing.expectEqualStrings(excerpt, rebuilt.items);}
test "appendPreviewSpans: zero column yields no highlight" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const excerpt = "> needle here\n"; var spans = std.ArrayListUnmanaged(vxfw.RichText.TextSpan).empty; try appendPreviewSpans(&spans, arena.allocator(), excerpt, 0, 6, defaultTheme()); for (spans.items) |span| { try testing.expect(!span.style.reverse); }}
test "appendPreviewSpans: match region clamps to the line" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const excerpt = "> abcdef\n"; var spans = std.ArrayListUnmanaged(vxfw.RichText.TextSpan).empty; try appendPreviewSpans(&spans, arena.allocator(), excerpt, 5, 99, defaultTheme()); var match_text: ?[]const u8 = null; for (spans.items) |span| { if (span.style.reverse) { match_text = span.text; } } try testing.expectEqualStrings("ef", match_text.?);}
test "sanitizeDisplayText: CSI sequences stripped" { const clean = try sanitizeDisplayText(testing.allocator, "a\x1b[31mred\x1b[0mb"); defer testing.allocator.free(clean); try testing.expectEqualStrings("aredb", clean);}
test "sanitizeDisplayText: OSC sequences stripped" { const clean = try sanitizeDisplayText(testing.allocator, "a\x1b]8;;http://x\x07linkb"); defer testing.allocator.free(clean); try testing.expectEqualStrings("alinkb", clean);}
test "sanitizeDisplayText: controls become spaces, tabs expand" { const clean = try sanitizeDisplayText(testing.allocator, "a\x00b\x1bc\x7fd\te"); defer testing.allocator.free(clean); try testing.expectEqualStrings("a b d e", clean);}
test "sanitizeDisplayText: bad UTF-8 repaired, good UTF-8 kept" { const clean = try sanitizeDisplayText(testing.allocator, "h\xff\xc3\xa9!\xe2\x82\xac"); defer testing.allocator.free(clean); try testing.expectEqualStrings("h�é!€", clean); try testing.expect(std.unicode.utf8ValidateSlice(clean));}
test "sanitizeDisplayText: output never carries ESC" { const inputs = [_][]const u8{ "\x1b[31m", "\x1b]0;title\x07", "plain", "a\rb\n", "\x9b31m", }; for (inputs) |input| { const clean = try sanitizeDisplayText(testing.allocator, input); defer testing.allocator.free(clean); try testing.expect(std.mem.indexOfScalar(u8, clean, 0x1B) == null); try testing.expect(std.unicode.utf8ValidateSlice(clean)); }}
test "sanitizeDisplayText: idempotent" { const once = try sanitizeDisplayText(testing.allocator, "a\x1b[1mb\tc\xff"); defer testing.allocator.free(once); const twice = try sanitizeDisplayText(testing.allocator, once); defer testing.allocator.free(twice); try testing.expectEqualStrings(once, twice);}
test "ListModel.init paints empty before first tick" { const items = [_][]const u8{ "src/main.zig", "README.md" }; const model = try ListModel.init(testing.allocator, &items, null, defaultTheme()); defer model.deinit(); try testing.expect(!model.loaded); try testing.expectEqual(@as(usize, 0), model.filtered.items.len); try testing.expectEqual(@as(?u32, 0), model.list_view.item_count); try model.refilter(""); try testing.expectEqual(@as(usize, 2), model.filtered.items.len);}
test "ListModel.refilter scores sanitized text, selects raw" { const items = [_][]const u8{ "a\x1b[31mmain.zig", "README.md" }; const model = try ListModel.init(testing.allocator, &items, null, defaultTheme()); defer model.deinit(); try model.refilter("main"); try testing.expectEqual(@as(usize, 1), model.ranked.len); try testing.expectEqual(@as(usize, 0), model.ranked[0].index); for (model.filtered.items[0].text) |span| { try testing.expect(std.mem.indexOfScalar(u8, span.text, 0x1B) == null); } try testing.expectEqualStrings("a\x1b[31mmain.zig", model.items[model.ranked[0].index]);}
test "buildDiffLines: colors additions, deletions and hunk headers" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const diff = "@@ -1 +1 @@\n-old\n+new\n\n context\n"; const lines = try buildDiffLines(arena.allocator(), diff); try testing.expectEqual(@as(usize, 5), lines.len); try testing.expectEqualStrings("@@ -1 +1 @@", lines[0].text[0].text); try testing.expectEqual(diff_hunk_style, lines[0].text[0].style); try testing.expectEqualStrings("-old", lines[1].text[0].text); try testing.expectEqual(diff_delete_style, lines[1].text[0].style); try testing.expectEqualStrings("+new", lines[2].text[0].text); try testing.expectEqual(diff_add_style, lines[2].text[0].style); try testing.expectEqualStrings(" ", lines[3].text[0].text); try testing.expectEqualStrings(" context", lines[4].text[0].text); try testing.expectEqual(@as(vaxis.Style, .{}), lines[4].text[0].style);}
test "clipPreviewLine: keeps UTF-8 sequences whole" { var line: [max_preview_line_bytes + 8]u8 = undefined; @memset(&line, 'a'); // A 2-byte sequence that crosses the clip point. line[max_preview_line_bytes - 1] = 0xC3; line[max_preview_line_bytes] = 0xA9; const clipped = clipPreviewLine(&line); try testing.expectEqual(max_preview_line_bytes - 1, clipped.len); try testing.expectEqual( max_preview_line_bytes, clipPreviewLine(line[0..max_preview_line_bytes]).len, );}
test "ListModel.refreshPreview loads lazily for highlighted item" { const Loader = struct { fn load(_: ?*anyopaque, arena: std.mem.Allocator, index: usize) anyerror!?[]const u8 { return switch (index) { 0 => try arena.dupe(u8, "+one\n"), else => null, }; } }; const items = [_][]const u8{ " M a.txt", " M b.txt" }; const source: PreviewSource = .{ .ctx = null, .load = Loader.load }; const model = try ListModel.init(testing.allocator, &items, source, defaultTheme()); defer model.deinit(); try model.refilter(""); try testing.expectEqualStrings("+one", model.preview_lines[0].text[0].text); try model.refilter("b.txt"); try testing.expectEqualStrings(no_preview_text, model.preview_lines[0].text[0].text);}
test "ListModel preview draws diffs taller than a u16 surface" { const Loader = struct { fn load(_: ?*anyopaque, arena: std.mem.Allocator, _: usize) anyerror!?[]const u8 { var text = std.ArrayListUnmanaged(u8).empty; for (0..2000) |_| { try text.appendSlice(arena, "+line\n"); } return text.items; } }; const items = [_][]const u8{" M a.txt"}; const source: PreviewSource = .{ .ctx = null, .load = Loader.load }; const model = try ListModel.init(testing.allocator, &items, source, defaultTheme()); defer model.deinit(); try model.refilter(""); try testing.expectEqual(@as(usize, 2000), model.preview_lines.len); var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); vxfw.DrawContext.init(.unicode); const ctx: vxfw.DrawContext = .{ .arena = arena.allocator(), .min = .{}, .max = .{ .width = 150, .height = 50 }, .cell_size = .{ .width = 10, .height = 20 }, }; const surface = try model.preview_scroll.draw(ctx); try testing.expectEqual(@as(u16, 50), surface.size.height); try testing.expect(model.preview_scroll.scroll.linesDown(preview_scroll_lines)); _ = try model.preview_scroll.draw(ctx); try testing.expectEqual(@as(u32, preview_scroll_lines), model.preview_scroll.scroll.top);}
test "appendCursorSpans: differs only by background" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const text = "src/main.zig"; const matches = [_]usize{ 4, 5, 6, 7 }; var normal = std.ArrayListUnmanaged(vxfw.RichText.TextSpan).empty; try appendHighlightSpans(&normal, arena.allocator(), text, &matches, defaultTheme().match); const theme = defaultTheme(); var cursor = std.ArrayListUnmanaged(vxfw.RichText.TextSpan).empty; try appendCursorSpans(&cursor, arena.allocator(), normal.items, theme.cursor_row); try testing.expectEqual(normal.items.len, cursor.items.len); for (normal.items, cursor.items) |plain, highlighted| { try testing.expectEqualStrings(plain.text, highlighted.text); try testing.expect(vaxis.Color.eql(plain.style.fg, highlighted.style.fg)); try testing.expectEqual(plain.style.reverse, highlighted.style.reverse); try testing.expectEqual(@as(u8, 8), highlighted.style.bg.index); } for (normal.items) |span| { try testing.expect(span.style.bg == .default); }}
test "splitGrepLine: column parsed" { const target = splitGrepLine("src/main.zig:12:4:needle"); try testing.expectEqualStrings("src/main.zig", target.file); try testing.expectEqual(@as(usize, 12), target.line); try testing.expectEqual(@as(usize, 4), target.column);}
test "appendDisplaySafeText: carriage returns become spaces" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); var spans = std.ArrayListUnmanaged(vxfw.RichText.TextSpan).empty; try appendDisplaySafeText(&spans, arena.allocator(), "a\rb\r", .{}); var rebuilt = std.ArrayListUnmanaged(u8).empty; defer rebuilt.deinit(testing.allocator); for (spans.items) |span| { try testing.expect(std.mem.indexOfScalar(u8, span.text, '\r') == null); try rebuilt.appendSlice(testing.allocator, span.text); } try testing.expectEqualStrings("a b ", rebuilt.items);}
test "appendDisplaySafeText: clean text yields one span" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); var spans = std.ArrayListUnmanaged(vxfw.RichText.TextSpan).empty; try appendDisplaySafeText(&spans, arena.allocator(), "abc", defaultTheme().match); try testing.expectEqual(@as(usize, 1), spans.items.len); try testing.expectEqualStrings("abc", spans.items[0].text); try testing.expect(spans.items[0].style.reverse);}
test "appendPreviewSpans: carriage returns never reach spans" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const excerpt = "> ab\rcd\n"; var spans = std.ArrayListUnmanaged(vxfw.RichText.TextSpan).empty; try appendPreviewSpans(&spans, arena.allocator(), excerpt, 1, 5, defaultTheme()); for (spans.items) |span| { try testing.expect(std.mem.indexOfScalar(u8, span.text, '\r') == null); }}
test "splitGrepLine: missing column yields zero" { const target = splitGrepLine("src/main.zig:12"); try testing.expectEqualStrings("src/main.zig", target.file); try testing.expectEqual(@as(usize, 12), target.line); try testing.expectEqual(@as(usize, 0), target.column);}
test "grepFiles: single word reports path, line and column" { var files = [_]GrepFile{ .{ .path = "notes.txt", .content = "first line\nsecond needle here\nthird\n" }, }; var lines = std.ArrayListUnmanaged([]const u8).empty; defer freeLines(testing.allocator, &lines); const truncated = try grepFiles(testing.allocator, &lines, &files, "needle"); try testing.expect(!truncated); try testing.expectEqual(@as(usize, 1), lines.items.len); try testing.expectEqualStrings("notes.txt:2:8:second needle here", lines.items[0]);}
test "grepFiles: space-separated words must share a line" { var files = [_]GrepFile{ .{ .path = "a.txt", .content = "alpha beta\nalpha only\nbeta only\n" }, }; var lines = std.ArrayListUnmanaged([]const u8).empty; defer freeLines(testing.allocator, &lines); const truncated = try grepFiles(testing.allocator, &lines, &files, "alpha beta"); try testing.expect(!truncated); try testing.expectEqual(@as(usize, 1), lines.items.len); try testing.expectEqualStrings("a.txt:1:1:alpha beta", lines.items[0]);}
test "grepFiles: lowercase query is case-insensitive, uppercase sensitive" { var files = [_]GrepFile{ .{ .path = "f.txt", .content = "Readme\nreadme\nREADME\n" }, }; var lines = std.ArrayListUnmanaged([]const u8).empty; defer freeLines(testing.allocator, &lines); _ = try grepFiles(testing.allocator, &lines, &files, "readme"); try testing.expectEqual(@as(usize, 3), lines.items.len); for (lines.items) |line| testing.allocator.free(line); lines.clearRetainingCapacity(); _ = try grepFiles(testing.allocator, &lines, &files, "Read"); try testing.expectEqual(@as(usize, 1), lines.items.len); try testing.expectEqualStrings("f.txt:1:1:Readme", lines.items[0]);}
test "grepFiles: repeated hits on one line collapse to a single row" { var files = [_]GrepFile{ .{ .path = "f.txt", .content = "needle and needle\nother\nneedle\n" }, }; var lines = std.ArrayListUnmanaged([]const u8).empty; defer freeLines(testing.allocator, &lines); _ = try grepFiles(testing.allocator, &lines, &files, "needle"); try testing.expectEqual(@as(usize, 2), lines.items.len); try testing.expectEqualStrings("f.txt:1:1:needle and needle", lines.items[0]); try testing.expectEqualStrings("f.txt:3:1:needle", lines.items[1]);}
test "grepFiles: blank queries yield nothing" { var files = [_]GrepFile{ .{ .path = "f.txt", .content = "content\n" }, }; var lines = std.ArrayListUnmanaged([]const u8).empty; defer lines.deinit(testing.allocator); _ = try grepFiles(testing.allocator, &lines, &files, ""); _ = try grepFiles(testing.allocator, &lines, &files, " "); try testing.expectEqual(@as(usize, 0), lines.items.len);}
test "grepFiles: reports truncated state at the row cap" { var content = std.ArrayListUnmanaged(u8).empty; defer content.deinit(testing.allocator); var number: usize = 0; const total_lines = max_grep_lines + 5; while (number < total_lines) : (number += 1) { try content.appendSlice(testing.allocator, "needle line\n"); } var files = [_]GrepFile{ .{ .path = "big.txt", .content = content.items }, }; var lines = std.ArrayListUnmanaged([]const u8).empty; defer freeLines(testing.allocator, &lines); const truncated = try grepFiles(testing.allocator, &lines, &files, "needle"); try testing.expect(truncated); try testing.expectEqual(max_grep_lines, lines.items.len);}
test "isBinaryContent: NUL within the probe window" { try testing.expect(isBinaryContent("text\x00more")); try testing.expect(!isBinaryContent("plain text\n")); try testing.expect(!isBinaryContent(""));}
test "GrepModel: corpus search fills rows from a disk tree" { var temp_directory = testing.tmpDir(.{ .iterate = true }); defer temp_directory.cleanup(); const test_input_output = testing.io; try temp_directory.dir.createDir(test_input_output, "sub", .fromMode(0o755)); try input_output.writeFile( test_input_output, temp_directory.dir, "sub/notes.txt", "hello\nfind the needle\n", 0o644, ); try input_output.writeFile( test_input_output, temp_directory.dir, "binary.bin", "a\x00b needle\n", 0o644, );
var model = try GrepModel.init(test_input_output, testing.allocator, &.{}, defaultTheme()); defer model.deinit(); const root = try walker.openWalkDir(test_input_output, temp_directory.dir); try model.loadCorpus(root); try testing.expectEqual(GrepState.done, model.state); try testing.expectEqual(@as(usize, 1), model.corpus.items.len); const truncated = try model.runSearch("needle"); try testing.expect(!truncated); try testing.expectEqual(@as(usize, 1), model.lines.items.len); const target = splitGrepLine(model.lines.items[0]); try testing.expectEqualStrings("sub/notes.txt", target.file); try testing.expectEqual(@as(usize, 2), target.line); try testing.expectEqual(@as(usize, 10), target.column); try testing.expectEqual(@as(?u32, 1), model.list_view.item_count); // Rows are styled on demand for the frame being drawn. const widget = GrepModel.widgetBuilder(model, 0, 0) orelse return error.TestUnexpectedResult; const rich: *vxfw.RichText = @ptrCast(@alignCast(widget.userdata)); try testing.expectEqual(@as(usize, 1), rich.text.len); try testing.expectEqualStrings(model.lines.items[0], rich.text[0].text); try testing.expectEqual(@as(u8, 8), rich.text[0].style.bg.index); const plain_widget = GrepModel.widgetBuilder( model, 0, 1, ) orelse return error.TestUnexpectedResult; const plain: *vxfw.RichText = @ptrCast(@alignCast(plain_widget.userdata)); try testing.expectEqualStrings(model.lines.items[0], plain.text[0].text); try testing.expect(plain.text[0].style.bg == .default); try testing.expect(GrepModel.widgetBuilder(model, 1, 0) == null);}
test "GrepModel: files above the size limit are skipped" { var temp_directory = testing.tmpDir(.{ .iterate = true }); defer temp_directory.cleanup(); const test_input_output = testing.io; const big_content = try testing.allocator.alloc(u8, max_grep_file_bytes + 1); defer testing.allocator.free(big_content); @memset(big_content, 'x'); @memcpy(big_content[0..7], "needle\n"); try input_output.writeFile( test_input_output, temp_directory.dir, "big.txt", big_content, 0o644, ); try input_output.writeFile( test_input_output, temp_directory.dir, "small.txt", "needle\n", 0o644, );
var model = try GrepModel.init(test_input_output, testing.allocator, &.{}, defaultTheme()); defer model.deinit(); const root = try walker.openWalkDir(test_input_output, temp_directory.dir); try model.loadCorpus(root); try testing.expectEqual(GrepState.done, model.state); try testing.expectEqual(@as(usize, 1), model.corpus.items.len); try testing.expectEqualStrings("small.txt", model.corpus.items[0].path); const truncated = try model.runSearch("needle"); try testing.expect(!truncated); try testing.expectEqual(@as(usize, 1), model.lines.items.len); const target = splitGrepLine(model.lines.items[0]); try testing.expectEqualStrings("small.txt", target.file);}
test "GrepModel: empty corpus searches cleanly" { var temp_directory = testing.tmpDir(.{ .iterate = true }); defer temp_directory.cleanup(); const test_input_output = testing.io; var model = try GrepModel.init(test_input_output, testing.allocator, &.{}, defaultTheme()); defer model.deinit(); const root = try walker.openWalkDir(test_input_output, temp_directory.dir); try model.loadCorpus(root); try testing.expectEqual(GrepState.done, model.state); try testing.expectEqual(@as(usize, 0), model.corpus.items.len); const truncated = try model.runSearch("needle"); try testing.expect(!truncated); try testing.expectEqual(@as(usize, 0), model.lines.items.len);}
test "GrepModel: file cap stops the walk early" { var temp_directory = testing.tmpDir(.{ .iterate = true }); defer temp_directory.cleanup(); const test_input_output = testing.io; for ([_][]const u8{ "a.txt", "b.txt", "c.txt" }) |name| { try input_output.writeFile( test_input_output, temp_directory.dir, name, "needle\n", 0o644, ); }
var model = try GrepModel.init(test_input_output, testing.allocator, &.{}, defaultTheme()); defer model.deinit(); const root = try walker.openWalkDir(test_input_output, temp_directory.dir); model.openLoader(root); try testing.expectEqual(GrepState.loading, model.state); const more = try model.loadCorpusStep(std.math.maxInt(usize), std.math.maxInt(i96), 2); // The corpus filled up, so the step asked the walk to stop early. try testing.expect(!more); try testing.expectEqual(GrepState.capped, model.state); try testing.expectEqual(@as(usize, 2), model.corpus.items.len); try testing.expect(model.loader == null);}
test "GrepModel: paused walk resumes when the query changes" { var temp_directory = testing.tmpDir(.{ .iterate = true }); defer temp_directory.cleanup(); const test_input_output = testing.io; var model = try GrepModel.init(test_input_output, testing.allocator, &.{}, defaultTheme()); defer model.deinit(); const root = try walker.openWalkDir(test_input_output, temp_directory.dir); model.openLoader(root); // The row list filled while files were still queued. model.state = .paused; model.truncated = true;
var ctx: vxfw.EventContext = .{ .io = test_input_output, .alloc = testing.allocator, .cmds = .empty, }; defer ctx.cmds.deinit(testing.allocator); try GrepModel.onChange(model, &ctx, "narrow"); try testing.expectEqual(GrepState.loading, model.state); // Resuming must schedule the walk again. try testing.expectEqual(@as(usize, 1), ctx.cmds.items.len); // A repeated change while loading does not stack another tick. try GrepModel.onChange(model, &ctx, "narrowish"); try testing.expectEqual(@as(usize, 1), ctx.cmds.items.len);}
test "excerptFromContent: window around the target line" { var content = std.ArrayListUnmanaged(u8).empty; defer content.deinit(testing.allocator); var number: usize = 1; while (number <= 30) : (number += 1) { const line = try std.fmt.allocPrint(testing.allocator, "line{d}\n", .{number}); defer testing.allocator.free(line); try content.appendSlice(testing.allocator, line); } const excerpt = try excerptFromContent(testing.allocator, content.items, 10); defer testing.allocator.free(excerpt); try testing.expect(std.mem.indexOf(u8, excerpt, "> line10\n") != null); try testing.expect(std.mem.indexOf(u8, excerpt, " line5\n") != null); try testing.expect(std.mem.indexOf(u8, excerpt, " line25\n") != null); try testing.expect(std.mem.indexOf(u8, excerpt, "line26\n") == null);}
test "excerptFromContent: line past the end yields empty" { const excerpt = try excerptFromContent(testing.allocator, "only\n", 99); defer testing.allocator.free(excerpt); try testing.expectEqual(@as(usize, 0), excerpt.len);}
test "excerptFromContent: big buffers are fine" { var content = std.ArrayListUnmanaged(u8).empty; defer content.deinit(testing.allocator); var number: usize = 1; while (number <= 4000) : (number += 1) { const line = try std.fmt.allocPrint( testing.allocator, "a fairly long line {d} with some padding text to grow the buffer\n", .{number}, ); defer testing.allocator.free(line); try content.appendSlice(testing.allocator, line); } try testing.expect(content.items.len > 64 * 1024); const excerpt = try excerptFromContent(testing.allocator, content.items, 2000); defer testing.allocator.free(excerpt); try testing.expect(std.mem.indexOf(u8, excerpt, "> a fairly long line 2000 ") != null);}