10

I would like to see the current working directory in the prompt of my R console. When using options(prompt=paste(getwd(),">> ")) the working directory at the start of the session is shown. But it never gets updated when I change the working directory during that session:

/home/sieste >> setwd("newdir")
/home/sieste >> cat("damn!\n")

What I do at the moment is to redefine the setwd function in my .Rprofile

setwd <- function(...) {
  base::setwd(...)
  options(prompt=paste(getwd(),">> "))
}

Now the prompt gets updated correctly whenever I call setwd. My question is: Is there a more elegant way of updating the prompt dynamically, independent of which function I call and without having to redefine base functions?

sieste
  • 8,296
  • 3
  • 33
  • 48
  • Your solution seems elegant enough, I doubt there exists a simpler one. – tonytonov Aug 05 '14 at 10:08
  • You basically have your solution, but the part of your question that reads "independent of which function I call" is unclear and the "without having to redefine base functions" part is easily solved by calling your function something other than `setwd` like `setwd_and_update_prompt` or whatever you want. – Thomas Aug 05 '14 at 10:43
  • @Thomas: Suppose I execute some function which, under the hood, calls `base::setwd()` and changes the working directory. My solution would not update the prompt then. I would like the prompt to be updated after every command, like Linux shells do. – sieste Aug 05 '14 at 10:51
  • Great hack but being more cautious could prevent from the issue encountered in this other [question](https://stackoverflow.com/q/76785769/6537892) – pietrodito Jul 28 '23 at 08:24

1 Answers1

4

Because prompt option is really just a string, without any special directives evaluated inside (unlike shell prompt), you have to change it if you change working directory to get current working directory inside.

The solution you use seems the best to me. A bit hacky, but any solution will be as you want to implement something quite fundamental that is not supported by R itself.

Moreover, you don’t have to fear functions executing base::setwd under the hood, which would get your prompt out of sync with real working directory. That does not happen in practice. As Thomas pointed out in the comments, probably no base functions (other than source) call setwd. The only functions that do are related to package building and installation. And I noticed that even in source and usually in the other functions, setwd is used like owd <- setwd(dir); on.exit(setwd(owd)), so that the working directory is set back to original when the function finishes.

Community
  • 1
  • 1
Palec
  • 12,743
  • 8
  • 69
  • 138
  • 1
    Included most of relevant info from the comments and expanded on `source` a little bit. Even `source` is not a concern to you, because it changes working directory only temporarily. – Palec Aug 06 '14 at 10:32