Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get correct indentation when pasting in VS Code

Create a new HTML document in Visual Studio Code then paste this:

<body>
    <div>
        <ul>
            <li>Foo</li>
            <li>Bar</li>
        </ul>
    </div>
</body>

Copy the <ul></ul> statement. Insert a new line after </ul>.

<body>
    <div>
        <ul>
            <li>Foo</li>
            <li>Bar</li>
        </ul>
        | <-- cursor    
    </div>
</body>

... then paste.

<body>
    <div>
        <ul>
            <li>Foo</li>
            <li>Bar</li>
        </ul>
        <ul>
                <li>Foo</li>
                <li>Bar</li>
            </ul>        
    </div>
</body>

The indentation is completely messed up. A tons of related question are answering this question with:

Disable the "editor.formatOnPaste": true, from your settings.

The fact is that I have already disabled this feature. Otherwise I would have got even worse:

<body>
    <div>
        <ul>
            <li>Foo</li>
            <li>Bar</li>
        </ul>
<ul>
    <li>Foo</li>
    <li>Bar</li>
</ul>
    </div>
</body>

Is there a way to just paste what I copied AS-IS or either get a correct formatting such as:

<body>
    <div>
        <ul>
            <li>Foo</li>
            <li>Bar</li>
        </ul>
        <ul>
            <li>Foo</li>
            <li>Bar</li>
        </ul>
    </div>
</body>

Please the Shift+Alt+F is not an answer because it will format the whole document and it requires additional operations.

like image 761
nowox Avatar asked Jan 28 '19 10:01

nowox


People also ask

How do I paste code with proper indentation?

A simple fix is to try Ctrl + Shift + V after copying the code. It will paste all codes correctly with indentations in it.

How do you correct formatting in VSCode?

VS Code has great support for source code formatting. The editor has two explicit format actions: Format Document (Ctrl+Shift+I) - Format the entire active file. Format Selection (Ctrl+K Ctrl+F) - Format the selected text.


1 Answers

Thanks to @Galzor for pointing out the issue. Scrolling through Github issues I got workaround for this issue without any additional extension.

  1. Press CTRL+Z after copy paste. It will give you correct indentation. (It works with PasteOnFormat option disabled.)
  2. Or change editing file's language mode to PLAIN TEXT then paste. (You can find language mode in bottom right corner in VS Code) It will not mess up indentation. Then change back language mode to original again.

Hope it helps someone and gets fixed soon!

like image 174
Shinebayar G Avatar answered Oct 15 '22 08:10

Shinebayar G