I know there are a lot of posts about this, but I couldn´t get it to work.
I use tabs for coding. Is there a way, to convert always spaces to tabs? I.e. on open and on Save files? Anyone got an idea?

// edit:
My desire is to do this automatically! -> open, save or on the fly
Does anyone know how to do?


I tried this:

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')

And here are my user Settings:

{
    "auto_complete_selector": "source - comment, meta.tag - punctuation.definition.tag.begin",
    "auto_indent": true,
    "detect_indentation": true,
    "draw_white_space": "all",
    "ensure_newline_at_eof_on_save": true,
    "expand_tabs_on_save": true,
    "font_face": "SourceCodePro-Regular",
    "font_size": 10,
    "format_on_save": true,
    "ignored_packages":
    [
        "Vintage"
    ],
    "indent_to_bracket": true,
    "open_files_in_new_window": false,
    "smart_indent": true,
    "tab_size": 4,
    "translate_tabs_to_spaces": false,
    "trim_automatic_white_space": true,
    "trim_trailing_white_space_on_save": true,
    "use_tab_stops": false,
    "word_wrap": false
}

Solution 1:

On the bottom right-hand corner of your Sublime Text window, you'll see an indentation indicator that looks a lot like this:

Indentation options menu

Clicking it will open a menu with options to adjust your indentation preferences, and more importantly, Convert Indentation to Tabs/Spaces.

enter image description here

The same menu is listed under View -> Indentation.

Solution 2:

At the bottom of the Sublime window, you'll see something representing your tab/space setting.

You'll then get a dropdown with a bunch of options. The options you care about are:

  • Convert Indentation to Spaces
  • Convert Indentation to Tabs

Apply your desired setting to the entire document.

Hope this helps.

Solution 3:

As you might already know, you can customize your indention settings in Preferences.sublime-settings, for example:

"detect_indentation": true,
"tab_size": 4,
"translate_tabs_to_spaces": false

This will set your editor to use tabs that are 4 spaces wide and will override the default behavior that causes Sublime to match the indention of whatever file you're editing. With these settings, re-indenting the file will cause any spaces to be replaced with tabs.

As far as automatically re-indenting when opening a file, that's not quite as easy (but probably isn't a great idea since whitespace changes wreak havoc on file diffs). What might be a better course of action: you can map a shortcut for re-indention and just trigger that when you open a new file that needs fixing.