textwrap
A Rust library for wrapping, filling, and indenting text, most often used to format command-line output.
Repository Health
Technical Analysis
textwrap is a mature Rust library for wrapping and indenting text so it renders cleanly in a terminal or any fixed-width context. Rather than breaking lines greedily, it uses an optimal-fit algorithm that looks ahead to minimize ragged gaps at the ends of lines.
With nearly 400 million downloads, it is a workhorse dependency for command-line programs that format dynamic output, and it also handles proportional fonts for PDF generation or HTML5 canvas rendering via WebAssembly.
What You Get
wrap()to split text into a vector of lines andfill()to produce a single wrapped string- An optimal-fit line-breaking algorithm that minimizes ragged right edges (via the
smawkfeature) - Unicode-correct width handling and line-break detection out of the box
- Configurable indentation, word splitting, and optional language-aware hyphenation
- Cargo features to disable Unicode or drop optional dependencies for a smaller binary
Common Use Cases
- Formatting CLI help text, tables, and dynamic output to the current terminal width
- Indenting or re-flowing paragraphs of prose to a fixed column count
- Wrapping text drawn in a proportional font for PDF or HTML5 canvas output
- Adding consistent leading indentation to generated or logged text blocks
Under The Hood
Architecture - The crate splits its concerns across focused modules: wrap.rs/fill.rs are the public entry points, core.rs holds the fragment model and width accounting, wrap_algorithms/ implements both the first-fit and optimal-fit (SMAWK) line-breakers, word_separators.rs and word_splitters.rs decide where words may break, indentation.rs/refill.rs handle indent and re-flow, and options.rs ties configuration together. Tech Stack - Rust edition 2021 (MSRV 1.81); default features pull in icu_segmenter for Unicode line breaking, unicode-width for display width, and smawk for optimal fit, all of which are opt-out Cargo features. Code Quality - The library is well-tested (unit tests plus a fuzzing module in fuzzing.rs) and uses version-sync to keep documented versions accurate; the codebase is idiomatic and clearly separated by responsibility. API Design - A two-function happy path (wrap and fill) covers most needs, while an Options builder exposes the full configuration surface, and the crate documentation walks through the algorithm trade-offs with runnable examples.