# <unlabeled code block>
library(rformat)

cat(rformat("x=1+2"))

cat(rformat("f=function(x,y){
if(x>0)
y=mean(x,na.rm=TRUE)
else y=NA
}"))

# <unlabeled code block>
# 2 spaces per level
cat(rformat("f <- function(x) {\nif (x) {\ny\n}\n}", indent = 2L))

# Tab indent (shown as \t in output)
rformat("f <- function(x) {\nif (x) {\ny\n}\n}", indent = "\t")

# <unlabeled code block>
long_call <- "result <- some_function(alpha, bravo, charlie, delta)"

# Default 80: fits on one line
cat(rformat(long_call))

# Narrow limit: forces wrapping
cat(rformat(long_call, line_limit = 40))

# <unlabeled code block>
long_sig <- paste0(
    "my_function <- function(alpha, beta, gamma, ",
    "delta, epsilon, zeta, eta, theta, iota) ",
    "{\n    1\n}")

# Paren-aligned (default): continuation aligns to (
cat(rformat(long_sig, wrap = "paren"))

# Fixed: continuation uses 8-space indent
cat(rformat(long_sig, wrap = "fixed"))

# <unlabeled code block>
long_def <- paste0(
    "my_function <- function(alpha, beta, gamma, ",
    "delta, epsilon, zeta, eta, theta, iota) ",
    "{\n    y <- 1\n    y\n}")

# K&R (default): { on same line as )
cat(rformat(long_def, brace_style = "kr"))

# Allman: { on its own line
cat(rformat(long_def, brace_style = "allman"))

# <unlabeled code block>
code <- "f <- function(x) {
if (x > 0) y <- log(x)
if (x < 0) stop('negative')
}"

# Default: bare bodies left alone
cat(rformat(code))

# Add braces
cat(rformat(code, control_braces = TRUE))

# <unlabeled code block>
code <- "y <- if (x > 0) log(x) else NA"

# Default: inline if-else preserved
cat(rformat(code))

# Expanded to multi-line
cat(rformat(code, expand_if = TRUE))

# <unlabeled code block>
# Top-level } else on separate lines is a parse error.
# else_same_line (the default) repairs it:
code <- "if (x) {\n    1\n}\nelse {\n    2\n}"
cat(rformat(code))

# <unlabeled code block>
code <- "f <- function(x) {
if (x > 0) {
    y <- log(x)
}
else {
    y <- NA
}
y
}"

# Default: else joins the } line
cat(rformat(code))

# Preserve } / else on separate lines
cat(rformat(code, join_else = FALSE))

# <unlabeled code block>
code <- "f <- function(x, y) {\n    x + y\n}"

# Default: no space
cat(rformat(code))

# With space
cat(rformat(code, function_space = TRUE))

# <unlabeled code block>
code <- "f=function(x){
y=if(x>0) log(x) else NA
y
}"

cat(rformat(code,
    indent = 2L,
    brace_style = "allman",
    control_braces = TRUE,
    expand_if = TRUE))

# <unlabeled code block>
# Format a file (dry run)
f <- tempfile(fileext = ".R")
writeLines("x=1+2", f)
rformat_file(f, dry_run = TRUE)

# Format all R files in a directory (dry run)
d <- file.path(tempdir(), "rformat_demo")
dir.create(d, showWarnings = FALSE)
writeLines("y = 3", file.path(d, "example.R"))
rformat_dir(d, dry_run = TRUE)
unlink(d, recursive = TRUE)
unlink(f)

