---
title: "An Introduction to *excerptr*"
author: "Andreas Dominik Cullmann"
date: 2021-08-03, 16:26:49
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{An Introduction to excerptr}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---
```{r setup, include=FALSE}
# adapted from reticulate vignettes/python_packages.Rmd

if (!reticulate::py_available(initialize = TRUE)) {
    knitr::opts_chunk$set(eval = FALSE)
} else {
    inst <- tryCatch(reticulate::py_install("excerpts"), error = identity)
    if (inherits(inst, "error")) {
        knitr::opts_chunk$set(eval = FALSE)
    } else {
        knitr::opts_chunk$set(eval = TRUE)
    }
}
```


excerptr is an R interface to the python package [excerpts](https://pypi.org/project/excerpts/).
See there for more on the Why.

Suppose you have a script

```{r, comment = ""}
path <- system.file("tests", "files", "some_file.R", package = "excerptr")
cat(readLines(path), sep = "\n")
```
and you would want to excerpt the comments marked by '%' into a file giving you the table of contents of your script.
Then 
```{r}
excerptr::excerptr(file_name = path, run_pandoc = FALSE, output_path = tempdir())
```
gives you

```{r, comment = ""}
cat(readLines(file.path(tempdir(), sub("\\.R$", ".md", basename(path)))), 
    sep = "\n")
```

If you have pandoc installed, you can convert the markdown output into html:

```{r}
is_pandoc_installed <- nchar(Sys.which("pandoc")) > 0 &&
                              nchar(Sys.which("pandoc-citeproc")) > 0
is_pandoc_version_sufficient <- FALSE
if (is_pandoc_installed) {
    reference <- "1.12.3"
    version <- strsplit(system2(Sys.which("pandoc"), "--version", stdout = TRUE), 
                        split = " ")[[1]][2]
    if (utils::compareVersion(version, reference) >= 0)
        is_pandoc_version_sufficient <- TRUE
}
if (is_pandoc_version_sufficient) 
    excerptr::excerptr(file_name = path, pandoc_formats = "html", 
                       output_path = tempdir())
```
This runs pandoc on your excerpted comments and generates an html file you can view via:
```{r, comment = ""}
if (is_pandoc_version_sufficient) 
    cat(readLines(file.path(tempdir(), sub("\\.R$", ".html", basename(path)))), 
        sep = "\n")
```
```{r, echo = FALSE, results = "hide"}
if (is_pandoc_version_sufficient) 
    excerptr::excerptr(file_name = path, pandoc_formats = "html", 
                       output_path = file.path(rprojroot::find_root(rprojroot::is_r_package), 
                                               "inst", "tests", "files")
                       )
```
You browse it via
```{r, eval = FALSE}
browseURL(file.path(tempdir(), sub("\\.R$", ".html", basename(path))))

```


