| 1 |
# Find first knitr frame on the stack |
| 2 |
knitr_exit_frame <- function(envir) { |
| 3 |
frames <- as.list(sys.frames()) |
| 4 |
|
| 5 |
frame_loc <- frame_loc(envir, frames) |
| 6 |
if (!frame_loc) { |
| 7 |
return(envir) |
| 8 |
} |
| 9 |
|
| 10 |
knitr_ns <- asNamespace("knitr") |
| 11 |
|
| 12 |
# This doesn't handle correctly the recursive case (knitr called |
| 13 |
# within a chunk). Handling this would be a little fiddly for an |
| 14 |
# uncommon edge case. |
| 15 |
for (i in seq(1, frame_loc)) { |
| 16 |
if (identical(topenv(frames[[i]]), knitr_ns)) { |
| 17 |
return(frames[[i]]) |
| 18 |
} |
| 19 |
} |
| 20 |
|
| 21 |
NULL |
| 22 |
} |
| 23 |
|
| 24 |
source_exit_frame <- function(envir) { |
| 25 |
source_exit_frame_option(envir) %||% envir |
| 26 |
} |
| 27 |
|
| 28 |
# Returns an environment if expression is called directly from `source()`. |
| 29 |
# Otherwise returns `NULL`. |
| 30 |
source_exit_frame_option <- function(envir, frames = as.list(sys.frames())) { |
| 31 |
calls <- as.list(sys.calls()) |
| 32 |
|
| 33 |
i <- frame_loc(envir, frames) |
| 34 |
if (!i) { |
| 35 |
return(NULL) |
| 36 |
} |
| 37 |
|
| 38 |
if (i < 4) { |
| 39 |
return(NULL) |
| 40 |
} |
| 41 |
|
| 42 |
is_call <- function(x, fn) { |
| 43 |
is.call(x) && identical(x[[1]], fn) |
| 44 |
} |
| 45 |
calls <- as.list(calls) |
| 46 |
|
| 47 |
if (!is_call(calls[[i - 3]], quote(source))) { |
| 48 |
return(NULL) |
| 49 |
} |
| 50 |
if (!is_call(calls[[i - 2]], quote(withVisible))) { |
| 51 |
return(NULL) |
| 52 |
} |
| 53 |
if (!is_call(calls[[i - 1]], quote(eval))) { |
| 54 |
return(NULL) |
| 55 |
} |
| 56 |
if (!is_call(calls[[i - 0]], quote(eval))) { |
| 57 |
return(NULL) |
| 58 |
} |
| 59 |
|
| 60 |
frames[[i - 3]] |
| 61 |
} |
| 62 |
|
| 63 |
frame_loc <- function(envir, frames) { |
| 64 |
n <- length(frames) |
| 65 |
if (!n) { |
| 66 |
return(0) |
| 67 |
} |
| 68 |
|
| 69 |
for (i in seq_along(frames)) { |
| 70 |
if (identical(frames[[n - i + 1]], envir)) { |
| 71 |
return(n - i + 1) |
| 72 |
} |
| 73 |
} |
| 74 |
|
| 75 |
0 |
| 76 |
} |
| 77 |
|
| 78 |
in_knitr <- function(envir) { |
| 79 |
knitr_in_progress() && identical(knitr::knit_global(), envir) |
| 80 |
} |
| 81 |
knitr_in_progress <- function() { |
| 82 |
isTRUE(getOption("knitr.in.progress")) |
| 83 |
} |