A Go package to remove shared indentation from a multiline string.
In Go, raw string literals preserve every character from the source, including leading whitespace. When a multiline string is indented to align with surrounding code, that indentation becomes part of the value. This package identifies the shared indentation across lines and removes it.
- Go 1.24 or later.
Install the latest version of the package by running the following command:
go get github.com/humtta/dedent@latestThis package provides only two functions:
Daccepts a string and returns a new one with the shared indentation removed from each line.Dfformats the given string withfmt.Sprintfand passes the result toD.
Here's an example:
package main
import (
"fmt"
"github.com/humtta/dedent"
)
func main() {
html := `
<div>
<h1>Hello, %s!</h1>
</div>
`
fmt.Print(dedent.D(html))
// Output:
// <div>
// <h1>Hello, %s!</h1>
// </div>
fmt.Print(dedent.Df(html, "World"))
// Output:
// <div>
// <h1>Hello, World!</h1>
// </div>
}The package applies the following rules when processing a multiline string:
- Removes the first line if it's empty or blank.
- Removes the longest indentation shared by all non-blank lines.
- Removes all whitespace from blank lines.
- Does not remove trailing whitespace from non-blank lines.
- Does not remove empty lines.
- Does not treat spaces and tabs as equivalent characters. Shared indentation evaluation requires byte-for-byte equivalence.
- Supports only LF line endings.
The full API reference is available on Go Packages.
This project is licensed under the MIT License.