[][src]Crate textwrap

The textwrap library provides functions for word wrapping and filling text.

Wrapping text can be very useful in commandline programs where you want to format dynamic output nicely so it looks good in a terminal. A quick example:

fn main() {
    let text = "textwrap: a small library for wrapping text.";
    println!("{}", textwrap::fill(text, 18));

When you run this program, it will display the following output:

textwrap: a small
library for
wrapping text.

If you enable the hyphenation feature, you can get automatic hyphenation for a number of languages:

use hyphenation::{Language, Load, Standard};
use textwrap::{fill, Options};

fn main() {
    let text = "textwrap: a small library for wrapping text.";
    let dictionary = Standard::from_embedded(Language::EnglishUS).unwrap();
    let options = Options::new(18).splitter(dictionary);
    println!("{}", fill(text, &options));

The program will now output:

textwrap: a small
library for wrap-
ping text.

Wrapping Strings at Compile Time

If your strings are known at compile time, please take a look at the procedural macros from the textwrap-macros crate.

Displayed Width vs Byte Size

To word wrap text, one must know the width of each word so one can know when to break lines. This library measures the width of text using the displayed width (computed via UnicodeWidthStr), not the size in bytes.

This is important for non-ASCII text. ASCII characters such as a and ! are simple and take up one column each. This means that the displayed width is equal to the string length in bytes. However, non-ASCII characters and symbols take up more than one byte when UTF-8 encoded: é is 0xc3 0xa9 (two bytes) and is 0xe2 0x9a 0x99 (three bytes) in UTF-8, respectively.

This is why we take care to use the displayed width instead of the byte count when computing line lengths. All functions in this library handle Unicode characters like this.

Cargo Features

The textwrap library has two optional features:



Building blocks for advanced wrapping functionality.



Simple and default way to split words: splitting on existing hyphens only.


Use this as a Options.splitter to avoid any kind of hyphenation:


Holds settings for wrapping and filling text.



The WordSplitter trait describes where words can be split.



Removes common leading whitespace from each line.


Fill a line of text at width characters.


Fill text in-place without reallocating the input string.


Add prefix to each non-empty line.


Return the current terminal width. If the terminal width cannot be determined (typically because the standard output is not connected to a terminal), a default width of 80 characters will be used.


Wrap a line of text at width characters.