(This answer is based on a previous answer of mine from another problem : my previous answer)
The solution is to use the literate
option within the lsset
command. I modified your code (note that you need only enter $
and not \$
in the actual code listing. For visual purposes, I included a coloring for the $ but you may change it to suit your needs.
\documentclass[12pt,oneside,a4paper]{scrartcl}
\usepackage{textcomp}
\usepackage{listings}
\usepackage{color}
\definecolor{lightgray}{rgb}{.9, .9, .9}
\definecolor{darkgray}{rgb}{.4, .4, .4}
\definecolor{purple}{rgb}{0.65, 0.12, 0.82}
\lstdefinelanguage{JavaScript}{
keywords={typeof, new, true, false, catch, function, return, null, catch, switch, var, if, in, while, do, else, case, break},
keywordstyle=\color{blue}\bfseries,
ndkeywords={class, export, boolean, throw, implements, import, this},
ndkeywordstyle=\color{darkgray}\bfseries,
identifierstyle=\color{black},
sensitive=false,
comment=[l]{//},
morecomment=[s]{/*}{*/},
commentstyle=\color{purple}\ttfamily,
stringstyle=\color{red}\ttfamily,
morestring=[b]',
morestring=[b]"}
\lstset{
language=JavaScript,
backgroundcolor=\color{lightgray},
extendedchars=true,
basicstyle=\footnotesize\ttfamily,
showstringspaces=false,
showspaces=false,
numbers=left,
numberstyle=\footnotesize\ttfamily,
numbersep=9pt,
tabsize=2,
breaklines=true,
showtabs=false,
frame=leftline,
caption=\lstname,
literate={\$}{{\textcolor{blue}{\$}}}1
}
\begin{document}
\begin{lstlisting}[name=Beispiel mit JavaScript Bibliothek (jQuery)]
$("p").elements.each(function() {
$(this).html = "Element erkannt";
});
\end{lstlisting}
\end{document}
The result is
@Yihui's fix from the mailing list solved the problem for me:
knit_hooks$set(document = function(x) {sub('\\usepackage[]{color}', '\\usepackage{xcolor}', x, fixed = TRUE)})
Ps.: I've also raised an issue to that effect, as @Yihui requested.
Best Answer
This can happen if your row names start with a left bracket, in which case you get the problem that David described in his comment. I've not seen it be a problem with brackets in the body of the table (but it may happen in some case). If that is what you are seeing, you can add a custom
sanitize.rownames.function
argument to theprint.xtable
function to wrap these in braces.This
.tex
file generated from this (not shown) will give a valid PDF, where without thesanitize.rownames.function
, it will give an error:Note that if you might have other special characters that also need to be sanitized in your row names, you will have to also include that in your custom function as the default sanitization function is not used if you supply one.