gohugoio / hugo

The world’s fastest framework for building websites.
https://gohugo.io
Apache License 2.0
74.32k stars 7.43k forks source link

Add a hook to render/highlight Markdown inline code #12307

Open razonyang opened 4 months ago

razonyang commented 4 months ago

Currently, we're able to highlight inline code via shortcode as follows.

The {{< highlight python "hl_inline=true" >}}range(){{< /highlight >}} function is used to generate a sequence of numbers.

We can make this usage shorter without shortcode if support a hook to render inline code like render-codeblock does.

// theme's scoped custom hook
{{ $code := .Text }}
{{ if strings.HasPrefix "#!" }}
  {{ highlight ... }}
{{ else }}
  <code>{{ $code }}</code>
{{ end }}
The `#!python range()` function is used to generate a sequence of numbers.
akbyrd commented 4 months ago

I was just about to make the same request. This would be a very welcome improvement. It feels like we're fighting the markup language if we have to replace a built-in feature like `inline code` with {{< highlight cpp "hl_inline=true" >}}inline code{{< /highlight >}}

A render hook to enable highlighting feels like it plays into the strengths of hugo + markdown.

The "shebang" approach of embedding the language in the text is clever. I love it.

A temporary solution that's at least a little bit shorter than the default

{{< code >}}#!json { "label": "hugo build" }{{< /code >}}
{{- $opts := dict "hl_inline" true }}

{{- $matches := findRESubmatch "#!(\\w+) (.*)" .Inner 1 }}
{{- with index $matches 0 }}
    {{- $lang := index . 1 }}
    {{- $code := index . 2 }}
    {{- (highlight $code $lang $opts) }}
{{- else }}
    {{- (highlight .Inner "" $opts) }}
{{- end -}}

Or, taking a cue from jmooring, which ends up simpler

{{< hl json >}}{ "label": "hugo build" }{{< /hl >}}
{{- $lang := or (.Get 0) "" }}
{{- $opts := dict "hl_inline" true }}
{{- (highlight .Inner $lang $opts) -}}

In the future this could also combine nicely with inline markdown attributes. Currently we can only add attributes to block elements, but there are places where it would be super useful for inline elements, like list items or, in this case, the language for inline code.