Keep indents on empty lines
Asked Answered
G

8

55

Is it possible to make VSCode keep indents on empty lines?

Could not find such a setting neither natively nor in "Beautify" extension.

Example of desired behavior:

code screenshot

UPDATE: eventually I've just switched to Prettier - and never had to think about code style again as it's just being formatted automatically for me.

Garbage answered 25/12, 2017 at 12:9 Comment(7)
And why would you want that? Perhaps the settings for editor.trimAutoWhitespace and files.trimTrailingWhitespace are what you're looking for?Teutonism
I would like to achieve the same functionality as with IntelliJ IDEA's feature called "Keep indents on empty lines". When it's on and you run the "Reformat Code" action, IntelliJ makes sure the empty lines are properly indented, as you can see in the example screenshot I've just added.Garbage
editor.trimAutoWhitespace is indeed what you want.Circassian
Thanks Scruffy, but unfortunately it didn't do the trick.Garbage
Prettier doesn't seem to preserve indentation on empty lines when I format the documentMallee
The thing with Prettier is that you can completely stop thinking about formatting altogether once it's integrated into your development workflow. You just save your file and Prettier takes it from there. Who cares about the indents on empty lines (or any other code cosmetics) as long as the code is readable and ALWAYS formatted according to the same rules, without you even having to think about it!? I just type the code wherever the cursor is and hit the save button to have Prettier format it for me :-)Garbage
I see people suggesting trimAutoWhitespace, but I don't think @StasKorzovsky is talking about "editing". trimAutoWhitespace applies when you are editing a file. He's talking about formatting an existing code. I have trimAutoWhitespace set to false, so I "keep" the indented empty lines when I'm editing, but when I format the document (e.g. PHP and Intelephense), indented blank lines are trimmed. This requires another solution.Tinea
S
46

Go to File > Preferences > Settings.

If you use the JSON settings editor, add the line:

"editor.trimAutoWhitespace": false,

If you use the UI settings editor, use the setting named "Editor: Trim Auto Whitespace"

Selsyn answered 1/4, 2018 at 21:16 Comment(3)
I don't know what "on the right side means. Perhaps the interface changed since 2018? Anyway, I typed "editor.trimAutoWhitespace" into the search bar and was able to turn it off via radio button.Anjanette
editor.trimAutoWhitespace does not exist on vs code 1.76.2 on Mac :(Fulgent
Is there a way to make it false only for .diff files?Unhappy
H
15

Bit of an old question, but I found that a combination of the settings:

"editor.trimAutoWhitespace": false,
"editor.renderWhitespace": "all"

...worked for me.

NOTE: (19/03/2021)

It appears that this issue, registered on GitHub, is still an open case.

Humism answered 2/7, 2018 at 8:10 Comment(6)
This works except when I format the document. Formatting still thinks I want to get rid of the whitespace in otherwise empty lines.Mallee
@KyleDelaney - Now that I think about it, formatting is specific to the language, it may be down to the syntax processor that you're using (notice the italics!) ;o).Humism
How do I modify the syntax processor?Mallee
@KyleDelaney - Well it's the language or whatever you're using. You can NPM all sorts of syntax highlighters and formatters into VS Code. (It's similar to the Ctrl + K, Ctrl + D keys in Visual Studio itself.) You can also write your own if you're feeling g energetic!Humism
I mean, I'm happy to just grab an extension that does this. I just don't know any that do.Mallee
@KyleDelaney - Just do a search for the language you're using. There are usually a handful of good extensions you can use. Some extensions will reformat the code in different ways and may provide a way of tailoring what you're doing.Humism
J
6

As of: 2022-02-01

Here is the solution that worked for me even with VSCODE formatting(linting) on:

There are two native VSCODE settings that format your code automatically:

  1. "editor.formatOnSave": true,
  2. "editor.formatOnType": true,

These settings affect your text editor only if "editor.defaultFormatter" is not null

Here are the problems

  1. The "editor.trimAutoWhitespace" VSCODE setting solves the problem but only works on the "editor.formatOnType" autoformat, when you save the document this setting is ignored.
  2. You may also want to trimAutoWhitespaces on all cases but the ones where you are leaving an indent on an empty row. (this was my case).

In my case, while coding, I test my code in the terminal chunck by chunck. The problem with, in my case, python is that the end of a for loops and a conditional is defined by indentation. In this case since the terminal run the code line by line, and not in chuncks, with the removal of the indentation, the terminal thinks that the for and if commands are finished before they actually are.

Here is the solution:

  1. Never define an edit.defaultFormatter in your VSCODE settings define it per language.

How do you do that?

  • Change VSCODE "editor.defaultFormatter" to null as in:
    "editor.defaultFormatter": null,

  • Change the language formatter to your prefered one. In my case:
    python.formatting.provider": "black"

VSCODE gives you the possibility of choosing a formatting (linting) provider for any language. These providers' rules are way more detailed than the VSCode native rules. In VS code press CRTL+SHIFT+P and search for "preferences: Configure Language Specific Settings...". Then define your formatting provider for said language.

  1. Every provider (in my case "black") provides the option of ignoring some sort of formatting rule. Set the ignore argument for this provider. In my case I only ignore 2 rules and my setting is:
  • "python.formatting.blackArgs": [ "--ignore=E501,W293" ],

Rule E501 = Row with more than 80 character.

Rule W293 = Empty Row containing only WhiteSpaces.

Ignoring W293 allows the Auto Trim White Spaces to keep working for every kind of trailing White Spaces except for the case referred to in W293.

Jewfish answered 1/2, 2022 at 20:22 Comment(1)
I have to say that VS Code has a history of adding and removing their own linters for common languages/markups (e.g. HTML and CSS), which makes it difficult to manage some settings. Also, the settings editor.formatOnSave and editor.formatOnType default to false at present. Useful information - thank-you.Humism
C
4

Timestamp:
2021, using VS Code v1.56.2

Use Case:

You use editor.action.trimTrailingWhitespace. Later you wish to write new code in a function. You navigate to a blank line within the function, but discover this line isn't indented and is completely empty. In this scenario, you have four choices:

  1. Hit Tab multiple times until your cursor is at the proper indentation.
  2. Navigate up to a line with proper indentation, press End, then press Enter.
  3. Click your mouse to the right of a properly indented line, then press Enter.
  4. Press Ctrl + ] repeatedly to indent the empty line.[See Footnote 1]

This answer automates this workflow by inserting the indentation for you (when you navigate to an empty line surrounded by indented lines).

Background: Spent 3 hours trying all of the solutions on this page (and many different extensions). Couldn't find anything else which worked.

Solution via Extension

implicit-indent Extension by jemc:
https://marketplace.visualstudio.com/items?itemName=jemc.vscode-implicit-indent

Automatically indents an empty line when navigated to (if its surrounding lines are indented).

Functionality

From experimenting, here's how implicit-indent seems to work:

  • Checks and matches either tab or space indentation automatically.

  • Determines spaces or tabs based on indentation of surrounding text, regardless of editor settings.[See Footnote 2]

  • Clicking on an empty line automatically indents to match surroundings.

  • If pressing the up or down arrow key navigates the caret (a.k.a. text cursor) to an empty line, implicit-indent will automatically indent the line and place the cursor to the right of the indentation (making it feel the same as if the line were already indented).

    -> Before or is pressed, it doesn't matter what column the caret is on, this extension will trigger regardless.
     

  • Navigating to an empty line matches nested indentation.
    Assume you have the following:

    Where |n| represents a line
    and c represents the caret / text cursor
    and only line |2| is empty.
    
    |1|    indented line
    |2|                         (empty line)
    |3|  c    indented line
    
         ^ assume caret is on line |3|
           (caret can be at any column)
    

    Pressing the up arrow key results in the following:

    |1|   indented line
    |2|      c 
    |3|      indented line
    
             ^ Line |2| (previously empty)
               is automatically indented to 
               match nested indentation 
               of line |3| 
    
               and the caret is automatically moved
               to the end of the inserted whitespace
    
               (as if the line were already indented).
    

VS Code

As of 2021 May, the following GitHub issues are still unresolved:

https://github.com/microsoft/vscode/issues/49661
https://github.com/microsoft/vscode/issues/54210
https://github.com/OmniSharp/omnisharp-vscode/issues/1980
https://github.com/OmniSharp/omnisharp-vscode/issues/1680

Using implicit-indent is the only workaround I've discovered so far.

I'll amend this answer when automatic indentation is added to VS Code's native settings.




[Footnote 1]

As an alternative to this extension, you can use Tab or the following indent/unindent functionality built-in to VS Code to manually indent an empty line. Slightly out of scope, but it's a good hotkey to know about.

Default built-in hotkeys are:

  • Hotkey: CTRL + ]
    Command: editor.action.indentLines
    What it does:
    Indent current line (if no selection)
    or indent all selected or partially-selected lines.
  • Hotkey: CTRL + [
    Command: editor.action.outdentLines
    What it does:
    "Outdent" (a.k.a "unindent" a.k.a dedent)
    current line (if no selection)
    or outdent all selected or partially-selected lines.

[Footnote 2]

Note: regardless of whether you use this extension or not, you can quickly replace your current document's indentation (to either leading tabs or leading spaces) by using the following VS Code commands:

  • editor.action.indentationToTabs
  • editor.action.indentationToSpaces
Cheekpiece answered 23/5, 2021 at 21:54 Comment(2)
implicit-indent extension is good, it put cursor on correct place when you click on line, but it also spawn spaces in this line (from beginning until cursor), and not removing them after clicking on another line. So if you didn't typed anything on this line, you'll have to remove those spaces manually.Maleate
This is a great extension, unfortunately it triggers git changes whenever you navigate into an empty line.Rack
K
3

I had the same issue but after removing :

"editor.autoIndent": "none"

I was good to go.

Kenric answered 29/4, 2020 at 11:27 Comment(1)
editor.autoIndent does not exist on vs code 1.76.2 on MacFulgent
C
1

That is probably eslint (and/or beautify) doing that. Look at

"no-trailing-spaces": ["error", { "skipBlankLines": false }],

I have that in my eslintrc.json file and so I get errors on blank lines with spaces or tabs on them. Setting "skipBlankLines" to true might work for you.

Controversial answered 1/4, 2018 at 21:36 Comment(0)
R
1

Answer edited as for VSC version 1.56.2 and newer.

The command editor.action.insertLineAfter makes a new line and moves the cursor there preserving the indentation. To bind that command to Enter key, go to your keyboard shortcuts (press ctrl + k ctrl + s) then press the page with the pivot arrow icon on the far right top.

enter image description here

add the following inside keybindings.json to look like so:

// Place your key bindings in this file to override the defaults
[
    {
        "key": "enter",
        "command": "editor.action.insertLineAfter",
        "when": "editorTextFocus && !editorReadonly"
    },
]

It worked for my without re-opening of VSC

Riproaring answered 22/5, 2019 at 14:16 Comment(0)
B
1

I was having this issue with writing Flutter code.

Only solution for me was to change my default formatter to Flutter.

UPDATE: I also needed to disable Dart: Enable SDK Formatter

Berners answered 19/7, 2022 at 15:31 Comment(1)
I also needed to disable Dart: Enable SDK FormatterSunderland

© 2022 - 2024 — McMap. All rights reserved.