From d994b57fee21ef43ae7fc1726fffb20329c7d0e6 Mon Sep 17 00:00:00 2001 From: tobias Date: Sat, 14 Feb 2026 11:14:25 +0100 Subject: [PATCH] visidata: fix hidecol and add menu entry --- config/visidata/plugins/hidecol.py | 47 +++++++++++++++++------------- 1 file changed, 27 insertions(+), 20 deletions(-) diff --git a/config/visidata/plugins/hidecol.py b/config/visidata/plugins/hidecol.py index 88a3712..d57c38d 100644 --- a/config/visidata/plugins/hidecol.py +++ b/config/visidata/plugins/hidecol.py @@ -10,32 +10,39 @@ def hide_empty_and_superfluous_cols(sheet): Given a sheet, hides columns that are empty or superfluous (contain the same value in every row). """ - # Count how many columns were hidden counter = 0 - # Check each column for being empty or superfluous - for col in sheet.visibleCols: - # If the column is not hidden - if col.width and col.width > 0: - # Check if the column is empty (all cells are empty or None) - if all([col.getValue(row) in (None, "", "null") for row in sheet.rows]): - # Hide the column - col.width = 0 - counter += 1 - # Skip the next check for same values since all cells are empty or None + # Iterate over a snapshot; hiding columns mutates sheet.visibleCols. + for col in list(sheet.visibleCols): + if not col.width or col.width <= 0: + continue + + # Single pass over rows: track emptiness and distinct non-empty values. + all_empty = True + nonempty_vals = set() + for row in sheet.rows: + v = col.getValue(row) + if v in (None, "", "null"): continue + all_empty = False + nonempty_vals.add(str(v)) + if len(nonempty_vals) > 1: + break - # Check if the column is superfluous (contains the same value in every row) - # collect all values in the column as strings - values = set([f'{col.getValue(row)}' for row in sheet.rows if col.getValue(row) not in (None, "", "null")]) - # If there is only one value in the column - if len(values) == 1: - # Hide the column - col.width = 0 - counter += 1 + if all_empty or len(nonempty_vals) == 1: + col.width = 0 + counter += 1 + if counter: vd.status(f"Hid {counter} empty/superfluous columns.") else: vd.status("No empty/superfluous columns to hide.") -Sheet.addCommand(None, "tke-hidecol", "sheet.hide_empty_and_superfluous_cols()") +Sheet.addCommand( + None, + "tke-hidecol", + "sheet.hide_empty_and_superfluous_cols()", + helpstr="Hide columns that are empty or have the same value in every row.", +) +# Make the command discoverable in the top menu bar (no default keybinding). +vd.addMenuItem("Column", "Hide", "empty/superfluous columns", "tke-hidecol")