Ref references the correct number, but nameref uses the wrong name

counterscross-referencinghyperrefnameref

This is my first question, so I'm sorry if there are detiails missing or my question could be written more clearly. Any help is greatly appreciated.

I want to use hyperref to reference the name of one of my Appendices such that I can write:

...detailed information is found in \nameref{App:B}

And have the result be

...detailed information is found in Appendix B - Matlab Code

The thing is, my appendices are unnumbered so I have used \refstepcounter to increment the chapter counter manually. Now, when I use \ref to reference the appendix the outputted number is correct but when using \nameref, the compiled name is the last numbered chapter.

I have narrowed down the issue to have something to do with \refstepcounter redefining \ @currentlabel but even so I really struggle with understanding the exact details of what \refstepcounter has done to my \label and how to fix it.

My current code says something in the lines of

\documentclass[a4paper,11pt]{scrreprt}
\begin{document}

\usepackage{hyperref}

\chapter{Some numbered chapter}


\chapter*{Appendix B - Matlab Code}
\refstepcounter{chapter}\label{App:B}
\addcontentsline{toc}{chapter}{Appendix B - Matlab Code}

Best Answer

Your main problem is, that you try to fake numbered chapters with commands for not numbered chapters. Instead you should use \chapter{…} and configure the output to what you want. For example:

\documentclass{scrreprt}
\usepackage{hyperref}

\newcommand*{\tocchapapp}{}
\AddToHook{scrreprt/appendix}{%
  % Code from https://sf.net/p/koma-script/wiki-en/HowTo_TocAppendixPrefix/
  \renewcommand*{\tocchapapp}{\chapapp\ }%
  \addtocontents{\csname ext@toc\endcsname}{%
    \string\DeclareTOCStyleEntry[numwidth+=5em]{chapter}{chapter}%
  }%
  % Additionally add the prefix to the format of the headings:
  \renewcommand*{\chapterformat}{\appendixname\ \thechapter\ --\ }%
  % and the format of the running heads:
  \renewcommand*{\chaptermarkformat}{\appendixname\ \thechapter\ --\ }%
}
% Again Code from https://sf.net/p/koma-script/wiki-en/HowTo_TocAppendixPrefix/
\renewcommand*{\addchaptertocentry}[2]{%
  \IfArgIsEmpty{#1}{% keine Nummer:
    \addtocentrydefault{chapter}{#1}{#2}% wie bisher
  }{% mit Nummer:
    \addtocentrydefault{chapter}{\tocchapapp#1}{#2}%
  }%
}

\begin{document}

\tableofcontents

\chapter{Some numbered chapter}
See \autoref{App:B}: \nameref{App:B}

\appendix
\chapter{Matlab Code}
\label{App:B}
\end{document}

table of contents, one chapter and one appendix chapter