Convert Figma logo to code with AI

Nukesor logocomfy-table

:large_orange_diamond: Build beautiful terminal tables with automatic content wrapping

1,101
35
1,101
2

Top Related Projects

Pretty-print tabular data in Python, a library and a command-line utility. Repository migrated from bitbucket.org/astanin/python-tabulate.

50,391

Rich is a Python library for rich text and beautiful formatting in the terminal.

Display tabular data in a visually appealing ASCII table format

Quick Overview

Comfy-table is a Rust library for creating beautiful and customizable tables in the terminal. It offers a simple and intuitive API for building tables with various styling options, including support for Unicode box-drawing characters and ANSI colors.

Pros

  • Easy to use API with a fluent interface for table creation and customization
  • Supports Unicode box-drawing characters for visually appealing tables
  • Offers extensive styling options, including ANSI colors and custom cell alignment
  • Automatically handles text wrapping and column width calculations

Cons

  • Limited to terminal output, not suitable for GUI applications
  • May have performance overhead for very large tables
  • Requires Rust 1.56 or later, which might be an issue for some older projects

Code Examples

Creating a simple table:

use comfy_table::Table;

let mut table = Table::new();
table.set_header(vec!["Name", "Age", "City"]);
table.add_row(vec!["Alice", "28", "New York"]);
table.add_row(vec!["Bob", "33", "Los Angeles"]);
println!("{table}");

Customizing table style:

use comfy_table::*;
use comfy_table::presets::UTF8_FULL;

let mut table = Table::new();
table.load_preset(UTF8_FULL);
table.set_content_arrangement(ContentArrangement::Dynamic);
table.set_width(80);
table.set_header(vec!["Column 1", "Column 2"]);
table.add_row(vec!["Content 1", "Content 2"]);
println!("{table}");

Using ANSI colors:

use comfy_table::*;
use comfy_table::Color;

let mut table = Table::new();
table.set_header(vec![
    Cell::new("Header 1").fg(Color::Red),
    Cell::new("Header 2").fg(Color::Green),
]);
table.add_row(vec![
    Cell::new("Content 1").fg(Color::Blue),
    Cell::new("Content 2").fg(Color::Yellow),
]);
println!("{table}");

Getting Started

To use comfy-table in your Rust project, add the following to your Cargo.toml:

[dependencies]
comfy-table = "6.1.0"

Then, in your Rust code:

use comfy_table::Table;

fn main() {
    let mut table = Table::new();
    table.set_header(vec!["Column 1", "Column 2"]);
    table.add_row(vec!["Value 1", "Value 2"]);
    println!("{table}");
}

This will create and print a simple table with a header and one row of data.

Competitor Comparisons

Pretty-print tabular data in Python, a library and a command-line utility. Repository migrated from bitbucket.org/astanin/python-tabulate.

Pros of python-tabulate

  • More mature and widely adopted project with a larger user base
  • Supports a wider variety of table formats and styles
  • Offers more customization options for table output

Cons of python-tabulate

  • Less actively maintained compared to comfy-table
  • Slightly more complex API, which may be less intuitive for beginners
  • Lacks some modern features like ANSI color support

Code Comparison

python-tabulate:

from tabulate import tabulate
data = [["Name", "Age"], ["Alice", 24], ["Bob", 19]]
print(tabulate(data, headers="firstrow"))

comfy-table:

from comfy_table import Table
table = Table()
table.set_header(["Name", "Age"])
table.add_rows([["Alice", 24], ["Bob", 19]])
print(table)

Both libraries provide similar functionality for creating tables, but comfy-table offers a more object-oriented approach with a fluent API. python-tabulate uses a functional approach, which may be more familiar to some users. The choice between the two depends on personal preference and specific project requirements.

50,391

Rich is a Python library for rich text and beautiful formatting in the terminal.

Pros of rich

  • More comprehensive feature set, including syntax highlighting, progress bars, and markdown rendering
  • Larger community and more frequent updates
  • Extensive documentation and examples

Cons of rich

  • Steeper learning curve due to more complex API
  • Larger package size and potential performance overhead for simpler use cases

Code Comparison

rich:

from rich.console import Console
from rich.table import Table

table = Table(title="Sample Table")
table.add_column("Name", style="cyan")
table.add_column("Age", style="magenta")
table.add_row("Alice", "30")
Console().print(table)

comfy-table:

from comfy_table import Table

table = Table()
table.set_header(["Name", "Age"])
table.add_row(["Alice", "30"])
print(table)

Both libraries offer similar functionality for creating tables, but rich provides more styling options out of the box. comfy-table has a simpler API, which may be preferable for basic use cases. rich's additional features make it more versatile for complex console output, while comfy-table focuses primarily on table creation and formatting.

Display tabular data in a visually appealing ASCII table format

Pros of prettytable

  • More established project with a longer history and larger community
  • Supports a wider range of output formats (ASCII, HTML, LaTeX)
  • Offers more customization options for table styling

Cons of prettytable

  • Less modern API design compared to comfy-table
  • Slower performance for large tables
  • More complex setup and configuration for basic use cases

Code Comparison

prettytable:

from prettytable import PrettyTable
x = PrettyTable()
x.field_names = ["City name", "Area", "Population", "Annual Rainfall"]
x.add_row(["Adelaide", 1295, 1158259, 600.5])
print(x)

comfy-table:

from comfy_table import Table
table = Table()
table.set_header(["City name", "Area", "Population", "Annual Rainfall"])
table.add_row(["Adelaide", 1295, 1158259, 600.5])
print(table)

Both libraries provide similar functionality for creating and displaying tables in Python. prettytable offers more advanced features and output options, making it suitable for complex table formatting needs. However, comfy-table provides a more intuitive API and better performance for simpler use cases and larger datasets. The choice between the two depends on the specific requirements of your project and personal preference for API design.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Comfy-table

GitHub Actions Workflow docs license Crates.io codecov

comfy-table

Comfy-table is designed as a library for building beautiful terminal tables, while being easy to use.

Table of Contents

Features

  • Dynamic arrangement of content depending on a given width.
  • ANSI content styling for terminals (Colors, Bold, Blinking, etc.).
  • Styling Presets and preset modifiers to get you started.
  • Pretty much every part of the table is customizable (borders, lines, padding, alignment).
  • Constraints on columns that allow some additional control over how to arrange content.
  • Cross plattform (Linux, macOS, Windows).
  • It's fast enough.
    • Benchmarks show that a pretty big table with complex constraints is build in 470μs or ~0.5ms.
    • The table seen at the top of the readme takes ~30μs.
    • These numbers are from a overclocked i7-8700K with a max single-core performance of 4.9GHz.
    • To run the benchmarks yourselves, install criterion via cargo install cargo-criterion and run cargo criterion afterwards.

Comfy-table is written for the current stable Rust version. Older Rust versions may work but aren't officially supported.

Examples

use comfy_table::Table;

fn main() {
    let mut table = Table::new();
    table
        .set_header(vec!["Header1", "Header2", "Header3"])
        .add_row(vec![
            "This is a text",
            "This is another text",
            "This is the third text",
        ])
        .add_row(vec![
            "This is another text",
            "Now\nadd some\nmulti line stuff",
            "This is awesome",
        ]);

    println!("{table}");
}

Create a very basic table.
This table will become as wide as your content. Nothing fancy happening here.

+----------------------+----------------------+------------------------+
| Header1              | Header2              | Header3                |
+======================================================================+
| This is a text       | This is another text | This is the third text |
|----------------------+----------------------+------------------------|
| This is another text | Now                  | This is awesome        |
|                      | add some             |                        |
|                      | multi line stuff     |                        |
+----------------------+----------------------+------------------------+

More Features

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

fn main() {
    let mut table = Table::new();
    table
        .load_preset(UTF8_FULL)
        .apply_modifier(UTF8_ROUND_CORNERS)
        .set_content_arrangement(ContentArrangement::Dynamic)
        .set_width(40)
        .set_header(vec!["Header1", "Header2", "Header3"])
        .add_row(vec![
            Cell::new("Center aligned").set_alignment(CellAlignment::Center),
            Cell::new("This is another text"),
            Cell::new("This is the third text"),
        ])
        .add_row(vec![
            "This is another text",
            "Now\nadd some\nmulti line stuff",
            "This is awesome",
        ]);

    // Set the default alignment for the third column to right
    let column = table.column_mut(2).expect("Our table has three columns");
    column.set_cell_alignment(CellAlignment::Right);

    println!("{table}");
}

Create a table with UTF8 styling, and apply a modifier that gives the table round corners.
Additionally, the content will dynamically wrap to maintain a given table width.
If the table width isn't explicitely set and the program runs in a terminal, the terminal size will be used.

On top of this, we set the default alignment for the right column to Right and the alignment of the left top cell to Center.

╭────────────┬────────────┬────────────╮
│ Header1    ┆ Header2    ┆    Header3 │
╞════════════╪════════════╪════════════╡
│  This is a ┆ This is    ┆    This is │
│    text    ┆ another    ┆  the third │
│            ┆ text       ┆       text │
├╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┤
│ This is    ┆ Now        ┆    This is │
│ another    ┆ add some   ┆    awesome │
│ text       ┆ multi line ┆            │
│            ┆ stuff      ┆            │
╰────────────┴────────────┴────────────╯

Styling

use comfy_table::presets::UTF8_FULL;
use comfy_table::*;

fn main() {
    let mut table = Table::new();
    table.load_preset(UTF8_FULL)
        .set_content_arrangement(ContentArrangement::Dynamic)
        .set_width(80)
        .set_header(vec![
            Cell::new("Header1").add_attribute(Attribute::Bold),
            Cell::new("Header2").fg(Color::Green),
            Cell::new("Header3"),
        ])
        .add_row(vec![
             Cell::new("This is a bold text").add_attribute(Attribute::Bold),
             Cell::new("This is a green text").fg(Color::Green),
             Cell::new("This one has black background").bg(Color::Black),
        ])
        .add_row(vec![
            Cell::new("Blinky boi").add_attribute(Attribute::SlowBlink),
            Cell::new("This table's content is dynamically arranged. The table is exactly 80 characters wide.\nHere comes a reallylongwordthatshoulddynamicallywrap"),
            Cell::new("COMBINE ALL THE THINGS")
                .fg(Color::Green)
                .bg(Color::Black)
                .add_attributes(vec![
                    Attribute::Bold,
                    Attribute::SlowBlink,
                ])
        ]);

    println!("{table}");
}

This code generates the table that can be seen at the top of this document.

Code Examples

A few examples can be found in the example folder. To test an example, run cargo run --example $name. E.g.:

cargo run --example readme_table

If you're looking for more information, take a look at the tests folder. There are tests for almost every feature including a visual view for each resulting table.

Feature Flags

tty (enabled)

This flag enables support for terminals. In detail this means:

  • Automatic detection whether we're in a terminal environment. Only used when no explicit Table::set_width is provided.
  • Support for ANSI Escape Code styling for terminals.

custom_styling (disabled)

This flag enables support for custom styling of text inside of cells.

  • Text formatting still works, even if you roll your own ANSI escape sequences.
  • Rainbow text
  • Makes comfy-table 30-50% slower

reexport_crossterm (disabled)

With this flag, comfy-table re-exposes crossterm's Attribute and Color enum. By default, a mirrored type is exposed, which internally maps to the crossterm type.

This feature is very convenient if you use both comfy-table and crossterm in your code and want to use crossterm's types for everything interchangeably.

BUT if you enable this feature, you opt-in for breaking changes on minor/patch versions. Meaning, you have to update crossterm whenever you update comfy-table and you cannot update crossterm until comfy-table released a new version with that crossterm version.

Contributing

Comfy-table's main focus is on being minimalistic and reliable. A fixed set of features that just work for "normal" use-cases:

  • Normal tables (columns, rows, one cell per column/row).
  • Dynamic arrangement of content to a given width.
  • Some kind of manual intervention in the arrangement process.

If you come up with an idea or an improvement that fits into the current scope of the project, feel free to create an issue :)!

Some things however will most likely not be added to the project since they drastically increase the complexity of the library or cover very specific edge-cases.

Such features are:

  • Nested tables
  • Cells that span over multiple columns/rows
  • CSV to table conversion and vice versa

Unsafe

Comfy-table doesn't allow unsafe code in its code-base. As it's a "simple" formatting library it also shouldn't be needed in the future.

If one disables the tty feature flag, this is also true for all of its dependencies.

However, when enabling tty, Comfy-table uses one unsafe function call in its dependencies.
It can be circumvented by explicitely calling Table::force_no_tty.

  1. crossterm::terminal::size. This function is necessary to detect the current terminal width if we're on a tty. This is only called if no explicit width is provided via Table::set_width.

    http://rosettacode.org/wiki/Terminal_control/Dimensions#Library:_BSD_libc This is another libc call which is used to communicate with /dev/tty via a file descriptor.

    ...
    if wrap_with_result(unsafe { ioctl(fd, TIOCGWINSZ.into(), &mut size) }).is_ok() {
        Ok((size.ws_col, size.ws_row))
    } else {
        tput_size().ok_or_else(|| std::io::Error::last_os_error().into())
    }
    ...
    

Comparison with other libraries

The following are official statements of the other crate authors. This ticket can be used as an entry to find all other sibling tickets in the other projects.

Cli-table

The main focus of cli-table is to support all platforms and at the same time limit the dependencies to keep the compile times and crate size low.

Currently, this crate only pulls two external dependencies (other than cli-table-derive):

  • termcolor
  • unicode-width

With csv feature enabled, it also pulls csv crate as dependency.

Term-table

term-table is pretty basic in terms of features. My goal with the project is to provide a good set of tools for rendering CLI tables, while also allowing users to bring their own tools for things like colours. One thing that is unique to term-table (as far as I'm aware) is the ability to have different number of columns in each row of the table.

Prettytables-rs

prettytables-rs provides functionality for formatting and aligning tables. It his however abandoned since over three years and a rustsec/advisory-db entry has been requested.

Comfy-table

One of comfy-table's big foci is on providing a minimalistic, but rock-solid library for building text-based tables. This means that the code is very well tested, no usage of unsafe and unwrap is only used if we can be absolutely sure that it's safe. There're only one occurrence of unsafe in all of comfy-table's dependencies, to be exact inside the tty communication code, which can be explicitly disabled.

The other focus is on dynamic-length content arrangement. This means that a lot of work went into building an algorithm that finds a (near) optimal table layout for any given text and terminal width.