├── .github ├── FUNDING.yml └── workflows │ └── ci.yml ├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── src ├── error.rs ├── expr.rs ├── lib.rs └── unindent.rs ├── tests ├── compiletest.rs ├── test_concat.rs ├── test_formatdoc.rs ├── test_indoc.rs ├── test_unindent.rs ├── test_writedoc.rs └── ui │ ├── capture-var-nested.rs │ ├── capture-var-nested.stderr │ ├── no-arguments.rs │ ├── no-arguments.stderr │ ├── non-lit.rs │ ├── non-lit.stderr │ ├── non-string.rs │ ├── non-string.stderr │ ├── printdoc-binary.rs │ ├── printdoc-binary.stderr │ ├── printdoc-extra-arg.rs │ ├── printdoc-extra-arg.stderr │ ├── printdoc-no-arg.rs │ ├── printdoc-no-arg.stderr │ ├── printdoc-no-display.rs │ ├── printdoc-no-display.stderr │ ├── printdoc-no-named-arg.rs │ ├── printdoc-no-named-arg.stderr │ ├── three-arguments.rs │ ├── three-arguments.stderr │ ├── two-arguments.rs │ └── two-arguments.stderr └── unindent ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md └── src ├── lib.rs └── unindent.rs /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: dtolnay 2 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | pull_request: 6 | workflow_dispatch: 7 | schedule: [cron: "40 1 * * *"] 8 | 9 | permissions: 10 | contents: read 11 | 12 | env: 13 | RUSTFLAGS: -Dwarnings 14 | 15 | jobs: 16 | pre_ci: 17 | uses: dtolnay/.github/.github/workflows/pre_ci.yml@master 18 | 19 | test: 20 | name: Rust ${{matrix.rust}} 21 | needs: pre_ci 22 | if: needs.pre_ci.outputs.continue 23 | runs-on: ubuntu-latest 24 | strategy: 25 | fail-fast: false 26 | matrix: 27 | rust: [nightly, beta, stable, 1.59.0, 1.56.0] 28 | timeout-minutes: 45 29 | steps: 30 | - uses: actions/checkout@v4 31 | - uses: dtolnay/rust-toolchain@master 32 | with: 33 | toolchain: ${{matrix.rust}} 34 | - name: Enable type layout randomization 35 | run: echo RUSTFLAGS=${RUSTFLAGS}\ -Zrandomize-layout >> $GITHUB_ENV 36 | if: matrix.rust == 'nightly' 37 | - run: cargo check --workspace 38 | - run: cargo test --workspace 39 | if: matrix.rust != '1.56.0' 40 | - uses: actions/upload-artifact@v4 41 | if: matrix.rust == 'nightly' && always() 42 | with: 43 | name: Cargo.lock 44 | path: Cargo.lock 45 | continue-on-error: true 46 | 47 | doc: 48 | name: Documentation 49 | needs: pre_ci 50 | if: needs.pre_ci.outputs.continue 51 | runs-on: ubuntu-latest 52 | timeout-minutes: 45 53 | env: 54 | RUSTDOCFLAGS: -Dwarnings 55 | steps: 56 | - uses: actions/checkout@v4 57 | - uses: dtolnay/rust-toolchain@nightly 58 | - uses: dtolnay/install@cargo-docs-rs 59 | - run: cargo docs-rs 60 | - run: cargo docs-rs -p unindent 61 | 62 | clippy: 63 | name: Clippy 64 | runs-on: ubuntu-latest 65 | if: github.event_name != 'pull_request' 66 | timeout-minutes: 45 67 | steps: 68 | - uses: actions/checkout@v4 69 | - uses: dtolnay/rust-toolchain@clippy 70 | - run: cargo clippy --tests -- -Dclippy::all -Dclippy::pedantic 71 | 72 | miri: 73 | name: Miri 74 | needs: pre_ci 75 | if: needs.pre_ci.outputs.continue 76 | runs-on: ubuntu-latest 77 | timeout-minutes: 45 78 | steps: 79 | - uses: actions/checkout@v4 80 | - uses: dtolnay/rust-toolchain@miri 81 | with: 82 | toolchain: nightly-2025-05-16 # https://github.com/rust-lang/miri/issues/4323 83 | - run: cargo miri setup 84 | - run: cargo miri test 85 | env: 86 | MIRIFLAGS: -Zmiri-strict-provenance 87 | 88 | outdated: 89 | name: Outdated 90 | runs-on: ubuntu-latest 91 | if: github.event_name != 'pull_request' 92 | timeout-minutes: 45 93 | steps: 94 | - uses: actions/checkout@v4 95 | - uses: dtolnay/rust-toolchain@stable 96 | - uses: dtolnay/install@cargo-outdated 97 | - run: cargo outdated --workspace --exit-code 1 98 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | /Cargo.lock 3 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "indoc" 3 | version = "2.0.6" 4 | authors = ["David Tolnay "] 5 | categories = ["rust-patterns", "text-processing", "no-std", "no-std::no-alloc"] 6 | description = "Indented document literals" 7 | documentation = "https://docs.rs/indoc" 8 | edition = "2021" 9 | keywords = ["heredoc", "nowdoc", "multiline", "string", "literal"] 10 | license = "MIT OR Apache-2.0" 11 | repository = "https://github.com/dtolnay/indoc" 12 | rust-version = "1.56" 13 | 14 | [lib] 15 | proc-macro = true 16 | 17 | [dev-dependencies] 18 | rustversion = "1.0" 19 | trybuild = { version = "1.0.49", features = ["diff"] } 20 | unindent = { version = "0.2.3", path = "unindent" } 21 | 22 | [workspace] 23 | members = ["unindent"] 24 | 25 | [package.metadata.docs.rs] 26 | targets = ["x86_64-unknown-linux-gnu"] 27 | rustdoc-args = [ 28 | "--generate-link-to-definition", 29 | "--extern-html-root-url=core=https://doc.rust-lang.org", 30 | "--extern-html-root-url=alloc=https://doc.rust-lang.org", 31 | "--extern-html-root-url=std=https://doc.rust-lang.org", 32 | "--extern-html-root-url=proc_macro=https://doc.rust-lang.org", 33 | ] 34 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Permission is hereby granted, free of charge, to any 2 | person obtaining a copy of this software and associated 3 | documentation files (the "Software"), to deal in the 4 | Software without restriction, including without 5 | limitation the rights to use, copy, modify, merge, 6 | publish, distribute, sublicense, and/or sell copies of 7 | the Software, and to permit persons to whom the Software 8 | is furnished to do so, subject to the following 9 | conditions: 10 | 11 | The above copyright notice and this permission notice 12 | shall be included in all copies or substantial portions 13 | of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 16 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 17 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 18 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 19 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 20 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 21 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 22 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 23 | DEALINGS IN THE SOFTWARE. 24 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Indented Documents (indoc) 2 | ========================== 3 | 4 | [github](https://github.com/dtolnay/indoc) 5 | [crates.io](https://crates.io/crates/indoc) 6 | [docs.rs](https://docs.rs/indoc) 7 | [build status](https://github.com/dtolnay/indoc/actions?query=branch%3Amaster) 8 | 9 | This crate provides a procedural macro for indented string literals. The 10 | `indoc!()` macro takes a multiline string literal and un-indents it at compile 11 | time so the leftmost non-space character is in the first column. 12 | 13 | ```toml 14 | [dependencies] 15 | indoc = "2" 16 | ``` 17 | 18 | *Compiler requirement: rustc 1.56 or greater.* 19 | 20 |
21 | 22 | ## Using indoc 23 | 24 | ```rust 25 | use indoc::indoc; 26 | 27 | fn main() { 28 | let testing = indoc! {" 29 | def hello(): 30 | print('Hello, world!') 31 | 32 | hello() 33 | "}; 34 | let expected = "def hello():\n print('Hello, world!')\n\nhello()\n"; 35 | assert_eq!(testing, expected); 36 | } 37 | ``` 38 | 39 | Indoc also works with raw string literals: 40 | 41 | ```rust 42 | use indoc::indoc; 43 | 44 | fn main() { 45 | let testing = indoc! {r#" 46 | def hello(): 47 | print("Hello, world!") 48 | 49 | hello() 50 | "#}; 51 | let expected = "def hello():\n print(\"Hello, world!\")\n\nhello()\n"; 52 | assert_eq!(testing, expected); 53 | } 54 | ``` 55 | 56 | And byte string literals: 57 | 58 | ```rust 59 | use indoc::indoc; 60 | 61 | fn main() { 62 | let testing = indoc! {b" 63 | def hello(): 64 | print('Hello, world!') 65 | 66 | hello() 67 | "}; 68 | let expected = b"def hello():\n print('Hello, world!')\n\nhello()\n"; 69 | assert_eq!(testing[..], expected[..]); 70 | } 71 | ``` 72 | 73 |
74 | 75 | ## Formatting macros 76 | 77 | The indoc crate exports five additional macros to substitute conveniently for 78 | the standard library's formatting macros: 79 | 80 | - `formatdoc!($fmt, ...)` — equivalent to `format!(indoc!($fmt), ...)` 81 | - `printdoc!($fmt, ...)` — equivalent to `print!(indoc!($fmt), ...)` 82 | - `eprintdoc!($fmt, ...)` — equivalent to `eprint!(indoc!($fmt), ...)` 83 | - `writedoc!($dest, $fmt, ...)` — equivalent to `write!($dest, indoc!($fmt), ...)` 84 | - `concatdoc!(...)` — equivalent to `concat!(...)` with each string literal wrapped in `indoc!` 85 | 86 | ```rust 87 | use indoc::{concatdoc, printdoc}; 88 | 89 | const HELP: &str = concatdoc! {" 90 | Usage: ", env!("CARGO_BIN_NAME"), " [options] 91 | 92 | Options: 93 | -h, --help 94 | "}; 95 | 96 | fn main() { 97 | printdoc! {" 98 | GET {url} 99 | Accept: {mime} 100 | ", 101 | url = "http://localhost:8080", 102 | mime = "application/json", 103 | } 104 | } 105 | ``` 106 | 107 |
108 | 109 | ## Explanation 110 | 111 | The following rules characterize the behavior of the `indoc!()` macro: 112 | 113 | 1. Count the leading spaces of each line, ignoring the first line and any lines 114 | that are empty or contain spaces only. 115 | 2. Take the minimum. 116 | 3. If the first line is empty i.e. the string begins with a newline, remove the 117 | first line. 118 | 4. Remove the computed number of spaces from the beginning of each line. 119 | 120 |
121 | 122 | ## Unindent 123 | 124 | Indoc's indentation logic is available in the `unindent` crate. This may be 125 | useful for processing strings that are not statically known at compile time. 126 | 127 | The crate exposes two functions: 128 | 129 | - `unindent(&str) -> String` 130 | - `unindent_bytes(&[u8]) -> Vec` 131 | 132 | ```rust 133 | use unindent::unindent; 134 | 135 | fn main() { 136 | let indented = " 137 | line one 138 | line two"; 139 | assert_eq!("line one\nline two", unindent(indented)); 140 | } 141 | ``` 142 | 143 |
144 | 145 | #### License 146 | 147 | 148 | Licensed under either of Apache License, Version 149 | 2.0 or MIT license at your option. 150 | 151 | 152 |
153 | 154 | 155 | Unless you explicitly state otherwise, any contribution intentionally submitted 156 | for inclusion in this crate by you, as defined in the Apache-2.0 license, shall 157 | be dual licensed as above, without any additional terms or conditions. 158 | 159 | -------------------------------------------------------------------------------- /src/error.rs: -------------------------------------------------------------------------------- 1 | use proc_macro::{Delimiter, Group, Ident, Literal, Punct, Spacing, Span, TokenStream, TokenTree}; 2 | 3 | pub type Result = std::result::Result; 4 | 5 | pub struct Error { 6 | begin: Span, 7 | end: Span, 8 | msg: String, 9 | } 10 | 11 | impl Error { 12 | pub fn new(span: Span, msg: &str) -> Self { 13 | Self::new2(span, span, msg) 14 | } 15 | 16 | pub fn new2(begin: Span, end: Span, msg: &str) -> Self { 17 | Error { 18 | begin, 19 | end, 20 | msg: msg.to_owned(), 21 | } 22 | } 23 | 24 | pub fn to_compile_error(&self) -> TokenStream { 25 | // compile_error! { $msg } 26 | TokenStream::from_iter(vec![ 27 | TokenTree::Ident(Ident::new("compile_error", self.begin)), 28 | TokenTree::Punct({ 29 | let mut punct = Punct::new('!', Spacing::Alone); 30 | punct.set_span(self.begin); 31 | punct 32 | }), 33 | TokenTree::Group({ 34 | let mut group = Group::new(Delimiter::Brace, { 35 | TokenStream::from_iter(vec![TokenTree::Literal({ 36 | let mut string = Literal::string(&self.msg); 37 | string.set_span(self.end); 38 | string 39 | })]) 40 | }); 41 | group.set_span(self.end); 42 | group 43 | }), 44 | ]) 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/expr.rs: -------------------------------------------------------------------------------- 1 | use crate::error::{Error, Result}; 2 | use proc_macro::token_stream::IntoIter as TokenIter; 3 | use proc_macro::{Spacing, Span, TokenStream, TokenTree}; 4 | use std::iter::{self, Peekable}; 5 | 6 | pub fn parse(input: &mut Peekable, require_comma: bool) -> Result { 7 | #[derive(PartialEq)] 8 | enum Lookbehind { 9 | JointColon, 10 | DoubleColon, 11 | JointHyphen, 12 | Other, 13 | } 14 | 15 | let mut expr = TokenStream::new(); 16 | let mut lookbehind = Lookbehind::Other; 17 | let mut angle_bracket_depth = 0; 18 | 19 | loop { 20 | if angle_bracket_depth == 0 { 21 | match input.peek() { 22 | Some(TokenTree::Punct(punct)) if punct.as_char() == ',' => { 23 | return Ok(expr); 24 | } 25 | _ => {} 26 | } 27 | } 28 | match input.next() { 29 | Some(TokenTree::Punct(punct)) => { 30 | let ch = punct.as_char(); 31 | let spacing = punct.spacing(); 32 | expr.extend(iter::once(TokenTree::Punct(punct))); 33 | lookbehind = match ch { 34 | ':' if lookbehind == Lookbehind::JointColon => Lookbehind::DoubleColon, 35 | ':' if spacing == Spacing::Joint => Lookbehind::JointColon, 36 | '<' if lookbehind == Lookbehind::DoubleColon => { 37 | angle_bracket_depth += 1; 38 | Lookbehind::Other 39 | } 40 | '>' if angle_bracket_depth > 0 && lookbehind != Lookbehind::JointHyphen => { 41 | angle_bracket_depth -= 1; 42 | Lookbehind::Other 43 | } 44 | '-' if spacing == Spacing::Joint => Lookbehind::JointHyphen, 45 | _ => Lookbehind::Other, 46 | }; 47 | } 48 | Some(token) => expr.extend(iter::once(token)), 49 | None => { 50 | return if require_comma { 51 | Err(Error::new( 52 | Span::call_site(), 53 | "unexpected end of macro input", 54 | )) 55 | } else { 56 | Ok(expr) 57 | }; 58 | } 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! [![github]](https://github.com/dtolnay/indoc) [![crates-io]](https://crates.io/crates/indoc) [![docs-rs]](https://docs.rs/indoc) 2 | //! 3 | //! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github 4 | //! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust 5 | //! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs 6 | //! 7 | //!
8 | //! 9 | //! This crate provides a procedural macro for indented string literals. The 10 | //! `indoc!()` macro takes a multiline string literal and un-indents it at 11 | //! compile time so the leftmost non-space character is in the first column. 12 | //! 13 | //! ```toml 14 | //! [dependencies] 15 | //! indoc = "2" 16 | //! ``` 17 | //! 18 | //!
19 | //! 20 | //! # Using indoc 21 | //! 22 | //! ``` 23 | //! use indoc::indoc; 24 | //! 25 | //! fn main() { 26 | //! let testing = indoc! {" 27 | //! def hello(): 28 | //! print('Hello, world!') 29 | //! 30 | //! hello() 31 | //! "}; 32 | //! let expected = "def hello():\n print('Hello, world!')\n\nhello()\n"; 33 | //! assert_eq!(testing, expected); 34 | //! } 35 | //! ``` 36 | //! 37 | //! Indoc also works with raw string literals: 38 | //! 39 | //! ``` 40 | //! use indoc::indoc; 41 | //! 42 | //! fn main() { 43 | //! let testing = indoc! {r#" 44 | //! def hello(): 45 | //! print("Hello, world!") 46 | //! 47 | //! hello() 48 | //! "#}; 49 | //! let expected = "def hello():\n print(\"Hello, world!\")\n\nhello()\n"; 50 | //! assert_eq!(testing, expected); 51 | //! } 52 | //! ``` 53 | //! 54 | //! And byte string literals: 55 | //! 56 | //! ``` 57 | //! use indoc::indoc; 58 | //! 59 | //! fn main() { 60 | //! let testing = indoc! {b" 61 | //! def hello(): 62 | //! print('Hello, world!') 63 | //! 64 | //! hello() 65 | //! "}; 66 | //! let expected = b"def hello():\n print('Hello, world!')\n\nhello()\n"; 67 | //! assert_eq!(testing[..], expected[..]); 68 | //! } 69 | //! ``` 70 | //! 71 | //!

72 | //! 73 | //! # Formatting macros 74 | //! 75 | //! The indoc crate exports five additional macros to substitute conveniently 76 | //! for the standard library's formatting macros: 77 | //! 78 | //! - `formatdoc!($fmt, ...)` — equivalent to `format!(indoc!($fmt), ...)` 79 | //! - `printdoc!($fmt, ...)` — equivalent to `print!(indoc!($fmt), ...)` 80 | //! - `eprintdoc!($fmt, ...)` — equivalent to `eprint!(indoc!($fmt), ...)` 81 | //! - `writedoc!($dest, $fmt, ...)` — equivalent to `write!($dest, indoc!($fmt), ...)` 82 | //! - `concatdoc!(...)` — equivalent to `concat!(...)` with each string literal wrapped in `indoc!` 83 | //! 84 | //! ``` 85 | //! # macro_rules! env { 86 | //! # ($var:literal) => { 87 | //! # "example" 88 | //! # }; 89 | //! # } 90 | //! # 91 | //! use indoc::{concatdoc, printdoc}; 92 | //! 93 | //! const HELP: &str = concatdoc! {" 94 | //! Usage: ", env!("CARGO_BIN_NAME"), " [options] 95 | //! 96 | //! Options: 97 | //! -h, --help 98 | //! "}; 99 | //! 100 | //! fn main() { 101 | //! printdoc! {" 102 | //! GET {url} 103 | //! Accept: {mime} 104 | //! ", 105 | //! url = "http://localhost:8080", 106 | //! mime = "application/json", 107 | //! } 108 | //! } 109 | //! ``` 110 | //! 111 | //!

112 | //! 113 | //! # Explanation 114 | //! 115 | //! The following rules characterize the behavior of the `indoc!()` macro: 116 | //! 117 | //! 1. Count the leading spaces of each line, ignoring the first line and any 118 | //! lines that are empty or contain spaces only. 119 | //! 2. Take the minimum. 120 | //! 3. If the first line is empty i.e. the string begins with a newline, remove 121 | //! the first line. 122 | //! 4. Remove the computed number of spaces from the beginning of each line. 123 | 124 | #![doc(html_root_url = "https://docs.rs/indoc/2.0.6")] 125 | #![allow( 126 | clippy::derive_partial_eq_without_eq, 127 | clippy::from_iter_instead_of_collect, 128 | clippy::module_name_repetitions, 129 | clippy::needless_doctest_main, 130 | clippy::needless_pass_by_value, 131 | clippy::trivially_copy_pass_by_ref, 132 | clippy::type_complexity 133 | )] 134 | 135 | mod error; 136 | mod expr; 137 | #[allow(dead_code)] 138 | mod unindent; 139 | 140 | use crate::error::{Error, Result}; 141 | use crate::unindent::do_unindent; 142 | use proc_macro::token_stream::IntoIter as TokenIter; 143 | use proc_macro::{Delimiter, Group, Ident, Literal, Punct, Spacing, Span, TokenStream, TokenTree}; 144 | use std::iter::{self, Peekable}; 145 | use std::str::FromStr; 146 | 147 | #[derive(Copy, Clone, PartialEq)] 148 | enum Macro { 149 | Indoc, 150 | Format, 151 | Print, 152 | Eprint, 153 | Write, 154 | Concat, 155 | } 156 | 157 | /// Unindent and produce `&'static str` or `&'static [u8]`. 158 | /// 159 | /// Supports normal strings, raw strings, bytestrings, and raw bytestrings. 160 | /// 161 | /// # Example 162 | /// 163 | /// ``` 164 | /// # use indoc::indoc; 165 | /// # 166 | /// // The type of `program` is &'static str 167 | /// let program = indoc! {" 168 | /// def hello(): 169 | /// print('Hello, world!') 170 | /// 171 | /// hello() 172 | /// "}; 173 | /// print!("{}", program); 174 | /// ``` 175 | /// 176 | /// ```text 177 | /// def hello(): 178 | /// print('Hello, world!') 179 | /// 180 | /// hello() 181 | /// ``` 182 | #[proc_macro] 183 | pub fn indoc(input: TokenStream) -> TokenStream { 184 | expand(input, Macro::Indoc) 185 | } 186 | 187 | /// Unindent and call `format!`. 188 | /// 189 | /// Argument syntax is the same as for [`std::format!`]. 190 | /// 191 | /// # Example 192 | /// 193 | /// ``` 194 | /// # use indoc::formatdoc; 195 | /// # 196 | /// let request = formatdoc! {" 197 | /// GET {url} 198 | /// Accept: {mime} 199 | /// ", 200 | /// url = "http://localhost:8080", 201 | /// mime = "application/json", 202 | /// }; 203 | /// println!("{}", request); 204 | /// ``` 205 | /// 206 | /// ```text 207 | /// GET http://localhost:8080 208 | /// Accept: application/json 209 | /// ``` 210 | #[proc_macro] 211 | pub fn formatdoc(input: TokenStream) -> TokenStream { 212 | expand(input, Macro::Format) 213 | } 214 | 215 | /// Unindent and call `print!`. 216 | /// 217 | /// Argument syntax is the same as for [`std::print!`]. 218 | /// 219 | /// # Example 220 | /// 221 | /// ``` 222 | /// # use indoc::printdoc; 223 | /// # 224 | /// printdoc! {" 225 | /// GET {url} 226 | /// Accept: {mime} 227 | /// ", 228 | /// url = "http://localhost:8080", 229 | /// mime = "application/json", 230 | /// } 231 | /// ``` 232 | /// 233 | /// ```text 234 | /// GET http://localhost:8080 235 | /// Accept: application/json 236 | /// ``` 237 | #[proc_macro] 238 | pub fn printdoc(input: TokenStream) -> TokenStream { 239 | expand(input, Macro::Print) 240 | } 241 | 242 | /// Unindent and call `eprint!`. 243 | /// 244 | /// Argument syntax is the same as for [`std::eprint!`]. 245 | /// 246 | /// # Example 247 | /// 248 | /// ``` 249 | /// # use indoc::eprintdoc; 250 | /// # 251 | /// eprintdoc! {" 252 | /// GET {url} 253 | /// Accept: {mime} 254 | /// ", 255 | /// url = "http://localhost:8080", 256 | /// mime = "application/json", 257 | /// } 258 | /// ``` 259 | /// 260 | /// ```text 261 | /// GET http://localhost:8080 262 | /// Accept: application/json 263 | /// ``` 264 | #[proc_macro] 265 | pub fn eprintdoc(input: TokenStream) -> TokenStream { 266 | expand(input, Macro::Eprint) 267 | } 268 | 269 | /// Unindent and call `write!`. 270 | /// 271 | /// Argument syntax is the same as for [`std::write!`]. 272 | /// 273 | /// # Example 274 | /// 275 | /// ``` 276 | /// # use indoc::writedoc; 277 | /// # use std::io::Write; 278 | /// # 279 | /// let _ = writedoc!( 280 | /// std::io::stdout(), 281 | /// " 282 | /// GET {url} 283 | /// Accept: {mime} 284 | /// ", 285 | /// url = "http://localhost:8080", 286 | /// mime = "application/json", 287 | /// ); 288 | /// ``` 289 | /// 290 | /// ```text 291 | /// GET http://localhost:8080 292 | /// Accept: application/json 293 | /// ``` 294 | #[proc_macro] 295 | pub fn writedoc(input: TokenStream) -> TokenStream { 296 | expand(input, Macro::Write) 297 | } 298 | 299 | /// Unindent and call `concat!`. 300 | /// 301 | /// Argument syntax is the same as for [`std::concat!`]. 302 | /// 303 | /// # Example 304 | /// 305 | /// ``` 306 | /// # use indoc::concatdoc; 307 | /// # 308 | /// # macro_rules! env { 309 | /// # ($var:literal) => { 310 | /// # "example" 311 | /// # }; 312 | /// # } 313 | /// # 314 | /// const HELP: &str = concatdoc! {" 315 | /// Usage: ", env!("CARGO_BIN_NAME"), " [options] 316 | /// 317 | /// Options: 318 | /// -h, --help 319 | /// "}; 320 | /// 321 | /// print!("{}", HELP); 322 | /// ``` 323 | /// 324 | /// ```text 325 | /// Usage: example [options] 326 | /// 327 | /// Options: 328 | /// -h, --help 329 | /// ``` 330 | #[proc_macro] 331 | pub fn concatdoc(input: TokenStream) -> TokenStream { 332 | expand(input, Macro::Concat) 333 | } 334 | 335 | fn expand(input: TokenStream, mode: Macro) -> TokenStream { 336 | match try_expand(input, mode) { 337 | Ok(tokens) => tokens, 338 | Err(err) => err.to_compile_error(), 339 | } 340 | } 341 | 342 | fn try_expand(input: TokenStream, mode: Macro) -> Result { 343 | let mut input = input.into_iter().peekable(); 344 | 345 | let prefix = match mode { 346 | Macro::Indoc | Macro::Format | Macro::Print | Macro::Eprint => None, 347 | Macro::Write => { 348 | let require_comma = true; 349 | let mut expr = expr::parse(&mut input, require_comma)?; 350 | expr.extend(iter::once(input.next().unwrap())); // add comma 351 | Some(expr) 352 | } 353 | Macro::Concat => return do_concat(input), 354 | }; 355 | 356 | let first = input.next().ok_or_else(|| { 357 | Error::new( 358 | Span::call_site(), 359 | "unexpected end of macro invocation, expected format string", 360 | ) 361 | })?; 362 | 363 | let preserve_empty_first_line = false; 364 | let unindented_lit = lit_indoc(first, mode, preserve_empty_first_line)?; 365 | 366 | let macro_name = match mode { 367 | Macro::Indoc => { 368 | require_empty_or_trailing_comma(&mut input)?; 369 | return Ok(TokenStream::from(TokenTree::Literal(unindented_lit))); 370 | } 371 | Macro::Format => "format", 372 | Macro::Print => "print", 373 | Macro::Eprint => "eprint", 374 | Macro::Write => "write", 375 | Macro::Concat => unreachable!(), 376 | }; 377 | 378 | // #macro_name! { #unindented_lit #args } 379 | Ok(TokenStream::from_iter(vec![ 380 | TokenTree::Ident(Ident::new(macro_name, Span::call_site())), 381 | TokenTree::Punct(Punct::new('!', Spacing::Alone)), 382 | TokenTree::Group(Group::new( 383 | Delimiter::Brace, 384 | prefix 385 | .unwrap_or_else(TokenStream::new) 386 | .into_iter() 387 | .chain(iter::once(TokenTree::Literal(unindented_lit))) 388 | .chain(input) 389 | .collect(), 390 | )), 391 | ])) 392 | } 393 | 394 | fn do_concat(mut input: Peekable) -> Result { 395 | let mut result = TokenStream::new(); 396 | let mut first = true; 397 | 398 | while input.peek().is_some() { 399 | let require_comma = false; 400 | let mut expr = expr::parse(&mut input, require_comma)?; 401 | let mut expr_tokens = expr.clone().into_iter(); 402 | if let Some(token) = expr_tokens.next() { 403 | if expr_tokens.next().is_none() { 404 | let preserve_empty_first_line = !first; 405 | if let Ok(literal) = lit_indoc(token, Macro::Concat, preserve_empty_first_line) { 406 | result.extend(iter::once(TokenTree::Literal(literal))); 407 | expr = TokenStream::new(); 408 | } 409 | } 410 | } 411 | result.extend(expr); 412 | if let Some(comma) = input.next() { 413 | result.extend(iter::once(comma)); 414 | } else { 415 | break; 416 | } 417 | first = false; 418 | } 419 | 420 | // concat! { #result } 421 | Ok(TokenStream::from_iter(vec![ 422 | TokenTree::Ident(Ident::new("concat", Span::call_site())), 423 | TokenTree::Punct(Punct::new('!', Spacing::Alone)), 424 | TokenTree::Group(Group::new(Delimiter::Brace, result)), 425 | ])) 426 | } 427 | 428 | fn lit_indoc(token: TokenTree, mode: Macro, preserve_empty_first_line: bool) -> Result { 429 | let span = token.span(); 430 | let mut single_token = Some(token); 431 | 432 | while let Some(TokenTree::Group(group)) = single_token { 433 | single_token = if group.delimiter() == Delimiter::None { 434 | let mut token_iter = group.stream().into_iter(); 435 | token_iter.next().xor(token_iter.next()) 436 | } else { 437 | None 438 | }; 439 | } 440 | 441 | let single_token = 442 | single_token.ok_or_else(|| Error::new(span, "argument must be a single string literal"))?; 443 | 444 | let repr = single_token.to_string(); 445 | let is_string = repr.starts_with('"') || repr.starts_with('r'); 446 | let is_byte_string = repr.starts_with("b\"") || repr.starts_with("br"); 447 | 448 | if !is_string && !is_byte_string { 449 | return Err(Error::new(span, "argument must be a single string literal")); 450 | } 451 | 452 | if is_byte_string { 453 | match mode { 454 | Macro::Indoc => {} 455 | Macro::Format | Macro::Print | Macro::Eprint | Macro::Write => { 456 | return Err(Error::new( 457 | span, 458 | "byte strings are not supported in formatting macros", 459 | )); 460 | } 461 | Macro::Concat => { 462 | return Err(Error::new( 463 | span, 464 | "byte strings are not supported in concat macro", 465 | )); 466 | } 467 | } 468 | } 469 | 470 | let begin = repr.find('"').unwrap() + 1; 471 | let end = repr.rfind('"').unwrap(); 472 | let repr = format!( 473 | "{open}{content}{close}", 474 | open = &repr[..begin], 475 | content = do_unindent(&repr[begin..end], preserve_empty_first_line), 476 | close = &repr[end..], 477 | ); 478 | 479 | let mut lit = Literal::from_str(&repr).unwrap(); 480 | lit.set_span(span); 481 | Ok(lit) 482 | } 483 | 484 | fn require_empty_or_trailing_comma(input: &mut Peekable) -> Result<()> { 485 | let first = match input.next() { 486 | Some(TokenTree::Punct(punct)) if punct.as_char() == ',' => match input.next() { 487 | Some(second) => second, 488 | None => return Ok(()), 489 | }, 490 | Some(first) => first, 491 | None => return Ok(()), 492 | }; 493 | let last = input.last(); 494 | 495 | let begin_span = first.span(); 496 | let end_span = last.as_ref().map_or(begin_span, TokenTree::span); 497 | let msg = format!( 498 | "unexpected {token} in macro invocation; indoc argument must be a single string literal", 499 | token = if last.is_some() { "tokens" } else { "token" } 500 | ); 501 | Err(Error::new2(begin_span, end_span, &msg)) 502 | } 503 | -------------------------------------------------------------------------------- /src/unindent.rs: -------------------------------------------------------------------------------- 1 | use std::slice::Split; 2 | 3 | pub fn unindent(s: &str) -> String { 4 | let preserve_empty_first_line = false; 5 | do_unindent(s, preserve_empty_first_line) 6 | } 7 | 8 | // Compute the maximal number of spaces that can be removed from every line, and 9 | // remove them. 10 | pub fn unindent_bytes(s: &[u8]) -> Vec { 11 | let preserve_empty_first_line = false; 12 | do_unindent_bytes(s, preserve_empty_first_line) 13 | } 14 | 15 | pub(crate) fn do_unindent(s: &str, preserve_empty_first_line: bool) -> String { 16 | let bytes = s.as_bytes(); 17 | let unindented = do_unindent_bytes(bytes, preserve_empty_first_line); 18 | String::from_utf8(unindented).unwrap() 19 | } 20 | 21 | fn do_unindent_bytes(s: &[u8], preserve_empty_first_line: bool) -> Vec { 22 | // Document may start either on the same line as opening quote or 23 | // on the next line 24 | let ignore_first_line = 25 | !preserve_empty_first_line && (s.starts_with(b"\n") || s.starts_with(b"\r\n")); 26 | 27 | // Largest number of spaces that can be removed from every 28 | // non-whitespace-only line after the first 29 | let spaces = s 30 | .lines() 31 | .skip(1) 32 | .filter_map(count_spaces) 33 | .min() 34 | .unwrap_or(0); 35 | 36 | let mut result = Vec::with_capacity(s.len()); 37 | for (i, line) in s.lines().enumerate() { 38 | if i > 1 || (i == 1 && !ignore_first_line) { 39 | result.push(b'\n'); 40 | } 41 | if i == 0 { 42 | // Do not un-indent anything on same line as opening quote 43 | result.extend_from_slice(line); 44 | } else if line.len() > spaces { 45 | // Whitespace-only lines may have fewer than the number of spaces 46 | // being removed 47 | result.extend_from_slice(&line[spaces..]); 48 | } 49 | } 50 | result 51 | } 52 | 53 | pub trait Unindent { 54 | type Output; 55 | 56 | fn unindent(&self) -> Self::Output; 57 | } 58 | 59 | impl Unindent for str { 60 | type Output = String; 61 | 62 | fn unindent(&self) -> Self::Output { 63 | unindent(self) 64 | } 65 | } 66 | 67 | impl Unindent for String { 68 | type Output = String; 69 | 70 | fn unindent(&self) -> Self::Output { 71 | unindent(self) 72 | } 73 | } 74 | 75 | impl Unindent for [u8] { 76 | type Output = Vec; 77 | 78 | fn unindent(&self) -> Self::Output { 79 | unindent_bytes(self) 80 | } 81 | } 82 | 83 | impl Unindent for &T { 84 | type Output = T::Output; 85 | 86 | fn unindent(&self) -> Self::Output { 87 | (**self).unindent() 88 | } 89 | } 90 | 91 | // Number of leading spaces in the line, or None if the line is entirely spaces. 92 | fn count_spaces(line: &[u8]) -> Option { 93 | for (i, ch) in line.iter().enumerate() { 94 | if *ch != b' ' && *ch != b'\t' { 95 | return Some(i); 96 | } 97 | } 98 | None 99 | } 100 | 101 | // Based on core::str::StrExt. 102 | trait BytesExt { 103 | fn lines(&self) -> Split bool>; 104 | } 105 | 106 | impl BytesExt for [u8] { 107 | fn lines(&self) -> Split bool> { 108 | fn is_newline(b: &u8) -> bool { 109 | *b == b'\n' 110 | } 111 | let bytestring = if self.starts_with(b"\r\n") { 112 | &self[1..] 113 | } else { 114 | self 115 | }; 116 | bytestring.split(is_newline as fn(&u8) -> bool) 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /tests/compiletest.rs: -------------------------------------------------------------------------------- 1 | #[rustversion::attr(not(nightly), ignore = "requires nightly")] 2 | #[cfg_attr(miri, ignore = "incompatible with miri")] 3 | #[test] 4 | fn ui() { 5 | let t = trybuild::TestCases::new(); 6 | t.compile_fail("tests/ui/*.rs"); 7 | } 8 | -------------------------------------------------------------------------------- /tests/test_concat.rs: -------------------------------------------------------------------------------- 1 | use indoc::concatdoc; 2 | 3 | macro_rules! env { 4 | ($var:literal) => { 5 | "test" 6 | }; 7 | } 8 | 9 | static HELP: &str = concatdoc! {" 10 | Usage: ", env!("CARGO_BIN_NAME"), " [options] 11 | 12 | Options: 13 | -h, --help 14 | "}; 15 | 16 | #[test] 17 | fn test_help() { 18 | let expected = "Usage: test [options]\n\nOptions:\n -h, --help\n"; 19 | assert_eq!(HELP, expected); 20 | } 21 | -------------------------------------------------------------------------------- /tests/test_formatdoc.rs: -------------------------------------------------------------------------------- 1 | use indoc::formatdoc; 2 | 3 | #[test] 4 | fn carriage_return() { 5 | // Every line in the string ends with \r\n 6 | let indoc = formatdoc! {" 7 | {} 8 | 9 | \\{} 10 | {}", 11 | 'a', 'b', 'c' 12 | }; 13 | let expected = "a\n\n \\b\nc"; 14 | assert_eq!(indoc, expected); 15 | } 16 | 17 | #[test] 18 | fn empty_string() { 19 | let indoc = formatdoc! {""}; 20 | let expected = ""; 21 | assert_eq!(indoc, expected); 22 | } 23 | 24 | #[test] 25 | fn joined_first_line() { 26 | let indoc = formatdoc! {"\ 27 | {}", 'a' 28 | }; 29 | let expected = "a"; 30 | assert_eq!(indoc, expected); 31 | } 32 | 33 | #[test] 34 | fn joined_lines() { 35 | let indoc = formatdoc! {" 36 | {}\ 37 | {} 38 | {}\ 39 | {} 40 | {}", 41 | 'a', 'b', 'c', 'd', 'e' 42 | }; 43 | let expected = "ab\ncd\ne"; 44 | assert_eq!(indoc, expected); 45 | } 46 | 47 | #[test] 48 | fn no_leading_newline() { 49 | let indoc = formatdoc! {"{} 50 | {} 51 | {}", 'a', 'b', 'c'}; 52 | let expected = "a\nb\nc"; 53 | assert_eq!(indoc, expected); 54 | } 55 | 56 | #[test] 57 | fn one_line() { 58 | let indoc = formatdoc! {"a"}; 59 | let expected = "a"; 60 | assert_eq!(indoc, expected); 61 | } 62 | 63 | #[test] 64 | fn raw_string() { 65 | let indoc = formatdoc! {r#" 66 | {:?}" 67 | 68 | \\{} 69 | {}"#, 70 | "a", 'b', 'c' 71 | }; 72 | let expected = "\"a\"\"\n\n \\\\b\nc"; 73 | assert_eq!(indoc, expected); 74 | } 75 | 76 | #[test] 77 | fn string() { 78 | let indoc = formatdoc! {" 79 | {} 80 | 81 | \\{} 82 | {}", 83 | 'a', 'b', 'c' 84 | }; 85 | let expected = "a\n\n \\b\nc"; 86 | assert_eq!(indoc, expected); 87 | } 88 | 89 | #[test] 90 | fn string_trailing_newline() { 91 | let indoc = formatdoc! {" 92 | {} 93 | 94 | \\{} 95 | {} 96 | ", 97 | 'a', 'b', 'c' 98 | }; 99 | let expected = "a\n\n \\b\nc\n"; 100 | assert_eq!(indoc, expected); 101 | } 102 | 103 | #[test] 104 | fn trailing_whitespace() { 105 | let indoc = formatdoc! {" 106 | {} {below} 107 | 108 | {} {below} 109 | 110 | {} {below} 111 | 112 | end", 113 | 2, 0, -2, below = "below" 114 | }; 115 | let expected = "2 below\n \n0 below\n\n-2 below\n\nend"; 116 | assert_eq!(indoc, expected); 117 | } 118 | -------------------------------------------------------------------------------- /tests/test_indoc.rs: -------------------------------------------------------------------------------- 1 | use indoc::indoc; 2 | 3 | const HELP: &str = indoc! {" 4 | Usage: ./foo 5 | "}; 6 | 7 | #[test] 8 | fn test_global() { 9 | let expected = "Usage: ./foo\n"; 10 | assert_eq!(HELP, expected); 11 | } 12 | 13 | #[test] 14 | fn byte_string() { 15 | let indoc = indoc! {b" 16 | a 17 | 18 | \\b 19 | c" 20 | }; 21 | let expected = b"a\n\n \\b\nc"; 22 | assert_eq!(indoc, expected); 23 | } 24 | 25 | #[test] 26 | fn carriage_return() { 27 | // Every line in the string ends with \r\n 28 | let indoc = indoc! {" 29 | a 30 | 31 | \\b 32 | c" 33 | }; 34 | let expected = "a\n\n \\b\nc"; 35 | assert_eq!(indoc, expected); 36 | } 37 | 38 | #[test] 39 | fn trailing_comma() { 40 | let indoc = indoc! { 41 | " 42 | test 43 | ", 44 | }; 45 | let expected = "test\n"; 46 | assert_eq!(indoc, expected); 47 | } 48 | 49 | #[test] 50 | fn empty_string() { 51 | let indoc = indoc! {""}; 52 | let expected = ""; 53 | assert_eq!(indoc, expected); 54 | } 55 | 56 | #[test] 57 | fn joined_first_line() { 58 | let indoc = indoc! {"\ 59 | a" 60 | }; 61 | let expected = "a"; 62 | assert_eq!(indoc, expected); 63 | } 64 | 65 | #[test] 66 | fn joined_lines() { 67 | let indoc = indoc! {" 68 | a\ 69 | b 70 | c\ 71 | d 72 | e" 73 | }; 74 | let expected = "ab\ncd\ne"; 75 | assert_eq!(indoc, expected); 76 | } 77 | 78 | #[test] 79 | fn no_leading_newline() { 80 | let indoc = indoc! {"a 81 | b 82 | c"}; 83 | let expected = "a\nb\nc"; 84 | assert_eq!(indoc, expected); 85 | } 86 | 87 | #[test] 88 | fn one_line() { 89 | let indoc = indoc! {"a"}; 90 | let expected = "a"; 91 | assert_eq!(indoc, expected); 92 | } 93 | 94 | #[test] 95 | fn raw_byte_string() { 96 | let indoc = indoc! {br#" 97 | "a" 98 | 99 | \\b 100 | c"# 101 | }; 102 | let expected = b"\"a\"\n\n \\\\b\nc"; 103 | assert_eq!(indoc, expected); 104 | } 105 | 106 | #[test] 107 | fn raw_string() { 108 | let indoc = indoc! {r#" 109 | "a" 110 | 111 | \\b 112 | c"# 113 | }; 114 | let expected = "\"a\"\n\n \\\\b\nc"; 115 | assert_eq!(indoc, expected); 116 | } 117 | 118 | #[test] 119 | fn string() { 120 | let indoc = indoc! {" 121 | a 122 | 123 | \\b 124 | c" 125 | }; 126 | let expected = "a\n\n \\b\nc"; 127 | assert_eq!(indoc, expected); 128 | } 129 | 130 | #[test] 131 | fn string_trailing_newline() { 132 | let indoc = indoc! {" 133 | a 134 | 135 | \\b 136 | c 137 | "}; 138 | let expected = "a\n\n \\b\nc\n"; 139 | assert_eq!(indoc, expected); 140 | } 141 | 142 | #[test] 143 | fn trailing_whitespace() { 144 | let indoc = indoc! {" 145 | 2 below 146 | 147 | 0 below 148 | 149 | -2 below 150 | 151 | end" 152 | }; 153 | let expected = "2 below\n \n0 below\n\n-2 below\n\nend"; 154 | assert_eq!(indoc, expected); 155 | } 156 | 157 | #[test] 158 | fn indoc_as_format_string() { 159 | let s = format!(indoc! {"{}"}, true); 160 | assert_eq!(s, "true"); 161 | } 162 | 163 | #[test] 164 | fn test_metavariable() { 165 | macro_rules! indoc_wrapper { 166 | ($e:expr) => { 167 | indoc!($e) 168 | }; 169 | } 170 | 171 | let indoc = indoc_wrapper! {" 172 | macros, how do they work 173 | "}; 174 | let expected = "macros, how do they work\n"; 175 | assert_eq!(indoc, expected); 176 | } 177 | -------------------------------------------------------------------------------- /tests/test_unindent.rs: -------------------------------------------------------------------------------- 1 | #![allow(clippy::shadow_unrelated)] 2 | 3 | use unindent::{unindent, unindent_bytes, Unindent}; 4 | 5 | #[test] 6 | fn fn_unindent_str() { 7 | let s = " 8 | line one 9 | line two"; 10 | assert_eq!(unindent(s), "line one\nline two"); 11 | 12 | let s = "\n\t\t\tline one\n\t\t\tline two"; 13 | assert_eq!(unindent(s), "line one\nline two"); 14 | } 15 | 16 | #[test] 17 | fn fn_unindent_bytes() { 18 | let b = b" 19 | line one 20 | line two"; 21 | assert_eq!(unindent_bytes(b), b"line one\nline two"); 22 | 23 | let b = b"\n\t\t\tline one\n\t\t\tline two"; 24 | assert_eq!(unindent_bytes(b), b"line one\nline two"); 25 | } 26 | 27 | #[test] 28 | fn trait_unindent_str() { 29 | let s = " 30 | line one 31 | line two"; 32 | assert_eq!(s.unindent(), "line one\nline two"); 33 | 34 | let s = "\n\t\t\tline one\n\t\t\tline two"; 35 | assert_eq!(s.unindent(), "line one\nline two"); 36 | } 37 | 38 | #[test] 39 | fn trait_unindent_bytes() { 40 | let b = b" 41 | line one 42 | line two"; 43 | assert_eq!(b.unindent(), b"line one\nline two"); 44 | 45 | let b = b"\n\t\t\tline one\n\t\t\tline two"; 46 | assert_eq!(b.unindent(), b"line one\nline two"); 47 | } 48 | 49 | #[test] 50 | fn carriage_returns() { 51 | let s = "\r\n\tline one\r\n\tline two"; 52 | assert_eq!(unindent(s), "line one\r\nline two"); 53 | } 54 | -------------------------------------------------------------------------------- /tests/test_writedoc.rs: -------------------------------------------------------------------------------- 1 | #![allow(clippy::if_same_then_else, clippy::let_underscore_untyped)] 2 | 3 | use indoc::writedoc; 4 | use std::fmt::Write as _; 5 | 6 | #[test] 7 | fn test_write_to_string() { 8 | let mut s = String::new(); 9 | writedoc!( 10 | s, 11 | " 12 | one 13 | two 14 | ", 15 | ) 16 | .unwrap(); 17 | 18 | let expected = "one\ntwo\n"; 19 | assert_eq!(s, expected); 20 | } 21 | 22 | #[test] 23 | fn test_format_args() { 24 | let mut s = String::new(); 25 | writedoc!( 26 | s, 27 | " 28 | {} 29 | {} 30 | ", 31 | 0, 32 | 0, 33 | ) 34 | .unwrap(); 35 | 36 | let expected = "0\n0\n"; 37 | assert_eq!(s, expected); 38 | } 39 | 40 | #[test] 41 | fn test_angle_bracket_parsing() { 42 | const ZERO: usize = 0; 43 | 44 | struct Pair(A, B); 45 | impl Pair { 46 | const ONE: usize = 1; 47 | } 48 | 49 | let mut s = String::new(); 50 | let _ = writedoc! { 51 | if ZERO < Pair:: (), ()>::ONE { &mut s } else { &mut s }, 52 | "writedoc", 53 | }; 54 | 55 | let expected = "writedoc"; 56 | assert_eq!(s, expected); 57 | } 58 | -------------------------------------------------------------------------------- /tests/ui/capture-var-nested.rs: -------------------------------------------------------------------------------- 1 | use indoc::indoc; 2 | 3 | fn main() { 4 | let world = "world"; 5 | println!(indoc!("Hello {world}")); 6 | } 7 | -------------------------------------------------------------------------------- /tests/ui/capture-var-nested.stderr: -------------------------------------------------------------------------------- 1 | error: there is no argument named `world` 2 | --> tests/ui/capture-var-nested.rs:5:21 3 | | 4 | 5 | println!(indoc!("Hello {world}")); 5 | | ^^^^^^^^^^^^^^^ 6 | | 7 | = note: did you intend to capture a variable `world` from the surrounding scope? 8 | = note: to avoid ambiguity, `format_args!` cannot capture variables when the format string is expanded from a macro 9 | -------------------------------------------------------------------------------- /tests/ui/no-arguments.rs: -------------------------------------------------------------------------------- 1 | use indoc::indoc; 2 | 3 | fn main() { 4 | indoc!(); 5 | } 6 | -------------------------------------------------------------------------------- /tests/ui/no-arguments.stderr: -------------------------------------------------------------------------------- 1 | error: unexpected end of macro invocation, expected format string 2 | --> tests/ui/no-arguments.rs:4:5 3 | | 4 | 4 | indoc!(); 5 | | ^^^^^^^^ 6 | | 7 | = note: this error originates in the macro `indoc` (in Nightly builds, run with -Z macro-backtrace for more info) 8 | -------------------------------------------------------------------------------- /tests/ui/non-lit.rs: -------------------------------------------------------------------------------- 1 | use indoc::indoc; 2 | 3 | fn main() { 4 | indoc!(fail); 5 | } 6 | -------------------------------------------------------------------------------- /tests/ui/non-lit.stderr: -------------------------------------------------------------------------------- 1 | error: argument must be a single string literal 2 | --> tests/ui/non-lit.rs:4:12 3 | | 4 | 4 | indoc!(fail); 5 | | ^^^^ 6 | -------------------------------------------------------------------------------- /tests/ui/non-string.rs: -------------------------------------------------------------------------------- 1 | use indoc::indoc; 2 | 3 | fn main() { 4 | indoc!(64); 5 | } 6 | -------------------------------------------------------------------------------- /tests/ui/non-string.stderr: -------------------------------------------------------------------------------- 1 | error: argument must be a single string literal 2 | --> tests/ui/non-string.rs:4:12 3 | | 4 | 4 | indoc!(64); 5 | | ^^ 6 | -------------------------------------------------------------------------------- /tests/ui/printdoc-binary.rs: -------------------------------------------------------------------------------- 1 | use indoc::printdoc; 2 | 3 | fn main() { 4 | printdoc!(b""); 5 | } 6 | -------------------------------------------------------------------------------- /tests/ui/printdoc-binary.stderr: -------------------------------------------------------------------------------- 1 | error: byte strings are not supported in formatting macros 2 | --> tests/ui/printdoc-binary.rs:4:15 3 | | 4 | 4 | printdoc!(b""); 5 | | ^^^ 6 | -------------------------------------------------------------------------------- /tests/ui/printdoc-extra-arg.rs: -------------------------------------------------------------------------------- 1 | use indoc::printdoc; 2 | 3 | fn main() { 4 | printdoc!("", 0); 5 | } 6 | -------------------------------------------------------------------------------- /tests/ui/printdoc-extra-arg.stderr: -------------------------------------------------------------------------------- 1 | error: argument never used 2 | --> tests/ui/printdoc-extra-arg.rs:4:19 3 | | 4 | 4 | printdoc!("", 0); 5 | | -- ^ argument never used 6 | | | 7 | | formatting specifier missing 8 | -------------------------------------------------------------------------------- /tests/ui/printdoc-no-arg.rs: -------------------------------------------------------------------------------- 1 | use indoc::printdoc; 2 | 3 | fn main() { 4 | printdoc!("{}"); 5 | } 6 | -------------------------------------------------------------------------------- /tests/ui/printdoc-no-arg.stderr: -------------------------------------------------------------------------------- 1 | error: 1 positional argument in format string, but no arguments were given 2 | --> tests/ui/printdoc-no-arg.rs:4:16 3 | | 4 | 4 | printdoc!("{}"); 5 | | ^^ 6 | -------------------------------------------------------------------------------- /tests/ui/printdoc-no-display.rs: -------------------------------------------------------------------------------- 1 | use indoc::printdoc; 2 | 3 | struct NoDisplay; 4 | 5 | fn main() { 6 | printdoc!("{}", NoDisplay); 7 | } 8 | -------------------------------------------------------------------------------- /tests/ui/printdoc-no-display.stderr: -------------------------------------------------------------------------------- 1 | error[E0277]: `NoDisplay` doesn't implement `std::fmt::Display` 2 | --> tests/ui/printdoc-no-display.rs:6:21 3 | | 4 | 6 | printdoc!("{}", NoDisplay); 5 | | ^^^^^^^^^ `NoDisplay` cannot be formatted with the default formatter 6 | | 7 | = help: the trait `std::fmt::Display` is not implemented for `NoDisplay` 8 | = note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead 9 | = note: this error originates in the macro `$crate::format_args` which comes from the expansion of the macro `printdoc` (in Nightly builds, run with -Z macro-backtrace for more info) 10 | -------------------------------------------------------------------------------- /tests/ui/printdoc-no-named-arg.rs: -------------------------------------------------------------------------------- 1 | use indoc::printdoc; 2 | 3 | fn main() { 4 | printdoc!("{named}"); 5 | } 6 | -------------------------------------------------------------------------------- /tests/ui/printdoc-no-named-arg.stderr: -------------------------------------------------------------------------------- 1 | error[E0425]: cannot find value `named` in this scope 2 | --> tests/ui/printdoc-no-named-arg.rs:4:17 3 | | 4 | 4 | printdoc!("{named}"); 5 | | ^^^^^ not found in this scope 6 | -------------------------------------------------------------------------------- /tests/ui/three-arguments.rs: -------------------------------------------------------------------------------- 1 | use indoc::indoc; 2 | 3 | fn main() { 4 | indoc!(" 5 | a 6 | b 7 | c 8 | " 64 128); 9 | } 10 | -------------------------------------------------------------------------------- /tests/ui/three-arguments.stderr: -------------------------------------------------------------------------------- 1 | error: unexpected tokens in macro invocation; indoc argument must be a single string literal 2 | --> tests/ui/three-arguments.rs:8:11 3 | | 4 | 8 | " 64 128); 5 | | ^^^^^^ 6 | -------------------------------------------------------------------------------- /tests/ui/two-arguments.rs: -------------------------------------------------------------------------------- 1 | use indoc::indoc; 2 | 3 | fn main() { 4 | indoc!(" 5 | a 6 | b 7 | c 8 | " 64); 9 | } 10 | -------------------------------------------------------------------------------- /tests/ui/two-arguments.stderr: -------------------------------------------------------------------------------- 1 | error: unexpected token in macro invocation; indoc argument must be a single string literal 2 | --> tests/ui/two-arguments.rs:8:11 3 | | 4 | 8 | " 64); 5 | | ^^ 6 | -------------------------------------------------------------------------------- /unindent/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "unindent" 3 | version = "0.2.4" 4 | authors = ["David Tolnay "] 5 | categories = ["text-processing"] 6 | description = "Remove a column of leading whitespace from a string" 7 | documentation = "https://docs.rs/unindent" 8 | edition = "2021" 9 | keywords = ["heredoc", "nowdoc", "multiline", "string", "literal"] 10 | license = "MIT OR Apache-2.0" 11 | repository = "https://github.com/dtolnay/indoc" 12 | 13 | [package.metadata.docs.rs] 14 | targets = ["x86_64-unknown-linux-gnu"] 15 | rustdoc-args = [ 16 | "--generate-link-to-definition", 17 | "--extern-html-root-url=core=https://doc.rust-lang.org", 18 | "--extern-html-root-url=alloc=https://doc.rust-lang.org", 19 | "--extern-html-root-url=std=https://doc.rust-lang.org", 20 | ] 21 | -------------------------------------------------------------------------------- /unindent/LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | ../LICENSE-APACHE -------------------------------------------------------------------------------- /unindent/LICENSE-MIT: -------------------------------------------------------------------------------- 1 | ../LICENSE-MIT -------------------------------------------------------------------------------- /unindent/README.md: -------------------------------------------------------------------------------- 1 | # Unindent 2 | 3 | [github](https://github.com/dtolnay/indoc) 4 | [crates.io](https://crates.io/crates/unindent) 5 | [docs.rs](https://docs.rs/unindent) 6 | [build status](https://github.com/dtolnay/indoc/actions?query=branch%3Amaster) 7 | 8 | This crate provides [`indoc`]'s indentation logic for use with strings that are 9 | not statically known at compile time. For unindenting string literals, use 10 | `indoc` instead. 11 | 12 | [`indoc`]: https://github.com/dtolnay/indoc 13 | 14 | This crate exposes two functions: 15 | 16 | - `unindent(&str) -> String` 17 | - `unindent_bytes(&[u8]) -> Vec` 18 | 19 | ```rust 20 | use unindent::unindent; 21 | 22 | fn main() { 23 | let indented = " 24 | line one 25 | line two"; 26 | assert_eq!("line one\nline two", unindent(indented)); 27 | } 28 | ``` 29 | 30 | ## Explanation 31 | 32 | The following rules characterize the behavior of unindent: 33 | 34 | 1. Count the leading spaces of each line, ignoring the first line and any lines 35 | that are empty or contain spaces only. 36 | 2. Take the minimum. 37 | 3. If the first line is empty i.e. the string begins with a newline, remove the 38 | first line. 39 | 4. Remove the computed number of spaces from the beginning of each line. 40 | 41 | This means there are a few equivalent ways to format the same string, so choose 42 | one you like. All of the following result in the string `"line one\nline 43 | two\n"`: 44 | 45 | ``` 46 | unindent(" / unindent( / unindent("line one 47 | line one / "line one / line two 48 | line two / line two / ") 49 | ") / ") / 50 | ``` 51 | 52 | ## License 53 | 54 | Licensed under either of 55 | 56 | * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 57 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 58 | 59 | at your option. 60 | 61 | ### Contribution 62 | 63 | Unless you explicitly state otherwise, any contribution intentionally submitted 64 | for inclusion in Indoc by you, as defined in the Apache-2.0 license, shall be 65 | dual licensed as above, without any additional terms or conditions. 66 | -------------------------------------------------------------------------------- /unindent/src/lib.rs: -------------------------------------------------------------------------------- 1 | //! [![github]](https://github.com/dtolnay/indoc) [![crates-io]](https://crates.io/crates/unindent) [![docs-rs]](https://docs.rs/unindent) 2 | //! 3 | //! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github 4 | //! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust 5 | //! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs 6 | //! 7 | //!
8 | //! 9 | //! ## Unindent 10 | //! 11 | //! This crate provides [`indoc`]'s indentation logic for use with strings that 12 | //! are not statically known at compile time. For unindenting string literals, 13 | //! use `indoc` instead. 14 | //! 15 | //! [`indoc`]: https://github.com/dtolnay/indoc 16 | //! 17 | //! This crate exposes two unindent functions and an extension trait: 18 | //! 19 | //! - `fn unindent(&str) -> String` 20 | //! - `fn unindent_bytes(&[u8]) -> Vec` 21 | //! - `trait Unindent` 22 | //! 23 | //! ``` 24 | //! use unindent::unindent; 25 | //! 26 | //! fn main() { 27 | //! let indented = " 28 | //! line one 29 | //! line two"; 30 | //! assert_eq!("line one\nline two", unindent(indented)); 31 | //! } 32 | //! ``` 33 | //! 34 | //! The `Unindent` extension trait expose the same functionality under an 35 | //! extension method. 36 | //! 37 | //! ``` 38 | //! use unindent::Unindent; 39 | //! 40 | //! fn main() { 41 | //! let indented = format!(" 42 | //! line {} 43 | //! line {}", "one", "two"); 44 | //! assert_eq!("line one\nline two", indented.unindent()); 45 | //! } 46 | //! ``` 47 | 48 | #![doc(html_root_url = "https://docs.rs/unindent/0.2.4")] 49 | #![allow( 50 | clippy::missing_panics_doc, 51 | clippy::module_name_repetitions, 52 | clippy::must_use_candidate, 53 | clippy::needless_doctest_main, 54 | clippy::trivially_copy_pass_by_ref, 55 | clippy::type_complexity 56 | )] 57 | 58 | mod unindent; 59 | 60 | pub use crate::unindent::*; 61 | -------------------------------------------------------------------------------- /unindent/src/unindent.rs: -------------------------------------------------------------------------------- 1 | ../../src/unindent.rs --------------------------------------------------------------------------------