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.
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().
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