Search code examples
configurationsublimetext2line-endings

Prevent modification of line endings in Sublime Text?


I am working on files with different line endings (unix and windows). I realize I can configure SublimeText to use one or the other via "default_line_ending" settings, but how can I have it automatically use the correct type for a given file (meaning don't change the line endings in a file when editing).


Solution

  • Sublime will detect the line endings used in the file and keep using that (but see below), so for example if you open a Unix file and a Windows file, each of those will be saved back to disk using their respective line endings without your having to do anything special.

    If you use the show_line_endings setting, Sublime shows you in the Status bar what type of line ending the current file is using (or will use; clicking it presents the menu that lets you choose a new one). As seen here, it defaults to being turned off.

    // Display line endings in the status bar
    "show_line_endings": false,
    

    That said, if you open files that are only a single line that doesn't have a line terminator character on it, the line ending defaults to the value in default_line_ending setting, which can make it appear as if Sublime is not properly detecting the line ending in use. In fact the issue there is that because there isn't a line ending character at all, it has no way to determine what sort of file you intended to open and has no choice but to fall back to the default.

    If that's the problem, you can mitigate it by altering the default value of this setting:

    // Set to true to ensure the last line of the file ends in a newline
    // character when saving
    "ensure_newline_at_eof_on_save": false,
    

    When this setting is turned on, Sublime ensures that the last line in the file has a line terminator on it, which will allow it to properly detect the appropriate file type next time you open it. The first time you save a file that's a single line, you may need to change the default terminator first to ensure that the correct one is used (this is where the setting referenced above comes in handy).

    A potential downside to this is that it makes all of your files appear at least two lines long to ensure that there's a line terminator in there, which may or may not be an issue.

    Failing that, if these files have very specific names, a plugin could likely be created that would flip the line ending setting on load or just prior to a save.

    Something to note is that one thing Sublime DOES NOT support is the idea of files with mixed line endings; When a file of that sort is saved back to disk, all of the line terminators are normalized to the one currently set. That's because Sublime normalizes the data in memory and doesn't keep a record of what each line previously ended with.