Example: If I have a document with 2 space indentation, and I want it to have 4 space indentation, how do I automatically convert it by using the Sublime Text editor?
Here's a neat trick in Sublime Text 2 or 3 to convert your indentation spacing in a document.
TL;DR:
Converting from 2 spaces to 4 spaces:
Ensure tab width is set to 2. Convert your 2-space indentation to tabs, switch to tab width 4, and then convert the indentation back to spaces.
The detailed description:
Go to:
View -> Indentation
It should read:
Indent using spaces [x]
Tab width: 2
Select:
Convert Indentation to Tabs
Then Select:
Tab width: 4
Convert Indentation to Spaces
Done.
If you find search and replace faster to use, you could use a regex replace like this:
Find (regex): (^|\G) {2}
(Instead of " {2}" <space>{2}
you can just write two spaces. Used it here for clarity.)
Replace with 4 spaces, or whatever you want, like \t
.
You have to add this code to your custom key bindings:
{ "keys": ["ctrl+f12"], "command": "set_setting", "args": {"setting": "tab_size", "value": 4} }
by pressing ctrl+f12, it will reindent your file to a tab size of 4. if you want a different tab size, you just change the "value" number. Te format is a simple json.
Recently I faced a similar problem. I was using the sublime editor. it's not an issue with the code but with the editor.
Below change in the preference settings worked for me.
Sublime Text menu -> Preferences -> Settings: Syntax-Specific:
{
"tab_size": 4,
"translate_tabs_to_spaces": true
}
I wrote a plugin for it. You can find it here or look for "ReIndent" in package control. It mostly does the same thing as Kyle Finley wrote but in a convenient way with shortcuts for converting between 2 and 4 and vice-versa.
I actually found it's better for my sanity to have user preferences to be defined like so:
"translate_tabs_to_spaces": true,
"tab_size": 2,
"indent_to_bracket": true,
"detect_indentation": false
The detect_indentation: false
is especially important, as it forces Sublime to honor these settings in every file, as opposed to the View -> Indentation
settings.
If you want to get fancy, you can also define a keyboard shortcut to automatically re-indent your code (YMMV) by pasting the following in Sublime -> Preferences -> Key Binding - User
:
[
{ "keys": ["ctrl+i"], "command": "reindent" }
]
and to visualize the whitespace:
"indent_guide_options": ["draw_active"],
"trim_trailing_white_space_on_save": true,
"ensure_newline_at_eof_on_save": true,
"draw_white_space": "all",
"rulers": [120],