yihui / formatR

Format R Code Automatically
https://yihui.org/formatr/
255 stars 52 forks source link

Comment parse error in 'if' block when 'tidy.source' is called #30

Closed ramhiser closed 11 years ago

ramhiser commented 11 years ago

If a comment is made after the if statement but before the { #code } block is invoked, an error results when using tidy.source.

To reproduce the error, create a file called test.r and add the following code:

world_ends <- TRUE                                                                                                                                                                                                                                                              
if (world_ends) # The world will end in 2012                                                                                                                                                                                                                                    
{                                                                                                                                                                                                                                                                               
  message("Goodbye, cruel world.")                                                                                                                                                                                                                                              
} 

Here's the error:

> tidy.source("test.r")
Error in base::parse(text = text, srcfile = NULL) (from tidy.R#112) :
  2:18: unexpected SPECIAL
1: world_ends <- TRUE                                                                                                                                                                                                                                                           
2: if (world_ends)  %InLiNe_IdEnTiFiEr%
                   ^

I'm using version 0.7.2 and the latest commit to the master branch on github.

yihui commented 11 years ago

That is a known limitation in Section 6: https://github.com/yihui/formatR/wiki

ramhiser commented 11 years ago

I see that now. Any recommendations on how to deal with this situation? Unfortunately, I encounter it from others far too often.

yihui commented 11 years ago

I think you can move these comments before if. First take a look at all such lines:

p = '^(\\s*if\\s*\\(.+\\)\\s*)(#.*)$'
x = readLines('file.R')
cat(grep(p, x, value = TRUE), sep = '\n')

If it is safe to move these comments, do it and save the modified code in another file.

writeLines(gsub(p, '\\2\n\\1', x), 'file2.R')

If you still feel unsafe, you can diff file.R file2.R and double check you did not really screw up the code.

Finally you tidy.source('file2.R').

ramhiser commented 11 years ago

Okay, thanks for your help.