#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

#776 in Text processing

Download history 236/week @ 2024-10-29 210/week @ 2024-11-05 331/week @ 2024-11-12

790 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

~215โ€“660KB
~16K SLoC