Is there any tool (editor, script, whatever...) available that can automatically reformat R code? It does not need to be customizable but it must be able to recognize statements separated by either semicolons or newlines since this code has both. If it can put all statements on a separate line, consistently indent code blocks and consistently place braces I will be very happy.
Edit: summarizing findings
Thanks for the great answers. Here is what I've found.
- Both ESS and StatET are great R editors and do a nice job of auto indenting blocks of code. StatET allows you to select-all and re-indent everything in a file at once. From what I could tell ESS allows you to indent an entire function def at once but not the entire file (please correct me if I missed it). Neither of these will fix brace placement or break up multi-statement lines. (Eg: i = n*b;a=i+1)
- formatR is awesome. In addition to fixing indentation it will also place braces consistently and split up multi-statement lines.
Here's a little function I wrote so that I can convert an entire source dir (using the same underlying function as formatR which is strangely in the animation package).
library("animation")
tidy.all <- function(inDir = NULL, outDir = NULL, ...) {
if (is.null(inDir) || is.na(outDir))
stop("inDir can't be null or NA")
if (!file.info(inDir)$isdir)
stop("inDir must be a directory")
if (is.null(outDir) || is.na(outDir))
stop("outDir can't be null or NA")
if (!file.exists(outDir))
dir.create(outDir)
if (!file.info(outDir)$isdir)
stop("outDir must be a directory")
for (f in dir(inDir)) {
currFile <- file.path(inDir, f)
if (length(grep(".*\\.R$", currFile, perl = T))) {
outFile <- file.path(outDir, f)
if (file.exists(outFile))
stop(paste("refusing to overwrite", outFile))
tidy.source(currFile, file = outFile, ...)
}
}
}