Learn R Programming

animation (version 1.1-0)

tidy.source: `Tidy up' R Code and Partially Preserve Comments

Description

Actually this function has nothing to do with code optimization; it just returns parsed source code, but some comments can be preserved, which is different with parse. See `Details'.

Usage

tidy.source(source = "clipboard", keep.comment = TRUE, 
    keep.blank.line = TRUE, begin.comment, end.comment, 
    output = TRUE, width.cutoff = 60L, ...)

Arguments

source
a string: location of the source code (default to be the clipboard; this means we can copy the code to clipboard and use tidy.souce() without specifying the argument source)
keep.comment
logical value: whether to keep comments or not?
keep.blank.line
logical value: whether to keep blank lines or not?
begin.comment, end.comment
identifiers to mark the comments
output
output to the console or a file using cat?
width.cutoff
passed to deparse: integer in [20, 500] determining the cutoff at which line-breaking is tried
...
other arguments passed to cat, e.g. file

Value

  • A list with components
  • text.tidyThe parsed code as a character vector.
  • text.maskThe code containing comments, which are masked in assignments.
  • begin.comment, end.commentidentifiers used to mark the comments
  • Note that 'clean' code will be printed in the console unless the output is redirected by sink, and we can also write the clean code to a file.

Details

This function helps the users to tidy up their source code in a sense that necessary indents and spaces will be added, etc. See parse. But comments which are in single lines will be preserved if keep.comment = TRUE (inline comments will be removed). The method to preserve comments is to protect them as strings in disguised assignments: combine end.comment to the end of a comment line and 'assign' the whole line to begin.comment, so the comment line will not be removed when parsed. At last, we remove the identifiers begin.comment and end.comment.

References

http://animation.yihui.name/animation:misc#tidy_up_r_source

See Also

parse, deparse, cat

Examples

Run this code
## tidy up the source code of image demo 
x = file.path(system.file(package = "graphics"), "demo", "image.R") 
# to console 
tidy.source(x)
# to a file
f = tempfile()
tidy.source(x, keep.blank.line = TRUE, file = f) 
## check the original code here and see the difference 
file.show(x)
file.show(f)
## if you've copied R code into the clipboard 
tidy.source("clipboard")
## write into clipboard again
tidy.source("clipboard", file = "clipboard")

Run the code above in your browser using DataLab