+4

'Ensure newline at EOF' could do to trim extra newlines.

Itai Ferber 6 years ago 0
The 'ensure newline at EOF' option in ST2 checks to see if the file ends in a newline, and if not, adds one. However, it doesn't trim any excessive newlines. So if a file ends in, say, 7 newlines, it doesn't trim them to just one.

By default, EnsureNewlineAtEof looks like the following:
class EnsureNewlineAtEof(sublime_plugin.EventListener):
    def on_pre_save(self, view):
        if view.settings().get("ensure_newline_at_eof_on_save") == True:
            if view.size() > 0 and view.substr(view.size() - 1) != '\n':
                edit = view.begin_edit()
                view.insert(edit, view.size(), "\n")
                view.end_edit(edit)

I think it would be really nice if it could trim excessive newlines, like so (this code doesn't mess around with the position of the cursor, so you don't get scrolled up or down in the file):
class EnsureNewlineAtEof(sublime_plugin.EventListener):
    def on_pre_save(self, view):
        if view.settings().get("ensure_newline_at_eof_on_save") == True:
            if view.size() > 0:
                edit = view.begin_edit()
                content = view.substr(sublime.Region(0, view.size())).rstrip()
                view.erase(edit, sublime.Region(len(content), view.size()))
                view.insert(edit, len(content), os.linesep) # linesep is used for cross-platform compatibility - and line encodings - but "\n" works too for the most part.
                view.end_edit(edit)

I've added this code to a custom plugin, but it would be much nicer to get this behavior by default. Or at least, get an additional option to trim excessive newlines from files.