[Tex/LaTex] Creating a new environment with one optional argument

environmentsoptional argumentsspacing

I want to create a new environment with one optional argument in LaTeX. Here is what I used:

\newenvironment{argument}[1][]{%
\par
\noindent
\textbf{Argument#1:}
\noindent}
{}

When there is no argument, it typesets the ':' right after the word 'Argument', which is how it should be.

However, when the optional argument is used, LaTeX doesn't add a space between the word 'Argument' and the optional argument provided.

In other words, what I want to achieve is that if the optional argument is provided (e.g. A), then LaTeX should add a space after the word 'Argument', like:

Argument A: some text

and when there is no optional argument, it should be like (without the space):

Argument: some text

Best Answer

Add a space before #1 in the environment's definition, and specify \unskip (which will remove the space) as the optional argument's default value.

\documentclass{article}

\newenvironment{argument}[1][\unskip]{%
\par
\noindent
\textbf{Argument #1:}
\noindent}
{}

\begin{document}

\begin{argument}
Some text.
\end{argument}

\begin{argument}[A]
Some text.
\end{argument}

\end{document}

enter image description here

Related Question