[Tex/LaTex] How to force a \hspace at the beginning of a line

spacing

My code is this:

\setlength{\parindent}{0ex}
\texttt{
x\hspace{1ex}\hspace{1ex}\hspace{1ex}y
\newline
\hspace{1ex}\hspace{1ex}\hspace{1ex}\hspace{1ex}y
}

What I'd like to see is:

x   y
    y

What I actually see is:

x   y
y

I've tried various other ways of inserting a space. So far, they've all resulted in leading whitespace being ignored.

I've also tried using \verbatim and \alltt but they eat too many of the other commands that I need preserved (not shown in the example above).

I suppose I could (in the script that emits the LaTeX) count the leading spaces in each line and use different \parindent values. I'm looking for something more elegant first.

Best Answer

The other answers here address how to use \hspace at the beginning of the line via the \hspace*.

An alternate way of inserting spaces of an appropriate width is to use \phantom{} which will take up as much space as would be required by the parameter passed to it. This will adapt more easily to cases where the amount of space you are trying to insert is not just an integer multiple of 1ex/1em.

As barbarabeeton: mentions em should be used for horizontal spaces, and ex for vertical ones. A good reference is Which measurement units should one use in LaTeX?.

enter image description here

\documentclass[border=5pt]{standalone}
\begin{document}
\texttt{\noindent
x\hspace{3ex}y
\newline\noindent
\phantom{x}\hspace{3ex}y
}
\end{document}