Making highlight shortcode "indentation-aware" for code blocks within list

It appears that syntax highlighting works differently for code fences and highlight shortcode, if they are a part of list items. See the following example:

1. Step 1 description
2. Step 2 description

    ``` bash
    $ vi echo.py
    ```

    {{< highlight python >}}
    from echo import echo

    class echoTest():
        ...
    {{< /highlight >}}

The first code block (bash shell inside code fences) is displayed as expected, with no indentation in the output.

$ vi echo.py

However, for the second code block (python code inside highlight shortcode), indentation is included in the resulting code block, which is not the behavior that I want.

    from echo import echo

    class echoTest():
        ...

So, to make it work, I have to put them differently, as in the following.

1. Step 1 description
2. Step 2 description

    ``` bash
    $ vi echo.py
    ```

    {{< highlight python >}}
from echo import echo

class echoTest():
    ...
    {{< /highlight >}}

Is there a better way to get around this issue? Or is there any other option to make highlight shortcode “indentation-aware”?

This is the same issue as:


I fix it with this custom version of highlight.html shortcode:

{{- $code := (trim .Inner "\n\r") -}}
{{- $lang := .Get 0 -}}
{{- $options := .Get 1 | default "" -}}
{{- $code_ending_in_line_with_spaces := (findRE "[\\r\\n][[:blank:]]+$" $code) -}}
{{/* Ref: https://github.com/gohugoio/hugo/issues/4717#issuecomment-449375012 */}}
{{- with $code_ending_in_line_with_spaces -}}
    {{- $code = (replace $code "\r" "") -}} {{/* Windows -> Unix style line endings for ease in further parsing */}}
    {{- $offset := (trim (index . 0) "\n") -}}
    {{- $lines := (split $code "\n") -}}
    {{- $num_lines := (len $lines) -}}
    {{- $scratch := newScratch -}}
    {{- $scratch.Add "lines_minus_offset" (slice) -}}
    {{- range $i, $line := $lines -}}
        {{- $line_minus_offset := (strings.TrimPrefix $offset $line) -}}
        {{- if (lt $i (sub $num_lines 1)) -}} {{/* Do not add the last blank line */}}
            {{- $scratch.Add "lines_minus_offset" (slice $line_minus_offset) -}}
        {{- end -}}
    {{- end -}}
    {{- $code = (delimit ($scratch.Get "lines_minus_offset") "\n") -}}
    {{- $scratch.Delete "lines_minus_offset" -}}
{{- end -}}
{{- highlight $code $lang $options -}}

/cc @bep can you please fix this shortcode inside hugo until you can find a better fix?

1 Like

@kaushalmodi,
Many thanks for pointing me to the issue. I hope your investigation gets the due acceptance.

I’m migrating our project site to Hugo, and this kind of issue will definitely become a blocker for persuading my team members (who’s still reluctant to switching from CMS) to move over to Hugo, because the project documentation contains a lot of procedural instructions with code examples.