comfy_table

Struct Table

Source
pub struct Table { /* private fields */ }
Expand description

This is the main interface for building a table. Each table consists of Rows, which in turn contain Cells.

There also exists a representation of a Column. Columns are automatically created when adding rows to a table.

Implementations§

Source§

impl Table

Source

pub fn new() -> Self

Create a new table with default ASCII styling.

Source

pub fn trim_fmt(&self) -> String

This is an alternative fmt function, which simply removes any trailing whitespaces. Trailing whitespaces often occur, when using tables without a right border.

Source

pub fn lines(&self) -> impl Iterator<Item = String>

This is an alternative to fmt, but rather returns an iterator to each line, rather than one String separated by newlines.

Source

pub fn set_header<T: Into<Row>>(&mut self, row: T) -> &mut Self

Set the header row of the table. This is usually the title of each column.
There’ll be no header unless you explicitly set it with this function.

use comfy_table::{Table, Row};

let mut table = Table::new();
let header = Row::from(vec!["Header One", "Header Two"]);
table.set_header(header);
Source

pub fn header(&self) -> Option<&Row>

Source

pub fn column_count(&mut self) -> usize

Returns the number of currently present columns.

use comfy_table::Table;

let mut table = Table::new();
table.set_header(vec!["Col 1", "Col 2", "Col 3"]);

assert_eq!(table.column_count(), 3);
Source

pub fn add_row<T: Into<Row>>(&mut self, row: T) -> &mut Self

Add a new row to the table.

use comfy_table::{Table, Row};

let mut table = Table::new();
table.add_row(vec!["One", "Two"]);
Source

pub fn add_row_if<P, T>(&mut self, predicate: P, row: T) -> &mut Self
where P: Fn(usize, &T) -> bool, T: Into<Row>,

Add a new row to the table if the predicate evaluates to true.

use comfy_table::{Table, Row};

let mut table = Table::new();
table.add_row_if(|index, row| true, vec!["One", "Two"]);
Source

pub fn add_rows<I>(&mut self, rows: I) -> &mut Self
where I: IntoIterator, I::Item: Into<Row>,

Add multiple rows to the table.

use comfy_table::{Table, Row};

let mut table = Table::new();
let rows = vec![
    vec!["One", "Two"],
    vec!["Three", "Four"]
];
table.add_rows(rows);
Source

pub fn add_rows_if<P, I>(&mut self, predicate: P, rows: I) -> &mut Self
where P: Fn(usize, &I) -> bool, I: IntoIterator, I::Item: Into<Row>,

Add multiple rows to the table if the predicate evaluates to true.

use comfy_table::{Table, Row};

let mut table = Table::new();
let rows = vec![
    vec!["One", "Two"],
    vec!["Three", "Four"]
];
table.add_rows_if(|index, rows| true, rows);
Source

pub fn row_count(&self) -> usize

Returns the number of currently present rows.

use comfy_table::Table;

let mut table = Table::new();
table.add_row(vec!["One", "Two"]);

assert_eq!(table.row_count(), 1);
Source

pub fn is_empty(&self) -> bool

Returns if the table is empty (contains no data rows).

use comfy_table::Table;

let mut table = Table::new();
assert!(table.is_empty());

table.add_row(vec!["One", "Two"]);
assert!(!table.is_empty());
Source

pub fn set_width(&mut self, width: u16) -> &mut Self

Enforce a max width that should be used in combination with dynamic content arrangement.
This is usually not necessary, if you plan to output your table to a tty, since the terminal width can be automatically determined.

Source

pub fn width(&self) -> Option<u16>

Get the expected width of the table.

This will be Some(width), if the terminal width can be detected or if the table width is set via set_width.

If neither is not possible, None will be returned.
This implies that both the Dynamic mode and the Percentage constraint won’t work.

Source

pub fn set_content_arrangement( &mut self, arrangement: ContentArrangement, ) -> &mut Self

Specify how Comfy Table should arrange the content in your table.

use comfy_table::{Table, ContentArrangement};

let mut table = Table::new();
table.set_content_arrangement(ContentArrangement::Dynamic);
Source

pub fn content_arrangement(&self) -> ContentArrangement

Get the current content arrangement of the table.

Source

pub fn set_delimiter(&mut self, delimiter: char) -> &mut Self

Set the delimiter used to split text in all cells.

A custom delimiter on a cell in will overwrite the column’s delimiter.
Normal text uses spaces ( ) as delimiters. This is necessary to help comfy-table understand the concept of words.

Source

pub fn force_no_tty(&mut self) -> &mut Self

In case you are sure you don’t want export tables to a tty or you experience problems with tty specific code, you can enforce a non_tty mode.

This disables:

If you use the dynamic content arrangement, you need to set the width of your desired table manually with set_width.

Source

pub fn use_stderr(&mut self) -> &mut Self

Use this function to check whether stderr is a tty.

The default is stdout.

Source

pub fn is_tty(&self) -> bool

Returns whether the table will be handled as if it’s printed to a tty.

By default, comfy-table looks at stdout and checks whether it’s a tty. This behavior can be changed via Table::force_no_tty and Table::use_stderr.

Source

pub fn enforce_styling(&mut self) -> &mut Self

Enforce terminal styling.

Only useful if you forcefully disabled tty, but still want those fancy terminal styles.

use comfy_table::Table;

let mut table = Table::new();
table.force_no_tty()
    .enforce_styling();
Source

pub fn should_style(&self) -> bool

Returns whether the content of this table should be styled with the current settings and environment.

Source

pub fn style_text_only(&mut self)

By default, the whole content of a cells will be styled. Calling this function disables this behavior for all cells, resulting in only the text of cells being styled.

Source

pub fn set_constraints<T: IntoIterator<Item = ColumnConstraint>>( &mut self, constraints: T, ) -> &mut Self

Convenience method to set a ColumnConstraint for all columns at once. Constraints are used to influence the way the columns will be arranged. Check out their docs for more information.

Attention: This function should be called after at least one row (or the headers) has been added to the table. Before that, the columns won’t initialized.

If more constraints are passed than there are columns, any superfluous constraints will be ignored.

use comfy_table::{Width::*, CellAlignment, ColumnConstraint::*, ContentArrangement, Table};

let mut table = Table::new();
table.add_row(&vec!["one", "two", "three"])
    .set_content_arrangement(ContentArrangement::Dynamic)
    .set_constraints(vec![
        UpperBoundary(Fixed(15)),
        LowerBoundary(Fixed(20)),
]);
Source

pub fn load_preset(&mut self, preset: &str) -> &mut Self

This function creates a TableStyle from a given preset string.
Preset strings can be found in styling::presets::*.

You can also write your own preset strings and use them with this function. There’s the convenience method Table::current_style_as_preset, which prints you a preset string from your current style configuration.
The function expects the to-be-drawn characters to be in the same order as in the TableComponent enum.

If the string isn’t long enough, the default ASCII_FULL style will be used for all remaining components.

If the string is too long, remaining charaacters will be simply ignored.

Source

pub fn current_style_as_preset(&mut self) -> String

Returns the current style as a preset string.

A pure convenience method, so you’re not force to fiddle with those preset strings yourself.

use comfy_table::Table;
use comfy_table::presets::UTF8_FULL;

let mut table = Table::new();
table.load_preset(UTF8_FULL);

assert_eq!(UTF8_FULL, table.current_style_as_preset())
Source

pub fn apply_modifier(&mut self, modifier: &str) -> &mut Self

Modify a preset with a modifier string from modifiers.

For instance, the UTF8_ROUND_CORNERS modifies all corners to be round UTF8 box corners.

use comfy_table::Table;
use comfy_table::presets::UTF8_FULL;
use comfy_table::modifiers::UTF8_ROUND_CORNERS;

let mut table = Table::new();
table.load_preset(UTF8_FULL);
table.apply_modifier(UTF8_ROUND_CORNERS);
Source

pub fn set_style( &mut self, component: TableComponent, character: char, ) -> &mut Self

Define the char that will be used to draw a specific component.
Look at TableComponent to see all stylable components

If None is supplied, the element won’t be displayed.
In case of a e.g. *BorderIntersection a whitespace will be used as placeholder, unless related borders and and corners are set to None as well.

For example, if TopBorderIntersections is None the first row would look like this:

+------ ------+
| this | test |

If in addition TopLeftCorner,TopBorder and TopRightCorner would be None as well, the first line wouldn’t be displayed at all.

use comfy_table::Table;
use comfy_table::presets::UTF8_FULL;
use comfy_table::TableComponent::*;

let mut table = Table::new();
// Load the UTF8_FULL preset
table.load_preset(UTF8_FULL);
// Set all outer corners to round UTF8 corners
// This is basically the same as the UTF8_ROUND_CORNERS modifier
table.set_style(TopLeftCorner, '╭');
table.set_style(TopRightCorner, '╮');
table.set_style(BottomLeftCorner, '╰');
table.set_style(BottomRightCorner, '╯');
Source

pub fn style(&mut self, component: TableComponent) -> Option<char>

Get a copy of the char that’s currently used for drawing this component.

use comfy_table::Table;
use comfy_table::TableComponent::*;

let mut table = Table::new();
assert_eq!(table.style(TopLeftCorner), Some('+'));
Source

pub fn remove_style(&mut self, component: TableComponent) -> &mut Self

Remove the style for a specific component of the table.
By default, a space will be used as a placeholder instead.
Though, if for instance all components of the left border are removed, the left border won’t be displayed.

Source

pub fn column(&self, index: usize) -> Option<&Column>

Get a reference to a specific column.

Source

pub fn column_mut(&mut self, index: usize) -> Option<&mut Column>

Get a mutable reference to a specific column.

Source

pub fn column_iter(&self) -> Iter<'_, Column>

Iterator over all columns

Source

pub fn column_iter_mut(&mut self) -> IterMut<'_, Column>

Get a mutable iterator over all columns.

use comfy_table::{Width::*, ColumnConstraint::*, Table};

let mut table = Table::new();
table.add_row(&vec!["First", "Second", "Third"]);

// Add a ColumnConstraint to each column (left->right)
// first -> min width of 10
// second -> max width of 8
// third -> fixed width of 10
let constraints = vec![
    LowerBoundary(Fixed(10)),
    UpperBoundary(Fixed(8)),
    Absolute(Fixed(10)),
];

// Add the constraints to their respective column
for (column_index, column) in table.column_iter_mut().enumerate() {
    let constraint = constraints.get(column_index).unwrap();
    column.set_constraint(*constraint);
}
Source

pub fn column_cells_iter(&self, column_index: usize) -> ColumnCellIter<'_>

Get a mutable iterator over cells of a column. The iterator returns a nested Option<Option<Cell>>, since there might be rows that are missing this specific Cell.

use comfy_table::Table;
let mut table = Table::new();
table.add_row(&vec!["First", "Second"]);
table.add_row(&vec!["Third"]);
table.add_row(&vec!["Fourth", "Fifth"]);

// Create an iterator over the second column
let mut cell_iter = table.column_cells_iter(1);
assert_eq!(cell_iter.next().unwrap().unwrap().content(), "Second");
assert!(cell_iter.next().unwrap().is_none());
assert_eq!(cell_iter.next().unwrap().unwrap().content(), "Fifth");
assert!(cell_iter.next().is_none());
Source

pub fn column_cells_with_header_iter( &self, column_index: usize, ) -> ColumnCellsWithHeaderIter<'_>

Get a mutable iterator over cells of a column, including the header cell. The header cell will be the very first cell returned. The iterator returns a nested Option<Option<Cell>>, since there might be rows that are missing this specific Cell.

use comfy_table::Table;
let mut table = Table::new();
table.set_header(&vec!["A", "B"]);
table.add_row(&vec!["First", "Second"]);
table.add_row(&vec!["Third"]);
table.add_row(&vec!["Fourth", "Fifth"]);

// Create an iterator over the second column
let mut cell_iter = table.column_cells_with_header_iter(1);
assert_eq!(cell_iter.next().unwrap().unwrap().content(), "B");
assert_eq!(cell_iter.next().unwrap().unwrap().content(), "Second");
assert!(cell_iter.next().unwrap().is_none());
assert_eq!(cell_iter.next().unwrap().unwrap().content(), "Fifth");
assert!(cell_iter.next().is_none());
Source

pub fn row(&self, index: usize) -> Option<&Row>

Reference to a specific row

Source

pub fn row_mut(&mut self, index: usize) -> Option<&mut Row>

Mutable reference to a specific row

Source

pub fn row_iter(&self) -> Iter<'_, Row>

Iterator over all rows

Source

pub fn row_iter_mut(&mut self) -> IterMut<'_, Row>

Get a mutable iterator over all rows.

use comfy_table::Table;
let mut table = Table::new();
table.add_row(&vec!["First", "Second", "Third"]);

// Add the constraints to their respective row
for row in table.row_iter_mut() {
    row.max_height(5);
}
assert!(table.row_iter_mut().len() == 1);
Source

pub fn column_max_content_widths(&self) -> Vec<u16>

Return a vector representing the maximum amount of characters in any line of this column.\

Attention This scans the whole current content of the table.

Source

pub fn discover_columns(&mut self)

Calling this might be necessary if you add new cells to rows that’re already added to the table.

If more cells than’re currently know to the table are added to that row, the table cannot know about these, since new Columns are only automatically detected when a new row is added.

To make sure everything works as expected, just call this function if you’re adding cells to rows that’re already added to the table.

Trait Implementations§

Source§

impl Clone for Table

Source§

fn clone(&self) -> Table

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Table

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Table

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl Display for Table

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl Freeze for Table

§

impl RefUnwindSafe for Table

§

impl Send for Table

§

impl Sync for Table

§

impl Unpin for Table

§

impl UnwindSafe for Table

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dst: *mut T)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.