diff options
author | Bjørn Erik Pedersen <[email protected]> | 2022-05-30 20:42:46 +0200 |
---|---|---|
committer | Bjørn Erik Pedersen <[email protected]> | 2022-05-31 09:05:54 +0200 |
commit | 6f7bf3f2d7eda178d0dba4a6bf3dfa50229df7ae (patch) | |
tree | 781580c54bed6942f1844def43750b027d8bbc76 /hugolib/shortcode.go | |
parent | 9e904d756be02ca30e4cd9abb1eae8ba01f9c8af (diff) | |
download | hugo-6f7bf3f2d7eda178d0dba4a6bf3dfa50229df7ae.tar.gz hugo-6f7bf3f2d7eda178d0dba4a6bf3dfa50229df7ae.zip |
Fix indentation in highlight shortcode
This commit adds a new `.InnerDeindent` method to the shortcode context, which is `.Inner` with any
indendation removed. This is then used in the built-in `highlight` shortcode to prevent the extra
whitespace getting hightlighted.
Fixes #4717
Diffstat (limited to 'hugolib/shortcode.go')
-rw-r--r-- | hugolib/shortcode.go | 29 |
1 files changed, 28 insertions, 1 deletions
diff --git a/hugolib/shortcode.go b/hugolib/shortcode.go index 366875b88..33767fc68 100644 --- a/hugolib/shortcode.go +++ b/hugolib/shortcode.go @@ -62,6 +62,12 @@ type ShortcodeWithPage struct { // this ordinal will represent the position of this shortcode in the page content. Ordinal int + // Indentation before the opening shortcode in the source. + indentation string + + innerDeindentInit sync.Once + innerDeindent template.HTML + // pos is the position in bytes in the source file. Used for error logging. posInit sync.Once posOffset int @@ -70,6 +76,27 @@ type ShortcodeWithPage struct { scratch *maps.Scratch } +// InnerDeindent returns the (potentially de-indented) inner content of the shortcode. +func (scp *ShortcodeWithPage) InnerDeindent() template.HTML { + if scp.indentation == "" { + return scp.Inner + } + scp.innerDeindentInit.Do(func() { + b := bp.GetBuffer() + text.VisitLinesAfter(string(scp.Inner), func(s string) { + if strings.HasPrefix(s, scp.indentation) { + b.WriteString(strings.TrimPrefix(s, scp.indentation)) + } else { + b.WriteString(s) + } + }) + scp.innerDeindent = template.HTML(b.String()) + bp.PutBuffer(b) + }) + + return scp.innerDeindent +} + // Position returns this shortcode's detailed position. Note that this information // may be expensive to calculate, so only use this in error situations. func (scp *ShortcodeWithPage) Position() text.Position { @@ -326,7 +353,7 @@ func renderShortcode( hasVariants = hasVariants || more } - data := &ShortcodeWithPage{Ordinal: sc.ordinal, posOffset: sc.pos, Params: sc.params, Page: newPageForShortcode(p), Parent: parent, Name: sc.name} + data := &ShortcodeWithPage{Ordinal: sc.ordinal, posOffset: sc.pos, indentation: sc.indentation, Params: sc.params, Page: newPageForShortcode(p), Parent: parent, Name: sc.name} if sc.params != nil { data.IsNamedParams = reflect.TypeOf(sc.params).Kind() == reflect.Map } |