{{- $link := .Destination -}}
{{- $isRemote := or (strings.HasPrefix $link "http") (strings.HasPrefix $link "mailto") -}}

{{- if not $isRemote -}}
  {{- $url := urls.Parse .Destination -}}
  {{- $fragment := "" -}}
  {{- with $url.Fragment }}{{ $fragment = printf "#%s" . }}{{ end -}}
  
  {{- /* Try to find the page by its path */ -}}
  {{- with .Page.GetPage $url.Path -}}
    {{- $link = printf "%s%s" .RelPermalink $fragment -}}
  {{- else -}}
    {{- /* If the page is not found, throw a warning during build. */ -}}
    {{- warnf "Broken link to page: '%s' found in file %s" .Destination .Page.File.Path -}}
  {{- end -}}
{{- end -}}

<a href="{{ $link | safeURL }}"{{ with .Title }} title="{{ . }}"{{ end }}>{{ .Text | safeHTML }}</a>
