4

Is it possible to show and evaluate a markdown text in Quarto / Rmarkdown?

I need to show both the raw markdown script and its compiled (evaluated) form, one after another. In Quarto, I can use the following code to show/format a markdown code, but this does not provide evaluated results (i.e. the link).

```{markdown}
#| echo: true
#| eval: true
[Quarto](https://quarto.org)
```

Thanks

shafee
  • 15,566
  • 3
  • 19
  • 47
Ahmed El-Gabbas
  • 398
  • 3
  • 10
  • I received the following [reply](https://github.com/quarto-dev/quarto-cli/discussions/3303) at Quarto github page. It is not possible to implement this as markdown is not a knitr language. – Ahmed El-Gabbas Nov 14 '22 at 10:25

1 Answers1

4

You can build your own evaluator with a Quarto Lua filter:

function CodeBlock (cb)
  if cb.classes:includes 'markdown' and cb.classes:includes 'eval' then
    return {cb} .. pandoc.read(cb.text).blocks
  end
end

Save the code to a file in your project and add that file to the filters YAML entry:

---
filters:
  - markdown-examples.lua
---

The filter requires slightly different syntax though:

```{.markdown .eval}
[Quarto](https://quarto.org)
```

This isn't fully satisfying though, as it only supports pandoc's Markdown and doesn't know about Quarto extensions to it.

tarleb
  • 19,863
  • 4
  • 51
  • 80
  • This works as expected! great.... Thanks @tarleb.. – Ahmed El-Gabbas Nov 14 '22 at 10:08
  • Is it possible to exclude comments after the hashtag from the output? For example ```{.markdown .eval} [Quarto](https://quarto.org) # a comment ``` – Ahmed El-Gabbas Nov 14 '22 at 10:44
  • 2
    You could replace `cb.text` with `cb.text:gsub(' +# .*\n', '')` to get rid of comments. – tarleb Nov 14 '22 at 13:01
  • Thanks @tarleb... It did not work. It gives this error when render the file `Error running filter ../Quarto_markdown.lua: PandocLuaError "Unknown reader: 0" stack traceback: ../Quarto_markdown.lua:3: in function 'CodeBlock'` – Ahmed El-Gabbas Nov 14 '22 at 14:49
  • 1
    That's a Lua pitfall that I always forget about. Please try to wrap the replacement code into an extra pair of parentheses. – tarleb Nov 14 '22 at 17:04
  • 1
    Thanks... Now there is no error. I needed to make a slight change in the regex to make it works (at least in one example); by replacing the match pattern with `" +# .+"` – Ahmed El-Gabbas Nov 14 '22 at 20:03