Search code examples
htmlvisual-studio-codeeditorindentation

How can I recursively unindent code in Visual Studio Code?


I have a block of code that has one too many indentations on every nested block in Visual Studio Code, two tabs(four spaces) per nested block. I want one tab(two spaces) per nested block. I can unindent a block with shift + tab, but if I unindent further, the nesting structure will not be preserved.

Is there a command in VS Code to recursively unindent an entire file or selection without having to manually remove each unwanted indentation(i.e. one tab from the first block, two tabs from the second block, etc.)? I wish to only change the indentation, so I cannot use automatic formatting which will make other changes like Prettier.

    <div class="grid-container">
        <div class="grid-item">
            <a href="https://www.goodreads.com/book/show/17255186-the-phoenix-project" target="_blank">
            <img src="https://i.gr-assets.com/images/S/compressed.photo.goodreads.com/books/1361113128l/17255186.jpg">
            </a>
        </div>
    </div>

Solution

    • Select 2 tabs (4 spaces) at the start of a line
    • Shift+Ctrl+L
    • type 1 tab (or 2 spaces)
    • Esc (leave multi cursor mode)

    If only part of the file needs unindent

    • Select 2 tabs (4 spaces) at the start of a line
    • use Ctrl+D as many times as you want/need, till all indents on all lines needed are selected
    • type 1 tab (or 2 spaces)
    • Esc (leave multi cursor mode)

    Multi Cursor method works for up to 10000 indents. If needed repeat for the next section in the file.

    Or with Find/Replace

    • Select 2 tabs (4 spaces) at the start of a line
    • Ctrl+H (start replace)
    • in replace box type: 1 tab (or 2 spaces)
    • if only part of the file needs unindent
      • select part of the file
      • tick inside selection in the Find dialog
    • click Replace All in the Find dialog