Question

How do I center text within a listing in Latex?

Or another way not using listing. (Need a box with monospace font)

Was it helpful?

Solution

The answer given at tex.stackexchange is:

\documentclass{article}
\usepackage{listings}
\renewcommand{\figurename}{Listing}
                    % replace figurename with the text that should preceed the caption
\begin{document}

\begin{figure}[thp] % the figure provides the caption
\centering          % which should be centered
\caption{Ausgabe des C-Programms}
\begin{tabular}{c}  % the tabular makes the listing as small as possible and centers it
\begin{lstlisting}[label={gtt_c_ausgabe}]
printf("Your code goes here.\n");
\end{lstlisting}
\end{tabular}
\end{figure}

\end{document}

...which still leaves me wondering:

Using a frame around the code, e.g. using \lstset{frame=single,frameround=tttt}, places the frame way over to the right. How can this be avoided?

What does the renewcommand bit do?

OTHER TIPS

I don't have an answer for the listing package on top of my head, but you could try the following:

\framebox[.9\linewidth]{\parbox{.85\linewidth}{\tt Hello World\\Second line}}

That produces a box with 90% of the line width, with text of width 85% of line width.

If you want it centered you just put \centering in front of the \tt command:

\framebox[.9\linewidth]{\parbox{.85\linewidth}{\centering \tt Hello World\\Second line}}

If you prefer the box without a frame, simply change \framebox into \makebox (and keep the arguments as they stand).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top