# Why is this \def not working as expected?

I am having a weird problem with \def. I am new to (La)TeX and can't figure this out.

I have a simple code as follows.

\documentclass[10pt,a4paper]{article}

\usepackage{listings}

\begin{document}

\lstset{
language=C++,
tabsize=4
}

\def\docend{\end{document}}

\def\codeend{\end{lstlisting}}

\begin{lstlisting}

class AClass
{
enum Types
{
t_one = 1
};
~AClass()
{
cout << _T("destructor") << endl;
}
}

\end{lstlisting}

%  \codeend

\docend


Using \codeend gives an error '...emergency stop...no legal \end found...". However, \docend works fine.

What mistake have I made? (FYI, using TeXMaker with Miktex 2.9 on Windows 7.)

• What’s the purpose of \docend? It’s better readable for others to leave the original definition. – Speravir Jan 27 '14 at 20:56
• Agreed. I used \docend to check if \end had a specific behavior , and kept it here for illustration. I don't use it in actual .tex file. – vin Jan 28 '14 at 10:12

Package listings changes the catcodes to get a verbatim listings. That means, that \end{lstlisting} is not executed the normal way, because the backslash is a normal character and \end is a string, not a macro. Thus listings explicitly looks for \end{lstlisting} in the input file and does not find it, if it is hidden in \codeend.

At least, the listings package offers to make your own environments using \lstnewenvironment, see section "4.16 Environments" of the package documentation.

An environment cpp (as suggested in the comment) can be defined as follows:

\documentclass[10pt,a4paper]{article}

\usepackage{listings}

\lstnewenvironment{cpp}{%
\lstset{%
language=C++,
tabsize=4,
}%
}{}

\newcommand*{\docend}{\end{document}}

\begin{document}

\begin{cpp}
class AClass
{
enum Types
{
t_one = 1
};
~AClass()
{
cout << _T("destructor") << endl;
}
}
\end{cpp}

\docend

• Wow! But can it be done the \codeend way, if so how? I ask this because I have \codestartX (X for C++ etc) and want to keep things consistent tag name wise. – vin Jan 27 '14 at 19:00
• OK, I'd rather use \begin{cpp} and \end{cpp}, which is also quite fine by me. (I posted the earlier comment about the same time as you edited the answer.) Thanks. – vin Jan 27 '14 at 19:11