[Tex/LaTex] Latex listings R: need mono-spaced font with bold keywords and correct caret (^)

listingsr

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}

Best Answer

instead of courier use

\documentclass{article}
\usepackage[T1]{fontenc}
    
\usepackage{beramono}
    
...