1 //! The textwrap library provides functions for word wrapping and
6 //! Wrapping text can be very useful in command-line programs where
7 //! you want to format dynamic output nicely so it looks good in a
8 //! terminal. A quick example:
11 //! # #[cfg(feature = "smawk")] {
12 //! let text = "textwrap: a small library for wrapping text.";
13 //! assert_eq!(textwrap::wrap(text, 18),
14 //! vec!["textwrap: a",
15 //! "small library for",
16 //! "wrapping text."]);
20 //! The [`wrap`] function returns the individual lines, use [`fill`]
21 //! is you want the lines joined with `'\n'` to form a `String`.
23 //! If you enable the `hyphenation` Cargo feature, you can get
24 //! automatic hyphenation for a number of languages:
27 //! #[cfg(feature = "hyphenation")] {
28 //! use hyphenation::{Language, Load, Standard};
29 //! use textwrap::{wrap, Options, WordSplitter};
31 //! let text = "textwrap: a small library for wrapping text.";
32 //! let dictionary = Standard::from_embedded(Language::EnglishUS).unwrap();
33 //! let options = Options::new(18).word_splitter(WordSplitter::Hyphenation(dictionary));
34 //! assert_eq!(wrap(text, &options),
35 //! vec!["textwrap: a small",
36 //! "library for wrap-",
41 //! See also the [`unfill`] and [`refill`] functions which allow you to
42 //! manipulate already wrapped text.
44 //! ## Wrapping Strings at Compile Time
46 //! If your strings are known at compile time, please take a look at
47 //! the procedural macros from the [textwrap-macros] crate.
49 //! ## Displayed Width vs Byte Size
51 //! To word wrap text, one must know the width of each word so one can
52 //! know when to break lines. This library will by default measure the
53 //! width of text using the _displayed width_, not the size in bytes.
54 //! The `unicode-width` Cargo feature controls this.
56 //! This is important for non-ASCII text. ASCII characters such as `a`
57 //! and `!` are simple and take up one column each. This means that
58 //! the displayed width is equal to the string length in bytes.
59 //! However, non-ASCII characters and symbols take up more than one
60 //! byte when UTF-8 encoded: `é` is `0xc3 0xa9` (two bytes) and `⚙` is
61 //! `0xe2 0x9a 0x99` (three bytes) in UTF-8, respectively.
63 //! This is why we take care to use the displayed width instead of the
64 //! byte count when computing line lengths. All functions in this
65 //! library handle Unicode characters like this when the
66 //! `unicode-width` Cargo feature is enabled (it is enabled by
69 //! # Indentation and Dedentation
71 //! The textwrap library also offers functions for adding a prefix to
72 //! every line of a string and to remove leading whitespace. As an
73 //! example, the [`indent`] function allows you to turn lines of text
74 //! into a bullet list:
87 //! assert_eq!(textwrap::indent(before, "* "), after);
90 //! Removing leading whitespace is done with [`dedent`]:
103 //! assert_eq!(textwrap::dedent(before), after);
108 //! The textwrap library can be slimmed down as needed via a number of
109 //! Cargo features. This means you only pay for the features you
112 //! The full dependency graph, where dashed lines indicate optional
113 //! dependencies, is shown below:
115 //! <img src="https://raw.githubusercontent.com/mgeisler/textwrap/master/images/textwrap-0.15.0.svg">
117 //! ## Default Features
119 //! These features are enabled by default:
121 //! * `unicode-linebreak`: enables finding words using the
122 //! [unicode-linebreak] crate, which implements the line breaking
123 //! algorithm described in [Unicode Standard Annex
124 //! #14](https://www.unicode.org/reports/tr14/).
126 //! This feature can be disabled if you are happy to find words
127 //! separated by ASCII space characters only. People wrapping text
128 //! with emojis or East-Asian characters will want most likely want
129 //! to enable this feature. See [`WordSeparator`] for details.
131 //! * `unicode-width`: enables correct width computation of non-ASCII
132 //! characters via the [unicode-width] crate. Without this feature,
133 //! every [`char`] is 1 column wide, except for emojis which are 2
134 //! columns wide. See the [`core::display_width`] function for
137 //! This feature can be disabled if you only need to wrap ASCII
138 //! text, or if the functions in [`core`] are used directly with
139 //! [`core::Fragment`]s for which the widths have been computed in
142 //! * `smawk`: enables linear-time wrapping of the whole paragraph via
143 //! the [smawk] crate. See the [`wrap_algorithms::wrap_optimal_fit`]
144 //! function for details on the optimal-fit algorithm.
146 //! This feature can be disabled if you only ever intend to use
147 //! [`wrap_algorithms::wrap_first_fit`].
149 //! With Rust 1.59.0, the size impact of the above features on your
150 //! binary is as follows:
152 //! | Configuration | Binary Size | Delta |
153 //! | :--- | ---: | ---: |
154 //! | quick-and-dirty implementation | 289 KB | — KB |
155 //! | textwrap without default features | 301 KB | 12 KB |
156 //! | textwrap with smawk | 317 KB | 28 KB |
157 //! | textwrap with unicode-width | 313 KB | 24 KB |
158 //! | textwrap with unicode-linebreak | 395 KB | 106 KB |
160 //! The above sizes are the stripped sizes and the binary is compiled
161 //! in release mode with this profile:
164 //! [profile.release]
166 //! codegen-units = 1
169 //! See the [binary-sizes demo] if you want to reproduce these
172 //! ## Optional Features
174 //! These Cargo features enable new functionality:
176 //! * `terminal_size`: enables automatic detection of the terminal
177 //! width via the [terminal_size] crate. See the
178 //! [`Options::with_termwidth`] constructor for details.
180 //! * `hyphenation`: enables language-sensitive hyphenation via the
181 //! [hyphenation] crate. See the [`word_splitters::WordSplitter`]
182 //! trait for details.
184 //! [unicode-linebreak]: https://docs.rs/unicode-linebreak/
185 //! [unicode-width]: https://docs.rs/unicode-width/
186 //! [smawk]: https://docs.rs/smawk/
187 //! [binary-sizes demo]: https://github.com/mgeisler/textwrap/tree/master/examples/binary-sizes
188 //! [textwrap-macros]: https://docs.rs/textwrap-macros/
189 //! [terminal_size]: https://docs.rs/terminal_size/
190 //! [hyphenation]: https://docs.rs/hyphenation/
192 #![doc(html_root_url = "https://docs.rs/textwrap/0.15.0")]
193 #![forbid(unsafe_code)] // See https://github.com/mgeisler/textwrap/issues/210
194 #![deny(missing_docs)]
195 #![deny(missing_debug_implementations)]
196 #![allow(clippy::redundant_field_names)]
198 // Make `cargo test` execute the README doctests.
200 #[doc = include_str!("../README.md")]
201 mod readme_doctest {}
203 use std
::borrow
::Cow
;
206 pub use crate::indentation
::{dedent, indent}
;
209 pub use word_separators
::WordSeparator
;
211 pub mod word_splitters
;
212 pub use word_splitters
::WordSplitter
;
214 pub mod wrap_algorithms
;
215 pub use wrap_algorithms
::WrapAlgorithm
;
219 #[cfg(feature = "unicode-linebreak")]
220 macro_rules
! DefaultWordSeparator
{
222 WordSeparator
::UnicodeBreakProperties
226 #[cfg(not(feature = "unicode-linebreak"))]
227 macro_rules
! DefaultWordSeparator
{
229 WordSeparator
::AsciiSpace
233 /// Holds configuration options for wrapping and filling text.
234 #[derive(Debug, Clone)]
235 pub struct Options
<'a
> {
236 /// The width in columns at which the text will be wrapped.
238 /// Indentation used for the first line of output. See the
239 /// [`Options::initial_indent`] method.
240 pub initial_indent
: &'a
str,
241 /// Indentation used for subsequent lines of output. See the
242 /// [`Options::subsequent_indent`] method.
243 pub subsequent_indent
: &'a
str,
244 /// Allow long words to be broken if they cannot fit on a line.
245 /// When set to `false`, some lines may be longer than
246 /// `self.width`. See the [`Options::break_words`] method.
247 pub break_words
: bool
,
248 /// Wrapping algorithm to use, see the implementations of the
249 /// [`wrap_algorithms::WrapAlgorithm`] trait for details.
250 pub wrap_algorithm
: WrapAlgorithm
,
251 /// The line breaking algorithm to use, see
252 /// [`word_separators::WordSeparator`] trait for an overview and
253 /// possible implementations.
254 pub word_separator
: WordSeparator
,
255 /// The method for splitting words. This can be used to prohibit
256 /// splitting words on hyphens, or it can be used to implement
257 /// language-aware machine hyphenation.
258 pub word_splitter
: WordSplitter
,
261 impl<'a
> From
<&'a Options
<'a
>> for Options
<'a
> {
262 fn from(options
: &'a Options
<'a
>) -> Self {
264 width
: options
.width
,
265 initial_indent
: options
.initial_indent
,
266 subsequent_indent
: options
.subsequent_indent
,
267 break_words
: options
.break_words
,
268 word_separator
: options
.word_separator
,
269 wrap_algorithm
: options
.wrap_algorithm
,
270 word_splitter
: options
.word_splitter
.clone(),
275 impl<'a
> From
<usize> for Options
<'a
> {
276 fn from(width
: usize) -> Self {
281 impl<'a
> Options
<'a
> {
282 /// Creates a new [`Options`] with the specified width. Equivalent to
285 /// # use textwrap::{Options, WordSplitter, WordSeparator, WrapAlgorithm};
286 /// # let width = 80;
287 /// # let actual = Options::new(width);
291 /// initial_indent: "",
292 /// subsequent_indent: "",
293 /// break_words: true,
294 /// #[cfg(feature = "unicode-linebreak")]
295 /// word_separator: WordSeparator::UnicodeBreakProperties,
296 /// #[cfg(not(feature = "unicode-linebreak"))]
297 /// word_separator: WordSeparator::AsciiSpace,
298 /// #[cfg(feature = "smawk")]
299 /// wrap_algorithm: WrapAlgorithm::new_optimal_fit(),
300 /// #[cfg(not(feature = "smawk"))]
301 /// wrap_algorithm: WrapAlgorithm::FirstFit,
302 /// word_splitter: WordSplitter::HyphenSplitter,
305 /// # assert_eq!(actual.width, expected.width);
306 /// # assert_eq!(actual.initial_indent, expected.initial_indent);
307 /// # assert_eq!(actual.subsequent_indent, expected.subsequent_indent);
308 /// # assert_eq!(actual.break_words, expected.break_words);
309 /// # assert_eq!(actual.word_splitter, expected.word_splitter);
312 /// Note that the default word separator and wrap algorithms
313 /// changes based on the available Cargo features. The best
314 /// available algorithms are used by default.
315 pub const fn new(width
: usize) -> Self {
319 subsequent_indent
: "",
321 word_separator
: DefaultWordSeparator
!(),
322 wrap_algorithm
: WrapAlgorithm
::new(),
323 word_splitter
: WordSplitter
::HyphenSplitter
,
327 /// Creates a new [`Options`] with `width` set to the current
328 /// terminal width. If the terminal width cannot be determined
329 /// (typically because the standard input and output is not
330 /// connected to a terminal), a width of 80 characters will be
331 /// used. Other settings use the same defaults as
332 /// [`Options::new`].
337 /// use textwrap::{termwidth, Options};
339 /// let options = Options::new(termwidth());
342 /// **Note:** Only available when the `terminal_size` feature is
344 #[cfg(feature = "terminal_size")]
345 pub fn with_termwidth() -> Self {
346 Self::new(termwidth())
350 impl<'a
> Options
<'a
> {
351 /// Change [`self.initial_indent`]. The initial indentation is
352 /// used on the very first line of output.
356 /// Classic paragraph indentation can be achieved by specifying an
357 /// initial indentation and wrapping each paragraph by itself:
360 /// use textwrap::{wrap, Options};
362 /// let options = Options::new(16).initial_indent(" ");
363 /// assert_eq!(wrap("This is a little example.", options),
364 /// vec![" This is a",
365 /// "little example."]);
368 /// [`self.initial_indent`]: #structfield.initial_indent
369 pub fn initial_indent(self, indent
: &'a
str) -> Self {
371 initial_indent
: indent
,
376 /// Change [`self.subsequent_indent`]. The subsequent indentation
377 /// is used on lines following the first line of output.
381 /// Combining initial and subsequent indentation lets you format a
382 /// single paragraph as a bullet list:
385 /// use textwrap::{wrap, Options};
387 /// let options = Options::new(12)
388 /// .initial_indent("* ")
389 /// .subsequent_indent(" ");
390 /// #[cfg(feature = "smawk")]
391 /// assert_eq!(wrap("This is a little example.", options),
392 /// vec!["* This is",
396 /// // Without the `smawk` feature, the wrapping is a little different:
397 /// #[cfg(not(feature = "smawk"))]
398 /// assert_eq!(wrap("This is a little example.", options),
399 /// vec!["* This is a",
404 /// [`self.subsequent_indent`]: #structfield.subsequent_indent
405 pub fn subsequent_indent(self, indent
: &'a
str) -> Self {
407 subsequent_indent
: indent
,
412 /// Change [`self.break_words`]. This controls if words longer
413 /// than `self.width` can be broken, or if they will be left
414 /// sticking out into the right margin.
419 /// use textwrap::{wrap, Options};
421 /// let options = Options::new(4).break_words(true);
422 /// assert_eq!(wrap("This is a little example.", options),
431 /// [`self.break_words`]: #structfield.break_words
432 pub fn break_words(self, setting
: bool
) -> Self {
434 break_words
: setting
,
439 /// Change [`self.word_separator`].
441 /// See [`word_separators::WordSeparator`] for details on the choices.
443 /// [`self.word_separator`]: #structfield.word_separator
444 pub fn word_separator(self, word_separator
: WordSeparator
) -> Options
<'a
> {
447 initial_indent
: self.initial_indent
,
448 subsequent_indent
: self.subsequent_indent
,
449 break_words
: self.break_words
,
450 word_separator
: word_separator
,
451 wrap_algorithm
: self.wrap_algorithm
,
452 word_splitter
: self.word_splitter
,
456 /// Change [`self.wrap_algorithm`].
458 /// See the [`wrap_algorithms::WrapAlgorithm`] trait for details on
461 /// [`self.wrap_algorithm`]: #structfield.wrap_algorithm
462 pub fn wrap_algorithm(self, wrap_algorithm
: WrapAlgorithm
) -> Options
<'a
> {
465 initial_indent
: self.initial_indent
,
466 subsequent_indent
: self.subsequent_indent
,
467 break_words
: self.break_words
,
468 word_separator
: self.word_separator
,
469 wrap_algorithm
: wrap_algorithm
,
470 word_splitter
: self.word_splitter
,
474 /// Change [`self.word_splitter`]. The
475 /// [`word_splitters::WordSplitter`] is used to fit part of a word
476 /// into the current line when wrapping text.
481 /// use textwrap::{Options, WordSplitter};
482 /// let opt = Options::new(80);
483 /// assert_eq!(opt.word_splitter, WordSplitter::HyphenSplitter);
484 /// let opt = opt.word_splitter(WordSplitter::NoHyphenation);
485 /// assert_eq!(opt.word_splitter, WordSplitter::NoHyphenation);
488 /// [`self.word_splitter`]: #structfield.word_splitter
489 pub fn word_splitter(self, word_splitter
: WordSplitter
) -> Options
<'a
> {
492 initial_indent
: self.initial_indent
,
493 subsequent_indent
: self.subsequent_indent
,
494 break_words
: self.break_words
,
495 word_separator
: self.word_separator
,
496 wrap_algorithm
: self.wrap_algorithm
,
502 /// Return the current terminal width.
504 /// If the terminal width cannot be determined (typically because the
505 /// standard output is not connected to a terminal), a default width
506 /// of 80 characters will be used.
510 /// Create an [`Options`] for wrapping at the current terminal width
511 /// with a two column margin to the left and the right:
514 /// use textwrap::{termwidth, Options};
516 /// let width = termwidth() - 4; // Two columns on each side.
517 /// let options = Options::new(width)
518 /// .initial_indent(" ")
519 /// .subsequent_indent(" ");
522 /// **Note:** Only available when the `terminal_size` Cargo feature is
524 #[cfg(feature = "terminal_size")]
525 pub fn termwidth() -> usize {
526 terminal_size
::terminal_size().map_or(80, |(terminal_size
::Width(w
), _
)| w
.into())
529 /// Fill a line of text at a given width.
531 /// The result is a [`String`], complete with newlines between each
532 /// line. Use the [`wrap`] function if you need access to the
533 /// individual lines.
535 /// The easiest way to use this function is to pass an integer for
536 /// `width_or_options`:
539 /// use textwrap::fill;
542 /// fill("Memory safety without garbage collection.", 15),
543 /// "Memory safety\nwithout garbage\ncollection."
547 /// If you need to customize the wrapping, you can pass an [`Options`]
548 /// instead of an `usize`:
551 /// use textwrap::{fill, Options};
553 /// let options = Options::new(15)
554 /// .initial_indent("- ")
555 /// .subsequent_indent(" ");
557 /// fill("Memory safety without garbage collection.", &options),
558 /// "- Memory safety\n without\n garbage\n collection."
561 pub fn fill
<'a
, Opt
>(text
: &str, width_or_options
: Opt
) -> String
563 Opt
: Into
<Options
<'a
>>,
565 // This will avoid reallocation in simple cases (no
566 // indentation, no hyphenation).
567 let mut result
= String
::with_capacity(text
.len());
569 for (i
, line
) in wrap(text
, width_or_options
).iter().enumerate() {
573 result
.push_str(line
);
579 /// Unpack a paragraph of already-wrapped text.
581 /// This function attempts to recover the original text from a single
582 /// paragraph of text produced by the [`fill`] function. This means
586 /// textwrap: a small
594 /// textwrap: a small library for wrapping text.
597 /// In addition, it will recognize a common prefix among the lines.
598 /// The prefix of the first line is returned in
599 /// [`Options::initial_indent`] and the prefix (if any) of the the
600 /// other lines is returned in [`Options::subsequent_indent`].
602 /// In addition to `' '`, the prefixes can consist of characters used
603 /// for unordered lists (`'-'`, `'+'`, and `'*'`) and block quotes
604 /// (`'>'`) in Markdown as well as characters often used for inline
605 /// comments (`'#'` and `'/'`).
607 /// The text must come from a single wrapped paragraph. This means
608 /// that there can be no `"\n\n"` within the text.
613 /// use textwrap::unfill;
615 /// let (text, options) = unfill("\
621 /// assert_eq!(text, "This is an example of a list item.\n");
622 /// assert_eq!(options.initial_indent, "* ");
623 /// assert_eq!(options.subsequent_indent, " ");
625 pub fn unfill(text
: &str) -> (String
, Options
<'_
>) {
626 let trimmed
= text
.trim_end_matches('
\n'
);
627 let prefix_chars
: &[_
] = &[' '
, '
-'
, '
+'
, '
*'
, '
>'
, '
#', '/'];
629 let mut options
= Options
::new(0);
630 for (idx
, line
) in trimmed
.split('
\n'
).enumerate() {
631 options
.width
= std
::cmp
::max(options
.width
, core
::display_width(line
));
632 let without_prefix
= line
.trim_start_matches(prefix_chars
);
633 let prefix
= &line
[..line
.len() - without_prefix
.len()];
636 options
.initial_indent
= prefix
;
638 options
.subsequent_indent
= prefix
;
640 for ((idx
, x
), y
) in prefix
.char_indices().zip(options
.subsequent_indent
.chars()) {
642 options
.subsequent_indent
= &prefix
[..idx
];
646 if prefix
.len() < options
.subsequent_indent
.len() {
647 options
.subsequent_indent
= prefix
;
652 let mut unfilled
= String
::with_capacity(text
.len());
653 for (idx
, line
) in trimmed
.split('
\n'
).enumerate() {
655 unfilled
.push_str(&line
[options
.initial_indent
.len()..]);
658 unfilled
.push_str(&line
[options
.subsequent_indent
.len()..]);
662 unfilled
.push_str(&text
[trimmed
.len()..]);
666 /// Refill a paragraph of wrapped text with a new width.
668 /// This function will first use the [`unfill`] function to remove
669 /// newlines from the text. Afterwards the text is filled again using
670 /// the [`fill`] function.
672 /// The `new_width_or_options` argument specify the new width and can
673 /// specify other options as well — except for
674 /// [`Options::initial_indent`] and [`Options::subsequent_indent`],
675 /// which are deduced from `filled_text`.
680 /// use textwrap::refill;
682 /// // Some loosely wrapped text. The "> " prefix is recognized automatically.
685 /// > safety without garbage
689 /// assert_eq!(refill(text, 20), "\
691 /// > without garbage
695 /// assert_eq!(refill(text, 40), "\
696 /// > Memory safety without garbage
700 /// assert_eq!(refill(text, 60), "\
701 /// > Memory safety without garbage collection.
705 /// You can also reshape bullet points:
708 /// use textwrap::refill;
715 /// assert_eq!(refill(text, 20), "\
716 /// - This is my list
720 pub fn refill
<'a
, Opt
>(filled_text
: &str, new_width_or_options
: Opt
) -> String
722 Opt
: Into
<Options
<'a
>>,
724 let trimmed
= filled_text
.trim_end_matches('
\n'
);
725 let (text
, options
) = unfill(trimmed
);
726 let mut new_options
= new_width_or_options
.into();
727 new_options
.initial_indent
= options
.initial_indent
;
728 new_options
.subsequent_indent
= options
.subsequent_indent
;
729 let mut refilled
= fill(&text
, new_options
);
730 refilled
.push_str(&filled_text
[trimmed
.len()..]);
734 /// Wrap a line of text at a given width.
736 /// The result is a vector of lines, each line is of type [`Cow<'_,
737 /// str>`](Cow), which means that the line will borrow from the input
738 /// `&str` if possible. The lines do not have trailing whitespace,
739 /// including a final `'\n'`. Please use the [`fill`] function if you
740 /// need a [`String`] instead.
742 /// The easiest way to use this function is to pass an integer for
743 /// `width_or_options`:
746 /// use textwrap::wrap;
748 /// let lines = wrap("Memory safety without garbage collection.", 15);
749 /// assert_eq!(lines, &[
751 /// "without garbage",
756 /// If you need to customize the wrapping, you can pass an [`Options`]
757 /// instead of an `usize`:
760 /// use textwrap::{wrap, Options};
762 /// let options = Options::new(15)
763 /// .initial_indent("- ")
764 /// .subsequent_indent(" ");
765 /// let lines = wrap("Memory safety without garbage collection.", &options);
766 /// assert_eq!(lines, &[
767 /// "- Memory safety",
774 /// # Optimal-Fit Wrapping
776 /// By default, `wrap` will try to ensure an even right margin by
777 /// finding breaks which avoid short lines. We call this an
778 /// “optimal-fit algorithm” since the line breaks are computed by
779 /// considering all possible line breaks. The alternative is a
780 /// “first-fit algorithm” which simply accumulates words until they no
781 /// longer fit on the line.
783 /// As an example, using the first-fit algorithm to wrap the famous
784 /// Hamlet quote “To be, or not to be: that is the question” in a
785 /// narrow column with room for only 10 characters looks like this:
788 /// # use textwrap::{WrapAlgorithm::FirstFit, Options, wrap};
790 /// # let lines = wrap("To be, or not to be: that is the question",
791 /// # Options::new(10).wrap_algorithm(FirstFit));
792 /// # assert_eq!(lines.join("\n") + "\n", "\
801 /// Notice how the second to last line is quite narrow because
802 /// “question” was too large to fit? The greedy first-fit algorithm
803 /// doesn’t look ahead, so it has no other option than to put
804 /// “question” onto its own line.
806 /// With the optimal-fit wrapping algorithm, the previous lines are
807 /// shortened slightly in order to make the word “is” go into the
808 /// second last line:
811 /// # #[cfg(feature = "smawk")] {
812 /// # use textwrap::{Options, WrapAlgorithm, wrap};
814 /// # let lines = wrap(
815 /// # "To be, or not to be: that is the question",
816 /// # Options::new(10).wrap_algorithm(WrapAlgorithm::new_optimal_fit())
818 /// # assert_eq!(lines.join("\n") + "\n", "\
827 /// Please see [`WrapAlgorithm`] for details on the choices.
831 /// The returned iterator yields lines of type `Cow<'_, str>`. If
832 /// possible, the wrapped lines will borrow from the input string. As
833 /// an example, a hanging indentation, the first line can borrow from
834 /// the input, but the subsequent lines become owned strings:
837 /// use std::borrow::Cow::{Borrowed, Owned};
838 /// use textwrap::{wrap, Options};
840 /// let options = Options::new(15).subsequent_indent("....");
841 /// let lines = wrap("Wrapping text all day long.", &options);
842 /// let annotated = lines
844 /// .map(|line| match line {
845 /// Borrowed(text) => format!("[Borrowed] {}", text),
846 /// Owned(text) => format!("[Owned] {}", text),
848 /// .collect::<Vec<_>>();
852 /// "[Borrowed] Wrapping text",
853 /// "[Owned] ....all day",
854 /// "[Owned] ....long.",
859 /// ## Leading and Trailing Whitespace
861 /// As a rule, leading whitespace (indentation) is preserved and
862 /// trailing whitespace is discarded.
864 /// In more details, when wrapping words into lines, words are found
865 /// by splitting the input text on space characters. One or more
866 /// spaces (shown here as “␣”) are attached to the end of each word:
869 /// "Foo␣␣␣bar␣baz" -> ["Foo␣␣␣", "bar␣", "baz"]
872 /// These words are then put into lines. The interword whitespace is
873 /// preserved, unless the lines are wrapped so that the `"Foo␣␣␣"`
874 /// word falls at the end of a line:
877 /// use textwrap::wrap;
879 /// assert_eq!(wrap("Foo bar baz", 10), vec!["Foo bar", "baz"]);
880 /// assert_eq!(wrap("Foo bar baz", 8), vec!["Foo", "bar baz"]);
883 /// Notice how the trailing whitespace is removed in both case: in the
884 /// first example, `"bar␣"` becomes `"bar"` and in the second case
885 /// `"Foo␣␣␣"` becomes `"Foo"`.
887 /// Leading whitespace is preserved when the following word fits on
888 /// the first line. To understand this, consider how words are found
889 /// in a text with leading spaces:
892 /// "␣␣foo␣bar" -> ["␣␣", "foo␣", "bar"]
895 /// When put into lines, the indentation is preserved if `"foo"` fits
896 /// on the first line, otherwise you end up with an empty line:
899 /// use textwrap::wrap;
901 /// assert_eq!(wrap(" foo bar", 8), vec![" foo", "bar"]);
902 /// assert_eq!(wrap(" foo bar", 4), vec!["", "foo", "bar"]);
904 pub fn wrap
<'a
, Opt
>(text
: &str, width_or_options
: Opt
) -> Vec
<Cow
<'_
, str>>
906 Opt
: Into
<Options
<'a
>>,
908 let options
= width_or_options
.into();
910 let initial_width
= options
912 .saturating_sub(core
::display_width(options
.initial_indent
));
913 let subsequent_width
= options
915 .saturating_sub(core
::display_width(options
.subsequent_indent
));
917 let mut lines
= Vec
::new();
918 for line
in text
.split('
\n'
) {
919 let words
= options
.word_separator
.find_words(line
);
920 let split_words
= word_splitters
::split_words(words
, &options
.word_splitter
);
921 let broken_words
= if options
.break_words
{
922 let mut broken_words
= core
::break_words(split_words
, subsequent_width
);
923 if !options
.initial_indent
.is_empty() {
924 // Without this, the first word will always go into
925 // the first line. However, since we break words based
926 // on the _second_ line width, it can be wrong to
927 // unconditionally put the first word onto the first
928 // line. An empty zero-width word fixed this.
929 broken_words
.insert(0, core
::Word
::from(""));
933 split_words
.collect
::<Vec
<_
>>()
936 let line_widths
= [initial_width
, subsequent_width
];
937 let wrapped_words
= options
.wrap_algorithm
.wrap(&broken_words
, &line_widths
);
940 for words
in wrapped_words
{
941 let last_word
= match words
.last() {
943 lines
.push(Cow
::from(""));
949 // We assume here that all words are contiguous in `line`.
950 // That is, the sum of their lengths should add up to the
954 .map(|word
| word
.len() + word
.whitespace
.len())
956 - last_word
.whitespace
.len();
958 // The result is owned if we have indentation, otherwise
959 // we can simply borrow an empty string.
960 let mut result
= if lines
.is_empty() && !options
.initial_indent
.is_empty() {
961 Cow
::Owned(options
.initial_indent
.to_owned())
962 } else if !lines
.is_empty() && !options
.subsequent_indent
.is_empty() {
963 Cow
::Owned(options
.subsequent_indent
.to_owned())
965 // We can use an empty string here since string
966 // concatenation for `Cow` preserves a borrowed value
967 // when either side is empty.
971 result
+= &line
[idx
..idx
+ len
];
973 if !last_word
.penalty
.is_empty() {
974 result
.to_mut().push_str(last_word
.penalty
);
979 // Advance by the length of `result`, plus the length of
980 // `last_word.whitespace` -- even if we had a penalty, we
981 // need to skip over the whitespace.
982 idx
+= len
+ last_word
.whitespace
.len();
989 /// Wrap text into columns with a given total width.
991 /// The `left_gap`, `middle_gap` and `right_gap` arguments specify the
992 /// strings to insert before, between, and after the columns. The
993 /// total width of all columns and all gaps is specified using the
994 /// `total_width_or_options` argument. This argument can simply be an
995 /// integer if you want to use default settings when wrapping, or it
996 /// can be a [`Options`] value if you want to customize the wrapping.
998 /// If the columns are narrow, it is recommended to set
999 /// [`Options::break_words`] to `true` to prevent words from
1000 /// protruding into the margins.
1002 /// The per-column width is computed like this:
1005 /// # let (left_gap, middle_gap, right_gap) = ("", "", "");
1006 /// # let columns = 2;
1007 /// # let options = textwrap::Options::new(80);
1008 /// let inner_width = options.width
1009 /// - textwrap::core::display_width(left_gap)
1010 /// - textwrap::core::display_width(right_gap)
1011 /// - textwrap::core::display_width(middle_gap) * (columns - 1);
1012 /// let column_width = inner_width / columns;
1015 /// The `text` is wrapped using [`wrap`] and the given `options`
1016 /// argument, but the width is overwritten to the computed
1021 /// Panics if `columns` is zero.
1026 /// use textwrap::wrap_columns;
1029 /// This is an example text, which is wrapped into three columns. \
1030 /// Notice how the final column can be shorter than the others.";
1032 /// #[cfg(feature = "smawk")]
1033 /// assert_eq!(wrap_columns(text, 3, 50, "| ", " | ", " |"),
1034 /// vec!["| This is | into three | column can be |",
1035 /// "| an example | columns. | shorter than |",
1036 /// "| text, which | Notice how | the others. |",
1037 /// "| is wrapped | the final | |"]);
1039 /// // Without the `smawk` feature, the middle column is a little more uneven:
1040 /// #[cfg(not(feature = "smawk"))]
1041 /// assert_eq!(wrap_columns(text, 3, 50, "| ", " | ", " |"),
1042 /// vec!["| This is an | three | column can be |",
1043 /// "| example text, | columns. | shorter than |",
1044 /// "| which is | Notice how | the others. |",
1045 /// "| wrapped into | the final | |"]);
1046 pub fn wrap_columns
<'a
, Opt
>(
1049 total_width_or_options
: Opt
,
1055 Opt
: Into
<Options
<'a
>>,
1057 assert
!(columns
> 0);
1059 let mut options
= total_width_or_options
.into();
1061 let inner_width
= options
1063 .saturating_sub(core
::display_width(left_gap
))
1064 .saturating_sub(core
::display_width(right_gap
))
1065 .saturating_sub(core
::display_width(middle_gap
) * (columns
- 1));
1067 let column_width
= std
::cmp
::max(inner_width
/ columns
, 1);
1068 options
.width
= column_width
;
1069 let last_column_padding
= " ".repeat(inner_width
% column_width
);
1070 let wrapped_lines
= wrap(text
, options
);
1071 let lines_per_column
=
1072 wrapped_lines
.len() / columns
+ usize::from(wrapped_lines
.len() % columns
> 0);
1073 let mut lines
= Vec
::new();
1074 for line_no
in 0..lines_per_column
{
1075 let mut line
= String
::from(left_gap
);
1076 for column_no
in 0..columns
{
1077 match wrapped_lines
.get(line_no
+ column_no
* lines_per_column
) {
1078 Some(column_line
) => {
1079 line
.push_str(column_line
);
1080 line
.push_str(&" ".repeat(column_width
- core
::display_width(column_line
)));
1083 line
.push_str(&" ".repeat(column_width
));
1086 if column_no
== columns
- 1 {
1087 line
.push_str(&last_column_padding
);
1089 line
.push_str(middle_gap
);
1092 line
.push_str(right_gap
);
1099 /// Fill `text` in-place without reallocating the input string.
1101 /// This function works by modifying the input string: some `' '`
1102 /// characters will be replaced by `'\n'` characters. The rest of the
1103 /// text remains untouched.
1105 /// Since we can only replace existing whitespace in the input with
1106 /// `'\n'`, we cannot do hyphenation nor can we split words longer
1107 /// than the line width. We also need to use `AsciiSpace` as the word
1108 /// separator since we need `' '` characters between words in order to
1109 /// replace some of them with a `'\n'`. Indentation is also ruled out.
1110 /// In other words, `fill_inplace(width)` behaves as if you had called
1111 /// [`fill`] with these options:
1114 /// # use textwrap::{core, Options, WordSplitter, WordSeparator, WrapAlgorithm};
1115 /// # let width = 80;
1118 /// initial_indent: "",
1119 /// subsequent_indent: "",
1120 /// break_words: false,
1121 /// word_separator: WordSeparator::AsciiSpace,
1122 /// wrap_algorithm: WrapAlgorithm::FirstFit,
1123 /// word_splitter: WordSplitter::NoHyphenation,
1127 /// The wrap algorithm is [`WrapAlgorithm::FirstFit`] since this
1128 /// is the fastest algorithm — and the main reason to use
1129 /// `fill_inplace` is to get the string broken into newlines as fast
1132 /// A last difference is that (unlike [`fill`]) `fill_inplace` can
1133 /// leave trailing whitespace on lines. This is because we wrap by
1134 /// inserting a `'\n'` at the final whitespace in the input string:
1137 /// let mut text = String::from("Hello World!");
1138 /// textwrap::fill_inplace(&mut text, 10);
1139 /// assert_eq!(text, "Hello \nWorld!");
1142 /// If we didn't do this, the word `World!` would end up being
1143 /// indented. You can avoid this if you make sure that your input text
1144 /// has no double spaces.
1148 /// In benchmarks, `fill_inplace` is about twice as fast as [`fill`].
1149 /// Please see the [`linear`
1150 /// benchmark](https://github.com/mgeisler/textwrap/blob/master/benches/linear.rs)
1152 pub fn fill_inplace(text
: &mut String
, width
: usize) {
1153 let mut indices
= Vec
::new();
1156 for line
in text
.split('
\n'
) {
1157 let words
= WordSeparator
::AsciiSpace
1159 .collect
::<Vec
<_
>>();
1160 let wrapped_words
= wrap_algorithms
::wrap_first_fit(&words
, &[width
as f64]);
1162 let mut line_offset
= offset
;
1163 for words
in &wrapped_words
[..wrapped_words
.len() - 1] {
1164 let line_len
= words
1166 .map(|word
| word
.len() + word
.whitespace
.len())
1169 line_offset
+= line_len
;
1170 // We've advanced past all ' ' characters -- want to move
1171 // one ' ' backwards and insert our '\n' there.
1172 indices
.push(line_offset
- 1);
1175 // Advance past entire line, plus the '\n' which was removed
1176 // by the split call above.
1177 offset
+= line
.len() + 1;
1180 let mut bytes
= std
::mem
::take(text
).into_bytes();
1181 for idx
in indices
{
1184 *text
= String
::from_utf8(bytes
).unwrap();
1191 #[cfg(feature = "hyphenation")]
1192 use hyphenation
::{Language, Load, Standard}
;
1195 fn options_agree_with_usize() {
1196 let opt_usize
= Options
::from(42_usize
);
1197 let opt_options
= Options
::new(42);
1199 assert_eq
!(opt_usize
.width
, opt_options
.width
);
1200 assert_eq
!(opt_usize
.initial_indent
, opt_options
.initial_indent
);
1201 assert_eq
!(opt_usize
.subsequent_indent
, opt_options
.subsequent_indent
);
1202 assert_eq
!(opt_usize
.break_words
, opt_options
.break_words
);
1204 opt_usize
.word_splitter
.split_points("hello-world"),
1205 opt_options
.word_splitter
.split_points("hello-world")
1211 assert_eq
!(wrap("foo", 10), vec
!["foo"]);
1216 assert_eq
!(wrap("foo bar baz", 5), vec
!["foo", "bar", "baz"]);
1223 "To be, or not to be, that is the question.",
1224 Options
::new(10).wrap_algorithm(WrapAlgorithm
::FirstFit
)
1226 vec
!["To be, or", "not to be,", "that is", "the", "question."]
1231 fn multiple_words_on_first_line() {
1232 assert_eq
!(wrap("foo bar baz", 10), vec
!["foo bar", "baz"]);
1237 assert_eq
!(wrap("foo", 0), vec
!["f", "o", "o"]);
1242 assert_eq
!(wrap("foo bar", 0), vec
!["f", "o", "o", "b", "a", "r"]);
1247 assert_eq
!(wrap("foo bar", usize::MAX
), vec
!["foo bar"]);
1249 let text
= "Hello there! This is some English text. \
1250 It should not be wrapped given the extents below.";
1251 assert_eq
!(wrap(text
, usize::MAX
), vec
![text
]);
1255 fn leading_whitespace() {
1256 assert_eq
!(wrap(" foo bar", 6), vec
![" foo", "bar"]);
1260 fn leading_whitespace_empty_first_line() {
1261 // If there is no space for the first word, the first line
1262 // will be empty. This is because the string is split into
1263 // words like [" ", "foobar ", "baz"], which puts "foobar " on
1264 // the second line. We never output trailing whitespace
1265 assert_eq
!(wrap(" foobar baz", 6), vec
!["", "foobar", "baz"]);
1269 fn trailing_whitespace() {
1270 // Whitespace is only significant inside a line. After a line
1271 // gets too long and is broken, the first word starts in
1272 // column zero and is not indented.
1273 assert_eq
!(wrap("foo bar baz ", 5), vec
!["foo", "bar", "baz"]);
1278 // We did not reset the in_whitespace flag correctly and did
1279 // not handle single-character words after a line break.
1281 wrap("aaabbbccc x yyyzzzwww", 9),
1282 vec
!["aaabbbccc", "x", "yyyzzzwww"]
1288 // The dash is an em-dash which takes up four bytes. We used
1289 // to panic since we tried to index into the character.
1290 let options
= Options
::new(1).word_separator(WordSeparator
::AsciiSpace
);
1291 assert_eq
!(wrap("x – x", options
), vec
!["x", "–", "x"]);
1295 fn wide_character_handling() {
1296 assert_eq
!(wrap("Hello, World!", 15), vec
!["Hello, World!"]);
1300 Options
::new(15).word_separator(WordSeparator
::AsciiSpace
)
1302 vec
!["Hello,", "World!"]
1305 // Wide characters are allowed to break if the
1306 // unicode-linebreak feature is enabled.
1307 #[cfg(feature = "unicode-linebreak")]
1311 Options
::new(15).word_separator(WordSeparator
::UnicodeBreakProperties
)
1313 vec
!["Hello, W", "orld!"]
1318 fn empty_line_is_indented() {
1319 // Previously, indentation was not applied to empty lines.
1320 // However, this is somewhat inconsistent and undesirable if
1321 // the indentation is something like a border ("| ") which you
1322 // want to apply to all lines, empty or not.
1323 let options
= Options
::new(10).initial_indent("!!!");
1324 assert_eq
!(fill("", &options
), "!!!");
1328 fn indent_single_line() {
1329 let options
= Options
::new(10).initial_indent(">>>"); // No trailing space
1330 assert_eq
!(fill("foo", &options
), ">>>foo");
1334 fn indent_first_emoji() {
1335 let options
= Options
::new(10).initial_indent("👉👉");
1337 wrap("x x x x x x x x x x x x x", &options
),
1338 vec
!["👉👉x x x", "x x x x x", "x x x x x"]
1343 fn indent_multiple_lines() {
1344 let options
= Options
::new(6).initial_indent("* ").subsequent_indent(" ");
1346 wrap("foo bar baz", &options
),
1347 vec
!["* foo", " bar", " baz"]
1352 fn indent_break_words() {
1353 let options
= Options
::new(5).initial_indent("* ").subsequent_indent(" ");
1354 assert_eq
!(wrap("foobarbaz", &options
), vec
!["* foo", " bar", " baz"]);
1358 fn initial_indent_break_words() {
1359 // This is a corner-case showing how the long word is broken
1360 // according to the width of the subsequent lines. The first
1361 // fragment of the word no longer fits on the first line,
1362 // which ends up being pure indentation.
1363 let options
= Options
::new(5).initial_indent("-->");
1364 assert_eq
!(wrap("foobarbaz", &options
), vec
!["-->", "fooba", "rbaz"]);
1369 assert_eq
!(wrap("foo-bar", 5), vec
!["foo-", "bar"]);
1373 fn trailing_hyphen() {
1374 let options
= Options
::new(5).break_words(false);
1375 assert_eq
!(wrap("foobar-", &options
), vec
!["foobar-"]);
1379 fn multiple_hyphens() {
1380 assert_eq
!(wrap("foo-bar-baz", 5), vec
!["foo-", "bar-", "baz"]);
1385 let options
= Options
::new(5).break_words(false);
1387 wrap("The --foo-bar flag.", &options
),
1388 vec
!["The", "--foo-", "bar", "flag."]
1393 fn repeated_hyphens() {
1394 let options
= Options
::new(4).break_words(false);
1395 assert_eq
!(wrap("foo--bar", &options
), vec
!["foo--bar"]);
1399 fn hyphens_alphanumeric() {
1400 assert_eq
!(wrap("Na2-CH4", 5), vec
!["Na2-", "CH4"]);
1404 fn hyphens_non_alphanumeric() {
1405 let options
= Options
::new(5).break_words(false);
1406 assert_eq
!(wrap("foo(-)bar", &options
), vec
!["foo(-)bar"]);
1410 fn multiple_splits() {
1411 assert_eq
!(wrap("foo-bar-baz", 9), vec
!["foo-bar-", "baz"]);
1416 let options
= Options
::new(5).break_words(false);
1417 assert_eq
!(wrap("foobar-baz", &options
), vec
!["foobar-", "baz"]);
1421 fn multiple_unbroken_words_issue_193() {
1422 let options
= Options
::new(3).break_words(false);
1424 wrap("small large tiny", &options
),
1425 vec
!["small", "large", "tiny"]
1428 wrap("small large tiny", &options
),
1429 vec
!["small", "large", "tiny"]
1434 fn very_narrow_lines_issue_193() {
1435 let options
= Options
::new(1).break_words(false);
1436 assert_eq
!(wrap("fooo x y", &options
), vec
!["fooo", "x", "y"]);
1437 assert_eq
!(wrap("fooo x y", &options
), vec
!["fooo", "x", "y"]);
1441 fn simple_hyphens() {
1442 let options
= Options
::new(8).word_splitter(WordSplitter
::HyphenSplitter
);
1443 assert_eq
!(wrap("foo bar-baz", &options
), vec
!["foo bar-", "baz"]);
1447 fn no_hyphenation() {
1448 let options
= Options
::new(8).word_splitter(WordSplitter
::NoHyphenation
);
1449 assert_eq
!(wrap("foo bar-baz", &options
), vec
!["foo", "bar-baz"]);
1453 #[cfg(feature = "hyphenation")]
1454 fn auto_hyphenation_double_hyphenation() {
1455 let dictionary
= Standard
::from_embedded(Language
::EnglishUS
).unwrap();
1456 let options
= Options
::new(10);
1458 wrap("Internationalization", &options
),
1459 vec
!["Internatio", "nalization"]
1462 let options
= Options
::new(10).word_splitter(WordSplitter
::Hyphenation(dictionary
));
1464 wrap("Internationalization", &options
),
1465 vec
!["Interna-", "tionaliza-", "tion"]
1470 #[cfg(feature = "hyphenation")]
1471 fn auto_hyphenation_issue_158() {
1472 let dictionary
= Standard
::from_embedded(Language
::EnglishUS
).unwrap();
1473 let options
= Options
::new(10);
1475 wrap("participation is the key to success", &options
),
1476 vec
!["participat", "ion is", "the key to", "success"]
1479 let options
= Options
::new(10).word_splitter(WordSplitter
::Hyphenation(dictionary
));
1481 wrap("participation is the key to success", &options
),
1482 vec
!["partici-", "pation is", "the key to", "success"]
1487 #[cfg(feature = "hyphenation")]
1488 fn split_len_hyphenation() {
1489 // Test that hyphenation takes the width of the whitespace
1491 let dictionary
= Standard
::from_embedded(Language
::EnglishUS
).unwrap();
1492 let options
= Options
::new(15).word_splitter(WordSplitter
::Hyphenation(dictionary
));
1494 wrap("garbage collection", &options
),
1495 vec
!["garbage col-", "lection"]
1500 #[cfg(feature = "hyphenation")]
1501 fn borrowed_lines() {
1502 // Lines that end with an extra hyphen are owned, the final
1503 // line is borrowed.
1504 use std
::borrow
::Cow
::{Borrowed, Owned}
;
1505 let dictionary
= Standard
::from_embedded(Language
::EnglishUS
).unwrap();
1506 let options
= Options
::new(10).word_splitter(WordSplitter
::Hyphenation(dictionary
));
1507 let lines
= wrap("Internationalization", &options
);
1508 assert_eq
!(lines
, vec
!["Interna-", "tionaliza-", "tion"]);
1509 if let Borrowed(s
) = lines
[0] {
1510 assert
!(false, "should not have been borrowed: {:?}", s
);
1512 if let Borrowed(s
) = lines
[1] {
1513 assert
!(false, "should not have been borrowed: {:?}", s
);
1515 if let Owned(ref s
) = lines
[2] {
1516 assert
!(false, "should not have been owned: {:?}", s
);
1521 #[cfg(feature = "hyphenation")]
1522 fn auto_hyphenation_with_hyphen() {
1523 let dictionary
= Standard
::from_embedded(Language
::EnglishUS
).unwrap();
1524 let options
= Options
::new(8).break_words(false);
1526 wrap("over-caffinated", &options
),
1527 vec
!["over-", "caffinated"]
1530 let options
= options
.word_splitter(WordSplitter
::Hyphenation(dictionary
));
1532 wrap("over-caffinated", &options
),
1533 vec
!["over-", "caffi-", "nated"]
1539 assert_eq
!(wrap("foobarbaz", 3), vec
!["foo", "bar", "baz"]);
1543 fn break_words_wide_characters() {
1544 // Even the poor man's version of `ch_width` counts these
1545 // characters as wide.
1546 let options
= Options
::new(5).word_separator(WordSeparator
::AsciiSpace
);
1547 assert_eq
!(wrap("Hello", options
), vec
!["He", "ll", "o"]);
1551 fn break_words_zero_width() {
1552 assert_eq
!(wrap("foobar", 0), vec
!["f", "o", "o", "b", "a", "r"]);
1556 fn break_long_first_word() {
1557 assert_eq
!(wrap("testx y", 4), vec
!["test", "x y"]);
1561 fn break_words_line_breaks() {
1562 assert_eq
!(fill("ab\ncdefghijkl", 5), "ab\ncdefg\nhijkl");
1563 assert_eq
!(fill("abcdefgh\nijkl", 5), "abcde\nfgh\nijkl");
1567 fn break_words_empty_lines() {
1569 fill("foo\nbar", &Options
::new(2).break_words(false)),
1575 fn preserve_line_breaks() {
1576 assert_eq
!(fill("", 80), "");
1577 assert_eq
!(fill("\n", 80), "\n");
1578 assert_eq
!(fill("\n\n\n", 80), "\n\n\n");
1579 assert_eq
!(fill("test\n", 80), "test\n");
1580 assert_eq
!(fill("test\n\na\n\n", 80), "test\n\na\n\n");
1584 Options
::new(7).wrap_algorithm(WrapAlgorithm
::FirstFit
)
1591 Options
::new(5).wrap_algorithm(WrapAlgorithm
::FirstFit
)
1593 "1 3 5\n7\n1 3 5\n7"
1598 fn preserve_line_breaks_with_whitespace() {
1599 assert_eq
!(fill(" ", 80), "");
1600 assert_eq
!(fill(" \n ", 80), "\n");
1601 assert_eq
!(fill(" \n \n \n ", 80), "\n\n\n");
1605 fn non_breaking_space() {
1606 let options
= Options
::new(5).break_words(false);
1607 assert_eq
!(fill("foo bar baz", &options
), "foo bar baz");
1611 fn non_breaking_hyphen() {
1612 let options
= Options
::new(5).break_words(false);
1613 assert_eq
!(fill("foo‑bar‑baz", &options
), "foo‑bar‑baz");
1618 assert_eq
!(fill("foo bar baz", 10), "foo bar\nbaz");
1622 fn fill_colored_text() {
1623 // The words are much longer than 6 bytes, but they remain
1624 // intact after filling the text.
1625 let green_hello
= "\u{1b}[0m\u{1b}[32mHello\u{1b}[0m";
1626 let blue_world
= "\u{1b}[0m\u{1b}[34mWorld!\u{1b}[0m";
1628 fill(&(String
::from(green_hello
) + " " + &blue_world
), 6),
1629 String
::from(green_hello
) + "\n" + &blue_world
1634 fn fill_unicode_boundary() {
1635 // https://github.com/mgeisler/textwrap/issues/390
1636 fill("\u{1b}!Ͽ", 10);
1640 fn fill_inplace_empty() {
1641 let mut text
= String
::from("");
1642 fill_inplace(&mut text
, 80);
1643 assert_eq
!(text
, "");
1647 fn fill_inplace_simple() {
1648 let mut text
= String
::from("foo bar baz");
1649 fill_inplace(&mut text
, 10);
1650 assert_eq
!(text
, "foo bar\nbaz");
1654 fn fill_inplace_multiple_lines() {
1655 let mut text
= String
::from("Some text to wrap over multiple lines");
1656 fill_inplace(&mut text
, 12);
1657 assert_eq
!(text
, "Some text to\nwrap over\nmultiple\nlines");
1661 fn fill_inplace_long_word() {
1662 let mut text
= String
::from("Internationalization is hard");
1663 fill_inplace(&mut text
, 10);
1664 assert_eq
!(text
, "Internationalization\nis hard");
1668 fn fill_inplace_no_hyphen_splitting() {
1669 let mut text
= String
::from("A well-chosen example");
1670 fill_inplace(&mut text
, 10);
1671 assert_eq
!(text
, "A\nwell-chosen\nexample");
1675 fn fill_inplace_newlines() {
1676 let mut text
= String
::from("foo bar\n\nbaz\n\n\n");
1677 fill_inplace(&mut text
, 10);
1678 assert_eq
!(text
, "foo bar\n\nbaz\n\n\n");
1682 fn fill_inplace_newlines_reset_line_width() {
1683 let mut text
= String
::from("1 3 5\n1 3 5 7 9\n1 3 5 7 9 1 3");
1684 fill_inplace(&mut text
, 10);
1685 assert_eq
!(text
, "1 3 5\n1 3 5 7 9\n1 3 5 7 9\n1 3");
1689 fn fill_inplace_leading_whitespace() {
1690 let mut text
= String
::from(" foo bar baz");
1691 fill_inplace(&mut text
, 10);
1692 assert_eq
!(text
, " foo bar\nbaz");
1696 fn fill_inplace_trailing_whitespace() {
1697 let mut text
= String
::from("foo bar baz ");
1698 fill_inplace(&mut text
, 10);
1699 assert_eq
!(text
, "foo bar\nbaz ");
1703 fn fill_inplace_interior_whitespace() {
1704 // To avoid an unwanted indentation of "baz", it is important
1705 // to replace the final ' ' with '\n'.
1706 let mut text
= String
::from("foo bar baz");
1707 fill_inplace(&mut text
, 10);
1708 assert_eq
!(text
, "foo bar \nbaz");
1712 fn unfill_simple() {
1713 let (text
, options
) = unfill("foo\nbar");
1714 assert_eq
!(text
, "foo bar");
1715 assert_eq
!(options
.width
, 3);
1719 fn unfill_trailing_newlines() {
1720 let (text
, options
) = unfill("foo\nbar\n\n\n");
1721 assert_eq
!(text
, "foo bar\n\n\n");
1722 assert_eq
!(options
.width
, 3);
1726 fn unfill_initial_indent() {
1727 let (text
, options
) = unfill(" foo\nbar\nbaz");
1728 assert_eq
!(text
, "foo bar baz");
1729 assert_eq
!(options
.width
, 5);
1730 assert_eq
!(options
.initial_indent
, " ");
1734 fn unfill_differing_indents() {
1735 let (text
, options
) = unfill(" foo\n bar\n baz");
1736 assert_eq
!(text
, "foo bar baz");
1737 assert_eq
!(options
.width
, 7);
1738 assert_eq
!(options
.initial_indent
, " ");
1739 assert_eq
!(options
.subsequent_indent
, " ");
1743 fn unfill_list_item() {
1744 let (text
, options
) = unfill("* foo\n bar\n baz");
1745 assert_eq
!(text
, "foo bar baz");
1746 assert_eq
!(options
.width
, 5);
1747 assert_eq
!(options
.initial_indent
, "* ");
1748 assert_eq
!(options
.subsequent_indent
, " ");
1752 fn unfill_multiple_char_prefix() {
1753 let (text
, options
) = unfill(" // foo bar\n // baz\n // quux");
1754 assert_eq
!(text
, "foo bar baz quux");
1755 assert_eq
!(options
.width
, 14);
1756 assert_eq
!(options
.initial_indent
, " // ");
1757 assert_eq
!(options
.subsequent_indent
, " // ");
1761 fn unfill_block_quote() {
1762 let (text
, options
) = unfill("> foo\n> bar\n> baz");
1763 assert_eq
!(text
, "foo bar baz");
1764 assert_eq
!(options
.width
, 5);
1765 assert_eq
!(options
.initial_indent
, "> ");
1766 assert_eq
!(options
.subsequent_indent
, "> ");
1770 fn unfill_whitespace() {
1771 assert_eq
!(unfill("foo bar").0, "foo bar");
1775 fn wrap_columns_empty_text() {
1776 assert_eq
!(wrap_columns("", 1, 10, "| ", "", " |"), vec
!["| |"]);
1780 fn wrap_columns_single_column() {
1782 wrap_columns("Foo", 3, 30, "| ", " | ", " |"),
1788 fn wrap_columns_uneven_columns() {
1789 // The gaps take up a total of 5 columns, so the columns are
1790 // (21 - 5)/4 = 4 columns wide:
1792 wrap_columns("Foo Bar Baz Quux", 4, 21, "|", "|", "|"),
1793 vec
!["|Foo |Bar |Baz |Quux|"]
1795 // As the total width increases, the last column absorbs the
1798 wrap_columns("Foo Bar Baz Quux", 4, 24, "|", "|", "|"),
1799 vec
!["|Foo |Bar |Baz |Quux |"]
1801 // Finally, when the width is 25, the columns can be resized
1802 // to a width of (25 - 5)/4 = 5 columns:
1804 wrap_columns("Foo Bar Baz Quux", 4, 25, "|", "|", "|"),
1805 vec
!["|Foo |Bar |Baz |Quux |"]
1810 #[cfg(feature = "unicode-width")]
1811 fn wrap_columns_with_emojis() {
1814 "Words and a few emojis 😍 wrapped in ⓶ columns",
1822 "✨ Words ⚽ wrapped in 👀",
1823 "✨ and a few ⚽ ⓶ columns 👀",
1830 fn wrap_columns_big_gaps() {
1831 // The column width shrinks to 1 because the gaps take up all
1834 wrap_columns("xyz", 2, 10, "----> ", " !!! ", " <----"),
1836 "----> x !!! z <----", //
1844 fn wrap_columns_panic_with_zero_columns() {
1845 wrap_columns("", 0, 10, "", "", "");