[Tex/LaTex] Custom environment with parameter: You can’t use `macro parameter character #’ in vertical mode

environments

I want to define a new environment to display blocks of plain text in a titled box, with whitespace reproduced exactly. Something like this

\begin{PlainText}{My Title}
Foo
Bar
\end{PlainText}

I'm putting a definition together by gathering various tips, but it doesn't work.

\newenvironment{TextFile}[1]{\ttfamily}{\par}
{
    #1\\[1ex]
    \begin{center}
    \begin{tabular}{|p{0.9\textwidth}|}
    \hline
    \\
}
{ 
    \\ \\
    \hline
    \end{tabular} 
    \end{center}
}

I only 80% understand how this is intended to work, I read the first line as meaning

TextFile is a new environment which takes one parameter, within it the font is monospace and \par means retain whitespace like HTML <pre>

I get an error at the #1\\[1ex] line

 You can't use `macro parameter character #' in vertical mode.

When it works, it should look like this:

enter image description here

Best Answer

The definition of

\newenvironment{TextFile}[1]{\ttfamily}{\par}
{
    #1\\[1ex]
    \begin{center}
    \begin{tabular}{|p{0.9\textwidth}|}
    \hline
    \\
}
{ 
    \\ \\
    \hline
    \end{tabular} 
    \end{center}
}

is wrong, at least the parts with { #1\\ }{...}, which are surely meant as the real document body, not something outside after the {\par} statement which is the end code part of the environment.

This way #1 ... etc. is meant as typesetting after the environment definition which must fail unless the definition is wrapped itself in another command or environment.

\documentclass{article}



\newenvironment{TextFile}[1]{\ttfamily%
    #1 \\[1ex]
    \begin{center}
    \begin{tabular}{|p{0.9\textwidth}|}
    \hline
    \\
}{% 
    \\ \\
    \hline
    \end{tabular} 
    \end{center}
    \par
}

\begin{document}

\begin{TextFile}{Foo}
Learning \LaTeXe\ is fun!
\end{TextFile}

\end{document}

enter image description here

Related Question