aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorTreehugger Robot <treehugger-gerrit@google.com>2020-09-09 23:21:48 +0000
committerGerrit Code Review <noreply-gerritcodereview@google.com>2020-09-09 23:21:48 +0000
commitc6e89ea6716ecbe6f0dcda01db37002a9a849ba1 (patch)
treecb9f4582cffd12d94b7d5b030a5fb73b1f3edce5
parente588b19a93e53ec8c8660dc116b0768944d41362 (diff)
parent5db8991729c679cb19d18b1e8d40c0220cb663b4 (diff)
downloadtextwrap-c6e89ea6716ecbe6f0dcda01db37002a9a849ba1.tar.gz
Merge "Upgrade rust/crates/textwrap to 0.12.1"
-rw-r--r--.appveyor.yml14
-rw-r--r--.cargo_vcs_info.json2
-rw-r--r--.circleci/config.yml11
-rw-r--r--.travis.yml16
-rw-r--r--Android.bp4
-rw-r--r--CHANGELOG.md180
-rw-r--r--Cargo.toml20
-rw-r--r--METADATA8
-rw-r--r--README.md217
-rw-r--r--benches/linear.rs16
-rw-r--r--examples/hyphenation.rs17
-rw-r--r--examples/layout.rs4
-rw-r--r--examples/termwidth.rs12
-rw-r--r--src/indentation.rs22
-rw-r--r--src/lib.rs235
-rw-r--r--src/splitting.rs17
-rw-r--r--tests/version-numbers.rs14
17 files changed, 495 insertions, 314 deletions
diff --git a/.appveyor.yml b/.appveyor.yml
index 3555d73..10bc961 100644
--- a/.appveyor.yml
+++ b/.appveyor.yml
@@ -3,21 +3,13 @@ environment:
- TOOLCHAIN: stable
- TOOLCHAIN: nightly
-matrix:
- allow_failures:
- - TOOLCHAIN: nightly
-
install:
- ps: Start-FileDownload 'https://static.rust-lang.org/rustup/dist/i686-pc-windows-gnu/rustup-init.exe'
- - rustup-init.exe -y --default-toolchain %TOOLCHAIN%
+ - rustup-init.exe -y --profile minimal --default-toolchain %TOOLCHAIN%
- set PATH=%PATH%;%USERPROFILE%\.cargo\bin
build_script:
- - cargo build --verbose --all-features
+ - cargo build --all-features
test_script:
- - cargo test --verbose --all-features
-
-cache:
- - '%USERPROFILE%\.cargo'
- - target
+ - cargo test --all-features
diff --git a/.cargo_vcs_info.json b/.cargo_vcs_info.json
index 67bb225..fdd0ea1 100644
--- a/.cargo_vcs_info.json
+++ b/.cargo_vcs_info.json
@@ -1,5 +1,5 @@
{
"git": {
- "sha1": "abcd618beae3f74841032aa5b53c1086b0a57ca2"
+ "sha1": "b2247874f041dd601dd3ee28c3dcdfa912da2646"
}
}
diff --git a/.circleci/config.yml b/.circleci/config.yml
index 4f928a6..b3d23b1 100644
--- a/.circleci/config.yml
+++ b/.circleci/config.yml
@@ -1,13 +1,18 @@
version: 2
jobs:
build:
- docker:
- - image: xd009642/tarpaulin
+ machine: true
steps:
- checkout
- run:
+ name: Pull xd009642/tarpaulin
+ command: docker pull xd009642/tarpaulin
+ - run:
name: Generate coverage report
- command: cargo tarpaulin --out Xml --all-features
+ command: >-
+ docker run --security-opt seccomp=unconfined
+ -v $PWD:/volume xd009642/tarpaulin
+ cargo tarpaulin --out Xml --all-features
- run:
name: Upload to codecov.io
command: bash <(curl -s https://codecov.io/bash) -Z -f cobertura.xml
diff --git a/.travis.yml b/.travis.yml
index 156418b..71b1f02 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -2,16 +2,14 @@ language: rust
rust:
- stable
- - beta
- nightly
- - 1.22.0
-cache: cargo
+install:
+ - cargo build --all-features --tests --examples
+ - >
+ if [[ $TRAVIS_RUST_VERSION == "nightly" ]]; then
+ cargo build --all-features --benches
+ fi
script:
- - cargo build --verbose --all-features
- - cargo test --verbose --all-features
-
-matrix:
- allow_failures:
- - rust: nightly
+ - cargo test --all-features
diff --git a/Android.bp b/Android.bp
index 71ee04f..9785e50 100644
--- a/Android.bp
+++ b/Android.bp
@@ -5,11 +5,11 @@ rust_library {
host_supported: true,
crate_name: "textwrap",
srcs: ["src/lib.rs"],
- edition: "2015",
+ edition: "2018",
rustlibs: [
"libunicode_width",
],
}
// dependent_library ["feature_list"]
-// unicode-width-0.1.7 "default"
+// unicode-width-0.1.8 "default"
diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
index 0000000..6527784
--- /dev/null
+++ b/CHANGELOG.md
@@ -0,0 +1,180 @@
+# Changelog
+
+This file lists the most important changes made in each release of
+`textwrap`.
+
+## Version 0.12.1 — July 3rd, 2020
+
+This is a bugfix release.
+
+* Fixed [#176][issue-176]: Mention compile-time wrapping by linking to
+ the [`textwrap-macros` crate].
+* 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.
+
+## Version 0.12.0 — June 26th, 2020
+
+The code has been updated to the [Rust 2018 edition][rust-2018] and
+each new release of `textwrap` will 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_size` feature has been replaced by `terminal_size`. The API
+is unchanged, it is just the name of the Cargo feature that changed.
+
+The `hyphenation` feature 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.
+
+## Version 0.11.0 — December 9th, 2018
+
+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 `dedent` handling of empty lines and
+ trailing newlines. Thanks @bbqsrc!
+* Fixed [#151][issue-151]: Release of version with hyphenation 0.7.
+
+## Version 0.10.0 — April 28th, 2018
+
+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.
+
+## Version 0.9.0 — October 5th, 2017
+
+The dependency on `term_size` is now optional, and by default this
+feature is not enabled. This is a *breaking change* for users of
+`Wrapper::with_termwidth`. Enable the `term_size` feature to restore
+the old functionality.
+
+Added a regression test for the case where `width` is set to
+`usize::MAX`, thanks @Fraser999! All public structs now implement
+`Debug`, thanks @hcpl!
+
+* Fixed [#101][issue-101]: Make `term_size` an optional dependency.
+
+## Version 0.8.0 — September 4th, 2017
+
+The `Wrapper` stuct is now generic over the type of word splitter
+being used. This means less boxing and a nicer API. The
+`Wrapper::word_splitter` method has been removed. This is a *breaking
+API change* if you used the method to change the word splitter.
+
+The `Wrapper` struct has two new methods that will wrap the input text
+lazily: `Wrapper::wrap_iter` and `Wrapper::into_wrap_iter`. Use those
+if you will be iterating over the wrapped lines one by one.
+
+* Fixed [#59][issue-59]: `wrap` could return an iterator. Thanks
+ @hcpl!
+* Fixed [#81][issue-81]: Set `html_root_url`.
+
+## Version 0.7.0 — July 20th, 2017
+
+Version 0.7.0 changes the return type of `Wrapper::wrap` from
+`Vec<String>` to `Vec<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 of `Wrapper::wrap`. Callers of the
+`textwrap::fill` convenience 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_whitespace` option 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.
+
+## Version 0.6.0 — May 22nd, 2017
+
+Version 0.6.0 adds builder methods to `Wrapper` for easy one-line
+initialization and configuration:
+
+```rust
+let wrapper = Wrapper::new(60).break_words(false);
+```
+
+It also add a new `NoHyphenation` word splitter that will never split
+words, not even at existing hyphens.
+
+* Fixed [#28][issue-28]: Support not squeezing whitespace.
+
+## Version 0.5.0 — May 15th, 2017
+
+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 `hyphenation` feature as described
+above. Afterwards, please change your code from
+```rust
+wrapper.corpus = Some(&corpus);
+```
+to
+```rust
+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.
+
+## Version 0.4.0 — January 24th, 2017
+
+Documented complexities and tested these via `cargo bench`.
+
+* Fixed [#13][issue-13]: Immediatedly add word if it fits.
+* Fixed [#14][issue-14]: Avoid splitting on initial hyphens.
+
+## Version 0.3.0 — January 7th, 2017
+
+Added support for automatic hyphenation.
+
+## Version 0.2.0 — December 28th, 2016
+
+Introduced `Wrapper` struct. Added support for wrapping on hyphens.
+
+## Version 0.1.0 — December 17th, 2016
+
+First public release with support for wrapping strings on whitespace.
+
+[rust-2018]: https://doc.rust-lang.org/edition-guide/rust-2018/
+[`textwrap-macros` crate]: https://crates.io/crates/textwrap-macros
+
+[issue-13]: https://github.com/mgeisler/textwrap/issues/13
+[issue-14]: https://github.com/mgeisler/textwrap/issues/14
+[issue-19]: https://github.com/mgeisler/textwrap/issues/19
+[issue-25]: https://github.com/mgeisler/textwrap/issues/25
+[issue-26]: https://github.com/mgeisler/textwrap/issues/26
+[issue-28]: https://github.com/mgeisler/textwrap/issues/28
+[issue-36]: https://github.com/mgeisler/textwrap/issues/36
+[issue-39]: https://github.com/mgeisler/textwrap/issues/39
+[issue-58]: https://github.com/mgeisler/textwrap/issues/58
+[issue-59]: https://github.com/mgeisler/textwrap/issues/59
+[issue-61]: https://github.com/mgeisler/textwrap/issues/61
+[issue-81]: https://github.com/mgeisler/textwrap/issues/81
+[issue-99]: https://github.com/mgeisler/textwrap/issues/99
+[issue-101]: https://github.com/mgeisler/textwrap/issues/101
+[issue-107]: https://github.com/mgeisler/textwrap/issues/107
+[issue-122]: https://github.com/mgeisler/textwrap/issues/122
+[issue-129]: https://github.com/mgeisler/textwrap/issues/129
+[issue-140]: https://github.com/mgeisler/textwrap/issues/140
+[issue-141]: https://github.com/mgeisler/textwrap/issues/141
+[issue-151]: https://github.com/mgeisler/textwrap/issues/151
+[issue-158]: https://github.com/mgeisler/textwrap/issues/158
+[issue-177]: https://github.com/mgeisler/textwrap/issues/177
+[issue-193]: https://github.com/mgeisler/textwrap/issues/193
diff --git a/Cargo.toml b/Cargo.toml
index 4ec570f..0a908ee 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -3,7 +3,7 @@
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
-# to registry (e.g. crates.io) dependencies
+# to registry (e.g., crates.io) dependencies
#
# If you believe there's an error in this file please file an
# issue against the rust-lang/cargo repository. If you're
@@ -11,11 +11,11 @@
# will likely look very different (and much more reasonable)
[package]
+edition = "2018"
name = "textwrap"
-version = "0.11.0"
+version = "0.12.1"
authors = ["Martin Geisler <martin@geisler.net>"]
-exclude = [".dir-locals.el"]
-description = "Textwrap is a small library for word wrapping, indenting, and\ndedenting strings.\n\nYou can use it to format strings (such as help and error messages) for\ndisplay in commandline applications. It is designed to be efficient\nand handle Unicode characters correctly.\n"
+description = "Textwrap is a library for word wrapping, indenting, and dedenting\nstrings.\n\nYou can use it to format strings (such as help and error messages) for\ndisplay in commandline applications. It is designed to be efficient\nand handle Unicode characters correctly.\n"
documentation = "https://docs.rs/textwrap/"
readme = "README.md"
keywords = ["text", "formatting", "wrap", "typesetting", "hyphenation"]
@@ -25,16 +25,16 @@ repository = "https://github.com/mgeisler/textwrap"
[package.metadata.docs.rs]
all-features = true
[dependencies.hyphenation]
-version = "0.7.1"
-features = ["embed_all"]
+version = "0.8"
+features = ["embed_en-us"]
optional = true
-[dependencies.term_size]
-version = "0.3.0"
+[dependencies.terminal_size]
+version = "0.1"
optional = true
[dependencies.unicode-width]
-version = "0.1.3"
+version = "0.1"
[dev-dependencies.lipsum]
version = "0.6"
@@ -45,7 +45,7 @@ version = "0.6"
version = "0.1"
[dev-dependencies.version-sync]
-version = "0.6"
+version = "0.9"
[badges.appveyor]
repository = "mgeisler/textwrap"
diff --git a/METADATA b/METADATA
index 99bb85a..e585ed0 100644
--- a/METADATA
+++ b/METADATA
@@ -7,13 +7,13 @@ third_party {
}
url {
type: ARCHIVE
- value: "https://static.crates.io/crates/textwrap/textwrap-0.11.0.crate"
+ value: "https://static.crates.io/crates/textwrap/textwrap-0.12.1.crate"
}
- version: "0.11.0"
+ version: "0.12.1"
license_type: NOTICE
last_upgrade_date {
year: 2020
- month: 5
- day: 6
+ month: 8
+ day: 27
}
}
diff --git a/README.md b/README.md
index 23a5439..20673a9 100644
--- a/README.md
+++ b/README.md
@@ -1,10 +1,10 @@
# Textwrap
-[![](https://img.shields.io/crates/v/textwrap.svg)][crates-io]
-[![](https://docs.rs/textwrap/badge.svg)][api-docs]
[![](https://travis-ci.org/mgeisler/textwrap.svg?branch=master)][travis-ci]
[![](https://ci.appveyor.com/api/projects/status/github/mgeisler/textwrap?branch=master&svg=true)][appveyor]
[![](https://codecov.io/gh/mgeisler/textwrap/branch/master/graph/badge.svg)][codecov]
+[![](https://img.shields.io/crates/v/textwrap.svg)][crates-io]
+[![](https://docs.rs/textwrap/badge.svg)][api-docs]
Textwrap is a small Rust crate for word wrapping text. You can use it
to format strings for display in commandline applications. The crate
@@ -13,32 +13,42 @@ the [Python textwrap module][py-textwrap].
## Usage
-Add this to your `Cargo.toml`:
+To use `textwrap`, add this to your `Cargo.toml` file:
```toml
[dependencies]
-textwrap = "0.11"
+textwrap = "0.12"
```
-and this to your crate root:
-```rust
-extern crate textwrap;
-```
+This gives you the text wrapping without of the optional features
+listed next.
+
+### `hyphenation`
+
+If you would like to have automatic language-sensitive hyphenation,
+enable the `hyphenation` feature:
-If you would like to have automatic hyphenation, specify the
-dependency as:
```toml
[dependencies]
-textwrap = { version = "0.11", features = ["hyphenation"] }
+textwrap = { version = "0.12", features = ["hyphenation"] }
```
+This gives you hyphenation support for US English. Please see the
+[`hyphenation` example] for an executable demo. Read the Getting
+Started section below to see how to load the hyphenation patterns for
+other languages.
+
+### `terminal_size`
+
To conveniently wrap text at the current terminal width, enable the
-`term_size` feature:
+`terminal_size` feature:
```toml
[dependencies]
-textwrap = { version = "0.11", features = ["term_size"] }
+textwrap = { version = "0.12", features = ["terminal_size"] }
```
+Please see the [`termwidth` example] for how to use this feature.
+
## Documentation
**[API documentation][api-docs]**
@@ -47,12 +57,9 @@ textwrap = { version = "0.11", features = ["term_size"] }
Word wrapping single strings is easy using the `fill` function:
```rust
-extern crate textwrap;
-use textwrap::fill;
-
fn main() {
let text = "textwrap: a small library for wrapping text.";
- println!("{}", fill(text, 18));
+ println!("{}", textwrap::fill(text, 18));
}
```
The output is
@@ -62,13 +69,14 @@ library for
wrapping text.
```
-With the `hyphenation` feature, you can get automatic hyphenation
-for [about 70 languages][patterns]. Your program must load and
-configure the hyphenation patterns to use:
-```rust
-extern crate hyphenation;
-extern crate textwrap;
+If you enable the `hyphenation` feature, you get support for automatic
+hyphenation for [about 70 languages][patterns] via high-quality TeX
+hyphenation patterns.
+
+Your program must load the hyphenation pattern and call
+`Wrapper::with_splitter` to use it:
+```rust
use hyphenation::{Language, Load, Standard};
use textwrap::Wrapper;
@@ -87,7 +95,18 @@ library for wrap-
ping text.
```
-The hyphenation uses high-quality TeX hyphenation patterns.
+The US-English hyphenation patterns are embedded when you enable the
+`hyphenation` feature. They are licensed under a [permissive
+license][en-us license] and take up about 88 KB of space in your
+application. If you need hyphenation for other languages, you need to
+download a [precompiled `.bincode` file][bincode] and load it
+yourself. Please see the [`hyphenation` documentation] for details.
+
+## 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].
+
## Examples
@@ -180,128 +199,8 @@ cost abstractions.
## Release History
-This section lists the largest changes per release.
-
-### Version 0.11.0 — December 9th, 2018
-
-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 `dedent` handling of empty lines and
- trailing newlines. Thanks @bbqsrc!
-* Fixed [#151][issue-151]: Release of version with hyphenation 0.7.
-
-### Version 0.10.0 — April 28th, 2018
-
-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.
-
-### Version 0.9.0 — October 5th, 2017
-
-The dependency on `term_size` is now optional, and by default this
-feature is not enabled. This is a *breaking change* for users of
-`Wrapper::with_termwidth`. Enable the `term_size` feature to restore
-the old functionality.
-
-Added a regression test for the case where `width` is set to
-`usize::MAX`, thanks @Fraser999! All public structs now implement
-`Debug`, thanks @hcpl!
-
-* Fixed [#101][issue-101]: Make `term_size` an optional dependency.
-
-### Version 0.8.0 — September 4th, 2017
-
-The `Wrapper` stuct is now generic over the type of word splitter
-being used. This means less boxing and a nicer API. The
-`Wrapper::word_splitter` method has been removed. This is a *breaking
-API change* if you used the method to change the word splitter.
-
-The `Wrapper` struct has two new methods that will wrap the input text
-lazily: `Wrapper::wrap_iter` and `Wrapper::into_wrap_iter`. Use those
-if you will be iterating over the wrapped lines one by one.
-
-* Fixed [#59][issue-59]: `wrap` could return an iterator. Thanks
- @hcpl!
-* Fixed [#81][issue-81]: Set `html_root_url`.
-
-### Version 0.7.0 — July 20th, 2017
-
-Version 0.7.0 changes the return type of `Wrapper::wrap` from
-`Vec<String>` to `Vec<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 of `Wrapper::wrap`. Callers of the
-`textwrap::fill` convenience 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_whitespace` option 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.
-
-### Version 0.6.0 — May 22nd, 2017
-
-Version 0.6.0 adds builder methods to `Wrapper` for easy one-line
-initialization and configuration:
-
-```rust
-let wrapper = Wrapper::new(60).break_words(false);
-```
-
-It also add a new `NoHyphenation` word splitter that will never split
-words, not even at existing hyphens.
-
-* Fixed [#28][issue-28]: Support not squeezing whitespace.
-
-### Version 0.5.0 — May 15th, 2017
-
-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 `hyphenation` feature as described
-above. Afterwards, please change your code from
-```rust
-wrapper.corpus = Some(&corpus);
-```
-to
-```rust
-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.
-
-### Version 0.4.0 — January 24th, 2017
-
-Documented complexities and tested these via `cargo bench`.
-
-* Fixed [#13][issue-13]: Immediatedly add word if it fits.
-* Fixed [#14][issue-14]: Avoid splitting on initial hyphens.
-
-### Version 0.3.0 — January 7th, 2017
-
-Added support for automatic hyphenation.
-
-### Version 0.2.0 — December 28th, 2016
-
-Introduced `Wrapper` struct. Added support for wrapping on hyphens.
-
-### Version 0.1.0 — December 17th, 2016
-
-First public release with support for wrapping strings on whitespace.
+Please see the [CHANGELOG file] for details on the changes made in
+each release.
## License
@@ -313,25 +212,13 @@ Contributions will be accepted under the same license.
[appveyor]: https://ci.appveyor.com/project/mgeisler/textwrap
[codecov]: https://codecov.io/gh/mgeisler/textwrap
[py-textwrap]: https://docs.python.org/library/textwrap
+[`textwrap-macros` crate]: https://crates.io/crates/textwrap-macros
+[`hyphenation` example]: https://github.com/mgeisler/textwrap/blob/master/examples/hyphenation.rs
+[`termwidth` example]: https://github.com/mgeisler/textwrap/blob/master/examples/termwidth.rs
[patterns]: https://github.com/tapeinosyne/hyphenation/tree/master/patterns-tex
+[en-us license]: https://github.com/hyphenation/tex-hyphen/blob/master/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-en-us.tex
+[bincode]: https://github.com/tapeinosyne/hyphenation/tree/master/dictionaries
+[`hyphenation` documentation]: http://docs.rs/hyphenation
[api-docs]: https://docs.rs/textwrap/
-[issue-13]: https://github.com/mgeisler/textwrap/issues/13
-[issue-14]: https://github.com/mgeisler/textwrap/issues/14
-[issue-19]: https://github.com/mgeisler/textwrap/issues/19
-[issue-25]: https://github.com/mgeisler/textwrap/issues/25
-[issue-26]: https://github.com/mgeisler/textwrap/issues/26
-[issue-28]: https://github.com/mgeisler/textwrap/issues/28
-[issue-36]: https://github.com/mgeisler/textwrap/issues/36
-[issue-39]: https://github.com/mgeisler/textwrap/issues/39
-[issue-58]: https://github.com/mgeisler/textwrap/issues/58
-[issue-59]: https://github.com/mgeisler/textwrap/issues/59
-[issue-61]: https://github.com/mgeisler/textwrap/issues/61
-[issue-81]: https://github.com/mgeisler/textwrap/issues/81
-[issue-99]: https://github.com/mgeisler/textwrap/issues/99
-[issue-101]: https://github.com/mgeisler/textwrap/issues/101
-[issue-107]: https://github.com/mgeisler/textwrap/issues/107
-[issue-122]: https://github.com/mgeisler/textwrap/issues/122
-[issue-129]: https://github.com/mgeisler/textwrap/issues/129
-[issue-141]: https://github.com/mgeisler/textwrap/issues/141
-[issue-151]: https://github.com/mgeisler/textwrap/issues/151
+[CHANGELOG file]: https://github.com/mgeisler/textwrap/blob/master/CHANGELOG.md
[mit]: LICENSE
diff --git a/benches/linear.rs b/benches/linear.rs
index 104398a..7215afa 100644
--- a/benches/linear.rs
+++ b/benches/linear.rs
@@ -3,13 +3,7 @@
// The benchmarks here verify that the complexity grows as O(*n*)
// where *n* is the number of characters in the text to be wrapped.
-#[cfg(feature = "hyphenation")]
-extern crate hyphenation;
-extern crate lipsum;
-extern crate rand;
-extern crate rand_xorshift;
extern crate test;
-extern crate textwrap;
#[cfg(feature = "hyphenation")]
use hyphenation::{Language, Load, Standard};
@@ -17,8 +11,6 @@ use lipsum::MarkovChain;
use rand::SeedableRng;
use rand_xorshift::XorShiftRng;
use test::Bencher;
-#[cfg(feature = "hyphenation")]
-use textwrap::Wrapper;
const LINE_LENGTH: usize = 60;
@@ -90,7 +82,7 @@ fn wrap_800(b: &mut Bencher) {
fn hyphenation_fill_100(b: &mut Bencher) {
let text = &lorem_ipsum(100);
let dictionary = Standard::from_embedded(Language::Latin).unwrap();
- let wrapper = Wrapper::with_splitter(LINE_LENGTH, dictionary);
+ let wrapper = textwrap::Wrapper::with_splitter(LINE_LENGTH, dictionary);
b.iter(|| wrapper.fill(text))
}
@@ -99,7 +91,7 @@ fn hyphenation_fill_100(b: &mut Bencher) {
fn hyphenation_fill_200(b: &mut Bencher) {
let text = &lorem_ipsum(200);
let dictionary = Standard::from_embedded(Language::Latin).unwrap();
- let wrapper = Wrapper::with_splitter(LINE_LENGTH, dictionary);
+ let wrapper = textwrap::Wrapper::with_splitter(LINE_LENGTH, dictionary);
b.iter(|| wrapper.fill(text))
}
@@ -108,7 +100,7 @@ fn hyphenation_fill_200(b: &mut Bencher) {
fn hyphenation_fill_400(b: &mut Bencher) {
let text = &lorem_ipsum(400);
let dictionary = Standard::from_embedded(Language::Latin).unwrap();
- let wrapper = Wrapper::with_splitter(LINE_LENGTH, dictionary);
+ let wrapper = textwrap::Wrapper::with_splitter(LINE_LENGTH, dictionary);
b.iter(|| wrapper.fill(text))
}
@@ -117,6 +109,6 @@ fn hyphenation_fill_400(b: &mut Bencher) {
fn hyphenation_fill_800(b: &mut Bencher) {
let text = &lorem_ipsum(800);
let dictionary = Standard::from_embedded(Language::Latin).unwrap();
- let wrapper = Wrapper::with_splitter(LINE_LENGTH, dictionary);
+ let wrapper = textwrap::Wrapper::with_splitter(LINE_LENGTH, dictionary);
b.iter(|| wrapper.fill(text))
}
diff --git a/examples/hyphenation.rs b/examples/hyphenation.rs
new file mode 100644
index 0000000..aa72fbe
--- /dev/null
+++ b/examples/hyphenation.rs
@@ -0,0 +1,17 @@
+#[cfg(feature = "hyphenation")]
+use hyphenation::{Language, Load, Standard};
+
+#[cfg(not(feature = "hyphenation"))]
+fn main() {
+ println!("Please run this example as");
+ println!();
+ println!(" cargo run --example hyphenation --features hyphenation");
+}
+
+#[cfg(feature = "hyphenation")]
+fn main() {
+ let text = "textwrap: a small library for wrapping text.";
+ let dictionary = Standard::from_embedded(Language::EnglishUS).unwrap();
+ let wrapper = textwrap::Wrapper::with_splitter(18, dictionary);
+ println!("{}", wrapper.fill(text));
+}
diff --git a/examples/layout.rs b/examples/layout.rs
index d36cb3a..ae818a2 100644
--- a/examples/layout.rs
+++ b/examples/layout.rs
@@ -1,8 +1,4 @@
#[cfg(feature = "hyphenation")]
-extern crate hyphenation;
-extern crate textwrap;
-
-#[cfg(feature = "hyphenation")]
use hyphenation::{Language, Load};
use textwrap::Wrapper;
diff --git a/examples/termwidth.rs b/examples/termwidth.rs
index 75db3aa..bd4070b 100644
--- a/examples/termwidth.rs
+++ b/examples/termwidth.rs
@@ -1,18 +1,14 @@
#[cfg(feature = "hyphenation")]
-extern crate hyphenation;
-extern crate textwrap;
-
-#[cfg(feature = "hyphenation")]
use hyphenation::{Language, Load, Standard};
-#[cfg(feature = "term_size")]
+#[cfg(feature = "terminal_size")]
use textwrap::Wrapper;
-#[cfg(not(feature = "term_size"))]
+#[cfg(not(feature = "terminal_size"))]
fn main() {
- println!("Please enable the term_size feature to run this example.");
+ println!("Please enable the terminal_size feature to run this example.");
}
-#[cfg(feature = "term_size")]
+#[cfg(feature = "terminal_size")]
fn main() {
#[cfg(not(feature = "hyphenation"))]
fn new_wrapper<'a>() -> (&'static str, Wrapper<'a, textwrap::HyphenSplitter>) {
diff --git a/src/indentation.rs b/src/indentation.rs
index 276ba10..ca19249 100644
--- a/src/indentation.rs
+++ b/src/indentation.rs
@@ -150,7 +150,7 @@ mod tests {
}
#[test]
- #[cfg_attr(rustfmt, rustfmt_skip)]
+ #[rustfmt::skip]
fn indent_nonempty() {
let x = vec![" foo",
"bar",
@@ -162,7 +162,7 @@ mod tests {
}
#[test]
- #[cfg_attr(rustfmt, rustfmt_skip)]
+ #[rustfmt::skip]
fn indent_empty_line() {
let x = vec![" foo",
"bar",
@@ -181,7 +181,7 @@ mod tests {
}
#[test]
- #[cfg_attr(rustfmt, rustfmt_skip)]
+ #[rustfmt::skip]
fn dedent_multi_line() {
let x = vec![" foo",
" bar",
@@ -193,7 +193,7 @@ mod tests {
}
#[test]
- #[cfg_attr(rustfmt, rustfmt_skip)]
+ #[rustfmt::skip]
fn dedent_empty_line() {
let x = vec![" foo",
" bar",
@@ -207,7 +207,7 @@ mod tests {
}
#[test]
- #[cfg_attr(rustfmt, rustfmt_skip)]
+ #[rustfmt::skip]
fn dedent_blank_line() {
let x = vec![" foo",
"",
@@ -225,7 +225,7 @@ mod tests {
}
#[test]
- #[cfg_attr(rustfmt, rustfmt_skip)]
+ #[rustfmt::skip]
fn dedent_whitespace_line() {
let x = vec![" foo",
" ",
@@ -243,7 +243,7 @@ mod tests {
}
#[test]
- #[cfg_attr(rustfmt, rustfmt_skip)]
+ #[rustfmt::skip]
fn dedent_mixed_whitespace() {
let x = vec!["\tfoo",
" bar"];
@@ -253,7 +253,7 @@ mod tests {
}
#[test]
- #[cfg_attr(rustfmt, rustfmt_skip)]
+ #[rustfmt::skip]
fn dedent_tabbed_whitespace() {
let x = vec!["\t\tfoo",
"\t\t\tbar"];
@@ -263,7 +263,7 @@ mod tests {
}
#[test]
- #[cfg_attr(rustfmt, rustfmt_skip)]
+ #[rustfmt::skip]
fn dedent_mixed_tabbed_whitespace() {
let x = vec!["\t \tfoo",
"\t \t\tbar"];
@@ -273,7 +273,7 @@ mod tests {
}
#[test]
- #[cfg_attr(rustfmt, rustfmt_skip)]
+ #[rustfmt::skip]
fn dedent_mixed_tabbed_whitespace2() {
let x = vec!["\t \tfoo",
"\t \tbar"];
@@ -283,7 +283,7 @@ mod tests {
}
#[test]
- #[cfg_attr(rustfmt, rustfmt_skip)]
+ #[rustfmt::skip]
fn dedent_preserve_no_terminating_newline() {
let x = vec![" foo",
" bar"].join("\n");
diff --git a/src/lib.rs b/src/lib.rs
index 2f82325..7bd3928 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -5,16 +5,13 @@
//! terminal. A quick example:
//!
//! ```no_run
-//! extern crate textwrap;
-//! use textwrap::fill;
-//!
//! fn main() {
//! let text = "textwrap: a small library for wrapping text.";
-//! println!("{}", fill(text, 18));
+//! println!("{}", textwrap::fill(text, 18));
//! }
//! ```
//!
-//! This will display the following output:
+//! When you run this program, it will display the following output:
//!
//! ```text
//! textwrap: a small
@@ -22,6 +19,39 @@
//! wrapping text.
//! ```
//!
+//! If you enable the `hyphenation` feature, you can get automatic
+//! hyphenation for a number of languages:
+//!
+//! ```no_run
+//! # #[cfg(feature = "hyphenation")]
+//! use hyphenation::{Language, Load, Standard};
+//! use textwrap::Wrapper;
+//!
+//! # #[cfg(feature = "hyphenation")]
+//! fn main() {
+//! let text = "textwrap: a small library for wrapping text.";
+//! let dictionary = Standard::from_embedded(Language::EnglishUS).unwrap();
+//! let wrapper = Wrapper::with_splitter(18, dictionary);
+//! println!("{}", wrapper.fill(text));
+//! }
+//!
+//! # #[cfg(not(feature = "hyphenation"))]
+//! # fn main() { }
+//! ```
+//!
+//! The program will now output:
+//!
+//! ```text
+//! 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
@@ -39,17 +69,29 @@
//! byte count when computing line lengths. All functions in this
//! library handle Unicode characters like this.
//!
+//! # Cargo Features
+//!
+//! The library has two optional features:
+//!
+//! * `terminal_size`: enables automatic detection of the terminal
+//! width via the [terminal_size][] crate. See the
+//! [`Wrapper::with_termwidth`] constructor for details.
+//!
+//! * `hyphenation`: enables language-sentive hyphenation via the
+//! [hyphenation][] crate. See the [`WordSplitter`] trait for
+//! details.
+//!
+//! [`textwrap-macros` crate]: https://crates.io/crates/textwrap-macros
//! [unicode-width]: https://docs.rs/unicode-width/
+//! [terminal_size]: https://crates.io/crates/terminal_size
+//! [hyphenation]: https://crates.io/crates/hyphenation
+//! [`Wrapper::with_termwidth`]: struct.Wrapper.html#method.with_termwidth
+//! [`WordSplitter`]: trait.WordSplitter.html
-#![doc(html_root_url = "https://docs.rs/textwrap/0.11.0")]
+#![doc(html_root_url = "https://docs.rs/textwrap/0.12.1")]
#![deny(missing_docs)]
#![deny(missing_debug_implementations)]
-
-#[cfg(feature = "hyphenation")]
-extern crate hyphenation;
-#[cfg(feature = "term_size")]
-extern crate term_size;
-extern crate unicode_width;
+#![allow(clippy::redundant_field_names)]
use std::borrow::Cow;
use std::str::CharIndices;
@@ -60,12 +102,19 @@ use unicode_width::UnicodeWidthStr;
/// A non-breaking space.
const NBSP: char = '\u{a0}';
+/// The CSI or "Control Sequence Introducer" introduces an ANSI escape
+/// sequence. This is typically used for colored text and will be
+/// ignored when computing the text width.
+const CSI: (char, char) = ('\u{1b}', '[');
+/// The final bytes of an ANSI escape sequence must be in this range.
+const ANSI_FINAL_BYTE: std::ops::RangeInclusive<char> = '\x40'..='\x7e';
+
mod indentation;
-pub use indentation::dedent;
-pub use indentation::indent;
+pub use crate::indentation::dedent;
+pub use crate::indentation::indent;
mod splitting;
-pub use splitting::{HyphenSplitter, NoHyphenation, WordSplitter};
+pub use crate::splitting::{HyphenSplitter, NoHyphenation, WordSplitter};
/// A Wrapper holds settings for wrapping and filling text. Use it
/// when the convenience [`wrap_iter`], [`wrap`] and [`fill`] functions
@@ -124,7 +173,10 @@ impl<'a> Wrapper<'a, HyphenSplitter> {
///
/// let wrapper = Wrapper::new(termwidth());
/// ```
- #[cfg(feature = "term_size")]
+ ///
+ /// **Note:** Only available when the `terminal_size` feature is
+ /// enabled.
+ #[cfg(feature = "terminal_size")]
pub fn with_termwidth() -> Wrapper<'a, HyphenSplitter> {
Wrapper::new(termwidth())
}
@@ -206,9 +258,7 @@ impl<'a, S: WordSplitter> Wrapper<'a, S> {
}
}
- /// Fill a line of text at `self.width` characters. Strings are
- /// wrapped based on their displayed width, not their size in
- /// bytes.
+ /// Fill a line of text at `self.width` characters.
///
/// The result is a string with newlines between each line. Use
/// the `wrap` method if you need access to the individual lines.
@@ -243,9 +293,7 @@ impl<'a, S: WordSplitter> Wrapper<'a, S> {
result
}
- /// Wrap a line of text at `self.width` characters. Strings are
- /// wrapped based on their displayed width, not their size in
- /// bytes.
+ /// Wrap a line of text at `self.width` characters.
///
/// # Complexities
///
@@ -286,9 +334,7 @@ impl<'a, S: WordSplitter> Wrapper<'a, S> {
self.wrap_iter(s).collect::<Vec<_>>()
}
- /// Lazily wrap a line of text at `self.width` characters. Strings
- /// are wrapped based on their displayed width, not their size in
- /// bytes.
+ /// Lazily wrap a line of text at `self.width` characters.
///
/// The [`WordSplitter`] stored in [`self.splitter`] is used
/// whenever when a word is too large to fit on the current line.
@@ -310,18 +356,18 @@ impl<'a, S: WordSplitter> Wrapper<'a, S> {
/// # Examples
///
/// ```
- /// use std::borrow::Cow;
+ /// use std::borrow::Cow::Borrowed;
/// 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(), Some(Borrowed("Zero-cost")));
+ /// assert_eq!(wrap20_iter.next(), Some(Borrowed("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(), Some(Borrowed("Zero-cost abstractions.")));
/// assert_eq!(wrap25_iter.next(), None);
/// ```
///
@@ -335,9 +381,7 @@ impl<'a, S: WordSplitter> Wrapper<'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.
+ /// Lazily wrap a line of text at `self.width` characters.
///
/// The [`WordSplitter`] stored in [`self.splitter`] is used
/// whenever when a word is too large to fit on the current line.
@@ -354,13 +398,13 @@ impl<'a, S: WordSplitter> Wrapper<'a, S> {
/// # Examples
///
/// ```
- /// use std::borrow::Cow;
+ /// use std::borrow::Cow::Borrowed;
/// 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(), Some(Borrowed("Zero-cost")));
+ /// assert_eq!(wrap20_iter.next(), Some(Borrowed("abstractions.")));
/// assert_eq!(wrap20_iter.next(), None);
/// ```
///
@@ -410,7 +454,7 @@ impl<'a, S: WordSplitter> Iterator for IntoWrapIter<'a, S> {
///
/// [`Wrapper::wrap_iter`]: struct.Wrapper.html#method.wrap_iter
#[derive(Debug)]
-pub struct WrapIter<'w, 'a: 'w, S: WordSplitter + 'w> {
+pub struct WrapIter<'w, 'a: 'w, S: WordSplitter> {
wrapper: &'w Wrapper<'a, S>,
inner: WrapIterImpl<'a>,
}
@@ -481,9 +525,23 @@ impl<'a> WrapIterImpl<'a> {
}
while let Some((idx, ch)) = self.char_indices.next() {
+ if ch == CSI.0 && self.char_indices.next().map(|(_, ch)| ch) == Some(CSI.1) {
+ // We have found the start of an ANSI escape code,
+ // typically used for colored text. We ignore all
+ // characters until we find a "final byte" in the
+ // range 0x40–0x7E.
+ while let Some((_, ch)) = self.char_indices.next() {
+ if ANSI_FINAL_BYTE.contains(&ch) {
+ break;
+ }
+ }
+ // Done with the escape sequence, we continue with
+ // next character in the outer loop.
+ continue;
+ }
+
let char_width = ch.width().unwrap_or(0);
let char_len = ch.len_utf8();
-
if ch == '\n' {
self.split = idx;
self.split_len = char_len;
@@ -529,15 +587,21 @@ impl<'a> WrapIterImpl<'a> {
// Advance the split point by the width of the
// whitespace and the head length.
self.split += self.split_len + head.len();
- self.split_len = 0;
+ // The new `split_len` is equal to the stretch
+ // of whitespace following the split.
+ self.split_len = remaining_text[head.len()..]
+ .char_indices()
+ .skip_while(|(_, ch)| is_whitespace(*ch))
+ .next()
+ .map_or(0, |(idx, _)| idx);
+ self.line_width_at_split += head.width() + hyp.width();
hyphen = hyp;
break;
}
}
if self.start >= self.split {
- // The word is too big to fit on a single line, so we
- // need to split it at the current index.
+ // The word is too big to fit on a single line.
if wrapper.break_words {
// Break work at current index.
self.split = idx;
@@ -545,8 +609,14 @@ impl<'a> WrapIterImpl<'a> {
self.line_width_at_split = self.line_width;
} else {
// Add smallest split.
- self.split = self.start + splits[0].0.len();
- self.split_len = 0;
+ self.split += self.split_len + splits[0].0.len();
+ // The new `split_len` is equal to the stretch
+ // of whitespace following the smallest split.
+ self.split_len = remaining_text[splits[0].0.len()..]
+ .char_indices()
+ .skip_while(|(_, ch)| is_whitespace(*ch))
+ .next()
+ .map_or(0, |(idx, _)| idx);
self.line_width_at_split = self.line_width;
}
}
@@ -560,6 +630,7 @@ impl<'a> WrapIterImpl<'a> {
self.line_width += wrapper.subsequent_indent.width();
self.line_width -= self.line_width_at_split;
self.line_width += char_width;
+ self.line_width_at_split = wrapper.subsequent_indent.width();
return Some(line);
}
@@ -600,13 +671,15 @@ impl<'a> WrapIterImpl<'a> {
/// .initial_indent(" ")
/// .subsequent_indent(" ");
/// ```
-#[cfg(feature = "term_size")]
+///
+/// **Note:** Only available when the `terminal_size` feature is
+/// enabled.
+#[cfg(feature = "terminal_size")]
pub fn termwidth() -> usize {
- term_size::dimensions_stdout().map_or(80, |(w, _)| w)
+ terminal_size::terminal_size().map_or(80, |(terminal_size::Width(w), _)| w.into())
}
-/// Fill a line of text at `width` characters. Strings are wrapped
-/// based on their displayed width, not their size in bytes.
+/// Fill a line of text at `width` characters.
///
/// The result is a string with newlines between each line. Use
/// [`wrap`] if you need access to the individual lines or
@@ -631,8 +704,7 @@ pub fn fill(s: &str, width: usize) -> String {
Wrapper::new(width).fill(s)
}
-/// Wrap a line of text at `width` characters. Strings are wrapped
-/// based on their displayed width, not their size in bytes.
+/// Wrap a line of text at `width` characters.
///
/// This function creates a Wrapper on the fly with default settings.
/// If you need to set a language corpus for automatic hyphenation, or
@@ -659,12 +731,11 @@ pub fn fill(s: &str, width: usize) -> String {
///
/// [`wrap_iter`]: fn.wrap_iter.html
/// [`wrap` method]: struct.Wrapper.html#method.wrap
-pub fn wrap(s: &str, width: usize) -> Vec<Cow<str>> {
+pub fn wrap(s: &str, width: usize) -> Vec<Cow<'_, str>> {
Wrapper::new(width).wrap(s)
}
-/// Lazily wrap a line of text at `width` characters. Strings are
-/// wrapped based on their displayed width, not their size in bytes.
+/// Lazily wrap a line of text at `width` characters.
///
/// This function creates a Wrapper on the fly with default settings.
/// It then calls the [`into_wrap_iter`] method. Hence, the return
@@ -678,16 +749,16 @@ pub fn wrap(s: &str, width: usize) -> Vec<Cow<str>> {
/// # Examples
///
/// ```
-/// use std::borrow::Cow;
+/// use std::borrow::Cow::Borrowed;
/// use textwrap::wrap_iter;
///
/// let mut wrap20_iter = wrap_iter("Zero-cost abstractions.", 20);
-/// assert_eq!(wrap20_iter.next(), Some(Cow::from("Zero-cost")));
-/// assert_eq!(wrap20_iter.next(), Some(Cow::from("abstractions.")));
+/// assert_eq!(wrap20_iter.next(), Some(Borrowed("Zero-cost")));
+/// assert_eq!(wrap20_iter.next(), Some(Borrowed("abstractions.")));
/// assert_eq!(wrap20_iter.next(), None);
///
/// let mut wrap25_iter = wrap_iter("Zero-cost abstractions.", 25);
-/// assert_eq!(wrap25_iter.next(), Some(Cow::from("Zero-cost abstractions.")));
+/// assert_eq!(wrap25_iter.next(), Some(Borrowed("Zero-cost abstractions.")));
/// assert_eq!(wrap25_iter.next(), None);
/// ```
///
@@ -695,15 +766,12 @@ pub fn wrap(s: &str, width: usize) -> Vec<Cow<str>> {
/// [`into_wrap_iter`]: struct.Wrapper.html#method.into_wrap_iter
/// [`IntoWrapIter`]: struct.IntoWrapIter.html
/// [`WrapIter`]: struct.WrapIter.html
-pub fn wrap_iter(s: &str, width: usize) -> IntoWrapIter<HyphenSplitter> {
+pub fn wrap_iter(s: &str, width: usize) -> IntoWrapIter<'_, HyphenSplitter> {
Wrapper::new(width).into_wrap_iter(s)
}
#[cfg(test)]
mod tests {
- #[cfg(feature = "hyphenation")]
- extern crate hyphenation;
-
use super::*;
#[cfg(feature = "hyphenation")]
use hyphenation::{Language, Load, Standard};
@@ -866,6 +934,26 @@ mod tests {
}
#[test]
+ fn multiple_unbroken_words_issue_193() {
+ let wrapper = Wrapper::new(3).break_words(false);
+ assert_eq!(
+ wrapper.wrap("small large tiny"),
+ vec!["small", "large", "tiny"]
+ );
+ assert_eq!(
+ wrapper.wrap("small large tiny"),
+ vec!["small", "large", "tiny"]
+ );
+ }
+
+ #[test]
+ fn very_narrow_lines_issue_193() {
+ let wrapper = Wrapper::new(1).break_words(false);
+ assert_eq!(wrapper.wrap("fooo x y"), vec!["fooo", "x", "y"]);
+ assert_eq!(wrapper.wrap("fooo x y"), vec!["fooo", "x", "y"]);
+ }
+
+ #[test]
fn no_hyphenation() {
let wrapper = Wrapper::with_splitter(8, NoHyphenation);
assert_eq!(wrapper.wrap("foo bar-baz"), vec!["foo", "bar-baz"]);
@@ -890,6 +978,23 @@ mod tests {
#[test]
#[cfg(feature = "hyphenation")]
+ fn auto_hyphenation_issue_158() {
+ let dictionary = Standard::from_embedded(Language::EnglishUS).unwrap();
+ let wrapper = Wrapper::new(10);
+ assert_eq!(
+ wrapper.wrap("participation is the key to success"),
+ vec!["participat", "ion is the", "key to", "success"]
+ );
+
+ let wrapper = Wrapper::with_splitter(10, dictionary);
+ assert_eq!(
+ wrapper.wrap("participation is the key to success"),
+ vec!["participa-", "tion is the", "key to", "success"]
+ );
+ }
+
+ #[test]
+ #[cfg(feature = "hyphenation")]
fn split_len_hyphenation() {
// Test that hyphenation takes the width of the wihtespace
// into account.
@@ -984,4 +1089,16 @@ mod tests {
fn fill_simple() {
assert_eq!(fill("foo bar baz", 10), "foo bar\nbaz");
}
+
+ #[test]
+ fn fill_colored_text() {
+ // The words are much longer than 6 bytes, but they remain
+ // intact after filling the text.
+ let green_hello = "\u{1b}[0m\u{1b}[32mHello\u{1b}[0m";
+ let blue_world = "\u{1b}[0m\u{1b}[34mWorld!\u{1b}[0m";
+ assert_eq!(
+ fill(&(String::from(green_hello) + " " + &blue_world), 6),
+ String::from(green_hello) + "\n" + &blue_world
+ );
+ }
}
diff --git a/src/splitting.rs b/src/splitting.rs
index f6b65af..fc9f9d4 100644
--- a/src/splitting.rs
+++ b/src/splitting.rs
@@ -5,9 +5,6 @@
//! functionality. [`HyphenSplitter`] is the default implementation of
//! this treat: it will simply split words on existing hyphens.
-#[cfg(feature = "hyphenation")]
-use hyphenation::{Hyphenator, Standard};
-
/// An interface for splitting words.
///
/// When the [`wrap_iter`] method will try to fit text into a line, it
@@ -18,7 +15,7 @@ use hyphenation::{Hyphenator, Standard};
///
/// If the `textwrap` crate has been compiled with the `hyphenation`
/// feature enabled, you will find an implementation of `WordSplitter`
-/// by the `hyphenation::language::Corpus` struct. Use this struct for
+/// by the `hyphenation::Standard` struct. Use this struct for
/// language-aware hyphenation. See the [`hyphenation` documentation]
/// for details.
///
@@ -27,9 +24,9 @@ use hyphenation::{Hyphenator, Standard};
/// [`hyphenation` documentation]: https://docs.rs/hyphenation/
pub trait WordSplitter {
/// Return all possible splits of word. Each split is a triple
- /// with a head, a hyphen, and a tail where `head + &hyphen +
- /// &tail == word`. The hyphen can be empty if there is already a
- /// hyphen in the head.
+ /// with a head, a hyphen, and a tail where `head + &tail == word`.
+ /// The hyphen can be empty if there is already a hyphen in the
+ /// head.
///
/// The splits should go from smallest to longest and should
/// include no split at all. So the word "technology" could be
@@ -121,9 +118,13 @@ impl WordSplitter for HyphenSplitter {
/// A hyphenation dictionary can be used to do language-specific
/// hyphenation using patterns from the hyphenation crate.
+///
+/// **Note:** Only available when the `hyphenation` feature is
+/// enabled.
#[cfg(feature = "hyphenation")]
-impl WordSplitter for Standard {
+impl WordSplitter for hyphenation::Standard {
fn split<'w>(&self, word: &'w str) -> Vec<(&'w str, &'w str, &'w str)> {
+ use hyphenation::Hyphenator;
// Find splits based on language dictionary.
let mut triples = Vec::new();
for n in self.hyphenate(word).breaks {
diff --git a/tests/version-numbers.rs b/tests/version-numbers.rs
index 85c52e3..3429514 100644
--- a/tests/version-numbers.rs
+++ b/tests/version-numbers.rs
@@ -1,17 +1,17 @@
-#[macro_use]
-extern crate version_sync;
-
#[test]
fn test_readme_deps() {
- assert_markdown_deps_updated!("README.md");
+ version_sync::assert_markdown_deps_updated!("README.md");
}
#[test]
-fn test_readme_changelog() {
- assert_contains_regex!("README.md", r"^### Version {version} — .* \d\d?.., 20\d\d$");
+fn test_changelog() {
+ version_sync::assert_contains_regex!(
+ "CHANGELOG.md",
+ r"^## Version {version} — .* \d\d?.., 20\d\d$"
+ );
}
#[test]
fn test_html_root_url() {
- assert_html_root_url_updated!("src/lib.rs");
+ version_sync::assert_html_root_url_updated!("src/lib.rs");
}