r-lib / styler

Non-invasive pretty printing of R code
https://styler.r-lib.org
Other
725 stars 71 forks source link

styler overwrites changes in an unsaved open file #768

Open Moohan opened 3 years ago

Moohan commented 3 years ago

If you make changes to an open document in RStudio, don't save them and then run styler::style_dir or styler::style_file, if it makes any changes it will do this on the saved version (rather than the open version) and then overwrite.

I think the ideal fix would be to make changes in an open document if it has unsaved changes. If that's not possible it would be good for styler to throw an error e.g. "Error: Tried to style a document with unsaved changes, please save or close the document then run style_file()" again.

lorenzwalthert commented 3 years ago

I understand what you describe. However, I think this is standard file system behaviour. Open files are overwritten and unsaved changes are lost. We could check with {rstudioapi} if a file is open and unsaved, and return an error. That might be more conservative than styling the contents directly.

Anyways, to style the current file, there is an Addin as well. I recommend creating a keyboard shortcut for that Addin (or use the RStudio palette) instead of going over the CLI API. Also, there are various ways for Autosaving in RStudio.

Moohan commented 3 years ago

An error would be great. I usually use the Addin as I go, but recently ran style_dir, I didn't realise that I hadn't saved a different file that I wasn't actively working on and lost changes in it.

lorenzwalthert commented 3 years ago

Interested in a PR? Relevant function to check for an open file is transform_file(). However, not sure {rstudioapi} even has this functionality...

Moohan commented 3 years ago

Sorry, meant to reply to this. I looked at a lot of rstudio API docs but it doesn't seem to be possible. Possibly someone else can figure out how or has an alternative suggestion but it's beyond me I think!

Moohan commented 3 years ago

I opened an issue on {rstudioapi} - https://github.com/rstudio/rstudioapi/issues/230

lorenzwalthert commented 3 years ago

Ok cool. Let’s see what they say...