textwrap
Library for word wrapping, indenting, and dedenting strings. Has optional support for Unicode and emojis as well as machine hyphenation.
0.16.2
409M downloads/mo
#281 most downloaded on crates.io
mgeisler/textwrap
What this package is like to depend on
Last release 1 years ago
03 Mar 2025
Release timing varies
gaps range from 3 weeks to 1.5 years
Nearly every release is documented
notes for 25 of 25 stable releases
2 versions withdrawn
withdrawn after publishing
10 years old
27 releases · first in 2016
0 releases in the last 12 months
see the full history below
Release timeline
27 releases · Dec 2016 to Mar 2025Releases
latest 27-
0.16.203 Mar 2025Release notes
Open source →Version 0.16.2 (2025-03-03)
This release fixes an unnecessary
f64cast, updates all dependencies, bumps
the minimum supported Rust version to 1.70.Release notes
Open source →This release fixes an unnecessary
f64cast, updates all dependencies, bumps the minimum supported Rust version to 1.70. -
0.16.117 Feb 2024Release notes
Open source →Version 0.16.1 (2024-02-17)
This release fixes
display_widthto ignore inline-hyperlinks. The minimum
supported version of Rust is now documented to be 1.56.Release notes
Open source →This release fixes
display_widthto ignore inline-hyperlinks. The minimum supported version of Rust is now documented to be 1.56. -
0.16.023 Oct 2022Release notes
Open source →Version 0.16.0 (2022-10-23)
This release marks
Optionsasnon_exhaustiveand extends it to make line endings configurable, it adds new fast paths tofillandwrap, and it fixes crashes inunfillandrefill.- #480: Mark
Optionsasnon_exhaustive. This will allow us to extend the struct in the future without breaking backwards compatibility. - #478: Add fast paths to
fillandwrap. This makes the functions 10-25 times faster when the no wrapping is needed. - #468: Fix
refillto add back correct line ending. - #467: Fix crashes in
unfillandrefill. - #458: Test with Rust 1.56 (first compiler release with support for Rust 2021).
- #454: Make line endings configurable.
- #448: Migrate to the Rust 2021 edition.
Release notes
Open source →This release marks
Optionsasnon_exhaustiveand extends it to make line endings configurable, it adds new fast paths tofillandwrap, and it fixes crashes inunfillandrefill.- #480: Mark
Optionsasnon_exhaustive. This will allow us to extend the struct in the future without breaking backwards compatibility. - #478: Add fast paths to
fillandwrap. This makes the functions 10-25 times faster when the no wrapping is needed. - #468: Fix
refillto add back correct line ending. - #467: Fix crashes in
unfillandrefill. - #458: Test with Rust 1.56 (first compiler release with support for Rust 2021).
- #454: Make line endings configurable.
- #448: Migrate to the Rust 2021 edition.
- #480: Mark
-
0.15.224 Oct 2022Release notes
Open source →Version 0.15.2 (2022-10-24)
This release is identical to 0.15.0 and is only there to give people a way to install crates which depend on the yanked 0.15.1 release. See #484 for details.
Release notes
Open source →This release is identical to 0.15.0 and is only there to give people a way to install crates which depend on the yanked 0.15.1 release. See #484 for details.
-
0.15.115 Sep 2022 withdrawnRelease notes
Open source →Version 0.15.1 (2022-09-15)
This release which fixes crashes in
unfillandrefill. It also adds a new option to make the line endings (\nor\r\n) configurable:Release notes
Open source →This release was yanked since it accidentally broke backwards compatibility with 0.15.0.
-
0.15.027 Feb 2022Release notes
Open source →Version 0.15.0 (2022-02-27)
This is a major feature release with two main changes:
-
#421: Use
f64instead ofusizefor fragment widths.This fixes problems with overflows in the internal computations of
wrap_optimal_fitwhen fragments (words) or line lengths had extreme values, such asusize::MAX. -
#438: Simplify
Optionsby removing generic type parameters.This change removes the new generic parameters introduced in version 0.14, as well as the original
WrapSplitterparameter which has been present since very early versions.The result is a simplification of function and struct signatures across the board. So what used to be
let options: Options< wrap_algorithms::FirstFit, word_separators::AsciiSpace, word_splitters::HyphenSplitter, > = Options::new(80);
if types are fully written out, is now simply
let options: Options<'_> = Options::new(80);
The anonymous lifetime represent the lifetime of the
initial_indentandsubsequent_indentstrings. The change is nearly performance neutral (a 1-2% regression).
Smaller improvements and changes:
- #404: Make documentation for short last-line penalty more precise.
- #405: Cleanup and simplify
Optionsdocstring. - #411: Default to
OptimalFitin interactive example. - #415: Add demo program to help compute binary sizes.
- #423: Add fuzz tests with fully arbitrary fragments.
- #424: Change
wrap_optimal_fitpenalties to non-negative numbers. - #430: Add
debug-wordsexample. - #432: Use precise dependency versions in Cargo.toml.
Release notes
Open source →This is a major feature release with two main changes:
-
#421: Use
f64instead ofusizefor fragment widths.This fixes problems with overflows in the internal computations of
wrap_optimal_fitwhen fragments (words) or line lengths had extreme values, such asusize::MAX. -
#438: Simplify
Optionsby removing generic type parameters.This change removes the new generic parameters introduced in version 0.14, as well as the original
WrapSplitterparameter which has been present since very early versions.The result is a simplification of function and struct signatures across the board. So what used to be
let options: Options< wrap_algorithms::FirstFit, word_separators::AsciiSpace, word_splitters::HyphenSplitter, > = Options::new(80);if types are fully written out, is now simply
let options: Options<'_> = Options::new(80);The anonymous lifetime represent the lifetime of the
initial_indentandsubsequent_indentstrings. The change is nearly performance neutral (a 1-2% regression).
Smaller improvements and changes:
- #404: Make documentation for short last-line penalty more precise.
- #405: Cleanup and simplify
Optionsdocstring. - #411: Default to
OptimalFitin interactive example. - #415: Add demo program to help compute binary sizes.
- #423: Add fuzz tests with fully arbitrary fragments.
- #424: Change
wrap_optimal_fitpenalties to non-negative numbers. - #430: Add
debug-wordsexample. - #432: Use precise dependency versions in Cargo.toml.
-
-
0.14.227 Jun 2021Release notes
Open source →Version 0.14.2 (2021-06-27)
The 0.14.1 release included more changes than intended and has been yanked. The change intended for 0.14.1 is now included in 0.14.2.
Release notes
Open source →The 0.14.1 release included more changes than intended and has been yanked. The change intended for 0.14.1 is now included in 0.14.2.
-
0.14.126 Jun 2021 withdrawnRelease notes
Open source →Version 0.14.1 (2021-06-26)
This release fixes a panic reported by @makoto, thanks!
- #391: Fix panic in
find_wordsdue to string access outside of a character boundary.
Release notes
Open source →This release fixes a panic reported by @Makoto, thanks!
- #391: Fix panic in
find_wordsdue to string access outside of a character boundary.
- #391: Fix panic in
-
0.14.005 Jun 2021Release notes
Open source →Version 0.14.0 (2021-06-05)
This is a major feature release which makes Textwrap more configurable and flexible. The high-level API of
textwrap::wrapandtextwrap::fillremains unchanged, but low-level structs have moved around.The biggest change is the introduction of new generic type parameters to the
Optionsstruct. These parameters lets you statically configure the wrapping algorithm, the word separator, and the word splitter. If you previously spelled out the full type forOptions, you now need to take the extra type parameters into account. This means thatlet options: Options<HyphenSplitter> = Options::new(80);
changes to
let options: Options< wrap_algorithms::FirstFit, word_separators::AsciiSpace, word_splitters::HyphenSplitter, > = Options::new(80);
This is quite a mouthful, so we suggest using type inferrence where possible. You won’t see any chance if you call
wrapdirectly with a width or with anOptionsvalue constructed on the fly. Please open an issue if this causes problems for you!New
WordSeparatorTrait-
#332: Add
WordSeparatortrait to allow customizing how words are found in a line of text. Until now, Textwrap would always assume that words are separated by ASCII space characters. You can now customize this as needed. -
#313: Add support for using the Unicode line breaking algorithm to find words. This is done by adding a second implementation of the new
WordSeparatortrait. The implementation uses the unicode-linebreak crate, which is a new optional dependency.With this, Textwrap can be used with East-Asian languages such as Chinese or Japanese where there are no spaces between words. Breaking a long sequence of emojis is another example where line breaks might be wanted even if there are no whitespace to be found. Feedback would be appreciated for this feature.
Indent
-
#353: Trim trailing whitespace from
prefixinindent.Before, empty lines would get no prefix added. Now, empty lines have a trimmed prefix added. This little trick makes
indentmuch more useful since you can now safely indent with"# "without creating trailing whitespace in the output due to the trailing whitespace in your prefix. -
#354: Make
indentabout 20% faster by preallocating the output string.
Documentation
- #308: Document handling of leading and trailing whitespace when wrapping text.
WebAssembly Demo
- #310: Thanks to WebAssembly, you can now try out Textwrap directly in your browser: https://mgeisler.github.io/textwrap/.
New Generic Parameters
-
#331: Remove outer boxing from
Options. -
#357: Replace
core::WrapAlgorithmenum with awrap_algorithms::WrapAlgorithmtrait. This allows for arbitrary wrapping algorithms to be plugged into the library. -
#358: Switch wrapping functions to use a slice for
line_widths. -
#368: Move
WordSeparatorandWordSplittertraits to separate modules. Before, Textwrap had several top-level structs such asNoHyphenationandHyphenSplitter. These implementations ofWordSplitternow lives in a dedicatedword_splittersmodule. Similarly, we have a newword_separatorsmodule for implementations ofWordSeparator. -
#369: Rename
Options::splittertoOptions::word_splitterfor consistency with the other fields backed by traits.
Release notes
Open source →This is a major feature release which makes Textwrap more configurable and flexible. The high-level API of
textwrap::wrapandtextwrap::fillremains unchanged, but low-level structs have moved around.The biggest change is the introduction of new generic type parameters to the
Optionsstruct. These parameters lets you statically configure the wrapping algorithm, the word separator, and the word splitter. If you previously spelled out the full type forOptions, you now need to take the extra type parameters into account. This means thatlet options: Options<HyphenSplitter> = Options::new(80);changes to
let options: Options< wrap_algorithms::FirstFit, word_separators::AsciiSpace, word_splitters::HyphenSplitter, > = Options::new(80);This is quite a mouthful, so we suggest using type inference where possible. You won’t see any chance if you call
wrapdirectly with a width or with anOptionsvalue constructed on the fly. Please open an issue if this causes problems for you!New
WordSeparatorTrait-
#332: Add
WordSeparatortrait to allow customizing how words are found in a line of text. Until now, Textwrap would always assume that words are separated by ASCII space characters. You can now customize this as needed. -
#313: Add support for using the Unicode line breaking algorithm to find words. This is done by adding a second implementation of the new
WordSeparatortrait. The implementation uses the unicode-linebreak crate, which is a new optional dependency.With this, Textwrap can be used with East-Asian languages such as Chinese or Japanese where there are no spaces between words. Breaking a long sequence of emojis is another example where line breaks might be wanted even if there are no whitespace to be found. Feedback would be appreciated for this feature.
Indent
-
#353: Trim trailing whitespace from
prefixinindent.Before, empty lines would get no prefix added. Now, empty lines have a trimmed prefix added. This little trick makes
indentmuch more useful since you can now safely indent with"# "without creating trailing whitespace in the output due to the trailing whitespace in your prefix. -
#354: Make
indentabout 20% faster by preallocating the output string.
Documentation
- #308: Document handling of leading and trailing whitespace when wrapping text.
WebAssembly Demo
- #310: Thanks to WebAssembly, you can now try out Textwrap directly in your browser. Please try it out: https://mgeisler.github.io/textwrap/.
New Generic Parameters
-
#331: Remove outer boxing from
Options. -
#357: Replace
core::WrapAlgorithmenum with awrap_algorithms::WrapAlgorithmtrait. This allows for arbitrary wrapping algorithms to be plugged into the library. -
#358: Switch wrapping functions to use a slice for
line_widths. -
#368: Move
WordSeparatorandWordSplittertraits to separate modules. Before, Textwrap had several top-level structs such asNoHyphenationandHyphenSplitter. These implementations ofWordSplitternow lives in a dedicatedword_splittersmodule. Similarly, we have a newword_separatorsmodule for implementations ofWordSeparator. -
#369: Rename
Options::splittertoOptions::word_splitterfor consistency with the other fields backed by traits.
-
-
0.13.423 Feb 2021Release notes
Open source →Version 0.13.4 (2021-02-23)
This release removes
println!statements which was left behind in
unfillby mistake.Release notes
Open source →This release removes
println!statements which was left behind inunfillby mistake. -
0.13.320 Feb 2021Release notes
Open source →This release contains a bugfix for
indentand improved handling of emojis. We’ve also added a new function for formatting text in columns and functions for reformatting already wrapped text.- #276: Extend
core::display_widthto handle emojis when the unicode-width Cargo feature is disabled. - #279: Make
indentpreserve existing newlines in the input string. Before,indent("foo", "")would return"foo\n"by mistake. It now returns"foo"instead. - #281: Ensure all
Optionsfields have examples. - #282: Add a
wrap_columnsfunction. - #294: Add new
unfillandrefillfunctions.
- #276: Extend
-
0.13.230 Dec 2020Release notes
Open source →This release primarily makes all dependencies optional. This makes it possible to slim down textwrap as needed.
-
0.13.110 Dec 2020Release notes
Open source →This is a bugfix release which fixes a regression in 0.13.0. The bug meant that colored text was wrapped incorrectly.
-
0.13.005 Dec 2020Release notes
Open source →This is a major release which rewrites the core logic, adds many new features, and fixes a couple of bugs. Most programs which use
textwrapstays the same, incompatibilities and upgrade notes are given below.Clone the repository and run the following to explore the new features in an interactive demo (Linux only):
$ cargo run --example interactive --all-featuresBug Fixes
Rewritten core wrapping algorithm
- #221: Reformulate wrapping in terms of words with whitespace and penalties.
The core wrapping algorithm has been completely rewritten. This fixed bugs and simplified the code, while also making it possible to use
textwrapoutside the context of the terminal.As part of this, trailing whitespace is now discarded consistently from wrapped lines. Before we would inconsistently remove whitespace at the end of wrapped lines, except for the last. Leading whitespace is still preserved.
New Features
Optimal-fit wrapping
- #234: Introduce wrapping using an optimal-fit algorithm.
This release adds support for new wrapping algorithm which finds a globally optimal set of line breaks, taking certain penalties into account. As an example, the old algorithm would produce
"To be, or" "not to be:" "that is" "the" "question"Notice how the fourth line with “the” is very short. The new algorithm shortens the previous lines slightly to produce fewer short lines:
"To be," "or not to" "be: that" "is the" "question"Use the new
textwrap::core::WrapAlgorithmenum to select between the new and old algorithm. By default, the new algorithm is used.The optimal-fit algorithm is inspired by the line breaking algorithm used in TeX, described in the 1981 article Breaking Paragraphs into Lines by Knuth and Plass.
In-place wrapping
- #226: Add a
fill_inplacefunction.
When the text you want to fill is already a temporary
String, you can now mutate it in-place withfill_inplace:let mut greeting = format!("Greetings {}, welcome to the game! You have {} lives left.", player.name, player.lives); fill_inplace(&mut greeting, line_width);This is faster than calling
filland it will reuse the memory already allocated for the string.Changed Features
Wrapperis replaced withOptions- #213: Simplify API with only top-level functions.
- #215: Reintroducing the type
parameter on
Options(previously known asWrapper). - #219: Allow using trait
objects with
fill&wrap. - #227: Replace
WrapOptionswithInto<Options>.
The
Wrapperstruct held the options (line width, indentation, etc) for wrapping text. It was also the entry point for actually wrapping the text via its methods such aswrap,wrap_iter,into_wrap_iter, andfillmethods.The struct has been replaced by a simpler
Optionsstruct which only holds options. TheWrappermethods are gone, their job has been taken over by the top-levelwrapandfillfunctions. The signature of these functions have changed fromfn fill(s: &str, width: usize) -> String; fn wrap(s: &str, width: usize) -> Vec<Cow<'_, str>>;to the more general
fn fill<'a, S, Opt>(text: &str, options: Opt) -> String where S: WordSplitter, Opt: Into<Options<'a, S>>; fn wrap<'a, S, Opt>(text: &str, options: Opt) -> Vec<Cow<'_, str>> where S: WordSplitter, Opt: Into<Options<'a, S>>;The
Into<Options<'a, S>bound allows you to pass anusize(which is interpreted as the line width) and a fullOptionsobject. This allows the new functions to work like the old, plus you can now fully customize the behavior of the wrapping viaOptionswhen needed.Code that call
textwrap::wraportextwrap::fillcan remain unchanged. Code that calls intoWrapper::wraporWrapper::fillwill need to be update. This is a mechanical change, please see #213 for examples.Thanks to @CryptJar and @Koxiat for their support in the PRs above!
Removed Features
-
The
wrap_iterandinto_wrap_itermethods are gone. This means that lazy iteration is no longer supported: you always get all wrapped lines back as aVec. This was done to simplify the code and to support the optimal-fit algorithm.The first-fit algorithm could still be implemented in an incremental fashion. Please let us know if this is important to you.
Other Changes
-
0.12.103 Jul 2020Release notes
Open source →This is a bugfix release.
- Fixed [#176][issue-176]: Mention compile-time wrapping by linking to the
[
textwrap-macroscrate]. - Fixed [#193][issue-193]: Wrapping with
break_words(false)was broken and would cause extra whitespace to be inserted when words were longer than the line width.
- Fixed [#176][issue-176]: Mention compile-time wrapping by linking to the
[
-
0.12.026 Jun 2020Release notes
Open source →The code has been updated to the [Rust 2018 edition][rust-2018] and each new release of
textwrapwill only support the latest stable version of Rust. Trying to support older Rust versions is a fool's errand: our dependencies keep releasing new patch versions that require newer and newer versions of Rust.The
term_sizefeature has been replaced byterminal_size. The API is unchanged, it is just the name of the Cargo feature that changed.The
hyphenationfeature now only embeds the hyphenation patterns for US-English. This slims down the dependency.- Fixed [#140][issue-140]: Ignore ANSI escape sequences.
- Fixed [#158][issue-158]: Unintended wrapping when using external splitter.
- Fixed [#177][issue-177]: Update examples to the 2018 edition.
-
0.11.009 Dec 2018Release notes
Open source →Due to our dependencies bumping their minimum supported version of Rust, the minimum version of Rust we test against is now 1.22.0.
- Merged [#141][issue-141]: Fix
dedenthandling of empty lines and trailing newlines. Thanks @bbqsrc! - Fixed [#151][issue-151]: Release of version with hyphenation 0.7.
- Merged [#141][issue-141]: Fix
-
0.10.028 Apr 2018Release notes
Open source →Due to our dependencies bumping their minimum supported version of Rust, the minimum version of Rust we test against is now 1.17.0.
- Fixed [#99][issue-99]: Word broken even though it would fit on line.
- Fixed [#107][issue-107]: Automatic hyphenation is off by one.
- Fixed [#122][issue-122]: Take newlines into account when wrapping.
- Fixed [#129][issue-129]: Panic on string with em-dash.
-
0.9.005 Oct 2017Release notes
Open source →The dependency on
term_sizeis now optional, and by default this feature is not enabled. This is a breaking change for users ofWrapper::with_termwidth. Enable theterm_sizefeature to restore the old functionality.Added a regression test for the case where
widthis set tousize::MAX, thanks @Fraser999! All public structs now implementDebug, thanks @hcpl!- Fixed [#101][issue-101]: Make
term_sizean optional dependency.
- Fixed [#101][issue-101]: Make
-
0.8.004 Sep 2017Release notes
Open source →The
Wrapperstruct is now generic over the type of word splitter being used. This means less boxing and a nicer API. TheWrapper::word_splittermethod has been removed. This is a breaking API change if you used the method to change the word splitter.The
Wrapperstruct has two new methods that will wrap the input text lazily:Wrapper::wrap_iterandWrapper::into_wrap_iter. Use those if you will be iterating over the wrapped lines one by one.- Fixed [#59][issue-59]:
wrapcould return an iterator. Thanks @hcpl! - Fixed [#81][issue-81]: Set
html_root_url.
- Fixed [#59][issue-59]:
-
0.7.020 Jul 2017Release notes
Open source →Version 0.7.0 changes the return type of
Wrapper::wrapfromVec<String>toVec<Cow<'a, str>>. This means that the output lines borrow data from the input string. This is a breaking API change if you relied on the exact return type ofWrapper::wrap. Callers of thetextwrap::fillconvenience function will see no breakage.The above change and other optimizations makes version 0.7.0 roughly 15-30% faster than version 0.6.0.
The
squeeze_whitespaceoption has been removed since it was complicating the above optimization. Let us know if this option is important for you so we can provide a work around.- Fixed [#58][issue-58]: Add a "fast_wrap" function.
- Fixed [#61][issue-61]: Documentation errors.
-
0.6.022 May 2017Release notes
Open source →Version 0.6.0 adds builder methods to
Wrapperfor easy one-line initialization and configuration:let wrapper = Wrapper::new(60).break_words(false);It also add a new
NoHyphenationword splitter that will never split words, not even at existing hyphens.- Fixed [#28][issue-28]: Support not squeezing whitespace.
-
0.5.015 May 2017Release notes
Open source →Version 0.5.0 has breaking API changes. However, this only affects code using the hyphenation feature. The feature is now optional, so you will first need to enable the
hyphenationfeature as described above. Afterwards, please change your code fromwrapper.corpus = Some(&corpus);to
wrapper.splitter = Box::new(corpus);Other changes include optimizations, so version 0.5.0 is roughly 10-15% faster than version 0.4.0.
- Fixed [#19][issue-19]: Add support for finding terminal size.
- Fixed [#25][issue-25]: Handle words longer than
self.width. - Fixed [#26][issue-26]: Support custom indentation.
- Fixed [#36][issue-36]: Support building without
hyphenation. - Fixed [#39][issue-39]: Respect non-breaking spaces.
-
0.4.024 Jan 2017Release notes
Open source →Documented complexities and tested these via
cargo bench.- Fixed [#13][issue-13]: Immediately add word if it fits.
- Fixed [#14][issue-14]: Avoid splitting on initial hyphens.
-
0.3.007 Jan 2017 -
0.2.029 Dec 2016 -
0.1.017 Dec 2016