226

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
}
chris
  • 4,827
  • 6
  • 35
  • 53
  • The plugin you posted is actually working fine for me on ST3, build 3059. Can you open up the console with `Ctrl + ~` and see if it's giving you any plugin errors? And if you have Package Control installed, can you see if `ExpandTabsOnSave` is listed as an installed plugin? – angerson Mar 20 '14 at 14:22
  • crazy one, seems to be installed (listed under list packages) and in console I can´t find any errors :-( – chris Mar 20 '14 at 14:52
  • Try adding `print("debug")` or similar to the plugin to see if it's executing or not on save. – angerson Mar 20 '14 at 15:03
  • omg, its works! was the wrong directory on windows machine, packages are listed in user/.../AppData/Roaming/SublimeText3/Packages Thanks a lot! – chris Mar 20 '14 at 15:21
  • Be sure you set that view as the active view for the window before running the command. May not be very likely, but as you posted it, it's possible it expands the tabs of a different page than the one you are trying to save. Even with the focus view, I suppose there is a chance it could save to a wrong file, but at least you can minimize the risk. – skuroda Mar 20 '14 at 22:37

11 Answers11

474

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.

angerson
  • 7,342
  • 1
  • 21
  • 24
  • 48
    yes, I know. My desire is to make this automatically ... any idea? – chris Mar 20 '14 at 14:02
  • 3
    @chrisツ Ah. Could you reformat your question to make that more explicitly obvious? I missed your meaning, so others might, too. – angerson Mar 20 '14 at 14:05
  • I don't have that status bar at the bottom – how do I get it? – geoidesic Apr 11 '17 at 07:33
  • 1
    And this does on the entire file, and can **not** be done only on a selection. – not2qubit Jan 08 '18 at 17:55
  • Very nice. I also did 'command-a' to select all, 'command-[' to un-indent, then 'edit > line > reindent' to fix the file. I'm sure this can be built into a macro. – Brooks DuBois Oct 29 '18 at 00:52
  • 1
    Something noteworthy here is that in Sublime when you select the indentation in your code if it is a tab you should see a straight line `----` and if it is spaced you see dots `....` – Shahroq Sep 20 '20 at 06:37
134

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.

starball
  • 20,030
  • 7
  • 43
  • 238
erier
  • 1,744
  • 1
  • 11
  • 14
  • 3
    I wish this could be done on-load and automatically... for all files which I open. I mean: the conversion of indentation spaces into tabs. It would be run automatically on-load :-) – Filip OvertoneSinger Rydlo Jun 30 '16 at 16:32
  • 1
    I hear you on that. I prefer tabs BUT I understand why lots of code is written with spaces. With spaces, there will be no inconsistencies between IDE's - a space is a space is a space. Tabs can take up variable number of spaces between IDE's and make code look weird. – erier Jul 05 '16 at 21:18
  • Hello @Green - what doesnt work about it? Let's get this worked out ... – erier Nov 29 '16 at 19:03
91

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.

Community
  • 1
  • 1
justin
  • 1,528
  • 11
  • 26
  • Just a reminder of how to get to settings. Press command + shift + P, then type 'settings' and it will come up with two windows, drop the code in @justin's answer in the tab on the right, ensuring it remains valid JSON. – dss May 02 '23 at 02:18
14

You can use the command palette to solve this issue.

Step 1: Ctrl + Shift + P (to activate the command palette)

Step 2: Type "Indentation", Choose "Indentation: Convert to Tabs"

Jojoleo
  • 171
  • 2
  • 12
8

In my case, this line solved the problem:

"translate_tabs_to_spaces": false
vljs
  • 978
  • 7
  • 15
5

Here is a solution that will automatically convert to tabs whenever you open a file.

Create this file: .../Packages/User/on_file_load.py:

import sublime
import sublime_plugin

class OnFileLoadEventListener(sublime_plugin.EventListener):

    def on_load_async(self, view):
        view.run_command("unexpand_tabs")

NOTE. It causes the file to be in an unsaved state after opening it, even if no actual space-to-tab conversion took place... maybe some can help with a fix for that...

TheStoryCoder
  • 3,403
  • 6
  • 34
  • 64
4

To automatically convert spaces to tabs on save, add the following Python script to a newly created subfolder called "UnexpandTabsOnSave" within "$SUBLIME_HOME$\Packages\":

import sublime, sublime_plugin, os

class ConvertSpacesToTabsOnSave( sublime_plugin.EventListener ):
  # Run Sublime's 'unexpand_tabs' command when saving any file
  def on_pre_save( self, view ):
    view.window().run_command( 'unexpand_tabs' )

Thank you for the initial resource.

sean2078
  • 5,131
  • 6
  • 32
  • 32
0

You can do replace tabs with spaces in all project files by:

  1. Doing a Replace all Ctrl+Shif+F
  2. Set regex search ^\A(.*)$
  3. Set directory to Your dir
  4. Replace by \1

    enter image description here

  5. This will cause all project files to be opened, with their buffer marked as dirty. With this, you can now optionally enable these next Sublime Text settings, to trim all files trailing white space and ensure a new line at the end of every file.

    You can enabled these settings by going on the menu Preferences -> Settings and adding these contents to your settings file:

    1. "ensure_newline_at_eof_on_save": true,
    2. "trim_trailing_white_space_on_save": true,
  6. Open the Sublime Text console, by going on the menu View -> Show Console (Ctrl+`) and run the command: import threading; threading.Thread( args=(set(),), target=lambda counterset: [ (view.run_command( "expand_tabs", {"set_translate_tabs": True} ), print( "Processing {:>5} view of {:>5}, view id {} {}".format( len( counterset ) + 1, len( window.views() ), view.id(), ( "Finished converting!" if len( counterset ) > len( window.views() ) - 2 else "" ) ) ), counterset.add( len( counterset ) ) ) for view in window.views() ] ).start()
  7. Now, save all changed files by going to the menu File -> Save All
Evandro Coan
  • 8,560
  • 11
  • 83
  • 144
0

if you have Mac just use help option (usually the last option on Mac's menu bar) then type: "tab indentation" and choose a tab indentation width

but generally, you can follow this path: view -> indentation

Ali
  • 112
  • 1
  • 3
-1

Here is how you to do it automatically on save: https://coderwall.com/p/zvyg7a/convert-tabs-to-spaces-on-file-save

Unfortunately the package is not working when you install it from the Package Manager.

Soheil
  • 769
  • 8
  • 17
-1

Use the following command to get it solved :

autopep8 -i <filename>.py
Sharyar Vohra
  • 182
  • 1
  • 11