Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

I have just learned how to insert source code into beamer with the listings package. However I dont know how to go about adding any syntax coloring on the C++ source code.

How do I do that?

Here is the code I am currently using for source code insertion.

\documentclass{beamer}
 \setbeamercovered{transparent}
%\usepackage{pxfonts}
\usepackage{listings}


\begin{document}

\begin{frame}[fragile]
\frametitle{Inserting source code}
  \lstset{language=C++}
\begin{lstlisting}
    #include<stdio.h>
    #include<iostream>
    int main(void)
    {
    printf("Hello World\n");
    return 0;
    }
\end{lstlisting}
\end{frame}
\end{document}
share|improve this question
add comment

1 Answer 1

up vote 9 down vote accepted

This is an example with C++ code highlighted; the two frames show the difference between adopting the typewriter font and not:

\documentclass{beamer}
 \setbeamercovered{transparent}
\usepackage{listings}

\begin{document}

% Using typewriter font: \ttfamily inside \lstset
\begin{frame}[fragile]
\frametitle{Inserting source code}
\lstset{language=C++,
                basicstyle=\ttfamily,
                keywordstyle=\color{blue}\ttfamily,
                stringstyle=\color{red}\ttfamily,
                commentstyle=\color{green}\ttfamily,
                morecomment=[l][\color{magenta}]{\#}
}
\begin{lstlisting}
    #include<stdio.h>
    #include<iostream>
    // A comment
    int main(void)
    {
    printf("Hello World\n");
    return 0;
    }
\end{lstlisting}
\end{frame}

\begin{frame}[fragile]
\frametitle{Inserting source code without setting typewriter}
\lstset{language=C++,
                keywordstyle=\color{blue},
                stringstyle=\color{red},
                commentstyle=\color{green},
                morecomment=[l][\color{magenta}]{\#}
}
\begin{lstlisting}
    #include<stdio.h>
    #include<iostream>
    // A comment
    int main(void)
    {
    printf("Hello World\n");
    return 0;
    }
\end{lstlisting}
\end{frame}
\end{document}

enter image description here

enter image description here

Notice that there's no difference from Beamer or standard document in using listings. The package guide explains in detail how to do this, but you can also find information looking at the apposite tag listing on this site. The command \ttfamily sets the given style in typewriter.

share|improve this answer
    
Thank you. One question. Could you explain what this "ttfamily " is? Is it a specific font? –  smilingbuddha Aug 21 '12 at 16:45
    
Yes, it's the typewriter font. –  Juri Robl Aug 21 '12 at 16:56
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.