Skip to content

Repository files navigation

Dedent

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.

Requirements

  • Go 1.24 or later.

Installation

Install the latest version of the package by running the following command:

go get github.com/humtta/dedent@latest

Usage

This package provides only two functions:

  • D accepts a string and returns a new one with the shared indentation removed from each line.
  • Df formats the given string with fmt.Sprintf and passes the result to D.

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>
}

Behavior

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.

Documentation

The full API reference is available on Go Packages.

License

This project is licensed under the MIT License.

About

Go package to dedent multiline strings

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Contributors

Languages