TransWikia.com

How do I define a macro that wraps a text and link to involve an underscore?

TeX - LaTeX Asked by kapple on March 3, 2021

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?

3 Answers

You can detokenize the output:

enter image description here

documentclass{article}

usepackage[T1]{fontenc}
usepackage{hyperref}

newcommand{cppsection}[1]{section{protectdetokenize{#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}

Correct answer by Werner on March 3, 2021

Probably this answer

And try:

documentclass{book}
usepackage{fontspec}

catcode`_=12
newcommandTest[1]{%
  section{#1}%
}
begin{document}

Test{test_test}
Text_text
end{document}

Answered by Elisey on March 3, 2021

% 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.

Answered by Donald Arseneau on March 3, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP