Search code examples
latexlistings

Latex: center text within listing


How do I center text within a listing in Latex?

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


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?