Sublime Forum

Sublime text 3 - option to delete all but 1 extra lines on bottom of a file upon save

#1

Hello everyone.

I’m wondering if there’s an option to delete all but 1 extra lines on the bottom of a file when saving. I know there is an option “ensure newline on save” and i have that enabled. This works fine - I get 1 newline when saving. However, if there is multiple newlines already on the bottom, and then I save, there will still be multiple newlines. I only want one.

Is there such an option? Thanks in advance.

1 Like

#2

trim_trailing_white_space_on_save?

0 Likes

#3

What that does is it trims trailing whitespace.
For example,

if i have
int main(){
return 0; //4 white spaces after the semicolon here
}

and i save it with trim_trailing_white_space_on_save enabled, it will only remove the 4 whitespaces after the smicolon, not any extra blank lines on the bottom.

0 Likes

#4

Oh right, sorry. Didn’t have my laptop at hand to check. If you search packagecontrol for “whitespace” there are a bunch of options that should work.

0 Likes

#5

there’s no setting for it, but it’s super simple to write a plugin to do it:

  • Tools menu -> Developer -> New Plugin…
  • Select All
  • replace with:
import sublime
import sublime_plugin

class DeleteExtraTrailingLines(sublime_plugin.EventListener):
    def on_pre_save(self, view):
        view.run_command('trim_trailing_extra_lines')

class TrimTrailingExtraLinesCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        match = self.view.find(r'(?<=\n)\s+\z', 0)
        if match != (-1, -1):
            self.view.erase(edit, match)
  • save in the folder ST recommends (Packages/User/) as something like trim_extra_trailing_lines.py
5 Likes

#6

@nexisn4

Install my plugin Single Trailing New Line which does exactly what you want. You can set it up to work with all files or those open in buffers with specific syntaxes.

4 Likes

#7

@kingkeith @mattst Great work. Not only is it implemented, but we have lite and deluxe versions to choose from!

4 Likes