textwrap

Struct Wrapper

Source
pub struct Wrapper<'a, S: WordSplitter> {
    pub width: usize,
    pub initial_indent: &'a str,
    pub subsequent_indent: &'a str,
    pub break_words: bool,
    pub splitter: S,
}
Expand description

A Wrapper holds settings for wrapping and filling text. Use it when the convenience wrap_iter, wrap and fill functions are not flexible enough.

The algorithm used by the WrapIter iterator (returned from the wrap_iter method) works by doing successive partial scans over words in the input string (where each single scan yields a single line) so that the overall time and memory complexity is O(n) where n is the length of the input string.

Fields§

§width: usize

The width in columns at which the text will be wrapped.

§initial_indent: &'a str

Indentation used for the first line of output.

§subsequent_indent: &'a str

Indentation used for subsequent lines of output.

§break_words: bool

Allow long words to be broken if they cannot fit on a line. When set to false, some lines may be longer than self.width.

§splitter: S

The method for splitting words. If the hyphenation feature is enabled, you can use a hyphenation::Standard dictionary here to get language-aware hyphenation.

Implementations§

Source§

impl<'a> Wrapper<'a, HyphenSplitter>

Source

pub fn new(width: usize) -> Wrapper<'a, HyphenSplitter>

Create a new Wrapper for wrapping at the specified width. By default, we allow words longer than width to be broken. A HyphenSplitter will be used by default for splitting words. See the WordSplitter trait for other options.

Source§

impl<'a, S: WordSplitter> Wrapper<'a, S>

Source

pub fn with_splitter(width: usize, splitter: S) -> Wrapper<'a, S>

Use the given WordSplitter to create a new Wrapper for wrapping at the specified width. By default, we allow words longer than width to be broken.

Source

pub fn initial_indent(self, indent: &'a str) -> Wrapper<'a, S>

Change self.initial_indent. The initial indentation is used on the very first line of output.

§Examples

Classic paragraph indentation can be achieved by specifying an initial indentation and wrapping each paragraph by itself:

use textwrap::Wrapper;

let wrapper = Wrapper::new(15).initial_indent("    ");
Source

pub fn subsequent_indent(self, indent: &'a str) -> Wrapper<'a, S>

Change self.subsequent_indent. The subsequent indentation is used on lines following the first line of output.

§Examples

Combining initial and subsequent indentation lets you format a single paragraph as a bullet list:

use textwrap::Wrapper;

let wrapper = Wrapper::new(15)
    .initial_indent("* ")
    .subsequent_indent("  ");
Source

pub fn break_words(self, setting: bool) -> Wrapper<'a, S>

Change self.break_words. This controls if words longer than self.width can be broken, or if they will be left sticking out into the right margin.

Source

pub fn fill(&self, s: &str) -> String

Fill a line of text at self.width characters. Strings are wrapped based on their displayed width, not their size in bytes.

The result is a string with newlines between each line. Use the wrap method if you need access to the individual lines.

§Complexities

This method simply joins the lines produced by wrap_iter. As such, it inherits the O(n) time and memory complexity where n is the input string length.

§Examples
use textwrap::Wrapper;

let wrapper = Wrapper::new(15);
assert_eq!(wrapper.fill("Memory safety without garbage collection."),
           "Memory safety\nwithout garbage\ncollection.");
Source

pub fn wrap(&self, s: &'a str) -> Vec<Cow<'a, str>>

Wrap a line of text at self.width characters. Strings are wrapped based on their displayed width, not their size in bytes.

§Complexities

This method simply collects the lines produced by wrap_iter. As such, it inherits the O(n) overall time and memory complexity where n is the input string length.

§Examples
use textwrap::Wrapper;

let wrap15 = Wrapper::new(15);
assert_eq!(wrap15.wrap("Concurrency without data races."),
           vec!["Concurrency",
                "without data",
                "races."]);

let wrap20 = Wrapper::new(20);
assert_eq!(wrap20.wrap("Concurrency without data races."),
           vec!["Concurrency without",
                "data races."]);

Notice that newlines in the input are preserved. This means that they force a line break, regardless of how long the current line is:

use textwrap::Wrapper;

let wrapper = Wrapper::new(40);
assert_eq!(wrapper.wrap("First line.\nSecond line."),
           vec!["First line.", "Second line."]);
Source

pub fn wrap_iter<'w>(&'w self, s: &'a str) -> WrapIter<'w, 'a, S>

Lazily wrap a line of text at self.width characters. Strings are wrapped based on their displayed width, not their size in bytes.

The WordSplitter stored in self.splitter is used whenever when a word is too large to fit on the current line. By changing the field, different hyphenation strategies can be implemented.

§Complexities

This method returns a WrapIter iterator which borrows this Wrapper. The algorithm used has a linear complexity, so getting the next line from the iterator will take O(w) time, where w is the wrapping width. Fully processing the iterator will take O(n) time for an input string of length n.

When no indentation is used, each line returned is a slice of the input string and the memory overhead is thus constant. Otherwise new memory is allocated for each line returned.

§Examples
use std::borrow::Cow;
use textwrap::Wrapper;

let wrap20 = Wrapper::new(20);
let mut wrap20_iter = wrap20.wrap_iter("Zero-cost abstractions.");
assert_eq!(wrap20_iter.next(), Some(Cow::from("Zero-cost")));
assert_eq!(wrap20_iter.next(), Some(Cow::from("abstractions.")));
assert_eq!(wrap20_iter.next(), None);

let wrap25 = Wrapper::new(25);
let mut wrap25_iter = wrap25.wrap_iter("Zero-cost abstractions.");
assert_eq!(wrap25_iter.next(), Some(Cow::from("Zero-cost abstractions.")));
assert_eq!(wrap25_iter.next(), None);
Source

pub fn into_wrap_iter(self, s: &'a str) -> IntoWrapIter<'a, S>

Lazily wrap a line of text at self.width characters. Strings are wrapped based on their displayed width, not their size in bytes.

The WordSplitter stored in self.splitter is used whenever when a word is too large to fit on the current line. By changing the field, different hyphenation strategies can be implemented.

§Complexities

This method consumes the Wrapper and returns a IntoWrapIter iterator. Fully processing the iterator has the same O(n) time complexity as wrap_iter, where n is the length of the input string.

§Examples
use std::borrow::Cow;
use textwrap::Wrapper;

let wrap20 = Wrapper::new(20);
let mut wrap20_iter = wrap20.into_wrap_iter("Zero-cost abstractions.");
assert_eq!(wrap20_iter.next(), Some(Cow::from("Zero-cost")));
assert_eq!(wrap20_iter.next(), Some(Cow::from("abstractions.")));
assert_eq!(wrap20_iter.next(), None);

Trait Implementations§

Source§

impl<'a, S: Clone + WordSplitter> Clone for Wrapper<'a, S>

Source§

fn clone(&self) -> Wrapper<'a, S>

Returns a copy 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<'a, S: Debug + WordSplitter> Debug for Wrapper<'a, S>

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<'a, S> Freeze for Wrapper<'a, S>
where S: Freeze,

§

impl<'a, S> RefUnwindSafe for Wrapper<'a, S>
where S: RefUnwindSafe,

§

impl<'a, S> Send for Wrapper<'a, S>
where S: Send,

§

impl<'a, S> Sync for Wrapper<'a, S>
where S: Sync,

§

impl<'a, S> Unpin for Wrapper<'a, S>
where S: Unpin,

§

impl<'a, S> UnwindSafe for Wrapper<'a, S>
where S: UnwindSafe,

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, dst: *mut T)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. 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.