9

When line-wrapping our output so it is visually pleasant, it would be helpful knowing the console window or at least the buffer width.

There are answers how to do this in C and C++, C# even has properties which make this task easy. But Rust?

Is there anything I could use to get this information, or should I just let the user decide where my program wraps the output?

TimB
  • 970
  • 8
  • 17

1 Answers1

7

There are multiple crates able to determine terminal width. Which one to use might depend on the exact relevant requirements for each situation. A good starting point might be to check out termion, which also provides a bunch of other useful low-level terminal handling functionality.

As can be seen on the linked page above, it supports multiple platforms. Yet anyone on Microsoft Windows should note that their platform is not mentioned:

There is also the termsize crate, which intends to no nothing more than determining the terminal size. This crate has an even wider platform support, and does work with Microsoft Windows.

After updating Cargo.toml dependencies, retrieving the terminal width (and height) with these two crates are as trivial as:

fn main() {
    let (x, y) = termion::terminal_size().unwrap();
    let termsize::Size {rows, cols} = termsize::get().unwrap();
    println!("          width  height");
    println!("termion:  {:4}    {:4}", x, y);
    println!("termsize: {:4}    {:4}", cols, rows);
}
sampi
  • 576
  • 5
  • 15