1

I want to create a command for subsections which should be referenced and indexable. The command has two params: code and name.

The command creates the subsection and the name (second parameter) is painted in the toc.

But when I try to use the code as a reference, it writes the name of a different (the first one) subsection!!

enter image description here

This is my not working code:


\documentclass{article}
\usepackage{hyperref}
\hypersetup{
    colorlinks=true,
    linkcolor=blue,
    filecolor=magenta,      
    urlcolor=blue,
}
\newcommand{\virtualSubsec}[3]{
    \phantomsection
    \par\nopagebreak
    \refstepcounter{subsection}
    \def\@currentlabelname{#1}
    \addcontentsline{toc}{subsection}{\protect\numberline{\thesubsection}#2}
    \label{#1}
    \textbf{#1 - #2}
    \par
    \textit{#3} 
    \par
}

\begin{document}

\tableofcontents
\section{This is a Section}
\subsection{This is a Subsection}

A line of text... 
\virtualSubsec{VS01}{Virtual Subsec 1}{
    this is the content of the first virtual subsection
}
\virtualSubsec{VS02}{Virtual Subsec 2}{
    this is the content of the second virtual subsection
}

\section{References}
autoref VS02 is working: \par
\autoref{VS02} \par %true => is subsection 1.2 
nameref VS02 is NOT working: \par
\nameref{VS02} \par 
it is painting "This is a Subsection" => false => it should be "Virtual Subsec 1"

\end{document}

what is the problem??

1 Answer 1

2

You must make @ a letter first. Without it you are defining \@ and not \@currentlabelname. Also you are using the wrong argument number:

\makeatletter %<-- make @ a letter
\newcommand{\virtualSubsec}[3]{
    \phantomsection
    \par\nopagebreak
    \refstepcounter{subsection}
    \def\@currentlabelname{#2}%<------ #2
    \addcontentsline{toc}{subsection}{\protect\numberline{\thesubsection}#2}
    \label{#1}
    \textbf{#1 - #2}
    \par
    \textit{#3}
    \par
}
\makeatother

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .