2

In many cases it makes sense that \hspace is ignored at the beginning of a new line (and this has been discussed many times). Yet why is \hspace not ignored at the beginning of a paragraph? Is this intentional? What is the rationale for this? If \hspace is part of a macro, I'd prefer that \hspace is ignored no matter whether it appears at the beginning of a newline inside a paragraph or at the beginning of a paragraph. How can one achieve that?

Here is a simple example

\documentclass{article}
\begin{document}

foo bar\\ baz

\hspace{2em} hspace indents at beginning of paragraph.\\
\hspace{2em} Otherwise it does not indent at beginning of line

Why?

\end{document}
2

\hspace expands to, essentially \hskip which produces what TeX calls "glue." Glue belong to the class of discardable items. These are the things TeX throws away at a line break. Since \\ is essentially \unskip\nobreak\hfil\break, TeX throws away the following \hskip.

To prevent discarding the glue, you can use \hspace*. But this isn't what you wanted.

You wanted a way to ignore the space at the beginning of the line as well. One possible way to do that is to make a new spacing macro that only inserts the space in horizontal mode.

\newcommand*\smarthspace[1]{%
    \ifhmode
        \hspace{#1}%
    \fi
}

The two caveats here are that normal paragraph indentation will still happen and using \noindent to suppress it will cause TeX to switch to horizontal mode and thus the space will be inserted. I don't have a good solution for that.

\documentclass{article}
\newcommand*\smarthspace[1]{%
    \ifhmode
        \hspace{#1}%
    \fi
}
\begin{document}

foo bar\\ baz

\smarthspace{2em} smarthspace does not add a space at beginning of paragraph\\
\smarthspace{2em} nor at the beginning of a line.\smarthspace{2em} It will in
the middle.

\end{document}

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.