Tables and Columns
Tables and columns are the foundation of cols. A Table is the top-level
container that owns all configuration, columns, and lines. Columns define the
vertical structure of the table: each column has a name (shown in the header
row), an optional width hint, and formatting flags. You typically set up your
columns first, then add lines with data.
Creating a table
#![allow(unused)]
fn main() {
use cols::Table;
let mut table = Table::new();
table.name_set("devices"); // used as the key in JSON output
}
Adding columns
The simplest way to add a column is new_column, which creates an auto-sized column:
#![allow(unused)]
fn main() {
table.new_column("NAME");
}
For more control, build a Column and add it with add_column:
#![allow(unused)]
fn main() {
use cols::Column;
table.add_column(Column::new("SIZE").width_fixed(6).right(true));
}
Width hints
Width hints guide the layout algorithm. There are three modes:
| Method | Meaning |
|---|---|
| (default) | Auto — sized to fit content |
.width_fixed(n) | At least n characters wide |
.width_fraction(f) | Fraction of terminal width (e.g. 0.25 = 25%) |
Fractional widths only apply when output goes to a terminal. When piped, columns auto-size to their content.
#![allow(unused)]
fn main() {
use cols::{Column, WidthHint};
// These are equivalent:
Column::new("PATH").width_fraction(0.25);
Column::new("PATH").width(WidthHint::Fraction(0.25));
}
Modifying columns after creation
Use table.column_mut(idx) to modify a column that’s already in the table:
#![allow(unused)]
fn main() {
table.column_mut(0).unwrap().right_set(true);
table.column_mut(0).unwrap().hidden_set(true);
}
Terminal settings
Control how the table interacts with the terminal:
#![allow(unused)]
fn main() {
use cols::TermForce;
// explicit width
table.termwidth_set(120);
// force terminal-aware layout
table.termforce_set(TermForce::Always);
// subtract margin from width
table.termwidth_reduce(4);
}
TermForce::Auto (the default) detects whether stdout is a TTY. Use Always in tests or when you want fixed-width output regardless of the output target.