{{- $params := .Page.Params | merge site.Params.page -}}
{{- $math := $params.math -}}
{{- if eq $math true -}}
  {{- $math = dict "enable" true | merge site.Params.page.math -}}
{{- else if eq $math false -}}
  {{- $math = dict "enable" false -}}
{{- end -}}

{{- /* 
  Mathematical formulas rendering:
    - KaTeX server-side rendering
    - MathJax client-side rendering
  Regular passthrough rendering:
    - [todo] support more features in future
*/ -}}
{{- if $math.enable -}}
  {{- if eq $math.type "katex" -}}
    {{- $katex := $math.katex -}}
    {{- $opts := dict "output" "htmlAndMathml" "displayMode" (eq $.Type "block") }}
    {{- $opts = dict "throwOnError" $katex.throwOnError "errorColor" $katex.errorColor | merge $opts }}
    {{- $macros := $katex.macros | default dict -}}
    {{- if $macros -}}
      {{- $opts = dict "macros" $macros | merge $opts -}}
    {{- end -}}
    {{- /* render mathematical markup to HTML */ -}}
    {{- with try (transform.ToMath .Inner $opts) }}
      {{- with .Err }}
        {{- errorf "Unable to render mathematical markup to HTML using the transform.ToMath function. The KaTeX display engine threw the following error: %s: see %s." . $.Position }}
      {{- else }}
        {{- .Value }}
        {{- $.Page.Store.Set "hasKaTeX" true -}}
        {{- if eq hugo.Context.MarkupScope "home" -}}
          {{- site.Home.Store.Set "hasKaTeX" true -}}
        {{- end -}}
      {{- end }}
    {{- end -}}
  {{- else if eq $math.type "mathjax" -}}
    {{- if eq $.Type "block" -}}
      $${{- .Inner -}}$$
    {{- else -}}
      ${{ .Inner }}$
    {{- end -}}
    {{- $.Page.Store.Set "hasMathJax" true -}}
    {{- if eq hugo.Context.MarkupScope "home" -}}
      {{- site.Home.Store.Set "hasMathJax" true -}}
    {{- end -}}
  {{- end -}}
{{- else -}}
  {{- /* Regular passthrough rendering */ -}}
  {{- /* waiting for Hugo interface to get delimiters */ -}}
  {{- .Inner -}}
{{- end -}}
