Is there a way to output code chunk with stan formatting, reading file from R?

162 Views Asked by At

I've got a Stan model that I'd like to include in a Quarto doc (without copying/pasting code over). Currently, I can do this with:

```{r}
writeLines(readLines("model.stan"))

This gives the stan code, but formatted as a character string output from R --- is there a way to apply Stan's syntax highlighting to the output? This gives an example of outputting bash formatting, but I've been unable thus far to recreate with stan.

1

There are 1 best solutions below

3
shafee On BEST ANSWER

Try with the chunk option #| class-output: stan and use cat(readLines("<filename.ext>"), sep = "\n").

---
title: Test
format: html
---

```{r}
#| class-output: stan
#| echo: false
cat(readLines("test.stan"), sep = "\n")
```

However, in Quarto there is a more easy way to do that using the quarto extension include-code-files.

---
title: Test
format: html
filters:
   - include-code-files
---

```{.stan include="test.stan"}
```

output

stan code with syntax highlighting


test.stan

data {
  int<lower=0> N;
  vector[N] x;
  vector[N] y;
}
parameters {
  real alpha;
  real beta;
  real<lower=0> sigma;
}
model {
  y ~ normal(alpha + beta * x, sigma);
}