Is it possible to format current document or current line on Enter
press? This is my setting in VSCode
, settings.json
:
"files.autoSave": "afterDelay"
so this setting does not have any effect:
"editor.formatOnSave": true
and this setting does not helps to format on Enter
press:
"editor.formatOnType": true
may be macros (or any other extention) can trigger editor.action.formatDocument
event on Enter
press but I don’t know how to do it.
Please help!
P.S. I tried this with macros; In my settings.json
:
"macros": {
"formatOnEnter": [
"cursorDown",
"editor.action.formatDocument",
],
}
and in my keybindings.json
:
{
"key": "enter",
"command": "macros.formatOnEnter",
},
document is formatted and cursor is jumping to new line but cursor does not creates new line.
And may be it is better to format only current line but how?
2
Answers
By binding the Enter key to the format action, you’re overriding its default behaviour (which is normally used for creating a new line). If you still want the Enter key to insert a new line after formatting the document and format the whole file, you’ll need to chain commands, which is more complex and might require an extension like "multi-command". For big source files this kind of configuration can be CPU intensive too. Usually we write code and format it along the way with occasional help from IDE, but this way you want to always rely on some formatting rule forced on the project. You can also try to chain commands so that file is formatted on every save with similar approach which might be less CPU intensive if you safe file on demand.
If you decide to use "multi-command", here’s a brief guide:
As Enter key is overloaded and above solution might not work, you can instead just bind to a close shortcut like :
You need to turn on
Editor: Format On Type
You may check https://youtu.be/m-3Symq2-V8?t=53 to see how it works