{{- $dest := .Destination -}}
{{- $text := .Text -}}
{{- $title := .Title -}}

{{- $isExternal := or (strings.HasPrefix $dest "http://") (strings.HasPrefix $dest "https://") -}}

{{- if not $isExternal -}}
  {{- $path := $dest -}}
  {{- $frag := "" -}}

  {{- if in $dest "#" -}}
    {{- $parts := split $dest "#" -}}
    {{- $path = index $parts 0 -}}
    {{- $frag = index $parts 1 -}}
  {{- end -}}

  {{- if strings.HasSuffix $path ".md" -}}
    {{- $path = strings.TrimSuffix ".md" $path -}}
    {{- if ne $path "" -}}
      {{- $path = printf "%s/" $path -}}
    {{- end -}}
  {{- end -}}

  {{- $dest = $path -}}
  {{- if ne $frag "" -}}
    {{- $dest = printf "%s#%s" $dest $frag -}}
  {{- end -}}
{{- end -}}

<a href="{{ $dest | relURL }}"{{ with $title }} title="{{ . }}"{{ end }}>{{ $text | safeHTML }}</a>
