# Is it possible to add \hspace before \begin{lstlisting}?

Hello I would like to add some hspace before a \begin{lstlisting} part so that my code will be tabed to the right. this is not working:

\hspace{4mm}\begin{lstlisting}
dateRangeInput("daterange", "Select Date", start = min(OLS.Data$Date), end = max(OLS.Data$Date))
\end{lstlisting}

• See the listings manual, it has features to set the margins of a listing. – daleif Jun 19 '18 at 10:57
• @daleif okay I will have a look. Another question: How can I use comma in \hspace? for example \hspace{4.8mm} is not working, why and how can I fix it? – Belfort90 Jun 19 '18 at 11:08
• Please don't ask new unrelated questions, post another. \hspace{4.8mm} (using a dot, not comma) works just fine, but it ignored if used first on a line. – daleif Jun 19 '18 at 11:17
• @dalif: \hspace* doesn't work either: lstlistings starts on a new line. – Bernard Jun 19 '18 at 11:29
• @Bernard doesn't lstlisting start a new paragraph, so of course it does nothing. – daleif Jun 19 '18 at 11:50

Two possibilities:

Either the key xleftmargin=. You also have to change the caption margin via \captionsetup{margin=} from caption, or nesting the \stlistingsenvironment in an adjustwidth environment (from changepage).

\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{listings}
\usepackage{changepage}
\lstset{language=C}
\usepackage{caption}
\captionsetup[lstlisting]{singlelinecheck = off, format = plain}

\begin{document}

\section{A first section}

Some text. Some more text. Some more text. Some more text. Some more text. Some more text. Some more text. Some more text. Some more text.

{\captionsetup[lstlisting]{margin = 4.8mm}
\begin{lstlisting}[caption ={My caption}, label = lst1, xleftmargin=4.8mm]
for i:=maxint to 0 do
begin
{ do nothing }
end;
Write('Case insensitive ');
Write('Pascal keywords.');
\end{lstlisting}
}

\begin{lstlisting}[caption ={My caption}, label = lst1]
for i:=maxint to 0 do
begin
{ do nothing }
end;
Write('Case insensitive ');
Write('Pascal keywords.');
\end{lstlisting}

• Start the content of lstlisting on a new line. – Bernard Jun 19 '18 at 11:40