| 1 |
//! Functions related to the terminal size. |
| 2 |
|
| 3 |
use crate::Options; |
| 4 |
|
| 5 |
/// Return the current terminal width. |
| 6 |
/// |
| 7 |
/// If the terminal width cannot be determined (typically because the |
| 8 |
/// standard output is not connected to a terminal), a default width |
| 9 |
/// of 80 characters will be used. |
| 10 |
/// |
| 11 |
/// # Examples |
| 12 |
/// |
| 13 |
/// Create an [`Options`] for wrapping at the current terminal width |
| 14 |
/// with a two-column margin to the left and the right: |
| 15 |
/// |
| 16 |
/// ```no_run |
| 17 |
/// use textwrap::{termwidth, Options}; |
| 18 |
/// |
| 19 |
/// let width = termwidth() - 4; // Two columns on each side. |
| 20 |
/// let options = Options::new(width) |
| 21 |
/// .initial_indent(" ") |
| 22 |
/// .subsequent_indent(" "); |
| 23 |
/// ``` |
| 24 |
/// |
| 25 |
/// **Note:** Only available when the `terminal_size` Cargo feature is |
| 26 |
/// enabled. |
| 27 |
pub fn termwidth() -> usize { |
| 28 |
terminal_size::terminal_size().map_or(80, |(terminal_size::Width(w), _)| w.into()) |
| 29 |
} |
| 30 |
|
| 31 |
impl<'a> Options<'a> { |
| 32 |
/// Creates a new [`Options`] with `width` set to the current |
| 33 |
/// terminal width. If the terminal width cannot be determined |
| 34 |
/// (typically because the standard input and output are not |
| 35 |
/// connected to a terminal), a width of 80 characters will be |
| 36 |
/// used. Other settings use the same defaults as |
| 37 |
/// [`Options::new`]. |
| 38 |
/// |
| 39 |
/// Equivalent to: |
| 40 |
/// |
| 41 |
/// ```no_run |
| 42 |
/// use textwrap::{termwidth, Options}; |
| 43 |
/// |
| 44 |
/// let options = Options::new(termwidth()); |
| 45 |
/// ``` |
| 46 |
/// |
| 47 |
/// **Note:** Only available when the `terminal_size` feature is |
| 48 |
/// enabled. |
| 49 |
pub fn with_termwidth() -> Self { |
| 50 |
Self::new(termwidth()) |
| 51 |
} |
| 52 |
} |