{{ $currentLevel := .Level }}
{{ $currentHeaderKey :=  printf "H_%d" $currentLevel }}

{{ if not (.Page.Scratch.Get $currentHeaderKey) }}
  {{ .Page.Scratch.Set $currentHeaderKey 1 }}
{{ else }}
  {{ .Page.Scratch.Set $currentHeaderKey (add 1 (.Page.Scratch.Get $currentHeaderKey)) }}
{{ end }}

{{ if .Page.Scratch.Get "previousLevel" }}
  {{  $previousLevel := .Page.Scratch.Get "previousLevel" }}
  {{ if gt $previousLevel $currentLevel  }}
    {{ range $header := slice 1 2 3 4 5 6 }}
      {{ if gt $header $currentLevel }}
        {{ $.Page.Scratch.Delete (printf "H_%d" $header) }}
      {{ end }}
    {{ end }}
  {{ end }}
{{ end }}

{{ $counter := "" }}
{{ range $header := slice 1 2 3 4 5 6 }}
{{ if gt ($.Page.Scratch.Get (printf "H_%d" $header)) 0 }}
    {{ $counter = printf "%s%d." $counter ($.Page.Scratch.Get (printf "H_%d" $header))}}
{{ end }}
{{end}}

<h{{ add 1 .Level }} id="{{ .Anchor | safeURL }}" class="hx css-{{ .Page.File.UniqueID }}-h{{ add 1 .Level }}"><span class="counters">{{ $counter }} </span>{{ .Text | safeHTML }}<a class="hpar" href="#{{ .Anchor | safeURL }}">¶</a> {{ .Page.Scratch.Get "level" }}</h{{ add 1 .Level }}>

{{ .Page.Scratch.Set "previousLevel" .Level }}
