How can I convert tabs to spaces and vice versa in an existing file?
Asked Answered
P

9

238

I cannot figure out how to do this for the life of me apart from doing a find-replace on four 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 Visual Studio Code?

Paleobiology answered 28/11, 2015 at 18:10 Comment(1)
See also: #36815142Brose
J
408

Since fix of: https://github.com/Microsoft/vscode/issues/1228 the editor supports it out of the box. Simply go for:

  1. F1,
  2. indentationToSpaces or indentationToTabs (depending on your need)
  3. Enter.
Janice answered 29/5, 2016 at 12:13 Comment(6)
This only converts leading spaces/tabs.Autumnautumnal
For step 1 you could also do ctrl+shift+pHusein
None of the answers converts each tab to the correct and VARYING number of spaces. For example, enter this text and then convert: Line 1: "A\tB". Line 2: "ABC\tD".Tonsorial
Is there a way to do this for ALL files in a project?Renaissance
@NigelScott: I have the same question as the thread-starter. I want to convert ALL tabs in every file in my document. It appears that the above affects only indentation. Thumbs up to the comment from becko as wellUnwelcome
Amazingly, this still isn't built into Code. I tried a load of extensions, but most of them convert tabs directly into fixed number of spaces which will break any alignment (which is the main reason you would use tabs in the first place). This one does work though: marketplace.visualstudio.com/…Autumnautumnal
R
127

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.

Enter image description here

Radiothermy answered 4/5, 2018 at 17:35 Comment(2)
This only converts tabs in indentation, not all tabs.Ludovika
Does this work for converting future tabs to spaces, or only existing ones?Nikolaos
V
91

If you are trying to convert non-leading tabs to spaces (or vice versa) you can use a regex search and replace.

  1. Press CTRL + H
  2. Click the .* button to search using regular expressions.
  3. To search for tabs enter [\t] in Find box.
  4. Enter spaces in Replace box and perform your replace.

Search box in regex mode: screenshot of VSCode regex search box

Vaporetto answered 7/8, 2018 at 21:43 Comment(6)
This converts each tab to the same number of spaces, which isn't correct.Ludovika
doesnt work , add more spaces and everything gets messed upKaufmann
This is really helpful if you want to convert a tab separated data format to comma separated. :)Deltadeltaic
This answer is flexible. If you want to convert consecutive tabs to a fixed number of spaces and aren't familiar with regular expressions, please change [\t] to [\t]+.Tesstessa
@Kaufmann this answer is flexible, if you want to change programmatically , you just need to update the regex patternBackstitch
Yikes. I don't want to jump into regex hell, especially in VSC.Unwelcome
T
12

To round out these answers, I will add my take for converting each tab to n spaces.

  1. Highlight a tab character
  2. Use CTRL + F2 select all occurrences
  3. 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.

Tesstessa answered 16/7, 2021 at 18:47 Comment(0)
C
8
  1. Select Replace: Ctrl + H
  2. Enter a horizontal tab in the Find box: hold Alt and type 009 on the keypad.
  3. Enter a space (or more spaces) into the Replace box: press the space bar
  4. Press Enter to begin replacing Tabs with Space(s).
Colchicine answered 25/4, 2018 at 20:39 Comment(3)
This didn't work for me, but I posted an answer below on doing this for non-leading spaces/tabs using regular expressions.Vaporetto
This converts each tab to the same number of spaces, which isn't correct.Ludovika
ALT 009 might work on windows only?Blaeberry
R
6

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
Reenareenforce answered 24/11, 2021 at 1:47 Comment(6)
Just to follow up on this, I just downloaded Tab To Space by Takumil and it does exactly what it's supposed to do. I can't believe it had almost 2000 downloads and zero ratings. I wrote a review and gave it 5 stars, because while it only does one thing, it does it absolutely perfectly. Regardless of upvotes, this is the most complete answer to OP's question.Incarnation
Could you please explain how the extensions are different than the built-in functionality described in other answers? Per those answers, this seems like its actually quite easy with VSCode out of the box.Paleobiology
@ZachLysobey there are many different options, and most of them with the explanation. Which one are you comparing with?Reenareenforce
@AlexeiZ VSCode seems to happily convert tab <-> spaces and vice versa without any extensions. I'm just curious what, if any, additional value these extensions provide?Paleobiology
@Zach Lysobey VSCode doesn't convert tabs if they are not the leading characters in a new line. I guess that's the main problem for many ppl in this thread.Lore
@Lore ah that makes sense. I'd still personally go for another approach (like regex search+replace) but maybe this is useful for some folks then 👍Paleobiology
E
1

For converting indentation

Use the Convert Indentation to Tabs or Convert Indentation to Spaces command in the command palette.

By default, VS Code will try to detect what style of indentation an editor tab is using and match that behaviour when you press the tab key. You can disable that behaviour by putting "editor.detectIndentation": false in your settings.json file.

If you keep the indentation type detection on, you can set the indentation style for a new file with no indentation in it yet to tabs by using the Indent Using Tabs command in the command palette, or to spaces using Indent Using Spaces.

If you have editor.detectIndentation set to false, the editor.insertSpaces setting takes effect, whose default value is true, which causes the tab key to insert spaces instead of actual tab characters.

See also the editor.tabSize setting (the visual width of tabs, and how many spaces to insert when editor.insertSpaces is true and editor.detectIndentation is false).

You can also configure these settings on a per-language-mode basis by wrapping them in "[<language-ID>]: { ... }" blocks in your settings.json file.

You may also be interested in How to execute command across multiple files in VS Code?.

For fixed-width conversion anywhere

(emphasis on fixed-width- this is not tab-stop sensitive)

You can use the find widget (ctrl/cmd+f):

  • To go from tabs to spaces, either enable regex mode enabled (alt+r) and search for \t, or paste a tab character into the search field, and then put your number of spaces of choice in the replace field, and then press the "Replace All" button or use the keyboard shortcut shown in its tooltip.

  • To go from spaces to tabs, enable regex mode, and search for {1,N}, where N is your desired tabstop width, and then put \t in the replace field and Replace All. If you want a variant that preserves standalone single spaces, try putting {2,N}|((?<= {N-1}) ) in the search input instead. Again, note that this cannot preserve the exact visual spacing because of editor tabstop behaviour (tabs will be aligned to tab stops).

For replacing in multiple files, use the Search View, which has a similar interface to the find widget. You can exclude/include glob patterns to do replacement in using the extended search controls (Use the three-dot "Toggle Search Details" button).


I tried working on some more tab-stop-sensitive, vanilla-VS-Code solutions, but didn't get much headway and possibly ran into a VS Code bug. Maybe someday I'll come back to this, but I think in any project where you allow each user to choose how wide tabs are, and used or want to use tabs for non-leading-indentation, you will not get something ideal- at least- not with common tab-stop behaviours in IDEs.

Emphasis answered 1/6, 2023 at 23:32 Comment(0)
N
1

Here's a practical solution for the correct replacement (varying amount of spaces), and not only for leading whitespaces.

Assume your tab legnth is 4 spaces do the following:

  1. Replace ^(([^\t]*\t+)?([^\t]{4})*?[^\t]{0})\t with $1 (4 trailing spaces).
  2. Replace ^(([^\t]*\t+)?([^\t]{4})*?[^\t]{1})\t with $1 (3 trailing spaces).
  3. Replace ^(([^\t]*\t+)?([^\t]{4})*?[^\t]{2})\t with $1 (2 trailing spaces).
  4. Replace ^(([^\t]*\t+)?([^\t]{4})*?[^\t]{3})\t with $1 (1 trailing spaces).

After each replacement Press Ctrl+Alt+Enter repeatedly until no result can be found.


If your tab length is 2 spaces for example then you just need to do these:

  1. Replace ^(([^\t]*\t+)?([^\t]{4})*?[^\t]{0})\t with $1 (2 trailing spaces).
  2. Replace ^(([^\t]*\t+)?([^\t]{4})*?[^\t]{1})\t with $1 (1 trailing spaces).

Replacing spaces into tabs can be done in a similar way.

Nourish answered 21/8, 2023 at 21:35 Comment(0)
C
1

I couldn't make it work in Visual Studio Code, because as Nigel Scott and David Given have posted, the Convert Indentation to Spaces command in Visual Studio Code does not convert non-leading tabs.

Additionally, a search and replace for the tab character also does not take into account how wide is the effective horizontal space occupied by the tab character and blindly replaces them with 8 (or any other configured number of) spaces each. This breaks the visual appearance of existing indentation levels.

I guess implementing this case would need an extra command or extension in Visual Studio Code.

In case a non-Visual Studio Code solution is acceptable for you, vim can perform this conversion easily:

:set tabstop=8
:set expandtab
:retab

As suggested in the comment, I tried the Vim extension for Visual Studio Code and the above Vim commands work on it as expected too.

I am posting this because none of the existing answers worked for me and this is the top Google result for the question.

Chapel answered 1/1 at 15:32 Comment(1)
FYI, there is a VSCodeVim extension: marketplace.visualstudio.com/items?itemName=vscodevim.vim. I don't use it though, I only know it exists. I also don't know if you can use or port those commands on that extension.Gharry

© 2022 - 2024 — McMap. All rights reserved.