13

When editing an Sweave document in LaTeX (using the Noweb mode), Emacs knows to "ignore" code that is in <<>>= blocks. However, for interstitial \Sexpr{} blocks, this isn't the case. Given that R references by columns via '$' and LaTeX uses $ to set-off equations, these \Sexpr{} blocks often break the syntax highlighting, like so:

Emacs highlighting issue when using Sweave

I have a very rudimentary understanding the elisp & Emacs syntax highlighting, but my hope is that it might be possible to add something to .emacs that will disable any parsing/$ detection within \Sexpr{}'s.

John Horton
  • 4,122
  • 6
  • 31
  • 45
  • I assume you're using AUCTeX. In the default LaTeX mode that comes bundled with Emacs, this problem is less severe because the $...$ highlighting is only applied for short (single-line) math expressions, so it never "bleeds" like in your snapshot. IOW a bug report to the AUCTeX authors is in order. – Stefan Sep 20 '13 at 12:40

3 Answers3

8

I thought emacs with ESS has correct syntax highlighting for Sweave?

Anyway, the easiest "fix" is to just not use the $ operator but [[ instead. For example:

foo$p.value
foo[['p.value']]

Should give the same result. I think foo$p.value is just short for foo[["p.value",exact=FALSE]]

Sacha Epskamp
  • 46,463
  • 20
  • 113
  • 131
7

I don't have a fix either, but I'll pass along my workaround, which is to never (well, rarely) do any processing in \Sexpr chunks but instead to store things I want to use in \Sexpr in variables, and to do so in the same chunk I do the main calculations in.

<<echo=FALSE, results=hide>>=
t1 <- chisq.test(someVar)
p1 <- formatC(t1$p.value, format="%f", digits=2)
@

\dots with a $p$-value of \Sexpr{p1}.

While there are some downsides to this, I find it helps me to better keep track of what I want to present, and how I want to present it.

As an aside, consider using formatC instead of round as it can keep significant zeros (ie, 0.10 instead of 0.1).

Aaron left Stack Overflow
  • 36,704
  • 7
  • 77
  • 142
  • 1
    Good aside! I didn't know about the formatC thing. It's always driven me mad how R drops significant zeroes. – Chris Beeley Mar 27 '12 at 10:34
  • 1
    This approach also helps in the event of something like `\Sexpr{sprintf"%.2f",my.float)}` where emacs then treats everything after the percent symbol as a comment, which then breaks parenthesis matching, with all sorts of associated ugliness. – mac Oct 18 '12 at 13:47
5

I have no good answer for you as I am not an Emacs hacker, so I usually do one of two things:

  • Either add a simple % $ comment at the of the line to "close" the math expression from $ to $,

  • Or rewrite the expression to not use $-based subsetting:
    round(as.numeric(chisq.test(someVar)["p.value"]), 2).

Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725