# Why does \noindent not work properly here?

I defined a new environment, similar (but not equal) to listings:

\documentclass{ltxdoc}
\usepackage{lipsum}
\newenvironment{lines}
{\par\begingroup\nobreak
\vspace{3pt}\parindent0pt\hrule\kern5pt
\nobreak\obeylines\everypar{\strut}\endgroup}
{\par\begingroup\nobreak
\vspace{3pt}\parindent0pt\hrule\kern5pt
\nobreak\obeylines\everypar{\strut}\endgroup%
\noindent%
}
\begin{document}
\lipsum[1]
\begin{lines}
Some nifty code and stuffz
\end{lines}
\lipsum[2]
\end{document}


Why does my \noindent keep a small space before the text? Did I miss something?

• Add \ignorespacesafterend after \noindent. – egreg May 7 '14 at 21:10
• Thanks. Why doesn't it align automatically? – 1010011010 May 7 '14 at 21:12
• It does align but you added a space at the start of the line, so TeX typeset it. (ends of lines are word spaces in TeX) – David Carlisle May 7 '14 at 21:13

If you use \noindent you will almost always get this behaviour. The space is an inter word space being typeset from the end of line after the environment.

You can avoid the problem by using \ignorespacesafterend but that is papering over the cracks. The error is using \noindent which has started horizontal mode prematurely which is why the end of line is typeset as a space. LaTeX environments never do this. You should define the environment using trivlist then the environment will end in vertical mode, but if no blank line follows indentation will be suppressed (it is actually removed using \lastbox rather than not being added using \noindent.)

Something like this, adjust lengths to suit.

\documentclass{ltxdoc}
\usepackage{lipsum}
\newenvironment{linez}
{\trivlist\nopagebreak
\parindent0pt
\vspace{3pt}%
\hrule
\vspace{-3pt}%
\item\relax\obeylines}
{\par
\nopagebreak
\vspace{3pt}%
\hrule
\vspace{3pt}%
\endtrivlist}

\begin{document}
\lipsum[1]
\begin{linez}
Some nifty code and stuffz
Some nifty code and stuffz
Some nifty code and stuffz
Some nifty code and stuffz
\end{linez}
\lipsum[2]
\end{document}

• I've used trivlist and it also changed the indentation of items inside the environment. What is the most versatile solution to getting this whitespace back? \indent appears pretty crippled at the moment. – 1010011010 May 7 '14 at 21:26
• @1010011010 see update – David Carlisle May 7 '14 at 21:40

You're missing \ignorespacesafterend, but the definition doesn't do \obeylines, because you're enclosing it in a group and its effect disappears at \endgroup:

\documentclass{ltxdoc}
\usepackage{lipsum}
\newenvironment{linez}
{\par\nopagebreak
\vspace{3pt}
\parindent0pt
\hrule\kern5pt
\obeylines}
{\par
\nopagebreak
\vspace{3pt}
\hrule\kern5pt
\noindent\ignorespacesafterend}

\begin{document}
\lipsum[1]
\begin{linez}
Some nifty code and stuffz
Some nifty code and stuffz
Some nifty code and stuffz
Some nifty code and stuffz
\end{linez}
\lipsum[2]
\end{document}