2

I'm documenting some C++ code. Each C++ function will have it's own section in my documentation, and I am trying to have each section labelled and each mention of the function linked.

The macros I am currently using are

\usepackage{hyperref}

\newcommand{\cppsection}[1]{\section{#1}\label{#1}} \newcommand{\cppfcn}[1]{\hyperref[#1]{\texttt{#1}}}

which works for the most part...

...except for if the C++ function has an underscore. For example, \cppsection{my_fcn} doesn't work as it complains about the underscore for the section name, and \cppsection{my\_fcn} doesn't work as it complains about the backslash in the label definition.

This issue is likewise for the \cppfcn macro.

So my question is: Is there a way to define my macros to parse underscores for both the text and the label?

kapple
  • 93
  • 1
  • 7

3 Answers3

4

You can \detokenize the output:

enter image description here

\documentclass{article}

\usepackage[T1]{fontenc} \usepackage{hyperref}

\newcommand{\cppsection}[1]{\section{\protect\detokenize{#1}}\label{#1}} \newcommand{\cppfcn}[1]{\hyperref[#1]{\texttt{\detokenize{#1}}}}

\begin{document}

\tableofcontents

\cppsection{function} See \cppfcn{procedure}.

\cppsection{procedure} See \cppfcn{fnc_proc}.

\cppsection{fnc_proc} See \cppfcn{function}.

\end{document}

Werner
  • 603,163
  • You're a legend, your MWE works fine. But once I add a \tableofcontents it fails, complaining about the lack of a math environment for the underscore in the test.toc file. Any ideas? – kapple Oct 21 '20 at 03:33
  • @kapple: You need to \protect certain things that go in the ToC. Answer has been updated. – Werner Oct 21 '20 at 03:48
  • Works wonders, thanks heaps! – kapple Oct 21 '20 at 03:55
1

Probably this answer

And try:

\documentclass{book}
\usepackage{fontspec}

\catcode`_=12 \newcommand\Test[1]{% \section{#1}% } \begin{document}

\Test{test_test} Text_text \end{document}

Elisey
  • 401
  • 1
    Now try some math: $A_b$. You could instead do something like \newcommand\Test{\begingroup\catcode`\_=12 \Testaux} \newcommand\Testaux{\endgroup\section} – Phelype Oleinik Oct 21 '20 at 10:44
1
% optional, not necessary:  \usepackage[T1]{fontenc}
%
\usepackage[english]{babel}% or your language
\usepackage{underscore}
\usepackage{hyperref}
. . . 
\cppsection{my_fcn}

Subscripts will still work in math mode.