visidata: fix hidecol and add menu entry

This commit is contained in:
tobias
2026-02-14 11:14:25 +01:00
parent 40eb3fae7d
commit d994b57fee

View File

@@ -10,32 +10,39 @@ def hide_empty_and_superfluous_cols(sheet):
Given a sheet, hides columns that are empty or superfluous (contain the same Given a sheet, hides columns that are empty or superfluous (contain the same
value in every row). value in every row).
""" """
# Count how many columns were hidden
counter = 0 counter = 0
# Check each column for being empty or superfluous # Iterate over a snapshot; hiding columns mutates sheet.visibleCols.
for col in sheet.visibleCols: for col in list(sheet.visibleCols):
# If the column is not hidden if not col.width or col.width <= 0:
if col.width and col.width > 0: continue
# 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]): # Single pass over rows: track emptiness and distinct non-empty values.
# Hide the column all_empty = True
col.width = 0 nonempty_vals = set()
counter += 1 for row in sheet.rows:
# Skip the next check for same values since all cells are empty or None v = col.getValue(row)
if v in (None, "", "null"):
continue 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) if all_empty or len(nonempty_vals) == 1:
# collect all values in the column as strings col.width = 0
values = set([f'{col.getValue(row)}' for row in sheet.rows if col.getValue(row) not in (None, "", "null")]) counter += 1
# If there is only one value in the column
if len(values) == 1:
# Hide the column
col.width = 0
counter += 1
if counter:
vd.status(f"Hid {counter} empty/superfluous columns.") vd.status(f"Hid {counter} empty/superfluous columns.")
else: else:
vd.status("No empty/superfluous columns to hide.") 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")