vanilla-hugo/layouts/shortcodes/codelines.html
Danila Fedorin 9536c9fb25 Allow stripping leading whitespace from code blocks
Signed-off-by: Danila Fedorin <danila.fedorin@gmail.com>
2024-12-25 19:02:44 -08:00

60 lines
2.0 KiB
HTML

{{- $source := (readFile (printf "code/%s" (.Get 1))) -}}
{{- $allLines := split $source "\n" -}}
{{- $scratch := newScratch -}}
{{- if not (eq (int (.Get 2)) 1) -}}
{{- $scratch.Set "remLines" (after (sub (int (.Get 2)) 1) $allLines) -}}
{{- else -}}
{{- $scratch.Set "remLines" $allLines -}}
{{- end -}}
{{- $lines := first (add (sub (int (.Get 3)) (int (.Get 2))) 1) ($scratch.Get "remLines") -}}
{{- if (.Get 4) -}}
{{- $scratch.Set "opts" (printf ",%s" (.Get 4)) -}}
{{- else -}}
{{- $scratch.Set "opts" "" -}}
{{- end -}}
{{- if (.Get 5) -}}
{{- $scratch.Set "hidden" (.Get 5) -}}
{{- end -}}
{{- if or (.Page.Params.left_align_code) (.Get 6) -}}
{{- $scratch.Set "prefixLength" -1 -}}
{{- range $line := $lines -}}
{{- $leading := sub (len $line) (len (strings.TrimLeft " " $line)) -}}
{{- if and (ne $line "") (or (eq ($scratch.Get "prefixLength") -1) (le $leading ($scratch.Get "prefixLength"))) -}}
{{- $scratch.Set "prefixLength" $leading -}}
{{- end -}}
{{- end -}}
{{- $scratch.Set "joinedLines" "" -}}
{{- range $line := $lines -}}
{{- $scratch.Add "joinedLines" (substr $line ($scratch.Get "prefixLength")) -}}
{{- $scratch.Add "joinedLines" "\n" -}}
{{- end -}}
{{- else -}}
{{- $scratch.Set "joinedLines" (delimit $lines "\n") -}}
{{- end -}}
{{- partial "geturl.html" (dict "scratch" $scratch "path" (.Get 1) "lines" (slice (.Get 2) (.Get 3))) -}}
{{- partial "linerangestr.html" (dict "scratch" $scratch "from" (.Get 2) "to" (.Get 3)) -}}
{{- with ($scratch.Get "hidden") -}}
<details><summary>{{- . | markdownify -}}</summary>
{{- end -}}
{{- $groupconfig := dict
"url" ($scratch.Get "bestUrl")
"basePath" ($scratch.Get "bestPath")
"path" (.Get 1)
"comment" ($scratch.Get "comment")
"code" ($scratch.Get "joinedLines")
"firstLine" (int (.Get 2))
"lastLine" (int (.Get 3))
"language" (.Get 0)
"opts" (printf "linenos=table,linenostart=%d%s" (.Get 2) ($scratch.Get "opts"))
-}}
{{- partial "highlightgroup.html" $groupconfig -}}
{{- with ($scratch.Get "hidden") -}}
</details>
{{- end -}}