53 lines
1.7 KiB
Go
53 lines
1.7 KiB
Go
package sprigx
|
|
|
|
import (
|
|
`strings`
|
|
)
|
|
|
|
/*
|
|
extIndent serves as a much more flexible alternative to the Sprig `indent`.
|
|
|
|
It has 6 arguments (the last of which may be passed in via pipeline):
|
|
|
|
* levels: The level of indentation for the text. If less than or equal to `0`, `extIndent` just returns `<input>` as-is and NO-OPs otherwise.
|
|
* skipFirst: If true, skip indenting the first line. This is particularly handy if you like to visually align your function calls in your templates.
|
|
* skipEmpty: If true, do not add an indent to *empty* lines (where an "empty line" means "only has a linebreak").
|
|
* skipWhitespace: If true, do not add an indent to lines that *only* consist of whitespace (spaces, tabs, etc.) and a linebreak.
|
|
* indentString: The string to use as the "indent character". This can be any string, such as `" "`, `"\t"`, `"."`, `"|"`, `"=="` etc.
|
|
(In fact, if indentString is set to "\n" and levels is always set to 1, this function can even be used to doubelspace text!)
|
|
* input: The text to be indented. Because it is the last argument, `extIndent` works with pipelined text as well.
|
|
|
|
*/
|
|
func extIndent(levels int, skipFirst, skipEmpty, skipWhitespace bool, indentString, input string) (out string) {
|
|
|
|
var idx int
|
|
var pad string
|
|
var line string
|
|
var lines []string
|
|
|
|
if levels <= 0 {
|
|
out = input
|
|
return
|
|
}
|
|
|
|
pad = strings.Repeat(indentString, levels)
|
|
lines = strings.Split(input, "\n")
|
|
|
|
for idx, line = range lines {
|
|
if idx == 0 && skipFirst {
|
|
continue
|
|
}
|
|
if skipWhitespace && strings.TrimSpace(line) == "" && line != "" {
|
|
continue
|
|
}
|
|
if skipEmpty && (line == "" || line == "\r") {
|
|
continue
|
|
}
|
|
lines[idx] = pad + line
|
|
}
|
|
|
|
out = strings.Join(lines, "\n")
|
|
|
|
return
|
|
}
|