4

I am writting a long report and I would like to refer in every Section, Subsection, etc. to the Section, Subsection, etc. itself via a \ref{} (it is not enough to print the section name or number without a hyperref) as demonstrated in the example below.

\documentclass{article} 
\usepackage{xcolor}
\usepackage{hyperref}

\newcommand{\sectionlabel}{} 

\newcommand{\newSection}[2]{
    \section{#1}
    \label{Section:#2}
    \renewcommand{\sectionlabel}{Section:#2}}

\newcommand{\sectionref}[1]{Section~\ref{#1}}

\begin{document}

    \newSection{Title 1}{Section:1}

    \newSection{Title 2}{Section:2}

    \subsection{Subsection}

    This is Section~\ref{\sectionlabel}. 

\end{document}

Is it possible to directly to access the label name of the current section, subsection etc. without having to define a \newSection command or anything equivalent? More precisely, I am interested in a command \thisSectionLabel which can be used as

\documentclass{article} 
\usepackage{xcolor}
\usepackage{hyperref} 

\begin{document}

    \section{Title 1}
    \label{Section:1}

    \section{Title 2}
    \label{Section:2} 
    \subsection{Subsection}

    This is Section~\ref{\thisSectionLabel}. 

\end{document}

and produces the same output as the first example.

2 Answers 2

5

A more automated version supporting hyperlinks:

\documentclass{article} 
\usepackage{xcolor}
\usepackage{hyperref} 

\makeatletter
\newcommand\refthis{%
  \hyperlink\@currentHref\@currentlabel
}
\newcommand\refthistype[1]{%
  \begingroup
    \Hy@localanchornametrue
    \hyper@makecurrent{#1}%
    \hyperlink\@currentHref{\csname the#1\endcsname}%
  \endgroup
}
\makeatother
\begin{document}

    \section{Title 1}

    \section{Title 2}
    \subsection{Subsection}

    This is Subsection~\refthis\ in Section~\refthistype{section}. 

\end{document}

Here \refthis always refers to the most recent referenceable command, independent of the existence of a \label.

2
  • Thank you for your answer. Is it possible to refer to a specific environment? In your case \refthis refers to the Subsection instead of the Section "Title 2", which is what I want to achieve. Apr 14, 2018 at 14:39
  • @mathEnthusiast I added \refthistype to refer for example to the current section. Apr 14, 2018 at 15:06
5

Why not simply use the current values of the section and subsection counters?

\documentclass{article}
\begin{document}
\section{A section}
This is section \arabic{section}.
\subsection{A subsection}
This is subsection \arabic{section}.\arabic{subsection}
\end{document}

counters

1
  • Thank you for your reply. Because this does not provide the same functionality that I want to achieve. I want hyperreferences linking to Section 1 and Section 2. Apr 14, 2018 at 14:37

You must log in to answer this question.

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