withr/ 0000755 0001762 0000144 00000000000 14151431422 011404 5 ustar ligges users withr/NAMESPACE 0000644 0001762 0000144 00000003317 14151210400 012616 0 ustar ligges users # Generated by roxygen2: do not edit by hand
export(defer)
export(defer_parent)
export(deferred_clear)
export(deferred_run)
export(local_)
export(local_bmp)
export(local_cairo_pdf)
export(local_cairo_ps)
export(local_collate)
export(local_connection)
export(local_db_connection)
export(local_dir)
export(local_environment)
export(local_envvar)
export(local_file)
export(local_jpeg)
export(local_language)
export(local_libpaths)
export(local_locale)
export(local_makevars)
export(local_message_sink)
export(local_namespace)
export(local_options)
export(local_output_sink)
export(local_package)
export(local_par)
export(local_path)
export(local_pdf)
export(local_png)
export(local_postscript)
export(local_preserve_seed)
export(local_rng_version)
export(local_seed)
export(local_svg)
export(local_temp_libpaths)
export(local_tempdir)
export(local_tempfile)
export(local_tiff)
export(local_timezone)
export(local_xfig)
export(makevars_user)
export(set_makevars)
export(with_)
export(with_bmp)
export(with_cairo_pdf)
export(with_cairo_ps)
export(with_collate)
export(with_connection)
export(with_db_connection)
export(with_dir)
export(with_environment)
export(with_envvar)
export(with_file)
export(with_jpeg)
export(with_language)
export(with_libpaths)
export(with_locale)
export(with_makevars)
export(with_message_sink)
export(with_namespace)
export(with_options)
export(with_output_sink)
export(with_package)
export(with_par)
export(with_path)
export(with_pdf)
export(with_png)
export(with_postscript)
export(with_preserve_seed)
export(with_rng_version)
export(with_seed)
export(with_svg)
export(with_temp_libpaths)
export(with_tempdir)
export(with_tempfile)
export(with_tiff)
export(with_timezone)
export(with_xfig)
importFrom(stats,setNames)
withr/LICENSE 0000644 0001762 0000144 00000000053 13775602572 012430 0 ustar ligges users YEAR: 2020
COPYRIGHT HOLDER: withr authors
withr/README.md 0000644 0001762 0000144 00000011717 14151230316 012671 0 ustar ligges users
# withr - run code ‘with’ modified state
[](https://github.com/r-lib/withr/actions)
[](https://app.codecov.io/gh/r-lib/withr?branch=main)
[](https://www.r-pkg.org/pkg/withr)
## Overview
A set of functions to run code with safely and temporarily modified
global state, withr makes working with the global state, i.e. side
effects, less error-prone.
Pure functions, such as the `sum()` function, are easy to understand and
reason about: they always map the same input to the same output and have
no other impact on the workspace. In other words, pure functions have no
*side effects*: they are not affected by, nor do they affect, the global
state in any way apart from the value they return.
The behavior of some functions *is* affected by the global state.
Consider the `read.csv()` function: it takes a filename as an input and
returns the contents as an output. In this case, the output depends on
the contents of the file; i.e. the output is affected by the global
state. Functions like this deal with side effects.
The purpose of the withr package is to help you manage side effects in
your code. You may want to run code with secret information, such as an
API key, that you store as an environment variable. You may also want to
run code with certain options, with a given random-seed, or with a
particular working-directory.
The withr package helps you manage these situations, and more, by
providing functions to modify the global state temporarily, and safely.
These functions modify one of the global settings for duration of a
block of code, then automatically reset it after the block is completed.
## Installation
``` r
#Install the latest version with:
install.packages("withr")
```
Many of these functions were originally a part of the
[devtools](https://github.com/r-lib/devtools) package, this provides a
simple package with limited dependencies to provide access to these
functions.
- `with_collate()` / `local_collate()` - collation order
- `with_dir()` / `local_dir()` - working directory
- `with_envvar()` / `local_envvar()` - environment variables
- `with_libpaths()` / `local_libpaths()` - library paths
- `with_locale()` / `local_locale()` - any locale setting
- `with_makevars()` / `local_makevars()` / `set_makevars()` - makevars
variables
- `with_options()` / `local_options()` - options
- `with_par()` / `local_par()` - graphics parameters
- `with_path()` / `local_path()` - PATH environment variable
- `with_*()` and `local_*()` functions for the built in R devices,
`bmp`, `cairo_pdf`, `cairo_ps`, `pdf`, `postscript`, `svg`, `tiff`,
`xfig`, `png`, `jpeg`.
- `with_connection()` / `local_connection()` - R file connections
- `with_db_connection()` / `local_db_connection()` - DB conections
- `with_package()` / `local_package()`, `with_namespace()` /
`local_namespace()` and `with_environment()` /
`local_environment()` - to run code with modified object search
paths.
- `with_tempfile()` / `local_tempfile()` - create and clean up a temp
file.
- `with_file()` / `local_file()` - create and clean up a normal file.
- `with_message_sink()` / `local_message_sink()` - divert message
- `with_output_sink()` / `local_output_sink()` - divert output
- `with_preserve_seed()` / `with_seed()`- specify seeds
- `with_temp_libpaths()` / `local_temp_libpaths()` - library paths
- `defer()` / `defer_parent()` - defer
- `with_timezone()` / `local_timezone()` - timezones
- `with_rng_version()` / `local_rng_version()` - random number
generation version
## Usage
There are two sets of functions, those prefixed with `with_` and those
with `local_`. The former reset their state as soon as the `code`
argument has been evaluated. The latter reset when they reach the end of
their scope, usually at the end of a function body.
``` r
par("col" = "black")
my_plot <- function(new) {
with_par(list(col = "red", pch = 19),
plot(mtcars$hp, mtcars$wt)
)
par("col")
}
my_plot()
```
#> [1] "black"
par("col")
#> [1] "black"
f <- function(x) {
local_envvar(c("WITHR" = 2))
Sys.getenv("WITHR")
}
f()
#> [1] "2"
Sys.getenv("WITHR")
#> [1] ""
There are also `with_()` and `local_()` functions to construct new
`with_*` and `local_*` functions if needed.
``` r
Sys.getenv("WITHR")
#> [1] ""
with_envvar(c("WITHR" = 2), Sys.getenv("WITHR"))
#> [1] "2"
Sys.getenv("WITHR")
#> [1] ""
with_envvar(c("A" = 1),
with_envvar(c("A" = 2), action = "suffix", Sys.getenv("A"))
)
#> [1] "1 2"
```
# See Also
- [Devtools](https://github.com/r-lib/devtools)
withr/man/ 0000755 0001762 0000144 00000000000 14147463350 012171 5 ustar ligges users withr/man/with_makevars.Rd 0000644 0001762 0000144 00000003237 14036304442 015322 0 ustar ligges users % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/makevars.R
\name{with_makevars}
\alias{with_makevars}
\alias{local_makevars}
\title{Makevars variables}
\usage{
with_makevars(
new,
code,
path = makevars_user(),
assignment = c("=", ":=", "?=", "+=")
)
local_makevars(
.new = list(),
...,
.path = makevars_user(),
.assignment = c("=", ":=", "?=", "+="),
.local_envir = parent.frame()
)
}
\arguments{
\item{new, .new}{\verb{[named character]}\cr New variables and their values}
\item{code}{\code{[any]}\cr Code to execute in the temporary environment}
\item{path, .path}{\verb{[character(1)]}\cr location of existing \code{Makevars} file to modify.}
\item{assignment, .assignment}{\verb{[character(1)]}\cr assignment type to use.}
\item{...}{Additional new variables and their values.}
\item{.local_envir}{\verb{[environment]}\cr The environment to use for scoping.}
}
\value{
\code{[any]}\cr The results of the evaluation of the \code{code}
argument.
}
\description{
Temporarily change contents of an existing \code{Makevars} file.
}
\details{
If no \code{Makevars} file exists or the fields in \code{new} do
not exist in the existing \code{Makevars} file then the fields are added to
the new file. Existing fields which are not included in \code{new} are
appended unchanged. Fields which exist in \code{Makevars} and in \code{new}
are modified to use the value in \code{new}.
}
\examples{
writeLines("void foo(int* bar) { *bar = 1; }\n", "foo.c")
system("R CMD SHLIB --preclean -c foo.c")
with_makevars(c(CFLAGS = "-O3"), system("R CMD SHLIB --preclean -c foo.c"))
unlink(c("foo.c", "foo.so"))
}
\seealso{
\code{\link{withr}} for examples
}
withr/man/with_locale.Rd 0000644 0001762 0000144 00000003150 14036304442 014742 0 ustar ligges users % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/locale.R
\name{with_locale}
\alias{with_locale}
\alias{local_locale}
\title{Locale settings}
\usage{
with_locale(new, code)
local_locale(.new = list(), ..., .local_envir = parent.frame())
}
\arguments{
\item{new, .new}{\verb{[named character]}\cr New locale settings}
\item{code}{\code{[any]}\cr Code to execute in the temporary environment}
\item{...}{Additional arguments with locale settings.}
\item{.local_envir}{\verb{[environment]}\cr The environment to use for scoping.}
}
\value{
\code{[any]}\cr The results of the evaluation of the \code{code}
argument.
}
\description{
Temporarily change locale settings.
}
\details{
Setting the \code{LC_ALL} category is currently not implemented.
}
\examples{
## Change locale for time:
df <- data.frame(
stringsAsFactors = FALSE,
date = as.Date(c("2019-01-01", "2019-02-01")),
value = c(1, 2)
)
with_locale(new = c("LC_TIME" = "es_ES"), code = plot(df$date, df$value))
## Compare with:
# plot(df$date, df$value)
## Month names:
with_locale(new = c("LC_TIME" = "en_GB"), format(ISOdate(2000, 1:12, 1), "\%B"))
with_locale(new = c("LC_TIME" = "es_ES"), format(ISOdate(2000, 1:12, 1), "\%B"))
## Change locale for currencies:
with_locale(new = c("LC_MONETARY" = "it_IT"), Sys.localeconv())
with_locale(new = c("LC_MONETARY" = "en_US"), Sys.localeconv())
## Ordering:
x <- c("bernard", "bérénice", "béatrice", "boris")
with_locale(c(LC_COLLATE = "fr_FR"), sort(x))
with_locale(c(LC_COLLATE = "C"), sort(x))
}
\seealso{
\code{\link{withr}} for examples
\code{\link[=Sys.setlocale]{Sys.setlocale()}}
}
withr/man/withr.Rd 0000644 0001762 0000144 00000006233 14151210274 013607 0 ustar ligges users % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/with.R
\docType{package}
\name{withr}
\alias{withr}
\alias{withr-package}
\title{Execute code in temporarily altered environment}
\description{
All functions prefixed by \code{with_} work as follows. First, a particular
aspect of the global environment is modified (see below for a list).
Then, custom code (passed via the \code{code} argument) is executed.
Upon completion or error, the global environment is restored to the previous
state. Each \code{with_} function has a \code{local_} variant, which instead resets
the state when the current evaluation context ends (such as the end of a
function).
}
\section{Arguments pattern}{
\tabular{lll}{
\code{new} \tab \verb{[various]} \tab Values for setting \cr
\code{code} \tab \verb{[any]} \tab Code to execute in the temporary environment \cr
\code{...} \tab \tab Further arguments \cr
}
}
\section{Usage pattern}{
\code{with_...(new, code, ...)}
}
\section{withr functions}{
\itemize{
\item \code{\link[=with_collate]{with_collate()}}: collation order
\item \code{\link[=with_dir]{with_dir()}}: working directory
\item \code{\link[=with_envvar]{with_envvar()}}: environment variables
\item \code{\link[=with_libpaths]{with_libpaths()}}: library paths, replacing current libpaths
\item \code{\link[=with_locale]{with_locale()}}: any locale setting
\item \code{\link[=with_makevars]{with_makevars()}}: Makevars variables
\item \code{\link[=with_options]{with_options()}}: options
\item \code{\link[=with_par]{with_par()}}: graphics parameters
\item \code{\link[=with_path]{with_path()}}: \code{PATH} environment variable
\item \code{\link[=with_sink]{with_sink()}}: output redirection
}
}
\section{Creating new "with" functions}{
All \code{with_} functions are created by a helper function,
\code{\link[=with_]{with_()}}. This functions accepts two arguments:
a setter function and an optional resetter function. The setter function is
expected to change the global state and return an "undo instruction".
This undo instruction is then passed to the resetter function, which changes
back the global state. In many cases, the setter function can be used
naturally as resetter.
}
\examples{
getwd()
with_dir(tempdir(), getwd())
getwd()
Sys.getenv("WITHR")
with_envvar(c("WITHR" = 2), Sys.getenv("WITHR"))
Sys.getenv("WITHR")
with_envvar(c("A" = 1),
with_envvar(c("A" = 2), action = "suffix", Sys.getenv("A"))
)
# local variants are best used within other functions
f <- function(x) {
local_envvar(c("WITHR" = 2))
Sys.getenv("WITHR")
}
Sys.getenv("WITHR")
}
\seealso{
Useful links:
\itemize{
\item \url{https://withr.r-lib.org}
\item \url{https://github.com/r-lib/withr#readme}
\item Report bugs at \url{https://github.com/r-lib/withr/issues}
}
}
\author{
\strong{Maintainer}: Lionel Henry \email{lionel@rstudio.com}
Authors:
\itemize{
\item Jim Hester
\item Kirill Müller \email{krlmlr+r@mailbox.org}
\item Kevin Ushey \email{kevinushey@gmail.com}
\item Hadley Wickham \email{hadley@rstudio.com}
\item Winston Chang
}
Other contributors:
\itemize{
\item Jennifer Bryan [contributor]
\item Richard Cotton [contributor]
\item RStudio [copyright holder]
}
}
withr/man/with_db_connection.Rd 0000644 0001762 0000144 00000002475 14036304442 016320 0 ustar ligges users % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/db.R
\name{with_db_connection}
\alias{with_db_connection}
\alias{local_db_connection}
\title{DBMS Connections which disconnect themselves.}
\usage{
with_db_connection(con, code)
local_db_connection(con, .local_envir = parent.frame())
}
\arguments{
\item{con}{For \code{with_db_connection()} a named list with the connection(s) to
create. For \code{local_db_connection()} the code to create a single connection,
which is then returned.}
\item{code}{\code{[any]}\cr Code to execute in the temporary environment}
\item{.local_envir}{\verb{[environment]}\cr The environment to use for scoping.}
}
\value{
\code{[any]}\cr The results of the evaluation of the \code{code}
argument.
}
\description{
Connections to Database Management Systems which automatically disconnect. In
particular connections which are created with \code{DBI::dbConnect()} and closed
with \code{DBI::dbDisconnect()}.
}
\examples{
db <- tempfile()
with_db_connection(
list(con = DBI::dbConnect(RSQLite::SQLite(), db)), {
DBI::dbWriteTable(con, "mtcars", mtcars)
})
head_db_table <- function(...) {
con <- local_db_connection(DBI::dbConnect(RSQLite::SQLite(), db))
head(DBI::dbReadTable(con, "mtcars"), ...)
}
head_db_table()
unlink(db)
}
\seealso{
\code{\link{withr}} for examples
}
withr/man/with_par.Rd 0000644 0001762 0000144 00000002145 14036304442 014270 0 ustar ligges users % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/par.R
\name{with_par}
\alias{with_par}
\alias{local_par}
\title{Graphics parameters}
\usage{
with_par(new, code, no.readonly = FALSE)
local_par(
.new = list(),
...,
no.readonly = FALSE,
.local_envir = parent.frame()
)
}
\arguments{
\item{new, .new}{\verb{[named list]}\cr New graphics parameters and their values}
\item{code}{\code{[any]}\cr Code to execute in the temporary environment}
\item{no.readonly}{\verb{[logical(1)]}\cr see \code{\link[=par]{par()}} documentation.}
\item{...}{Additional graphics parameters and their values.}
\item{.local_envir}{\verb{[environment]}\cr The environment to use for scoping.}
}
\value{
\code{[any]}\cr The results of the evaluation of the \code{code}
argument.
}
\description{
Temporarily change graphics parameters.
}
\examples{
old <- par("col" = "black")
# This will be in red
with_par(list(col = "red", pch = 19),
plot(mtcars$hp, mtcars$wt)
)
# This will still be in black
plot(mtcars$hp, mtcars$wt)
par(old)
}
\seealso{
\code{\link{withr}} for examples
\code{\link[=par]{par()}}
}
withr/man/defer.Rd 0000644 0001762 0000144 00000005136 14036304442 013543 0 ustar ligges users % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/defer.R
\name{defer}
\alias{defer}
\alias{defer_parent}
\alias{deferred_run}
\alias{deferred_clear}
\title{Defer Evaluation of an Expression}
\usage{
defer(expr, envir = parent.frame(), priority = c("first", "last"))
defer_parent(expr, priority = c("first", "last"))
deferred_run(envir = parent.frame())
deferred_clear(envir = parent.frame())
}
\arguments{
\item{expr}{\verb{[expression]}\cr An expression to be evaluated.}
\item{envir}{\verb{[environment]}\cr Attach exit handlers to this environment.
Typically, this should be either the current environment or
a parent frame (accessed through \code{\link[=parent.frame]{parent.frame()}}).}
\item{priority}{\verb{[character(1)]}\cr Specify whether this handler should
be executed \code{"first"} or \code{"last"}, relative to any other
registered handlers on this environment.}
}
\description{
Similar to \code{\link[=on.exit]{on.exit()}}, but allows one to attach
an expression to be evaluated when exiting any frame currently
on the stack. This provides a nice mechanism for scoping side
effects for the duration of a function's execution.
}
\details{
\code{defer()} works by attaching handlers to the requested environment (as an
attribute called \code{"handlers"}), and registering an exit handler that
executes the registered handler when the function associated with the
requested environment finishes execution.
Deferred events can be set on the global environment, primarily to facilitate
the interactive development of code that is intended to be executed inside a
function or test. A message alerts the user to the fact that an explicit
\code{deferred_run()} is the only way to trigger these deferred events. Use
\code{deferred_clear()} to clear them without evaluation. The global environment
scenario is the main motivation for these functions.
}
\examples{
# define a 'local' function that creates a file, and
# removes it when the parent function has finished executing
local_file <- function(path) {
file.create(path)
defer_parent(unlink(path))
}
# create tempfile path
path <- tempfile()
# use 'local_file' in a function
local({
local_file(path)
stopifnot(file.exists(path))
})
# file is deleted as we leave 'local' local
stopifnot(!file.exists(path))
# investigate how 'defer' modifies the
# executing function's environment
local({
local_file(path)
print(attributes(environment()))
})
# defer and trigger events on the global environment
defer(print("one"))
defer(print("two"))
deferred_run()
defer(print("three"))
deferred_clear()
deferred_run()
}
\concept{local-related functions}
withr/man/with_language.Rd 0000644 0001762 0000144 00000001726 14147463350 015304 0 ustar ligges users % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/language.R
\name{with_language}
\alias{with_language}
\alias{local_language}
\title{Language}
\usage{
with_language(lang, code)
local_language(lang, .local_envir = parent.frame())
}
\arguments{
\item{lang}{A BCP47 language code like "en" (English), "fr" (French),
"fr_CA" (French Canadian). Formally, this is a lower case two letter
\href{https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes}{ISO 639 country code},
optionally followed by "_" or "-" and an upper case two letter
\href{https://en.wikipedia.org/wiki/ISO_3166-2}{ISO 3166 region code}.}
\item{code}{\code{[any]}\cr Code to execute in the temporary environment}
\item{.local_envir}{\verb{[environment]}\cr The environment to use for scoping.}
}
\description{
Temporarily change the language used for translations.
}
\examples{
with_language("en", try(mean[[1]]))
with_language("fr", try(mean[[1]]))
with_language("es", try(mean[[1]]))
}
withr/man/with_dir.Rd 0000644 0001762 0000144 00000001363 14036304442 014265 0 ustar ligges users % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/dir.R
\name{with_dir}
\alias{with_dir}
\alias{local_dir}
\title{Working directory}
\usage{
with_dir(new, code)
local_dir(new = list(), .local_envir = parent.frame())
}
\arguments{
\item{new}{\verb{[character(1)]}\cr New working directory}
\item{code}{\code{[any]}\cr Code to execute in the temporary environment}
\item{.local_envir}{\verb{[environment]}\cr The environment to use for scoping.}
}
\value{
\code{[any]}\cr The results of the evaluation of the \code{code}
argument.
}
\description{
Temporarily change the current working directory.
}
\examples{
getwd()
with_dir(tempdir(), getwd())
}
\seealso{
\code{\link{withr}} for examples
\code{\link[=setwd]{setwd()}}
}
withr/man/with_envvar.Rd 0000644 0001762 0000144 00000002555 14036304442 015014 0 ustar ligges users % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/env.R
\name{with_envvar}
\alias{with_envvar}
\alias{local_envvar}
\title{Environment variables}
\usage{
with_envvar(new, code, action = "replace")
local_envvar(
.new = list(),
...,
action = "replace",
.local_envir = parent.frame()
)
}
\arguments{
\item{new, .new}{\verb{[named character]}\cr New environment variables}
\item{code}{\code{[any]}\cr Code to execute in the temporary environment}
\item{action}{should new values \code{"replace"}, \code{"prefix"} or
\code{"suffix"} existing variables with the same name.}
\item{...}{Named arguments with new environment variables.}
\item{.local_envir}{\verb{[environment]}\cr The environment to use for scoping.}
}
\value{
\code{[any]}\cr The results of the evaluation of the \code{code}
argument.
}
\description{
Temporarily change system environment variables.
}
\details{
if \code{NA} is used those environment variables will be unset.
If there are any duplicated variable names only the last one is used.
}
\examples{
with_envvar(new = c("GITHUB_PAT" = "abcdef"), Sys.getenv("GITHUB_PAT"))
# with_envvar unsets variables after usage
Sys.getenv("TEMP_SECRET")
with_envvar(new = c("TEMP_SECRET" = "secret"), Sys.getenv("TEMP_SECRET"))
Sys.getenv("TEMP_SECRET")
}
\seealso{
\code{\link{withr}} for examples
\code{\link[=Sys.setenv]{Sys.setenv()}}
}
withr/man/set_makevars.Rd 0000644 0001762 0000144 00000001727 14036304442 015144 0 ustar ligges users % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/makevars.R
\name{set_makevars}
\alias{set_makevars}
\title{Create a new \code{Makevars} file, by adding new variables}
\usage{
set_makevars(
variables,
old_path = makevars_user(),
new_path = tempfile(),
assignment = c("=", ":=", "?=", "+=")
)
}
\arguments{
\item{variables}{\verb{[named character]}\cr new variables and their values}
\item{old_path}{\verb{[character(1)]}\cr location of existing \code{Makevars}
file to modify.}
\item{new_path}{\verb{[character(1)]}\cr location of the new \code{Makevars} file}
\item{assignment}{\verb{[character(1)]}\cr assignment type to use.}
}
\description{
You probably want \code{\link[=with_makevars]{with_makevars()}} instead of this function.
}
\details{
Unlike \code{\link[=with_makevars]{with_makevars()}}, it does not activate the new \code{Makevars}
file, i.e. it does not set the \code{R_MAKEVARS_USER} environment variable.
}
\keyword{internal}
withr/man/with_options.Rd 0000644 0001762 0000144 00000003122 14036304442 015175 0 ustar ligges users % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/options.R
\name{with_options}
\alias{with_options}
\alias{local_options}
\title{Options}
\usage{
with_options(new, code)
local_options(.new = list(), ..., .local_envir = parent.frame())
}
\arguments{
\item{new, .new}{\verb{[named list]}\cr New options and their values}
\item{code}{\code{[any]}\cr Code to execute in the temporary environment}
\item{...}{Additional options and their values}
\item{.local_envir}{\verb{[environment]}\cr The environment to use for scoping.}
}
\value{
\code{[any]}\cr The results of the evaluation of the \code{code}
argument.
}
\description{
Temporarily change global options.
}
\examples{
# number of significant digits to print
getOption("digits")
# modify temporarily the number of significant digits to print
with_options(list(digits = 3), getOption("digits"))
with_options(list(digits = 3), print(pi))
# modify temporarily the character to be used as the decimal point
getOption("digits")
with_options(list(OutDec = ","), print(pi))
# modify temporarily multiple options
with_options(list(OutDec = ",", digits = 3), print(pi))
# modify, within the scope of the function, the number of
# significant digits to print
print_3_digits <- function(x) {
# assign 3 to the option "digits" for the rest of this function
# after the function exits, the option will return to its previous
# value
local_options(list(digits = 3))
print(x)
}
print_3_digits(pi) # returns 3.14
print(pi) # returns 3.141593
}
\seealso{
\code{\link{withr}} for examples
\code{\link[=options]{options()}}
}
withr/man/with_package.Rd 0000644 0001762 0000144 00000006606 14036304442 015107 0 ustar ligges users % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/namespace.R
\name{with_package}
\alias{with_package}
\alias{local_package}
\alias{with_namespace}
\alias{local_namespace}
\alias{with_environment}
\alias{local_environment}
\title{Execute code with a modified search path}
\usage{
with_package(
package,
code,
pos = 2,
lib.loc = NULL,
character.only = TRUE,
logical.return = FALSE,
warn.conflicts = FALSE,
quietly = TRUE,
verbose = getOption("verbose")
)
local_package(
package,
pos = 2,
lib.loc = NULL,
character.only = TRUE,
logical.return = FALSE,
warn.conflicts = FALSE,
quietly = TRUE,
verbose = getOption("verbose"),
.local_envir = parent.frame()
)
with_namespace(package, code, warn.conflicts = FALSE)
local_namespace(package, .local_envir = parent.frame(), warn.conflicts = FALSE)
with_environment(
env,
code,
pos = 2L,
name = format(env),
warn.conflicts = FALSE
)
local_environment(
env,
pos = 2L,
name = format(env),
warn.conflicts = FALSE,
.local_envir = parent.frame()
)
}
\arguments{
\item{package}{\code{[character(1)]}\cr package name to load.}
\item{code}{\code{[any]}\cr Code to execute in the temporary environment}
\item{pos}{the position on the search list at which to attach the
loaded namespace. Can also be the name of a position on the current
search list as given by \code{\link[base]{search}()}.}
\item{lib.loc}{a character vector describing the location of \R
library trees to search through, or \code{NULL}. The default value
of \code{NULL} corresponds to all libraries currently known to
\code{\link[base]{.libPaths}()}.
Non-existent library trees are silently ignored.}
\item{character.only}{a logical indicating whether \code{package} or
\code{help} can be assumed to be character strings.}
\item{logical.return}{logical. If it is \code{TRUE}, \code{FALSE} or
\code{TRUE} is returned to indicate success.}
\item{warn.conflicts}{logical. If \code{TRUE}, warnings are
printed about \code{\link[base]{conflicts}} from attaching the new
package. A conflict is a function masking a function,
or a non-function masking a non-function. The default is \code{TRUE}
unless specified as \code{FALSE} in the \code{conflicts.policy} option.
}
\item{quietly}{a logical. If \code{TRUE}, no message confirming
package attaching is printed, and most often, no errors/warnings are
printed if package attaching fails.}
\item{verbose}{a logical. If \code{TRUE}, additional diagnostics are
printed.}
\item{.local_envir}{\verb{[environment]}\cr The environment to use for scoping.}
\item{env}{\code{[environment()]}\cr Environment to attach.}
\item{name}{name to use for the attached database. Names starting with
\code{package:} are reserved for \code{\link[base]{library}}.}
}
\value{
\code{[any]}\cr The results of the evaluation of the \code{code}
argument.
}
\description{
\code{with_package()} attaches a package to the search path, executes the code, then
removes the package from the search path. The package namespace is \emph{not}
unloaded however. \code{with_namespace()} does the same thing, but attaches the
package namespace to the search path, so all objects (even unexported ones) are also
available on the search path.
}
\examples{
\dontrun{
with_package("ggplot2", {
ggplot(mtcars) + geom_point(aes(wt, hp))
})
}
}
\seealso{
\code{\link{withr}} for examples
}
withr/man/devices.Rd 0000644 0001762 0000144 00000020503 14036304442 014073 0 ustar ligges users % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/devices.R
\name{devices}
\alias{devices}
\alias{with_dev}
\alias{with_device}
\alias{with_bmp}
\alias{local_bmp}
\alias{with_cairo_pdf}
\alias{local_cairo_pdf}
\alias{with_cairo_ps}
\alias{local_cairo_ps}
\alias{with_pdf}
\alias{local_pdf}
\alias{with_postscript}
\alias{local_postscript}
\alias{with_svg}
\alias{local_svg}
\alias{with_tiff}
\alias{local_tiff}
\alias{with_xfig}
\alias{local_xfig}
\alias{with_png}
\alias{local_png}
\alias{with_jpeg}
\alias{local_jpeg}
\title{Graphics devices}
\usage{
with_bmp(new, code, ...)
local_bmp(new = list(), ..., .local_envir = parent.frame())
with_cairo_pdf(new, code, ...)
local_cairo_pdf(new = list(), ..., .local_envir = parent.frame())
with_cairo_ps(new, code, ...)
local_cairo_ps(new = list(), ..., .local_envir = parent.frame())
with_pdf(
new,
code,
width,
height,
onefile,
family,
title,
fonts,
version,
paper,
encoding,
bg,
fg,
pointsize,
pagecentre,
colormodel,
useDingbats,
useKerning,
fillOddEven,
compress
)
local_pdf(
new = list(),
width,
height,
onefile,
family,
title,
fonts,
version,
paper,
encoding,
bg,
fg,
pointsize,
pagecentre,
colormodel,
useDingbats,
useKerning,
fillOddEven,
compress,
.local_envir = parent.frame()
)
with_postscript(
new,
code,
onefile,
family,
title,
fonts,
encoding,
bg,
fg,
width,
height,
horizontal,
pointsize,
paper,
pagecentre,
print.it,
command,
colormodel,
useKerning,
fillOddEven
)
local_postscript(
new = list(),
onefile,
family,
title,
fonts,
encoding,
bg,
fg,
width,
height,
horizontal,
pointsize,
paper,
pagecentre,
print.it,
command,
colormodel,
useKerning,
fillOddEven,
.local_envir = parent.frame()
)
with_svg(
new,
code,
width = 7,
height = 7,
pointsize = 12,
onefile = FALSE,
family = "sans",
bg = "white",
antialias = c("default", "none", "gray", "subpixel"),
...
)
local_svg(
new = list(),
width = 7,
height = 7,
pointsize = 12,
onefile = FALSE,
family = "sans",
bg = "white",
antialias = c("default", "none", "gray", "subpixel"),
...,
.local_envir = parent.frame()
)
with_tiff(new, code, ...)
local_tiff(new = list(), ..., .local_envir = parent.frame())
with_xfig(
new,
code,
onefile = FALSE,
encoding = "none",
paper = "default",
horizontal = TRUE,
width = 0,
height = 0,
family = "Helvetica",
pointsize = 12,
bg = "transparent",
fg = "black",
pagecentre = TRUE,
defaultfont = FALSE,
textspecial = FALSE
)
local_xfig(
new = list(),
onefile = FALSE,
encoding = "none",
paper = "default",
horizontal = TRUE,
width = 0,
height = 0,
family = "Helvetica",
pointsize = 12,
bg = "transparent",
fg = "black",
pagecentre = TRUE,
defaultfont = FALSE,
textspecial = FALSE,
.local_envir = parent.frame()
)
with_png(new, code, ...)
local_png(new = list(), ..., .local_envir = parent.frame())
with_jpeg(new, code, ...)
local_jpeg(new = list(), ..., .local_envir = parent.frame())
}
\arguments{
\item{new}{\code{[named character]}\cr New graphics device}
\item{code}{\code{[any]}\cr Code to execute in the temporary environment}
\item{...}{Additional arguments passed to the graphics device.}
\item{.local_envir}{\verb{[environment]}\cr The environment to use for scoping.}
\item{width}{the width of the device in inches.}
\item{height}{the height of the device in inches.}
\item{onefile}{should all plots appear in one file or in separate files?}
\item{family}{one of the device-independent font families,
\code{"sans"}, \code{"serif"} and \code{"mono"}, or a character
string specify a font family to be searched for in a
system-dependent way.
On unix-alikes (incl.\\ Mac), see
the \sQuote{Cairo fonts} section in the help for \code{\link[grDevices]{X11}}.
}
\item{title}{title string to embed as the \samp{/Title} field in the
file. Defaults to \code{"R Graphics Output"}.}
\item{fonts}{a character vector specifying \R graphics font family
names for additional fonts which will be included in the PDF file.
Defaults to \code{NULL}.}
\item{version}{a string describing the PDF version that will be
required to view the output. This is a minimum, and will be
increased (with a warning) if necessary. Defaults to \code{"1.4"},
but see \sQuote{Details}.}
\item{paper}{the target paper size. The choices are
\code{"a4"}, \code{"letter"}, \code{"legal"} (or \code{"us"}) and
\code{"executive"} (and these can be capitalized), or \code{"a4r"}
and \code{"USr"} for rotated (\sQuote{landscape}).
The default is \code{"special"}, which means that the \code{width}
and \code{height} specify the paper size. A further choice is
\code{"default"}; if this is selected, the
papersize is taken from the option \code{"papersize"}
if that is set and as \code{"a4"} if it is unset or empty.
Defaults to \code{"special"}.
}
\item{encoding}{the name of an encoding file. See
\code{\link[grDevices]{postscript}} for details. Defaults to \code{"default"}.}
\item{bg}{the initial background colour: can be overridden by setting
par("bg").}
\item{fg}{the initial foreground color to be used. Defaults to
\code{"black"}.}
\item{pointsize}{the default pointsize of plotted text (in big points).}
\item{pagecentre}{logical: should the device region be centred on the
page? -- is only relevant for \code{paper != "special"}.
Defaults to \code{TRUE}.}
\item{colormodel}{a character string describing the color model:
currently allowed values are \code{"srgb"}, \code{"gray"} (or
\code{"grey"}) and \code{"cmyk"}. Defaults to \code{"srgb"}. See section
\sQuote{Color models}.}
\item{useDingbats}{logical. Should small circles be rendered
\emph{via} the Dingbats font? Defaults to \code{FALSE}.
If \code{TRUE}, this can produce smaller and better output, but
there can font display problems in broken PDF viewers: although this
font is one of the 14 guaranteed to be available in all PDF viewers,
that guarantee is not always honoured.
For Unix-alikes (including macOS) see the \sQuote{Note} for a
possible fix for some viewers.}
\item{useKerning}{logical. Should kerning corrections be included in
setting text and calculating string widths? Defaults to \code{TRUE}.}
\item{fillOddEven}{logical controlling the polygon fill mode: see
\code{\link{polygon}} for details. Defaults to \code{FALSE}.}
\item{compress}{logical. Should PDF streams be generated with Flate
compression? Defaults to \code{TRUE}.}
\item{horizontal}{the orientation of the printed image, a logical.
Defaults to true, that is landscape orientation on paper sizes
with width less than height.}
\item{print.it}{logical: should the file be printed when the device is
closed? (This only applies if \code{file} is a real file name.)
Defaults to false.}
\item{command}{the command to be used for \sQuote{printing}. Defaults
to \code{"default"}, the value of option \code{"printcmd"}. The
length limit is \code{2*PATH_MAX}, typically 8096 bytes on unix systems and
520 bytes on windows.}
\item{antialias}{string, the type of anti-aliasing (if any) to be used;
defaults to \code{"default"}.}
\item{defaultfont}{logical: should the device use xfig's default
font?}
\item{textspecial}{logical: should the device set the textspecial flag
for all text elements. This is useful when generating pstex from xfig
figures.}
}
\value{
\code{[any]}\cr The results of the evaluation of the \code{code}
argument.
}
\description{
Temporarily use a graphics device.
}
\section{Functions}{
\itemize{
\item \code{with_bmp}: BMP device
\item \code{with_cairo_pdf}: CAIRO_PDF device
\item \code{with_cairo_ps}: CAIRO_PS device
\item \code{with_pdf}: PDF device
\item \code{with_postscript}: POSTSCRIPT device
\item \code{with_svg}: SVG device
\item \code{with_tiff}: TIFF device
\item \code{with_xfig}: XFIG device
\item \code{with_png}: PNG device
\item \code{with_jpeg}: JPEG device
}}
\examples{
# dimensions are in inches
with_pdf(file.path(tempdir(), "test.pdf"), width = 7, height = 5,
plot(runif(5))
)
# dimensions are in pixels
with_png(file.path(tempdir(), "test.png"), width = 800, height = 600,
plot(runif(5))
)
}
\seealso{
\code{\link{withr}} for examples
\code{\link[grDevices]{Devices}}
}
withr/man/with_.Rd 0000644 0001762 0000144 00000004470 14036304442 013570 0 ustar ligges users % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/local_.R, R/with_.R
\name{local_}
\alias{local_}
\alias{with_}
\title{Create a new "with" or "local" function}
\usage{
local_(set, reset = set, envir = parent.frame(), new = TRUE, dots = FALSE)
with_(set, reset = set, envir = parent.frame(), new = TRUE)
}
\arguments{
\item{set}{\verb{[function(...)]}\cr Function used to set the state.
The function can have arbitrarily many arguments, they will be replicated
in the formals of the returned function.}
\item{reset}{\verb{[function(x)]}\cr Function used to reset the state.
The first argument can be named arbitrarily, further arguments with default
values, or a "dots" argument, are supported but not used: The function will
be called as \code{reset(old)}.}
\item{envir}{\verb{[environment]}\cr Environment of the returned function.}
\item{new}{\verb{[logical(1)]}\cr Replace the first argument of the \code{set} function
by \code{new}? Set to \code{FALSE} if the \code{set} function only has optional arguments.}
}
\value{
\verb{[function(new, code, ...)]} A function with at least two arguments,
\itemize{
\item \code{new}: New state to use
\item \code{code}: Code to run in that state.
}
If there are more arguments to the function passed in \code{set} they are
added to the returned function. If \code{set} does not have arguments,
or \code{new} is \code{FALSE}, the returned function does not have a \code{code} argument.
}
\description{
These are constructors for \code{with_...} or \code{local_...} functions.
They are only needed if you want to alter some global state which is not
covered by the existing \code{with_...} functions, see \link{withr}
for an overview.
}
\details{
The \code{with_...} functions reset the state immediately after the
\code{code} argument has been evaluated. The \code{local_...} functions
reset their arguments after they go out of scope, usually at the end of the
function body.
}
\examples{
with_(setwd)
global_stack <- list()
set_global_state <- function(state, msg = "Changing global state.") {
global_stack <- c(list(state), global_stack)
message(msg)
state
}
reset_global_state <- function(state) {
old_state <- global_stack[[1]]
global_stack <- global_stack[-1]
stopifnot(identical(state, old_state))
}
with_(set_global_state, reset_global_state)
}
\keyword{internal}
withr/man/with_libpaths.Rd 0000644 0001762 0000144 00000002113 14036304442 015307 0 ustar ligges users % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/libpaths.R
\name{with_libpaths}
\alias{with_libpaths}
\alias{local_libpaths}
\title{Library paths}
\usage{
with_libpaths(new, code, action = "replace")
local_libpaths(new = list(), action = "replace", .local_envir = parent.frame())
}
\arguments{
\item{new}{\verb{[character]}\cr New library paths}
\item{code}{\code{[any]}\cr Code to execute in the temporary environment}
\item{action}{\verb{[character(1)]}\cr should new values \code{"replace"}, \code{"prefix"} or
\code{"suffix"} existing paths.}
\item{.local_envir}{\verb{[environment]}\cr The environment to use for scoping.}
}
\value{
\code{[any]}\cr The results of the evaluation of the \code{code}
argument.
}
\description{
Temporarily change library paths.
}
\examples{
.libPaths()
new_lib <- tempfile()
dir.create(new_lib)
with_libpaths(new_lib, print(.libPaths()))
unlink(new_lib, recursive = TRUE)
}
\seealso{
\code{\link{withr}} for examples
\code{\link[=.libPaths]{.libPaths()}}
Other libpaths:
\code{\link{with_temp_libpaths}()}
}
\concept{libpaths}
withr/man/with_collate.Rd 0000644 0001762 0000144 00000001566 14036304442 015137 0 ustar ligges users % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/collate.R
\name{with_collate}
\alias{with_collate}
\alias{local_collate}
\title{Collation Order}
\usage{
with_collate(new, code)
local_collate(new = list(), .local_envir = parent.frame())
}
\arguments{
\item{new}{\verb{[character(1)]}\cr New collation order}
\item{code}{\code{[any]}\cr Code to execute in the temporary environment}
\item{.local_envir}{\verb{[environment]}\cr The environment to use for scoping.}
}
\value{
\code{[any]}\cr The results of the evaluation of the \code{code}
argument.
}
\description{
Temporarily change collation order by changing the value of the
\code{LC_COLLATE} locale.
}
\examples{
# Modify collation order:
x <- c("bernard", "bérénice", "béatrice", "boris")
with_collate("fr_FR", sort(x))
with_collate("C", sort(x))
}
\seealso{
\code{\link{withr}} for examples
}
withr/man/with_connection.Rd 0000644 0001762 0000144 00000002030 14036304442 015636 0 ustar ligges users % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/connection.R
\name{with_connection}
\alias{with_connection}
\alias{local_connection}
\title{Connections which close themselves}
\usage{
with_connection(con, code)
local_connection(con, .local_envir = parent.frame())
}
\arguments{
\item{con}{For \code{with_connection()} a named list with the connection(s) to
create. For \code{local_connection()} the code to create a single connection,
which is then returned.}
\item{code}{\code{[any]}\cr Code to execute in the temporary environment}
\item{.local_envir}{\verb{[environment]}\cr The environment to use for scoping.}
}
\value{
\code{[any]}\cr The results of the evaluation of the \code{code}
argument.
}
\description{
R file connections which are automatically closed.
}
\examples{
with_connection(list(con = file("foo", "w")), {
writeLines(c("foo", "bar"), con)
})
read_foo <- function() {
readLines(local_connection(file("foo", "r")))
}
read_foo()
unlink("foo")
}
\seealso{
\code{\link{withr}} for examples
}
withr/man/makevars_user.Rd 0000644 0001762 0000144 00000000406 14036304442 015320 0 ustar ligges users % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/utils.R
\name{makevars_user}
\alias{makevars_user}
\title{Shim for tools::makevars_user()}
\usage{
makevars_user()
}
\description{
Shim for tools::makevars_user()
}
\keyword{internal}
withr/man/with_tempfile.Rd 0000644 0001762 0000144 00000003625 14036304442 015317 0 ustar ligges users % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/tempfile.R
\name{with_tempfile}
\alias{with_tempfile}
\alias{local_tempfile}
\alias{with_tempdir}
\alias{local_tempdir}
\title{Temporary files}
\usage{
with_tempfile(
new,
code,
envir = parent.frame(),
.local_envir = parent.frame(),
pattern = "file",
tmpdir = tempdir(),
fileext = ""
)
local_tempfile(
new = NULL,
envir = parent.frame(),
.local_envir = parent.frame(),
pattern = "file",
tmpdir = tempdir(),
fileext = ""
)
with_tempdir(
code,
clean = TRUE,
pattern = "file",
tmpdir = tempdir(),
fileext = ""
)
local_tempdir(
pattern = "file",
tmpdir = tempdir(),
fileext = "",
.local_envir = parent.frame(),
clean = TRUE
)
}
\arguments{
\item{new}{\verb{[character vector]}\cr (Deprecated for \code{local_tempfile()}) Names of temporary file handles to create.}
\item{code}{\code{[any]}\cr Code to execute in the temporary environment}
\item{envir}{\verb{[environment]}\cr Deprecated in favor of \code{.local_envir}.}
\item{.local_envir}{\verb{[environment]}\cr The environment to use for scoping.}
\item{pattern}{a non-empty character vector giving the initial part
of the name.}
\item{tmpdir}{a non-empty character vector giving the directory name}
\item{fileext}{a non-empty character vector giving the file extension}
\item{clean}{\verb{[logical(1)]}\cr A logical indicating if the temporary
directory should be deleted after use (\code{TRUE}, default) or left alone (\code{FALSE}).}
}
\value{
\code{[any]}\cr The results of the evaluation of the \code{code}
argument.
}
\description{
Temporarily create a tempfile, which is automatically removed afterwards.
}
\examples{
# check how big iris would be if written as csv vs RDS
tf <- with_tempfile("tf", {write.csv(iris, tf); file.size(tf)})
tf <- with_tempfile("tf", {saveRDS(iris, tf); file.size(tf)})
}
\seealso{
\code{\link{withr}} for examples
}
withr/man/with_sink.Rd 0000644 0001762 0000144 00000002760 14036304442 014455 0 ustar ligges users % Generated by roxygen2: do not edit by hand
% Please edit documentation in R/sink.R
\name{with_sink}
\alias{with_sink}
\alias{with_output_sink}
\alias{local_output_sink}
\alias{with_message_sink}
\alias{local_message_sink}
\title{Output redirection}
\usage{
with_output_sink(new, code, append = FALSE, split = FALSE)
local_output_sink(
new = list(),
append = FALSE,
split = FALSE,
.local_envir = parent.frame()
)
with_message_sink(new, code, append = FALSE)
local_message_sink(new = list(), append = FALSE, .local_envir = parent.frame())
}
\arguments{
\item{new}{\verb{[character(1)|connection]}\cr
A writable \link{connection} or a character string naming the file to write
to. Passing \code{NULL} will throw an error.}
\item{code}{\code{[any]}\cr Code to execute in the temporary environment}
\item{append}{logical. If \code{TRUE}, output will be appended to
\code{file}; otherwise, it will overwrite the contents of
\code{file}.}
\item{split}{logical: if \code{TRUE}, output will be sent to the new
sink and to the current output stream, like the Unix program \code{tee}.}
\item{.local_envir}{\verb{[environment]}\cr The environment to use for scoping.}
}
\value{
\code{[any]}\cr The results of the evaluation of the \code{code}
argument.
}
\description{
Temporarily divert output to a file via \code{\link[=sink]{sink()}}. For
sinks of type \code{message}, an error is raised if such a sink is already
active.
}
\seealso{
\code{\link{withr}} for examples
\code{\link[=sink]{sink()}}
}
withr/man/figures/ 0000755 0001762 0000144 00000000000 14151210371 013621 5 ustar ligges users withr/man/figures/README-unnamed-chunk-3-1.png 0000644 0001762 0000144 00000056730 14151210371 020330 0 ustar ligges users PNG
IHDR z4 iCCPkCGColorSpaceGenericRGB 8U]hU>+$Ԧ5lRфem,lAݝi&3i)>A['!j-P(G 3k~s,[%,-:t}
}-+*&¿ gPG݅ج8"e Ų]A b ;l õ Wϙ2_E,(ۈ#Zsێ<5)"E6N#ӽEkۃO0}*rUt.iei # ]r
>cU{t7+ԙg߃xu