5

I want to write R source code in my latex file so I'm using the listings package.

The problem is that I want R keywords to appear in blue but for instance a variable named abc.log.de appears with log in blue. I don't want that to happen if log is part of a larger variable name in R. (Example bellow)

How should I proceed?

\documentclass{article}
\usepackage{listings}
\usepackage{color}

\definecolor{dkgreen}{rgb}{0,0.6,0}
\definecolor{gray}{rgb}{0.5,0.5,0.5}
\definecolor{mauve}{rgb}{0.58,0,0.82}

\lstset{frame=tb,
language=R,
aboveskip=3mm,
belowskip=3mm,
showstringspaces=false,
columns=flexible,
numbers=none,
keywordstyle=\color{blue},
numberstyle=\tiny\color{gray},
commentstyle=\color{dkgreen},
stringstyle=\color{mauve},
breaklines=true,
breakatwhitespace=true,
tabsize=3
}

\begin{document}

\begin{lstlisting}
L.V2<-log(V2)
dados.log<-dados
\end{lstlisting}

\end{document}

enter image description here

  • 1
    Welcome to TeX.SX! Please help us to help you and add a minimal working example (MWE) that illustrates your problem. It will be much easier for us to reproduce your situation and find out what the issue is when we see compilable code, starting with \documentclass{...} and ending with \end{document}. – user31729 Dec 16 '14 at 18:26
  • 1
    @ChristianHupfer thanks! I've edited the question with a MWE. I appreciate your help. – Mary Dec 16 '14 at 18:32
7

By default, the R markup in the listings package regards the period . as an other (i.e., non-letter) type of character, along with _ and $, which allows to recognize keywords that include them (such as data.frame). However, this also meansthat variables defined in the form foo.keyword.bar will highlight the keyword between the periods.

You can prevent this behaviour by specifying the period . as a letter character in the listings markup, by adding alsoletter={.} in \lstset. Unfortunately, this will also prevent other keywords containing periods (such as data.frame or read.csv) from being highlighted.

Alternatively, you could name your variables differently in your code (e.g., dados.ln).

\documentclass{article}
\usepackage{listings}
\usepackage{color}

\lstset{frame=tb,
language=R,
keywordstyle=\color{blue},
alsoletter={.}
}

\begin{document}

\begin{lstlisting}
L.V2<-log(V2)
dados.log<-dados
\end{lstlisting}

\end{document}

enter image description here

Two minor points:

  • In your minimal working example, don't forget \documentclass{article}.
  • You don't need to show all the settings in a minimal working example.

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.