knitr::current_input() - 2 pases?

In a file named my_file.Rmd I use knitr::current_input() in 2 places

yaml:

---
title: "`r knitr::current_input()`"
---

and in a code chunk:

file  <- knitr::current_input()

Works great when I run this one line to render:

rmarkdown::render(input="my_file.Rmd")

But I am lazy and prefer knit to figure the file name to render, ie PRIOR to knitting the document, even if this requires two passes.

My confusion may be conceptual and appreciate any documentation suggestions.
Thx
(I nvim and not Rstudio.)

Hi,

Can you detailed the steps you do ? I am not quite sure about the "2 pases" you are doing ?

do you mean knitr::knit() ?

What is your confusion exactly ?

If I can understand better, I may be able to give pointers.

Thanks!

If you render the following chunk, this_file should show the name of *.Rmd file. No surprise here.

knitr::knitr_current_input()

this_file  <- knitr::current_input()
this_file

If you run, not render, the 2 lines of R code in the chunk then all bets are off. I get NULL for this_file. (Be sure to remove this_file from environment 1st).

And to render, I need to supply the file name.

rmarkdown::render(input= <file_name>)

So this may be very silly question, but I want the code to figure out the name of file.

Note: I use nvim-R, not Rstudio and can use vim to insert the file name, but want to see a direct way.

Thx

What run vs render mean ?

knitr::current_input() will return a value non NULL only when it is evaluated in a knitting process (knitr::knit()), which happens during rmarkdown::render().

You could also be interested in

or in non rstudio session

This could maybe help with your usage.

Hope it helps

1 Like

Thx.

thisfile looks useful.

In my post render means knit whole file and run means executing only few lines of R code in the file to console (like in RStudio can do)

Then I think it is why it is not working. knit::current_input() will only work when knitting. It should be aware of RStudio when run interactively and I don't think it is.

Interactively, you could get the result by using

rstudioapi::getActiveDocumentContext()$path

This would only work in RStudio IDE when rstudioapi package is available. You could use that conditionnaly probably, by using identical(.Platform$GUI, "RStudio") to test you are in RStudio or try rstudioapi when current_input() is NULL

Thanks ....

For possible future readers, I use neovim with nvim-R plugin.
File name is always in register "% .

So mapping like if (insert file) works fine:
nnoremap <leader>if "%p

1 Like

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.