yihui / formatR

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

Suggestion: Kernighan and Ritchie style #41

Closed gvfarns closed 10 years ago

gvfarns commented 10 years ago

The original indentation style pioneered by Kernighan and Ritchie in the book that defined the C language specified keeping open curly bracket on the same line for if, for, and other statements, but to put it on a line by itself for a function. The Linux kernel follows this style and so do I in my R code.

There is also a practical reason to use this formatting: vi/vim doesn't understand the beginnings of R functions unless the curly bracket is on a line by itself. As a result you can't highlight by function or easily move around by function in vim unless the curly bracket is by itself for a function. The same advantages are not present for other statements so putting it by itself everywhere is not necessary.

What I suggest is an option to enable the following formatting:

f <- function(x)
{
  if (x>0) {
    return(x^2)
  } else {
    return(-x^2)
  }
}

This is the formatting of the pure in heart. I think it would be great to be able to achieve this within the context of formatR. Thanks!

yihui commented 10 years ago

Styles in programming are not so much different from styles in dressing. In most cases, it does not really hurt if you use a different style. I understand people make different choices. I can certainly accommodate your style if the implementation is easy for me, but in this case, it is not easy unfortunately.

Personally I'm slightly against this style, because I do not want R code that is not supposed to be complete to be complete by chance (e.g. when you copy and run it), i.e.

{
  # function body
}

is a complete R expression when it is supposed to be the body of a function f:

f <- function()
{
  # function body
}

If you write

f <- function() {
  # function body
}

It is more unlikely that you copy a few lines of the code and it happens to be a complete expression.

No strong opinion here. Just a minor thought. Thanks for the suggestion anyway!