Search code examples
sublimetext3sublimetextline-endings

How do configure Sublime Text to always convert to Unix line endings on save?


I want all files that I ever save in Sublime Text to be in Unix line ending format, even when I open files that were originally saved in a different format that I later edited in Sublime Text?

Simply setting "default_line_ending": "unix" is not enough, because that doesn't convert Windows files as I mentioned. How do I do that?


Solution

  • Here's a quick plugin to do the job:

    import sublime_plugin
    
    class SetUnixLineEndingsCommand(sublime_plugin.TextCommand):
        def run(self, edit):
            self.view.set_line_endings("unix")
    
    
    class SetLineEndings(sublime_plugin.EventListener):
        def on_pre_save(self, view):
            view.run_command("set_unix_line_endings")
    

    In Sublime, select Tools → Developer → New Plugin…. In the window that opens, delete everything that's there and replace it with the program above. Hit Save, and the save file dialog should open in your Packages/User directory, whose location varies by OS and type of install:

    • Linux: ~/.config/sublime-text-3/Packages
    • OS X: ~/Library/Application Support/Sublime Text 3/Packages
    • Windows Regular Install: C:\Users\YourUserName\AppData\Roaming\Sublime Text 3\Packages
    • Windows Portable Install: InstallationFolder\Sublime Text 3\Data\Packages

    Save the file as set_unix_line_endings.py and it will activate immediately.

    The plugin will only change the line endings of a file if you edit the contents and then save it. Just opening a file to view won't change anything.

    If you no longer want the plugin active, just enter your Packages/User directory and either delete the file or change its suffix to something other than .py - set_unix_line_endings.py.bak works well for me.