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?

2
  • as for C and C++, you need specific OS feature, you should look at crates.io to find something that will help you
    – Stargateur
    Nov 16, 2019 at 16:14
  • Found three crates which look interesting. Thanks!
    – TimB
    Nov 16, 2019 at 16:23

1 Answer 1

9

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);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.