1

If you look at how this example below is rendered in StackExchange, you see a nice margins around the hello world code:

int main(int argc, char * argv[]) {
    printf("hello, world!\n");
}

I would like to obtain the same in LaTeX, but it seems an hard one... I would like the same result as in Stack Exchange around 3em top and bottom and 1em left and right. The framexleftmargin does not really work because it does not indent the frame and it looks quite ugly.

\documentclass[10pt, oneside]{article}

\usepackage[a4paper, total={16cm, 24cm}]{geometry}
\usepackage[utf8]{inputenc}
\usepackage{fontspec}
\usepackage[T1]{fontenc}
\usepackage[table]{xcolor}
\usepackage{listings}

\definecolor{mygray}{rgb}{0.9,0.9,0.9}

\lstset{
  language=c,
  backgroundcolor=\color{mygray},
  aboveskip=3em, % Not working
  belowskip=3em, % Not working
  % framexleftmargin=1em,
}

\begin{document}
\section{Some code}
 
Lorem Ipsum:

\begin{lstlisting}
int main(int argc, char * argv[]) {
    printf("hello, world!\n");
}
\end{lstlisting}
\end{document}
1

You have to draw a frame, because if you set frame=none the margin commands don't work. So you need frame=single and framerule=0pt to draw a frame that isn't visible. Now you can set the margins within the frame and then you have indent the whole frame, to align it with the text:

\documentclass[10pt]{article}

\usepackage[a4paper, showframe]{geometry}
\usepackage{fontspec}
\usepackage[table]{xcolor}
\usepackage{listings}

\definecolor{mygray}{rgb}{0.9,0.9,0.9}

\lstset{
  language=c,
  backgroundcolor=\color{mygray},
  frame=single,
  framerule=0pt,
  framextopmargin=3ex,
  framexbottommargin=3ex,
  framexleftmargin=1em,
  xleftmargin={\dimexpr 1em+3pt},
  linewidth={\dimexpr \linewidth-3pt}
}

\begin{document}
\section{Some code}
 
Lorem Ipsum:

\begin{lstlisting}
int main(int argc, char * argv[]) {
    printf("hello, world!\n");
}
\end{lstlisting}
\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.