6

I am using the listings package to display R code. I would like a monospaced font, bold keywords, and I would like code that works when the user cuts and pastes from the pdf file into rstudio. The default listings font works correctly when pasted, but does not display bold keywords. Some fonts display bold keywords, but the caret symbol is incorrect when pasted.

Here is sample code that illustrates the problem (cut and paste the fifth line in the listing to see what happens---the caret is wrong, i.e., it displays this character: ˆ, which is not recognized by R, rather than this: ^)

\documentclass{article}
\usepackage{graphicx,textcomp}
\usepackage{comment,lscape}
\usepackage{fancyvrb,listings}
\usepackage{listings,makeidx}
\usepackage{marginnote}
%\usepackage{pxfonts} % bold but wrong caret
\usepackage{courier} % bold but wrong caret
%\usepackage{ascii} % no bold
\lstloadlanguages{R}
\usepackage{hyperref}

\lstloadlanguages{R}
\lstdefinelanguage{Renhanced}[]{R}{%
  morekeywords={acf,ar,arima,arima.sim,colMeans,colSums,is.na,is.null,
    mapply,ms,na.rm,nlmin,replicate,row.names,rowMeans,rowSums,seasonal,
    sys.time,system.time,ts.plot,which.max,which.min},
  deletekeywords={Call},
  alsoletter={.\%},
  alsoother={:_\$}}
\lstset{language=Renhanced,extendedchars=false,
basicstyle=\small\ttfamily,
commentstyle=\textsl,
showstringspaces=false,
index=[1][keywords]}

\begin{document}

\begin{lstlisting}[float,frame=single,caption={A first example},label=list:ex1]
r <- 0.06
g <- 0.02
tt <- 1:5
cf0 <- 100
pv <- sum(cf0*(1+g)^(tt-1)/(1+r)^tt) 
print(pv, digits = 8)
[1] 437.41649
\end{lstlisting}

\end{document}
  • Could you be a bit more specific about what you mean by "the caret is wrong" (or "incorrect")? – Mico Jun 14 '12 at 18:06
  • @Mico: Thank you, I edited the question to clarify. – Robert McDonald Jun 14 '12 at 20:29
5

instead of courier use

\documentclass{article}
\usepackage[T1]{fontenc}
    
\usepackage{beramono}
    
...
  • Nice. I can attest that beramono provides the correct caret. One question: does including this package modify all/some of the mono font used in other parts of the document? (can there be a downside) Thanks. – PatrickT Nov 5 '17 at 17:17
  • 1
    Yes, the complete document has as mono font bera. But it is a very good mono font, much better than courier! – user2478 Nov 5 '17 at 17:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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