[Tex/LaTex] Why does \noindent not work properly here

indentation

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?

Best Answer

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.

enter image description here

\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}