From 7b9142e3ba828636e065661c27dfca5486f7f8b4 Mon Sep 17 00:00:00 2001 From: Eduard Tolosa Date: Tue, 3 Jun 2025 17:05:04 -0500 Subject: [PATCH] (feat): better history handling using priorities for commands --- functions/__based.fish | 72 ++++++++++++++++++++++++++++++++---------- 1 file changed, 56 insertions(+), 16 deletions(-) diff --git a/functions/__based.fish b/functions/__based.fish index f17ba2b..82085a8 100644 --- a/functions/__based.fish +++ b/functions/__based.fish @@ -5,9 +5,6 @@ function __based end set -l path (realpath (pwd)) - set -l prefix "" - - # Extract commandline prefix up to cursor safely set -l buffer (commandline --current-buffer) set -l cursor_pos (commandline -C) set -l prefix (string sub -l $cursor_pos -- "$buffer") @@ -16,26 +13,69 @@ function __based set prefix (string replace -a "'" "''" -- $prefix) set -l cmd_expr "%$prefix%" - - # If the user has disabled fuzzy matching if set -q BASED_NO_FUZZY set cmd_expr "$prefix%" end + # Build combined result set in SQL if test -n "$prefix" - sqlite3 $db " - SELECT cmd FROM log - WHERE path = '$path' - AND cmd LIKE '$cmd_expr' - ORDER BY counter DESC, ts DESC;" | string collect + set results (sqlite3 -batch $db " + SELECT DISTINCT cmd FROM ( + -- Prioritize commands in the current path, matching the prefix + SELECT cmd, MAX(ts) as max_ts, MAX(counter) as counter, 0 as priority + FROM log + WHERE path = '$path' AND cmd LIKE '$cmd_expr' + GROUP BY cmd + + UNION + + -- Append the commands from the imported fish history that match the prefix + SELECT cmd, MAX(ts) as max_ts, MAX(counter) as counter, 1 as priority + FROM log + WHERE path = 'fish_history' AND cmd LIKE '$cmd_expr' + AND cmd NOT IN ( + SELECT cmd + FROM log + WHERE path = '$path' AND cmd LIKE '$cmd_expr' + ) + GROUP BY cmd + ) + ORDER BY priority ASC, counter DESC, max_ts DESC;") else - sqlite3 $db " - SELECT cmd - FROM ( - SELECT cmd, MAX(ts) as max_ts + set results (sqlite3 -batch $db " + SELECT DISTINCT cmd FROM ( + -- Get the most recent command across all paths + SELECT cmd, max_ts, counter, priority FROM ( + SELECT cmd, MAX(ts) as max_ts, MAX(counter) as counter, 0 as priority FROM log - GROUP BY cmd + GROUP BY cmd + ORDER BY max_ts DESC + LIMIT 1 ) - ORDER BY max_ts DESC;" | string collect + + UNION + + -- Commands in the current context + SELECT cmd, MAX(ts) as max_ts, MAX(counter) as counter, 1 as priority + FROM log + WHERE path = '$path' + GROUP BY cmd + + UNION + + -- Commands in the imported fish history + SELECT cmd, MAX(ts) as max_ts, MAX(counter) as counter, 2 as priority + FROM log + WHERE path = 'fish_history' + AND cmd NOT IN ( + SELECT cmd + FROM log + WHERE path = '$path' + ) + GROUP BY cmd + ) + ORDER BY priority ASC, counter DESC, max_ts DESC;") end + + printf "%s\n" $results end