The R Project SVN R

Rev

Rev 88832 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
42333 ripley 1
% File src/library/base/man/source.Rd
68948 ripley 2
% Part of the R package, https://www.R-project.org
85219 maechler 3
% Copyright 1995-2023 R Core Team
42333 ripley 4
% Distributed under GPL 2 or later
5
 
2 r 6
\name{source}
71357 maechler 7
\title{Read R Code from a File, a Connection or Expressions}
8
\alias{source}
9
\alias{withAutoprint}
53899 ripley 10
\description{
11
  \code{source} causes \R to accept its input from the named file or URL
71357 maechler 12
  or connection or expressions directly.  Input is read and
13
  \code{\link{parse}}d from that file
53899 ripley 14
  until the end of the file is reached, then the parsed expressions are
15
  evaluated sequentially in the chosen environment.
71357 maechler 16
 
71376 maechler 17
  \code{withAutoprint(exprs)} is a wrapper for \code{source(exprs =
18
  exprs, ..)} with different defaults.  Its main purpose is to evaluate
87291 maechler 19
  and auto-print expressions as if in a top-level context, e.g, as in the
71376 maechler 20
  \R console.
53899 ripley 21
}
2 r 22
\usage{
2394 maechler 23
source(file, local = FALSE, echo = verbose, print.eval = echo,
71357 maechler 24
       exprs, spaced = use_file,
30912 ripley 25
       verbose = getOption("verbose"),
26
       prompt.echo = getOption("prompt"),
71357 maechler 27
       max.deparse.length = 150, width.cutoff = 60L,
71376 maechler 28
       deparseCtrl = "showAttributes",
71357 maechler 29
       chdir = FALSE,
85268 maechler 30
       catch.aborts = FALSE,
39996 murdoch 31
       encoding = getOption("encoding"),
32
       continue.echo = getOption("continue"),
46480 ripley 33
       skip.echo = 0, keep.source = getOption("keep.source"))
71357 maechler 34
 
72450 maechler 35
withAutoprint(exprs, evaluated = FALSE, local = parent.frame(),
36
              print. = TRUE, echo = TRUE, max.deparse.length = Inf,
71376 maechler 37
              width.cutoff = max(20, getOption("width")),
38
              deparseCtrl = c("keepInteger", "showAttributes", "keepNA"),
85219 maechler 39
              skip.echo = 0,
71376 maechler 40
              \dots)
2 r 41
}
42
\arguments{
71376 maechler 43
  \item{file}{a \link{connection} or a character string giving the
82703 maechler 44
    pathname of the file or URL to read from.  The \code{\link{stdin}()}
45
    connection reads from the console when interactive.}
56102 ripley 46
  \item{local}{\code{TRUE}, \code{FALSE} or an environment, determining
59274 ripley 47
    where the parsed expressions are evaluated.  \code{FALSE} (the
48
    default) corresponds to the user's workspace (the global
49
    environment) and \code{TRUE} to the environment from which
50
    \code{source} is called.}
11656 ripley 51
  \item{echo}{logical; if \code{TRUE}, each expression is printed
52
    after parsing, before evaluation.}
71357 maechler 53
  \item{print.eval, print.}{logical; if \code{TRUE}, the result of
11656 ripley 54
    \code{eval(i)} is printed for each expression \code{i}; defaults
46727 ripley 55
    to the value of \code{echo}.}
72450 maechler 56
  \item{exprs}{for \code{source()} and \code{withAutoprint(*, evaluated=TRUE)}:
57
    \emph{instead} of specifying \code{file}, an
71376 maechler 58
    \code{\link{expression}}, \code{\link{call}}, or \code{\link{list}}
72450 maechler 59
    of \code{\link{call}}'s, but \emph{not} an unevaluated \dQuote{expression}.
60
 
61
    for \code{withAutoprint()} (with default \code{evaluated=FALSE}):
62
    one or more unevaluated \dQuote{expressions}.
63
  }
64
  \item{evaluated}{logical indicating that \code{exprs} is passed to
65
    \code{source(exprs= *)} and hence must be evaluated, i.e., a formal
66
    \code{expression}, \code{call} or \code{list} of calls.}
71436 hornik 67
  \item{spaced}{logical indicating if newline (hence empty line) should
71357 maechler 68
    be printed before each expression (when \code{echo = TRUE}).}
11656 ripley 69
  \item{verbose}{if \code{TRUE}, more diagnostics (than just
70
    \code{echo = TRUE}) are printed during parsing and evaluation of
71
    input, including extra info for \bold{each} expression.}
72
  \item{prompt.echo}{character; gives the prompt to be used if
73
    \code{echo = TRUE}.}
74
  \item{max.deparse.length}{integer; is used only if \code{echo} is
43435 ripley 75
    \code{TRUE} and gives the maximal number of characters output for
76
    the deparse of a single expression.}
71357 maechler 77
  \item{width.cutoff}{integer, passed to \code{\link{deparse}()} which
78
    is used (only) when there are no source references.}
71376 maechler 79
  \item{deparseCtrl}{\code{\link{character}} vector, passed as
80
    \code{control} to \code{\link{deparse}()}, see also
81
    \code{\link{.deparseOpts}}.  In \R version <= 3.3.x, this was
82
    hardcoded to \code{"showAttributes"}, which is the default
83
    currently; \code{deparseCtrl = "all"} may be preferable, when strict
84
    back compatibility is not of importance.}
32492 ripley 85
  \item{chdir}{logical; if \code{TRUE} and \code{file} is a pathname,
86
    the \R working directory is temporarily changed to the directory
87
    containing \code{file} for evaluating.}
85953 hornik 88
  \item{catch.aborts}{logical indicating that \I{\dQuote{abort}ing} errors
85268 maechler 89
    should be caught.}
46850 ripley 90
  \item{encoding}{character vector.  The encoding(s) to be assumed when
35640 ripley 91
    \code{file} is a character string: see \code{\link{file}}.  A
53897 ripley 92
    possible value is \code{"unknown"} when the encoding is guessed: see
53899 ripley 93
    the \sQuote{Encodings} section.}
39996 murdoch 94
  \item{continue.echo}{character; gives the prompt to use on
95
    continuation lines if \code{echo = TRUE}.}
96
  \item{skip.echo}{integer; how many comment lines at the start of the
97
    file to skip if \code{echo = TRUE}.}
46480 ripley 98
  \item{keep.source}{logical: should the source formatting be retained
56321 ripley 99
    when echoing expressions, if possible?}
71357 maechler 100
  \item{\dots}{(for \code{withAutoprint()}:) further (non-file related)
101
    arguments to be passed to \code{source(.)}.}
2 r 102
}
12256 pd 103
\details{
46727 ripley 104
  Note that running code via \code{source} differs in a few respects
105
  from entering it at the \R command line.  Since expressions are not
106
  executed at the top level, auto-printing is not done.  So you will
107
  need to include explicit \code{print} calls for things you want to be
57939 hornik 108
  printed (and remember that this includes plotting by \CRANpkg{lattice},
88832 smeyer 109
  see \manual{R-FAQ}{Why do lattice/trellis graphics not work?}).
110
  Since the complete file is parsed before any of it is
55555 ripley 111
  run, syntax errors result in none of the code being run.  If an error
46727 ripley 112
  occurs in running a syntactically correct script, anything assigned
113
  into the workspace by code that has been run will be kept (just as
114
  from the command line), but diagnostic information such as
115
  \code{\link{traceback}()} will contain additional calls to
58773 ripley 116
  \code{\link{withVisible}}.
46727 ripley 117
 
20889 ripley 118
  All versions of \R accept input from a connection with end of line
85925 hornik 119
  marked by \abbr{LF} (as used on Unix), \abbr{CRLF} (as used on
120
  DOS/Windows) or \abbr{CR} (as used on classic Mac OS) and map this to
121
  newline.  The final line can be incomplete, that is missing the final
122
  end-of-line marker. 
20889 ripley 123
 
54234 murdoch 124
  If \code{keep.source} is true (the default in interactive use), the
125
  source of functions is kept so they can be listed exactly as input.
61433 ripley 126
 
56410 ripley 127
%   Using \code{echo = TRUE} and \code{keep.source = TRUE} may interact
128
%   badly with source code that includes \samp{#line nn "filename"}
66444 hornik 129
%   directives (e.g., code produced by older versions of
56410 ripley 130
%   \code{\link{Stangle}()}): \code{source()} will attempt to obtain the
131
%   source from the named file which may have changed since the code was
132
%   produced.  Use \code{keep.source = FALSE} to avoid this.
61433 ripley 133
 
38967 ripley 134
  Unlike input from a console, lines in the file or on a connection can
45921 ripley 135
  contain an unlimited number of characters.
61433 ripley 136
 
39996 murdoch 137
  When \code{skip.echo > 0}, that many comment lines at the start of
138
  the file will not be echoed.  This does not affect the execution of
139
  the code at all.  If there are executable lines within the first
140
  \code{skip.echo} lines, echoing will start with the first of them.
43435 ripley 141
 
142
  If \code{echo} is true and a deparsed expression exceeds
143
  \code{max.deparse.length}, that many characters are output followed by
61433 ripley 144
  \code{ .... [TRUNCATED] }.
12256 pd 145
}
53899 ripley 146
\section{Encodings}{
147
  By default the input is read and parsed in  the current encoding of
80048 maechler 148
  the \R session.  This is usually what is required, but occasionally
66444 hornik 149
  re-encoding is needed, e.g.\sspace{}if a file from a UTF-8-using system is to
53899 ripley 150
  be read on Windows (or \emph{vice versa}).
61433 ripley 151
 
53899 ripley 152
  The rest of this paragraph applies if \code{file} is an actual
82743 smeyer 153
  filename or URL (and not a connection).  If
53899 ripley 154
  \code{encoding = "unknown"}, an attempt is made to guess the encoding:
155
  the result of \code{\link{localeToCharset}()} is used as a guide.  If
156
  \code{encoding} has two or more elements, they are tried in turn until
157
  the file/URL can be read without error in the trial encoding.  If an
158
  actual \code{encoding} is specified (rather than the default or
159
  \code{"unknown"}) in a Latin-1 or UTF-8 locale then character strings
160
  in the result will be translated to the current encoding and marked as
161
  such (see \code{\link{Encoding}}).
61433 ripley 162
 
82743 smeyer 163
  If \code{file} is a connection,
53899 ripley 164
  it is not possible to re-encode the input inside \code{source}, and so
165
  the \code{encoding} argument is just used to mark character strings in the
166
  parsed input in Latin-1 and UTF-8 locales: see \code{\link{parse}}.
167
}
24300 ripley 168
\references{
88581 hornik 169
  \bibshow{R:Becker+Chambers+Wilks:1988}
24300 ripley 170
}
16 maechler 171
\seealso{
30461 ripley 172
  \code{\link{demo}} which uses \code{source};
20889 ripley 173
  \code{\link{eval}}, \code{\link{parse}} and \code{\link{scan}};
174
  \code{\link{options}("keep.source")}.
40411 ripley 175
 
176
  \code{\link{sys.source}} which is a streamlined version to source a
177
  file into an environment.
61433 ripley 178
 
88890 smeyer 179
  Section \manual{R-lang}{Directives} for a discussion of source
61433 ripley 180
  directives.
16 maechler 181
}
37100 maechler 182
\examples{
72450 maechler 183
someCond <- 7 > 6
184
## want an if-clause to behave "as top level" wrt auto-printing :
74363 maechler 185
## (all should look "as if on top level", e.g. non-assignments should print:)
72450 maechler 186
if(someCond) withAutoprint({
187
   x <- 1:12
188
   x-1
189
   (y <- (x-5)^2)
190
   z <- y
191
   z - 10
192
})
71357 maechler 193
 
37100 maechler 194
## If you want to source() a bunch of files, something like
195
## the following may be useful:
85219 maechler 196
sourceDir <- function(path, trace = TRUE, ...) {
85268 maechler 197
    op <- options(); on.exit(options(op)) # to reset after each
59759 ripley 198
    for (nm in list.files(path, pattern = "[.][RrSsQq]$")) {
61433 ripley 199
       if(trace) cat(nm,":")
37100 maechler 200
       source(file.path(path, nm), ...)
201
       if(trace) cat("\n")
80048 maechler 202
       options(op)
37100 maechler 203
    }
85219 maechler 204
}
71357 maechler 205
 
72450 maechler 206
suppressWarnings( rm(x,y) ) # remove 'x' or 'y' from global env
85219 maechler 207
withAutoprint({ x <- 1:2; cat("x=",x, "\n"); y <- x^2 })
72450 maechler 208
## x and y now exist:
209
stopifnot(identical(x, 1:2), identical(y, x^2))
210
 
211
withAutoprint({ formals(sourceDir); body(sourceDir) },
80079 hornik 212
              max.deparse.length = 20, verbose = TRUE)
72450 maechler 213
%% --> tests in  ../../../../tests/eval-etc.R
85268 maechler 214
 
215
## Continuing after (catchable) errors:
216
tc <- textConnection('1:3
217
 2 + "3"
218
 cat(" .. in spite of error: happily continuing! ..\n")
219
 6*7')
220
r <- source(tc, catch.aborts = TRUE)
221
## Error in 2 + "3" ....
222
## .. in spite of error: happily continuing! ..
223
stopifnot(identical(r, list(value = 42, visible=TRUE)))
37100 maechler 224
}
16 maechler 225
\keyword{file}
286 maechler 226
\keyword{programming}
11656 ripley 227
\keyword{connection}