VS Code and Positron include a feature that allows you to take specific actions when saving a file. I have configured VS Code and Positron to automatically format my Python and R code when I save a file. Auto formatting is a great way to ensure your code is consistently formatted correctly.
For formatting Python code, I use ruff (Open VSX, VS Code Marketplace) which has a VS Code extension. For formatting R code, I use air (Open VSX, VS Code Marketplace) which also has a VS Code/Positron extension.
To enable this behviour, add the following to your VS Code configuration file. To open your settings.json file, run one of the following from the Command Palette:
- Run Preferences: Open User Settings (JSON) to modify global user settings.
- Add the following sections:
{ "[r]": { "editor.formatOnSave": true, "editor.rulers": [ 80 ], "editor.tabSize": 4 }, "[python]": { "editor.codeActionsOnSave": { "source.organizeImports": "always" }, "editor.defaultFormatter": "charliermarsh.ruff", "editor.formatOnSave": true, "editor.rulers": [ 80 ], "editor.tabSize": 4 }, "ruff.nativeServer": "on", "ruff.organizeImports": true}
The "source.organizeImports": "always"
will use ruff to sort your imports and format your code.
Congratulations 🎉 Your code will be automatically formatted whenever you save a Python or R file!