-
Notifications
You must be signed in to change notification settings - Fork 0
/
panelize-code-cells-for-quarto-webr.R
60 lines (48 loc) · 1.93 KB
/
panelize-code-cells-for-quarto-webr.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# Switch Qmd code cell syntax ----
# Obtain a list of input files separated by `\n`
project_input <- Sys.getenv("QUARTO_PROJECT_INPUT_FILES")
# Convert the list into a new vector
project_input_files <- unlist(strsplit(project_input, split = "\n"))
# Use grep to find files with the .qmd extension
qmd_files <- grep("\\.qmd$", project_input_files, value = TRUE)
# Convert from Rmd style/ Historical chunk option syntax to Quarto's Hashpipe YAML syntax
for (qmd in qmd_files) {
knitr::convert_chunk_header(qmd, output = qmd, type = "yaml")
}
# Add panelize tag for converting from R to webR a code cell ----
# Function to wrap R code chunks in an RMarkdown file with ::: {.to-panel}
wrap_r_chunks_with_panel <- function(file_path) {
# Read the file content
lines <- readLines(file_path)
# Determine the number of additional lines needed
additional_lines <- sum(grepl("^```\\{r.*\\}$", lines)) * 2
# Create a vector to hold the modified lines
modified_lines <- character(length(lines) + additional_lines)
# Initialize variables to store the current position and chunk state
current_position <- 1
in_chunk <- FALSE
for (line in lines) {
if (grepl("^```\\{r.*\\}$", line) && !in_chunk) {
# Start of R code chunk
modified_lines[current_position] <- "::: {.to-webr}"
modified_lines[current_position + 1] <- line
current_position <- current_position + 2
in_chunk <- TRUE
} else if (grepl("^```$", line) && in_chunk) {
# End of R code chunk
modified_lines[current_position] <- line
modified_lines[current_position + 1] <- ":::"
current_position <- current_position + 2
in_chunk <- FALSE
} else {
# Regular line
modified_lines[current_position] <- line
current_position <- current_position + 1
}
}
# Write the modified content to the output file
writeLines(modified_lines, file_path)
}
for (qmd in qmd_files) {
wrap_r_chunks_with_panel(qmd)
}