Inserting LaTeX code into LaTeX

enter image description here

\documentclass{article}
\usepackage{xcolor}
\usepackage{listings}
\lstset
{
    language=[LaTeX]TeX,
    breaklines=true,
    basicstyle=\tt\scriptsize,
    keywordstyle=\color{blue},
    identifierstyle=\color{magenta},
}

\begin{document}
This is inline \lstinline!\TeX! and the following is displayed 

\begin{lstlisting}
\documentclass{article}
\begin{document}
Hello World
\end{document}
\end{lstlisting}

\end{document}

If you need source code and rendered output side by side, use showexpl (no need to load listings because showexpl loads listings automatically) as follows.

enter image description here

\documentclass{article}
\usepackage{tikz}
\usepackage{showexpl}
\lstset
{
    language=[LaTeX]TeX,
    breaklines=true,
    basicstyle=\tt\scriptsize,
    keywordstyle=\color{blue},
    identifierstyle=\color{magenta},
}

\begin{document}
This is inline \lstinline!\TeX! and the following is displayed 

\begin{lstlisting}
\documentclass{article}
\begin{document}
Hello World
\end{document}
\end{lstlisting}


\begin{LTXexample}[pos=b,preset=\centering,width=0.5\linewidth]
\begin{tikzpicture}
    \draw[fill=red] (0,0) circle (1);
\end{tikzpicture}
\end{LTXexample}

\end{document}

You can use \verb like this:

\documentclass{letter}
\begin{document}
Example: \verb!\usepackage{musixtex}!
\end{document}

Edits by Speravir and Sam Whited:

There is also a starred version, which makes the spaces visible:

\documentclass{article}
\begin{document}
\verb|\LaTeX vs. \LaTeX\ or \LaTeX{} \dots|

\verb*|\LaTeX vs. \LaTeX\ or \LaTeX{} \dots|

\LaTeX vs. \LaTeX\ or \LaTeX{} \dots
\end{document}

Multiline

If you end up with more than a short, one line, phrase you might also try the verbatim (built in) or Verbatim (an improved version located in the fancyvrb package) environments.

eg.

\begin{verbatim}
  Some LaTeX code here
  Which can be multiple lines
  \usepackage{musixtex}
  \begin{music}\nostartrule
  \instrumentnumber{1}

  ...
\end{verbatim}

Tags:

Verbatim