# history - Terminal history logging for fish shell (encrypted with SQLCipher)
set -g __kh_db "$HOME/.local/share/history/history.db"
set -g __kh_key_file "$HOME/.local/share/history/.key"
set -g __kh_last_command ""
function __kh_preexec --on-event fish_preexec
set -g __kh_last_command "$argv"
end
function __kh_postexec --on-event fish_postexec
set -l exit_code $status
set -l cmd "$__kh_last_command"
set -l pwd_path (pwd)
# Skip empty commands
test -z "$cmd"; and return
# Skip history command itself to avoid recursion
string match -qr '^history' "$cmd"; and return
# Skip if key file or database doesn't exist
test -f "$__kh_key_file"; or return
test -f "$__kh_db"; or return
# Escape single quotes for SQL (use fish's string replace)
set -l escaped_cmd (string replace -a "'" "''" -- "$cmd")
set -l escaped_pwd (string replace -a "'" "''" -- "$pwd_path")
# Log to database (async to not slow down shell)
fish -c "
set -l key (cat '$__kh_key_file')
sqlcipher '$__kh_db' \"PRAGMA key = '\$key'; INSERT INTO terminal_history (command, exit_code, pwd, shell) VALUES ('$escaped_cmd', $exit_code, '$escaped_pwd', 'fish');\"
" &>/dev/null &
end
# Initialize database if it doesn't exist
if not test -f "$__kh_db"
history-init 2>/dev/null
end