yihui / formatR

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

move { to the next line #18

Closed yihui closed 12 years ago

yihui commented 12 years ago

some people prefer

if (foo)
{
  bar
}

to

if (foo) {
  bar
}

is it always safe to gsub('{$', '\n{', code)?

jaredlander commented 12 years ago

I'm going to second this feature. I am a firm believer in the curly brace being on the next line and very much want it to look that way in my book.

yihui commented 12 years ago

In fact I wrote this issue here just for you. Note the date was the next day of our NY talk :)

jaredlander commented 12 years ago

When I saw it today I had a feeling it was because of me. Thanks!

yihui commented 12 years ago

do you also want

fun({

})

to be

fun(
{

})

? I guess you do not.

jaredlander commented 12 years ago

No, don't think that would be good.

With inline functions, they should remain too.

ldply(myData,function(x) { x*2 })
yihui commented 12 years ago

That is too complicated for me. In that case, you should use tidy=FALSE.

Now you can use options(left.brace.newline = TRUE) to move { to a new line. You probably have a few edge cases in which this does not work. Anyway, feel free to test.

jaredlander commented 12 years ago

You rock! Thanks. Can I call that option from a code chunk in knitr?

The example I showed above shouldn't be a problem even with tidy=TRUE because the curly is not on the end of the line.

For the regular expression moving the curly, a thought occurred to me that this might be even safer: gsub('\\){$', '\n{', code) because the curly will always come after the closing parenthesis of a function definition or an if statement.

Just gave the new option a quick test and it worked great. I'll throw a lot more at it over the next few days.

Thanks again!

jaredlander commented 12 years ago

Looked at your code, you already covered the closing parenthesis. . .nice.

yihui commented 12 years ago

yes, both ) and else are possible candidates before {

jaredlander commented 12 years ago

Sweet.

jaredlander commented 12 years ago

Can't seem how to pass that argument as an option in a chunk in knitr. Is there a simple way to do so that I'm missing?

yihui commented 12 years ago

Set options(left.brace.newline = TRUE) in your first chunk. It is not a chunk option, so you cannot do it in <<>>=

jaredlander commented 12 years ago

Got it, thanks.