WrapOptions

Struct WrapOptions 

Source
pub struct WrapOptions {
    pub trim: bool,
    pub hard: bool,
    pub word_wrap: bool,
}
Expand description

๐ŸŽ›๏ธ Configuration options for advanced text wrapping behavior.

This struct provides fine-grained control over how text is wrapped, including whitespace handling, word breaking strategies, and wrapping modes. All options work seamlessly with ANSI escape sequences and Unicode text.

ยงQuick Reference

OptionDefaultDescription
trimtrueRemove leading/trailing whitespace from wrapped lines
hardfalseBreak long words at column boundary (vs. moving to next line)
word_wraptrueRespect word boundaries when wrapping

ยงExamples

ยงDefault Configuration

use wrap_ansi::{wrap_ansi, WrapOptions};

// These are equivalent
let result1 = wrap_ansi("Hello world", 10, None);
let result2 = wrap_ansi("Hello world", 10, Some(WrapOptions::default()));
assert_eq!(result1, result2);
use wrap_ansi::{wrap_ansi, WrapOptions};

let options = WrapOptions::builder()
    .hard_wrap(true)           // Break long words
    .trim_whitespace(false)    // Preserve all whitespace
    .word_wrap(true)           // Still respect word boundaries where possible
    .build();

let text = "supercalifragilisticexpialidocious";
let wrapped = wrap_ansi(text, 10, Some(options));
// Result: "supercalif\nragilistic\nexpialidoc\nious"

ยงStruct Initialization

use wrap_ansi::{wrap_ansi, WrapOptions};

// Character-level wrapping for monospace layouts
let char_wrap = WrapOptions {
    hard: true,
    trim: true,
    word_wrap: false,  // Break anywhere, ignore word boundaries
};

let text = "hello world";
let wrapped = wrap_ansi(text, 7, Some(char_wrap));
// Result: "hello w\norld"

ยงCommon Configurations

ยงTerminal Output (Default)

let terminal = WrapOptions::default(); // Soft wrap, trim spaces, respect words

ยงCode/Monospace Text

let code = WrapOptions {
    hard: true,        // Break long identifiers
    trim: false,       // Preserve indentation
    word_wrap: false,  // Break anywhere for consistent columns
};

ยงNatural Language

let prose = WrapOptions {
    hard: false,       // Keep words intact
    trim: true,        // Clean up spacing
    word_wrap: true,   // Break at word boundaries
};

Fieldsยง

ยงtrim: bool

๐Ÿงน Whitespace trimming control

When true (default), leading and trailing spaces are automatically removed from lines that result from wrapping, creating clean, left-aligned text. When false, all whitespace is preserved exactly as in the input.

ยงUse Cases

  • true: Clean terminal output, formatted text display
  • false: Code formatting, preserving indentation, ASCII art

ยงExamples

use wrap_ansi::{wrap_ansi, WrapOptions};

let text = "   hello    world   ";

// With trimming (default)
let trimmed = wrap_ansi(text, 8, None);
assert_eq!(trimmed, "hello\nworld");

// Without trimming - preserves all spaces
let options = WrapOptions { trim: false, ..Default::default() };
let untrimmed = wrap_ansi(text, 8, Some(options));
assert_eq!(untrimmed, "   hello\n    \nworld   ");
ยงhard: bool

โšก Word breaking strategy

Controls how long words that exceed the column limit are handled:

  • false (default, soft wrapping): Long words move to the next line intact
  • true (hard wrapping): Long words are broken at the column boundary

ยงUse Cases

  • Soft wrap: Natural text flow, readability, terminal output
  • Hard wrap: Strict width constraints, tabular data, code formatting

ยงExamples

use wrap_ansi::{wrap_ansi, WrapOptions};

let long_word = "supercalifragilisticexpialidocious";

// Soft wrapping - word stays intact
let soft = wrap_ansi(long_word, 10, None);
assert_eq!(soft, "supercalifragilisticexpialidocious"); // No wrapping!

// Hard wrapping - word is broken
let options = WrapOptions { hard: true, ..Default::default() };
let hard = wrap_ansi(long_word, 10, Some(options));
assert_eq!(hard, "supercalif\nragilistic\nexpialidoc\nious");
ยงword_wrap: bool

๐Ÿ”ค Word boundary respect

Determines whether wrapping should occur at word boundaries (spaces) or can break anywhere within the text:

  • true (default): Text wraps at word boundaries, preserving word integrity
  • false: Text can wrap at any character position (character-level wrapping)

ยงUse Cases

  • Word boundaries: Natural language, readable text, most terminal output
  • Character boundaries: Monospace layouts, code, precise column control

ยงExamples

use wrap_ansi::{wrap_ansi, WrapOptions};

let text = "hello world";

// Word wrapping (default) - breaks at spaces
let word_wrap = wrap_ansi(text, 7, None);
assert_eq!(word_wrap, "hello\nworld");

// Character wrapping - breaks anywhere
let options = WrapOptions { word_wrap: false, ..Default::default() };
let char_wrap = wrap_ansi(text, 7, Some(options));
assert_eq!(char_wrap, "hello w\norld");

Implementationsยง

Sourceยง

impl WrapOptions

Source

pub fn builder() -> WrapOptionsBuilder

๐Ÿ—๏ธ Create a new fluent builder for WrapOptions.

This is the recommended way to create custom WrapOptions configurations as it provides a clean, readable interface with method chaining.

ยงExamples
use wrap_ansi::WrapOptions;

// Simple configuration
let options = WrapOptions::builder()
    .hard_wrap(true)
    .build();

// Complex configuration
let advanced = WrapOptions::builder()
    .hard_wrap(false)        // Soft wrapping
    .trim_whitespace(true)   // Clean output
    .word_wrap(true)         // Respect word boundaries
    .build();
Examples found in repository?
examples/improved_features.rs (line 8)
3fn main() -> Result<(), WrapError> {
4    println!("=== Wrap-ANSI Improved Features Demo ===\n");
5
6    // 1. Builder Pattern for Options
7    println!("1. Builder Pattern for Options:");
8    let options = WrapOptions::builder()
9        .hard_wrap(true)
10        .trim_whitespace(false)
11        .word_wrap(true)
12        .build();
13
14    let text = "This is a verylongwordthatexceedslimit example";
15    let wrapped = wrap_ansi(text, 15, Some(options));
16    println!("Input: {}", text);
17    println!("Output:\n{}\n", wrapped);
18
19    // 2. Error Handling with Input Validation
20    println!("2. Error Handling:");
21
22    // Valid input
23    match wrap_ansi_checked("Hello world", 10, None) {
24        Ok(result) => println!("Valid input wrapped: {}", result.replace('\n', "\\n")),
25        Err(e) => println!("Error: {}", e),
26    }
27
28    // Invalid column width
29    match wrap_ansi_checked("Hello world", 0, None) {
30        Ok(result) => println!("Result: {}", result),
31        Err(e) => println!("Expected error: {}", e),
32    }
33
34    // Large input (simulated)
35    let large_text = "x".repeat(100);
36    match wrap_ansi_checked(&large_text, 10, None) {
37        Ok(result) => println!(
38            "Large input handled: {} chars -> {} chars",
39            large_text.len(),
40            result.len()
41        ),
42        Err(e) => println!("Error with large input: {}", e),
43    }
44
45    println!();
46
47    // 3. ANSI Color Preservation with Named Constants
48    println!("3. ANSI Color Preservation:");
49    let colored_text =
50        "\u{001B}[31mThis is red text that will be wrapped across multiple lines\u{001B}[39m";
51    let wrapped_colored = wrap_ansi(colored_text, 20, None);
52    println!("Colored text wrapped:");
53    println!("{}", wrapped_colored);
54    println!();
55
56    // 4. Hyperlink Preservation
57    println!("4. Hyperlink Preservation:");
58    let hyperlink_text = "\u{001B}]8;;https://example.com\u{0007}This is a clickable link that spans multiple lines\u{001B}]8;;\u{0007}";
59    let wrapped_hyperlink = wrap_ansi(hyperlink_text, 15, None);
60    println!("Hyperlink text wrapped:");
61    println!("{}", wrapped_hyperlink);
62    println!();
63
64    // 5. Performance with Complex ANSI Sequences
65    println!("5. Complex ANSI Sequences:");
66    let complex_text =
67        "\u{001B}[31m\u{001B}[42mRed text on green background\u{001B}[39m\u{001B}[49m normal text";
68    let wrapped_complex = wrap_ansi(complex_text, 12, None);
69    println!("Complex ANSI wrapped:");
70    println!("{}", wrapped_complex);
71    println!();
72
73    // 6. Unicode Support
74    println!("6. Unicode Support:");
75    let unicode_text = "Hello ไธ–็•Œ ๐ŸŒ ใ“ใ‚“ใซใกใฏ";
76    let wrapped_unicode = wrap_ansi(unicode_text, 10, None);
77    println!("Unicode text wrapped:");
78    println!("{}", wrapped_unicode);
79
80    Ok(())
81}

Trait Implementationsยง

Sourceยง

impl Clone for WrapOptions

Sourceยง

fn clone(&self) -> WrapOptions

Returns a duplicate 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 WrapOptions

Sourceยง

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

Formats the value using the given formatter. Read more
Sourceยง

impl Default for WrapOptions

Sourceยง

fn default() -> Self

Returns the โ€œdefault valueโ€ for a type. Read more
Sourceยง

impl Hash for WrapOptions

Sourceยง

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 ยท Sourceยง

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Sourceยง

impl PartialEq for WrapOptions

Sourceยง

fn eq(&self, other: &WrapOptions) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 ยท Sourceยง

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Sourceยง

impl Copy for WrapOptions

Sourceยง

impl Eq for WrapOptions

Sourceยง

impl StructuralPartialEq for WrapOptions

Auto Trait Implementationsยง

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, dest: *mut u8)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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, 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.