#indentation #string-literal #string #proc-macro #string-formatting #formatting

macro dedent

Procedural macro for stripping indentation from multi-line string literals

2 releases

0.1.1 Nov 3, 2024
0.1.0 Nov 3, 2024

#755 in Text processing

Download history 202/week @ 2024-10-28 173/week @ 2024-11-04 317/week @ 2024-11-11 364/week @ 2024-11-18 139/week @ 2024-11-25 398/week @ 2024-12-02 240/week @ 2024-12-09

1,142 downloads per month

MIT license

7KB

dedent

A Rust procedural macro for stripping whitespace from multi-line string literals while preserving relative indentation.

Features

  • ๐Ÿ“ Preserves relative indentation between lines
  • ๐Ÿงน Trims leading and trailing empty lines

Usage

use dedent::dedent;

fn main() {
    // Basic usage
    let code = dedent!(r#"
        fn main() {
            println!("Hello, world!");
        }
    "#);
    
    println!("{}", code);
    // Output:
    // fn main() {
    //     println!("Hello, world!");
    // }

    // Works with varying indentation
    let text = dedent!(r#"
        First line
          Indented line
            More indented
        Back to start
    "#);
    
    println!("{}", text);
    // Output:
    // First line
    //   Indented line
    //     More indented
    // Back to start
}

How It Works

The dedent! macro:

  1. Takes a string literal as input
  2. Splits it into lines
  3. Calculates the minimum indentation level across all non-empty lines
  4. Removes that amount of whitespace from the start of each line
  5. Removes leading and trailing empty lines
  6. Preserves relative indentation between lines

License

Licensed under:

Credits

This crate is inspired by the dedent npm package.

Dependencies

~220โ€“660KB
~16K SLoC