# Macro to document LaTeX command with index

I am writing a document, to explain LaTeX usage. Obviously, this document contains a lot of LaTeX commands.

I defined a macro, that will take one argument (the command name) and print it in typewriterfont. To make life easy, I thought it a clever idea, to let the macro add the backslash. This works fine for me:

Years later, I thought the time has come to add an index to the document. I added the \index command into my macro. This is how I did it:

\newcommand{\cmd}[1]{%
\cmd@font{\textbackslash#1}%
% Don't forget to reset the font!
\normalfont\selectfont%
% Insert the command to the index, but preserve the backslash
\def\@cmd{#1}
\index{#1@\texttt{\@cmd}}%
}%


This works quite sufficent, the only drawback is, that the index just lists the pure command name without the backslash. Stupid me wasn't able, to think of a clever way, to add the backslash.

Here you can see the index:

If I change my macro by adding a backslash to the index argument, like this

\newcommand{\cmd}[1]{%
\cmd@font{\textbackslash#1}%
% Don't forget to reset the font!
\normalfont\selectfont%
% Insert the command to the index, but preserve the backslash
\def\@cmd{\#1}
\index{#1@\texttt{\@cmd}}%
}%


it won't print the backslash, but the #1. Here is a sample picture of the desaster :-)

What should be a clever way to implement this feature?

This is the obvious MWE:

\documentclass{article}
\usepackage{makeidx}\makeindex

\makeatletter
\def\cmd@font{\normalfont\ttfamily\selectfont}
\newcommand{\cmd}[1]{%
\cmd@font{\textbackslash#1}%
% Don't forget to reset the font!
\normalfont\selectfont%
% Insert the command to the index, but preserve the backslash
\def\@cmd{#1}
\index{#1@\texttt{\@cmd}}%
}%
\makeatother

\begin{document}

Command \cmd{index} will be used to create a word in the index file,
while \cmd{printindex} will will print the sorted index.

\printindex{}
\end{document}


You can use \textbackslash. Using this in your MWe produces the index:

\documentclass{article}
\usepackage{makeidx}\makeindex

\makeatletter
\def\cmd@font{\normalfont\ttfamily\selectfont}
\newcommand{\cmd}[1]{%
\cmd@font{\textbackslash#1}%
% Don't forget to reset the font!
\normalfont\selectfont%
% Insert the command to the index, but preserve the backslash
\def\@cmd{#1}
\index{#1@\texttt{\textbackslash\@cmd}}%
}%
\makeatother

\begin{document}

Command \cmd{index} will be used to create a word in the index file,
while \cmd{printindex} will will print the sorted index.

\printindex{}
\end{document}


Btw, you might want to switch to using imakeidx. It works pretty much exactly the same, via \usepackage{imakeidx}, but with a number of improvements such as automatic index compilation.

• Thank you. Didn't thought, it was that easy. – Jan Dec 11 '19 at 14:49
• @Jan It's often the case tat you just need to know some (obscure) command:) Glad it helped. – Andrew Dec 11 '19 at 18:39