From 445a3561d38552a452c242237f8cc04223d728b4 Mon Sep 17 00:00:00 2001 From: Christoph Heinrich Date: Sat, 18 Jun 2022 03:29:32 +0200 Subject: console: add history deduplication Deduplicate history like the fish shell. So for example entering "cmd 1" then "cmd 2" then "cmd 3" then "cmd 1" would result in a history of [cmd 2][cmd 3][cmd 1] instead of [cmd 1][cmd 2][cmd 3][cmd 1] Adds a function `history_add` to replace directly adding to history. Adds an option `history_dedup` to activate the deduplication. Defaults to on. --- player/lua/console.lua | 25 +++++++++++++++++++++---- 1 file changed, 21 insertions(+), 4 deletions(-) (limited to 'player/lua') diff --git a/player/lua/console.lua b/player/lua/console.lua index 3377380e8d..935753d19c 100644 --- a/player/lua/console.lua +++ b/player/lua/console.lua @@ -25,8 +25,10 @@ local opts = { -- have to be a monospaced font. font = "", -- Set the font size used for the REPL and the console. This will be - -- multiplied by "scale." + -- multiplied by "scale". font_size = 16, + -- Remove duplicate entries in history as to only keep the latest one. + history_dedup = true, } function detect_platform() @@ -232,7 +234,7 @@ function show_and_type(text, cursor_pos) -- Save the line currently being edited, just in case if line ~= text and line ~= '' and history[#history] ~= line then - history[#history + 1] = line + history_add(line) end line = text @@ -374,13 +376,28 @@ function help_command(param) log_add('', output) end +-- Add a line to the history and deduplicate +function history_add(text) + if opts.history_dedup then + -- More recent entries are more likely to be repeated + for i = #history, 1, -1 do + if history[i] == text then + table.remove(history, i) + break + end + end + end + + history[#history + 1] = text +end + -- Run the current command and clear the line (Enter) function handle_enter() if line == '' then return end if history[#history] ~= line then - history[#history + 1] = line + history_add(line) end -- match "help []", return or "", strip all whitespace @@ -416,7 +433,7 @@ function go_history(new_pos) -- entry. This makes it much less frustrating to accidentally hit Up/Down -- while editing a line. if old_pos == #history + 1 and line ~= '' and history[#history] ~= line then - history[#history + 1] = line + history_add(line) end -- Now show the history line (or a blank line for #history + 1) -- cgit v1.2.3