How can I convert tabs to spaces and vice versa in an existing file
Visual Studio-CodeWhitespaceVisual Studio-Code Problem Overview
I cannot figure out how to do this for the life of me apart from doing a find-replace on 4 spaces and converting to tabs (Version 0.10.2). I can't think of an editor/IDE that doesn't have a specific feature to do this. Does VSCode?
Visual Studio-Code Solutions
Solution 1 - Visual Studio-Code
Since fix of: https://github.com/Microsoft/vscode/issues/1228 the editor supports it out of the box. Simply go for:
F1
,indentationToSpaces
orindentationToTabs
(depending on your need)Enter
.
Solution 2 - Visual Studio-Code
Another way to do it is click the current indentation (Tab/Spaces:n) on the footer which will open your indentation options where you can select what you want to do.
Solution 3 - Visual Studio-Code
If you are trying to convert non-leading tabs to spaces (or vice versa) you can use a regex search and replace.
- Press CTRL + H
- Click the
.*
button to search using regular expressions. - To search for tabs enter
[\t]
in Find box. - Enter spaces in Replace box and perform your replace.
Solution 4 - Visual Studio-Code
- Select Replace: CTRL-H
- Enter Horizontal Tab in Find box: hold ATL and type 009 on the keypad.
- Enter a space(or more spaces) into the Replace box: press space bar
- Press Enter to begin replacing Tabs with Space(s).
Solution 5 - Visual Studio-Code
To round out these answers, I will add my take for converting each tab to n spaces.
- Highlight a tab character
- Use
CTRL
+F2
select all occurrences - Press
SPACE
n times
This is the easiest way to do this (going beyond only converting leading tabs).
Note that this does not convert consecutive tabs to k spaces. It converts each tab. For consecutive tabs please see my comment on jrupe's answer. You will need VS Code find and replace with regular expressions to accomplish that.
Solution 6 - Visual Studio-Code
Press F1 and then type into textbox convert indentation to spaces or whatever you want ones
Solution 7 - Visual Studio-Code
On Visual Studio, Ctrl+K+F did the trick for me.
Solution 8 - Visual Studio-Code
Fast forward to 2020/2021, there are some extensions that will give us that conversion. I have just needed that functionality (hence I found this article), and searching for extensions I found:
- geocode.spacecadet - providing both TAB->SPC and SPC->TAB, but not updated since 2017, with 1.3k installs, 3.5 review
- takumii.tabspace - TAB->SPC, from 2020, 1.5k installs, no reviews
- pygc.spacetab - SPC->TAB, from... wait, literally yesterday! (or today depending on your TZ), 2 installs, no reviews