R/exams_integration.R

Defines functions detect_rmd_format exams_task

Documented in exams_task

#' Convert an exams Rmd task to a QTI 2.1 XML file
#'
#' Helper function for using tasks written in the `exams` Rmd format inside
#' `rqti` sections. The function converts the given Rmd file with
#' [exams::exams2qti21()] and returns the path to the generated XML file.
#'
#' This function is mainly useful when `exams` tasks need to be combined with
#' native `rqti` tasks in one section, for example:
#' `section(exams_task(path_to_file, title = "Exams task"))`.
#'
#' @param path Character string. Path to an Rmd file written in the `exams`
#'   format.
#' @param title Character string or `NULL`. Optional title passed to
#'   [exams::exams2qti21()] via the `ititle` argument.
#'
#' @return Character string. Path to the QTI 2.1 XML file generated by
#'   [exams::exams2qti21()] in a temporary directory.
#'
#' @examplesIf interactive()
#' path <- system.file("exams", "example.Rmd", package = "rqti")
#' section(exams_task(path, title = "Exams task"))
#'
#' @importFrom exams exams2qti21
#' @export
exams_task <- function(path, title = NULL) {
    temp_dir <- tempdir()
    exams_xml <- exams::exams2qti21(file = path,
                                      dir = temp_dir,
                                      zip = FALSE,
                                      base64 = TRUE,
                                      ititle = title)
    xml_path <-  file.path(temp_dir,
                           paste0(exams_xml$exam1$exercise1$metainfo$id,
                                  ".xml"))
    return(xml_path)
}

# detector which Rmd format is used in the file (rqti or exams)
detect_rmd_format <- function(file) {
    if (!file.exists(file)) {
        stop("File does not exist: ", file, call. = FALSE)
    }

    yaml <- rmarkdown::yaml_front_matter(file)
    has_yaml <- length(yaml) > 0

    x <- readLines(file, warn = FALSE, encoding = "UTF-8")
    has_meta_information <- any(
        grepl("^meta[- ]?information\\s*$", x, ignore.case = TRUE)
    )

    if (has_yaml && !has_meta_information) {
        return("rqti_rmd")
    }

    if (has_meta_information && !has_yaml) {
        return("exams_rmd")
    }

    return("unknown")
}

Try the rqti package in your browser

Any scripts or data that you put into this service are public.

rqti documentation built on Sept. 21, 2026, 5:08 p.m.