How can I ensure that an environment always starts on a new line? (a new paragraph / horizontal box)?

If you want that the environment starts a new paragraph with no indentation and also ignores spaces after it,

\newenvironment{test}
 {\par\noindent\ignorespaces}
 {\ignorespacesafterend}

The missing \ignorespaces is the cause for the small spaces in the third example. This happens because \noindent starts a new paragraph (note that \par only ends a paragraph) and so the space after \begin{test} (generated by the end-of-line) is not ignored.


It is almost always best to avoid starting horizontal mode in the begin code of the environment, so do not use \noindent or \leavevmode etc.

The usual way is as a trivlist, the exact parameters of which can be customised, and this is how center quote verbatim etc work.

Note your test file makes overfull lines as the fbox adds space around a parbox that is already full width.

enter image description here

\documentclass{article}
%\usepackage{fontspec}
\usepackage{lipsum}

\newenvironment{test}
  {\trivlist{}\item\relax}% <-- before env hook
  {\endtrivlist}% <-- after env hook

\begin{document}

\noindent X\dotfill X

\begin{test}
\fbox{\parbox{\linewidth}{\lipsum[1]}}
\end{test}
\begin{test}
\fbox{\parbox{\linewidth}{\lipsum[1]}}
\end{test}

\begin{test}
\fbox{\parbox{\linewidth}{\lipsum[1]}}
\end{test}
\end{document}

To see one (of many) disadvantages to starting hmode in the environment definition try a test such as

\begin{test}

\fbox{\parbox{\linewidth}{\lipsum[1]}}
\end{test}

with the definition here and compare with other definitions. Environments that start a paragraph ought to silently accept the environment content starting with a paragraph break.

Tags:

Environments