Search code examples
sublimetext2indentationsublimetextsublimetext3

How to execute a command to all files on a sublime text project?


I searched all over the web to find how to execute a sublime text command for all files and then save. I need to refactor my old project that has indentation issues like hard tabs.

What I want is to execute the command "expand_tabs" to the whole project. How can I do it?


Solution

  • UPDATE: I've turned this into a nicely documented ST plugin. Find it here: https://github.com/maliayas/SublimeText_TabToSpaceConverter


    I've written a small plugin that does this. Put this code under "Packages/User/BatchTabToSpaceFixer.py":

    import sublime
    import sublime_plugin
    
    
    class BatchTabToSpaceFixerCommand(sublime_plugin.TextCommand):
        def run(self, view):
            self.run_all_views()
            # self.run_current_view()
    
        def is_enabled(self):
            return len(sublime.active_window().views()) > 0
    
        def run_all_views(self):
            for view in sublime.active_window().views():
                self.process(view)
    
        def run_current_view(self):
            self.process(sublime.active_window().active_view())
    
        def process(self, view):
            # Previous tab size
            view.run_command('set_setting', {"setting": "tab_size", "value": 3})
    
            # This trick will correctly convert inline (not leading) tabs.
            view.run_command('expand_tabs', {"set_translate_tabs": True})  # This will touch inline tabs
            view.run_command('unexpand_tabs', {"set_translate_tabs": True})  # This won't
    
            # New tab size
            view.run_command('set_setting', {"setting": "tab_size", "value": 4})
    
            view.run_command('expand_tabs', {"set_translate_tabs": True})
    

    Then open your project files that you want to be processed. The plugin will process open tabs and leave them dirty. You can do a "Save All" once you think everything is OK.

    Don't forget to edit your previous and new tab size in the code. For example my case was from 3 (as tab) to 4 (spaces). In such a case this plugin will correctly preserve vertical inline (not leading) alignments that were made using tabs.

    If you wish, you can assign a shortcut key for this job:

    {"keys": ["ctrl+alt+t"], "command": "batch_tab_to_space_fixer"}