I would like to automatically format TypeScript code using the build-in formatter when I save a file in Visual Studio Code.
I'm aware of the following options, but none of them is good enough:
Format manually Shift + Alt + F
Format on type "editor.formatOnType": true
It formats the line when you press enter. Unfortunatelly, it leaves it unformatted when you mouse-click another line or press up/down arrow.
Use existing extension
I tried this one, but it does not seem to work too well.
Use beautify "beautify.onSave": true
It does not work with TypeScript
Write custom extension
It's tricky if you want to handle autosaves and builds correctly.
As of September 2016 (VSCode 1.6), this is now officially supported.
Add the following to your settings.json file:
"editor.formatOnSave": true
No need to add commands anymore. For those who are new to Visual Studio Code and searching for an easy way to format code on saving, kindly follow the below steps.
Open Settings by pressing [Cmd+,] in Mac (or [Ctrl+,] in Windows/Linux) or using the below screenshot.
Type 'format' in the search box and enable the option 'Format On Save'.
You are done. Thank you.
If you would like to auto format on save just with Javascript source, add this one into Users Setting (press CmdShiftP or CtrlShiftP then type Open Settings (JSON) to open settings.json file)
"[javascript]": { "editor.formatOnSave": true }
For eslint:
"editor.codeActionsOnSave": { "source.fixAll.eslint": true }
For neet formatting for any language you can use Prettier - code formatter.
After applying this you can format code Alt + Shift + f
The best to avoid conflicts is defining individual formatters for each language, for instance if I am working with Rust and Typescript I would like to format code using the extensions Rust-Analyzer and Prettier respectively, therefore on my .vscode/settings.json:
{
"editor.defaultFormatter": null,
"[rust]": {
"editor.defaultFormatter": "rust-lang.rust-analyzer",
"editor.formatOnSave": true
},
"[typescript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
}
}
Remember that both Prettier and rust-analyzer extensions must be installed first.
For MAC user,
add this line into your Default Settings
File path is: /Users/USER_NAME/Library/Application Support/Code/User/settings.json
"tslint.autoFixOnSave": true
Sample of the file would be:
{
"window.zoomLevel": 0,
"workbench.iconTheme": "vscode-icons",
"typescript.check.tscVersion": false,
"vsicons.projectDetection.disableDetect": true,
"typescript.updateImportsOnFileMove.enabled": "always",
"eslint.autoFixOnSave": true,
"tslint.autoFixOnSave": true
}
After hours of struggle... below steps worked.
Full details below.
Install this extension
https://marketplace.visualstudio.com/items?itemName=pucelle.run-on-save
Add below json, to below file:
File:
<your-project-directory>\.vscode\settings.json
OR
%UserProfile%\AppData\Roaming\Code\User\settings.json
JSON:
NOTE: Make sure commas before and after below block.
"files.autoSave": "afterDelay",
"files.autoSaveDelay": 1000,
"runOnSave.statusMessageTimeout": 3000,
"runOnSave.commands": [
{
"match": ".*\\.*",
"command": "editor.action.formatDocument",
"runIn": "vscode"
}
],
Now, when the code is changed, after 1 second, it gets formatted & saved automatically.
For me formatOnSave wasn't working because I had prettier installed and hadn't yet chosen between the built-in and prettier as my default formatter.
To trigger the selection dialog I had to press Alt + Shift + f on my json file.
First, you need to choose the formatter which you have just added as an extension.
Press ctrl + alt + f and choose the formatter that you want from the dropdown.
Post that with every save it will get automatically formatted.
If you use Prettier and this line
"editor.formatOnSave": true
Doesn't work to format on save, you might need to add another command to settings.json
"editor.defaultFormatter": "esbenp.prettier-vscode",
In addition to enabling setting Format On Save, for python developers, you may need to install autopep8 package which is used by vscode as default to format the python code when the code is saved.
pip install autopep8
and then, press ctrl + s to see changes.
Goto settings and search format
check Editor: Format On Save
or follow these steps
Related
I'm using VsCode with Prettied Extension. Prettier in some cases is formatting inside the HTML element (I.g. Class value), which is annoying, because its breaking the property in multiple lines unnecessarily, Hence:
I don't want to use “prettier-ignore” comments for every line in code because its tedious and
I don't want to use .prettierignore file in root, because in my understanding it ignores the HTML files and also turn off vscode's default HTML formatter.
I want to allow prettier for all the languages except for HTML, so I put a file with the extension .prettierrc in project root with the content as following:
{
"editor.defaultFormatter": "esbenp.prettier-vscode",
"[html]": {
"editor.defaultFormatter": null
}
}
Now my question is:
Can I use .prettierignore file in root, if so, will it disable vscode's HTML default formatter?
Check my .prettierrc config file and let me know if its the right (or another) way.
A good workaround for your desired result would be to switch HTML formatting to the default vscode formatter and then leave everything else for Prettier. We can do that just by changing a value in our settings.json
You can press Ctrl + Shift + P in vscode to open the command pallete and search for open settings, you will find a setting called Preferences: Open Settings (JSON) or you can straight up go to C: -> Users -> UserName -> Roaming -> Code -> User and then open settings.json.
Then make sure to change/fill in these values:
"editor.defaultFormatter": "esbenp.prettier-vscode",
"[html]": {
"editor.defaultFormatter": "vscode.html-language-features"
},
That way you don't need any prettier configuration files. I hope I helped.
I have installed prettier extension for VS Code, set it as default formatter, also set format on save to true in VS Code's settings file, and files are set to be saved automatically after some time delay.
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true,
"files.autoSave": "afterDelay"
But prettier is not formatting my code when file is saved automatically after 2 seconds delay. Code is only formatted if i:
manually format the code using option + Shift + F keyboard shortcut.
press command + S
Here's my .prettierrc file
{
"trailingComma": "es5",
"tabWidth": 4,
"semi": true,
"singleQuote": true
}
How can i make prettier format my code automatically on file save?
After some searching, i found out that the following setting
"editor.formatOnSave": true
only works if:
Code formatter is available.
The files are NOT set to be saved after a delay.
And the editor must not be shutting down.
I had set the prettier as the default formatter using the following setting:
"editor.defaultFormatter": "esbenp.prettier-vscode"
But I had set files to be saved automatically after a delay as specified in the following setting:
"files.autoSave": "afterDelay"
This setting was the cause of the problem in my case.
"files.autoSave" setting can have one of the following values:
"off": A dirty editor is never automatically saved.
"afterDelay": A dirty editor is automatically saved after the configured files.autoSaveDelay.
"onFocusChange": A dirty editor is automatically saved when the editor loses focus.
"onWindowChange": A dirty editor is automatically saved when the window loses focus.
Setting "files.autoSave" to any possible value other than "afterDelay" will fix the issue. I solved this issue by setting "files.autoSave" to "onFocusChange".
I'm editing someone else's code and I only want to change 1 line of a 9000 line file. But every time I save, VS Code formats the entire file and removes any trailing white space. This is a no-no because when I push this up, the reviewer will have no idea which line to look at.
I've tried disabling prettier, adding all files to .prettierignore, going into VS Code settings and disabling any suggestions of a formatter or white space trimming, turning off formatOnSave.
Here is my .vscode/settings.json
{
"prettier.disableLanguages": [
"js",
"json",
"javascript"
],
"javascript.format.enable": false,
"typescript.format.enable": false,
"json.format.enable": false,
"html.format.enable": false,
"emmet.showAbbreviationSuggestions": false,
"css.validate": false,
"editor.defaultFormatter": null,
"editor.formatOnSave": false,
"[javascript]": {
"editor.formatOnSave": false,
"editor.defaultFormatter": null
},
"editor.trimAutoWhitespace": false,
"diffEditor.ignoreTrimWhitespace": false,
"files.trimTrailingWhitespace": false,
"files.trimFinalNewlines": false,
"eslint.format.enable": false,
"files.autoSave": "off",
}
The only thing that seems to work is if I do CTRL + SHIFT + P, then SAVE WITHOUT FORMATTING. But what setting can I have so I can just do that with normal saving?
Did you try adding
"editor.formatOnSave": false
in your user settings rather than in your project settings?
Had the same problem, just bind 'cmd + s' to saving without formatting.
press cmd+shift+p then search for save without formatting and click on the configure icon, then bind it with 'cmd + s', problem gone :)
In the case it is ESLint, and not Prettier, the solution is:
Open Preferences: Open Settings (JSON) and configure:
"editor.formatOnSave": false,
"editor.codeActionsOnSave": {
"source.fixAll": false,
"source.fixAll.eslint": false
}
I don't have Prettier but the solution may be similar.
In my case, I uninstalled prettier and was using html-css-js code formatter. I had already unchecked format on save, and had tried many other methods. I finally changed a setting in formatter.json (settings of html-css-js formatter) and then it worked.
Steps:
ctrl + shift + P
Formatter Config
If "onSave": true, change true to false
Save the formatter.json and reload window.
This worked for me. I can use auto-save after this as well.
I came across this problem a while back. I disabled the formatOnSave option in settings.
Goto File > Preferences > Settings or Ctrl + ,.
In User tab choose Text editor and navigate
to Formatting, disable the formatOnSave option.
YW!
Perhaps this plugin called Formatting Toggle by tombonnike can help you.
It disables the autosave with a toggle.
From its description:
A VS Code extension that allows you to toggle the formatter (Prettier, Beautify, …) ON and OFF with a simple click.
In my case I had two default code formatters that had conflicting settings, "prettier" was set not to format on save but JS-CSS-HTML Formatter was still set as my default formatter for some file types. I suggest using only one formatter and removing any unused / conflicting ones from your extensions list.
The way I used was to:
Open a file type ( one that's giving you formatting on save issues. )
Click on the file type and select "Configure 'yourFiletype' language based settings.. from the dropdown.
Delete the line that sets your default formatter: ex) "editor.defaultFormatter": "lonefy.vscode-JS-CSS-HTML-formatter"
Then go back to your file and try formatting normally, ( my hotkey is: alt + shift+ f ), it should prompt you to select your default formatter.
This should help minimize conflicting formatters issues.
I've just stumbled across this question while experiencing the exact same problem. The way I solved it, was just to switch the language of the document to plain text (you can do so by clicking on the language in the bottom navigation bar). If you then hit "save", no reformatting happens.
Disadvantage: You get no syntax highlighting. But if you just want to fix a typo or something and don't want to mess with the settings or install an extension, it's probably an ok workaround.
Save without Formatting
The ideal solution to this would just be to use the "Save without Formatting" command.
This can be executed by either:
Selecting it in the command palette: CTRL + SHIFT + P
Doing the keyboard shortcut: CTRL + K, S
This lets you save files, bypassing any formatters that may run automatically.
Format on Save
You might want to disable auto-formatting entirely. You might just not like it, or because it can be annoying when paired with files.autoSave which saves automatically, and therefore formats automatically too.
First check your global settings and see if you have editor.formatOnSave enabled. If so, then disable it.
You can navigate to your settings by either:
Navigating the menu bar: File → Preferences → Settings
Doing the keyboard shortcut: CTRL + ,
Then search for editor.formatOnSave and disable it.
If it's still auto-formatting, then it might be enabled in workspace settings. Check if the root of the workspace has a file at .vscode/settings.json, and if so, if it has editor.formatOnSave. If it does, then either disable it there or just delete the file to stop it from overriding your global settings.
Other Extensions
Check if any other extensions are performing code actions on save. Other answers here cover this topic a bit, but in general, you can just navigate through your setting and search terms like "save" or "format".
All UI navigation and keyboard shortcuts are taken from the Linux installation, they may vary on other platforms.
Go to C:\Users[user]\AppData\Roaming\Code\User
and change the editor.formatOnSave option to false.
I just got the same problem and while trying these solutions, I realized that when you click ctrl + shift + P, and type "Save without formatting", the option will have a settings icon on the right corner, click there to configure keybinding, you can put any keybinding you want there, for example ctrl + k, which I put. It worked instantly and it was very easy, so you can have the best of both worlds.
Thanks to Guillermo's answer.
In VScode Goto File -> Preferences -> Settings -> (User tab) Text Editor -> Formatting -> Here uncheck the Format On Save
I've got an error when trying to format my code in Visual Studio. I have the following plugins installed for the languages I use:
shell-format (bash)
Go (golang)
PyFormat (python)
I have also set up a keybinding SHIFT+ALT+F to format a file, with the when condition:
editorHasDocumentFormattingProvider && editorTextFocus && !editorReadonly
But whenever I use this shortcut (or use auto-format on save), nothing is formatted and I see this error in the toolbar at the bottom:
"Extension 'JSON Language Features' cannot format [filepath]"
I don't know what this extension even is, since I don't have any JSON-based extentions installed.
Has anyone else seen something similar?
I just had this with Python, and it turned out the issue was that I had a line in my settings like this:
"editor.defaultFormatter": "vscode.json-language-features",
Since I wanted Python to use black. and it's that that wasn't working and giving me the same error message you're getting, I changed the line above so it was only relevant for json, and double checked formatters for other languages (don't forget to check settings for user, remote and workspace).
In the end, my settings for default formatting looked like this:
"editor.formatOnSave": true,
"[python]": {
"editor.codeActionsOnSave": {
"source.organizeImports.python": true,
}
},
"[django-html]": {
"editor.formatOnSave": false,
},
"[vue]": {
"editor.defaultFormatter": "octref.vetur"
},
"[json]": {
"editor.defaultFormatter": "vscode.json-language-features",
},
And presto, my Python format on save was working again.
I suspect your problem is the same, but post your settings.json if making that vscode.json-language-features json specific doesn't work ...
Currently in VSCode settings you can configure format on save as following:
"editor.formatOnSave": true
I want to exclude some file extensions, for example only format JavaScript but not HTML files.
You can use language specific settings to enable it for a specific language only, e.g. JavaScript:
"[javascript]": {
"editor.formatOnSave": true
}
To disable it for a specific language, you could switch the global default to true and combine it with a language-specific false:
"editor.formatOnSave": true
"[javascript]": {
"editor.formatOnSave": false
}
Note that language specific settings are based on language identifiers rather than directly on file extensions. There's an open feature request to allow for file extension specific settings as well.
In cases where the language ID isn't specific enough, "files.associations" could be used to remap files with a specific extension and/or in a specific directory to another ID, but this will affect syntax highlighting, code completion, etc. as well. For instance, this would work to disable formatting for JavaScript files in out directories, but they will be treated as plaintext:
"[javascript]": {
"editor.formatOnSave": true
},
"files.associations": {
"**/out/**/*.js": "plaintext"
}
If you came across this question as I did because you were redirected because of this question VSCode : disable formatting of a specific file (or extension) which says, this is a duplicate (I don't feel so, because I wanted it for a specific file) and you're looking for a "one-time" solution:
VS Code has a shortcut "now" (I don't know since when) for saving a file without formatting listed under the command workbench.action.files.saveWithoutFormatting - Default keybinding should be
CTRL + K CTRL + SHIFT + S
(simply keep CTRL pressed and then type K + SHIFT + S).
On OS X the default keybinding is
CMD + k then press s
I messed up my keyboard keys with VSCode. One alternative could be utilizing the VSCode commands to save without formating by doing CTRL+SHIFT+P and executing the
command. :)
On Mac, use ⌘ + K, S
On Linux, use Ctrl + K S
On Windows, use Ctrl + K Ctrl + Shift + S
To check the VS Code keyboard shortcuts: Ctrl + K, Ctrl + S (yes, almost the same as the above) and search for "save without formatting"
If anyone could have faced auto-format or format on saving for .env or other setting or environment file and it has a long string that caused an error and you are looking for a solution,
HERE IS IT (ADD THE BELOW IN YOUR VS CODE SETTINGS.JSON)
"files.associations": {
".env": "plaintext"
},
"[plaintext]": {
"editor.formatOnSave": false
},
You can use the below settings in Vscode and use "python.formatting.autopep8Args" to specify files or some pattern to ignore files you want. Of course, assuming that you are using autopep8 to format you python files other code formatters might have other ways to configure this.
{
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"python.formatting.autopep8Args": ["--exclude settings.py"],
"[python]": {
"editor.defaultFormatter": "ms-python.python",
"editor.formatOnSave": true
}
}
Using language specific setting can fix the issue but you will lose the code highlighting
"editor.formatOnSave": true
"[javascript]": {
"editor.formatOnSave": false
}
My solution was to create the file called ".prettierignore" in the root and
type the file name you want to skip the auto formating. Learn more about in https://prettier.io/docs/en/ignore.html
This way, the auto-formatting will be disabled for the specific file and also you won't lose the code-highlighting.
As a workaround, this extension allow to easily toggle formatting by clicking a button on the status bar.