// SPDX-License-Identifier: GPL-3.0-or-later package render import ( "fmt" "regexp" "strings" ) // The markers that stand for an escaped placeholder while the Markdown is // rendered. They are private use characters, which neither Markdown nor the // templates treat in any special way. const ( escapeOpen = "" escapeClose = "" ) // escaped matches a marker with the name of the placeholder it stands for. var escaped = regexp.MustCompile(escapeOpen + `([a-z0-9_]+)` + escapeClose) // SubstituteEscaped replaces the {{name}} placeholders of text like Substitute // does, except those with a backslash right before them (an odd number of // backslashes: two make a literal backslash). The backslash is dropped and the // placeholder is replaced by a marker that Unescape turns back into the written // placeholder once the Markdown has been rendered. An unknown placeholder is an // error that names the file; an escaped one is not looked up. func SubstituteEscaped(name, text string, ctx map[string]string) (string, error) { var out strings.Builder last := 0 for _, loc := range placeholder.FindAllStringSubmatchIndex(text, -1) { start, end := loc[0], loc[1] key := text[loc[2]:loc[3]] slashes := 0 for i := start - 1; i >= last && text[i] == '\\'; i-- { slashes++ } if slashes%2 == 1 { out.WriteString(text[last : start-1]) out.WriteString(escapeOpen + key + escapeClose) } else { value, ok := ctx[key] if !ok { return "", fmt.Errorf("%s: unknown placeholder {{%s}}", name, key) } out.WriteString(text[last:start]) out.WriteString(value) } last = end } out.WriteString(text[last:]) return out.String(), nil } // Unescape turns the markers left by SubstituteEscaped back into the // placeholders as they were written. func Unescape(s string) string { return escaped.ReplaceAllString(s, "{{$1}}") }