Last Updated: September 09, 2019
·
53.11K
· regularjack

Convert Tabs to Spaces on file save

It's good practice to use spaces instead of tabs when indenting code. Sublime Text 2 allows you to convert tabs to spaces in existing files manually (View -> Indentation -> Convert indentation to spaces).

However, this can be done automatically when saving the file. Paste the code below into a new file called ExpandTabsOnSave.py and save it under $SUBLIME_HOME$\Packages\ExpandTabsOnSave\.

import sublime, sublime_plugin, os

class ExpandTabsOnSave(sublime_plugin.EventListener):
  # Run ST's 'expand_tabs' command when saving a file
  def on_pre_save(self, view):
    if view.settings().get('expand_tabs_on_save') == 1:
      view.window().run_command('expand_tabs')

You can enable the plugin for a given project by pasting the following into the Project's .sublime-project file:

"settings": {
    "expand_tabs_on_save": true
}

If instead you wish to enable it globally, use your Settings file (Preferences -> Settings - User):

"expand_tabs_on_save": true

9 Responses
Add your response

You should release that as a installable extension via the package manager. Would make it easier to use.

over 1 year ago ·

That really useful to me, I've looking for this script long time. tkx so much!

over 1 year ago ·

Thanks very much!

Agreed with @ro-ka.

over 1 year ago ·

There is a package, but it works only in ST2.

If you're using ST3 you should clone my git repo: https://github.com/alfredbez/ExpandTabsOnSave-SublimeText

Otherwise search for 'ExpandTabsOnSave' in PackageManager and remove '.window' on line 7 in ExpandTabsOnSave.py

over 1 year ago ·

UPDATE: Use this Package for ST2 & ST3 https://github.com/bubenkoff/ExpandTabsOnSave-SublimeText

over 1 year ago ·

dont work for me in ST 3 :(

over 1 year ago ·

works with Sublime Text 3 for me. Thanks! That's perfect!

over 1 year ago ·

All fine on ST3 as well for me, just followed the instructions.

over 1 year ago ·

This is great.

over 1 year ago ·