Getting the directory of a document being rendered

The title says it all. I'd like to get the directory path of a .qmd/.Rmd document being rendered.

E.g., considering I'm rendering bar.Rmd in a project with the following structure:

.
└── foo
    └── bar.Rmd

I'd like to get /path_to_proj/foo/.

This is what knitr::opts_knit$get("output.dir") returns by default. I need it for a package though and since this path can be changed by the user with knitr::opts_knit$set(), I'm looking for more robust alternative.

Is there another way to get this that will always return the right path?

Note that getwd() returns different paths depending on the rendering approach so it won't do it.

is this helpful ?
Using here with rmarkdown • here (r-lib.org)

I'm not keen on adding a dependency for such a trivial thing to be honest.

knitr seems to use getwd() to get the rendering path. I'm probably missing something but I should be able to get what I want with that function.

Edit:
using getwd() returns the right path when using quarto/rmarkdown::render() but only returns the path to the root of the project when rendering directly from R Studio.

knitr has an advanced function called knitr::current_input(). Maybe this is what you are looking for ?

1 Like

knitr::current_input() returns the name of the file being rendered (bar.Rmd here), not the directory containing that file. I ended up using knitr::opts_knit$get("output.dir") because this option is not documented and not recommend to tweak, so less likely to be modified by a user.

My bad, I've just noticed the dir parameter in knitr::current_input()… So that works. I submitted the package to CRAN a couple of days ago so that's probably too late for this version.

Edit: Looking at the code of knitr::current_input(), it's actually getting the dir path from knitr::opts_knit$get("output.dir").

Yes it has to get it from somewhere. knitr::current_input() is the user -facing API. knitr::opts_knit$get("output.dir") is internal. It is best to use the user facing function for this

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.