Sublime Forum

Remove any extra/blank lines at end of file on save?

#1

Hello,

How can this be done? I have the RegReplace plugin installed but I can’t quite figure this out?

Any tips? Thanks!

0 Likes

#2

Not sure if it’s quite right, but try setting trim_trailing_white_space_on_save to true.

0 Likes

#3

trim_trailing_white_space_on_save removes white spaces at the end of lines.

0 Likes

#4

yeah I have that set to true, but it does not remove any extra/blank lines at the end of the file

0 Likes

#5

Pretty sure this regex will work. Haven’t fully tested it, but in the files I had open,it looks like it works properly.

\s]*$(?!\w\W])
0 Likes

#6

That works beautifully :smile: Thank you so much!

0 Likes

#7

Is there a way to get Sublime Text 3 to do this automagically when I save? Also, where do I enter that regexp? Thanks in advance :smile:

0 Likes

#8

Anyone? Am I being ignored cause it’s a really stupid question?

0 Likes

#9

@philsown, you can do this with the RegReplace plugin. I personally have RegReplace setup to strip excessive newlines at the end of the file and also ensure there is one and only one newline at the end of file; all of this happens on save. I will try and post more info later today on this.

0 Likes

#10

@philsown if you use the RegReplace plugin

  • you can add the two replacements
    definitions as shown below. - Turn on_save
    to true - And then add the on_save_sequence
    rule

This setup trims newlines from the beginning of the file and the end of the file. And then it makes sure there is a single newline at the end.

[pre=#161616]{
“replacements”: {

    "trim_excessive_newlines": {
        // (new lines at end of file | new lines at start of file)
        "find": "(((\\r?\\n)+)(?=(\\r?\\n){1}(?!\\s\\S\\r\\n]))|(?<!\\s\\S\\r\\n])((\\r?\\n)+))",
        "replace": ""
    },
    "ensure_newline_at_file_end":{
        "find": "((^\n\r])(?!\\s\\S\\r\\n]))",
        "replace": "\\1\\n"
    },

},

// If on_save is true, RegReplace will search through the file patterns listed below right before a file is saved,
// if the file name matches a file pattern, the sequence will be applied before the file is saved.
// RegReplace will apply all sequences that apply to a given file in the order they appear below.
"on_save": true,

// on_save replacements
"on_save_sequences": 
    // Strip dangling commas

    // Remove trim newlines
    {
        "file_pattern": "*"],
        "sequence": "trim_excessive_newlines", "ensure_newline_at_file_end"]
    },

],[/pre]
0 Likes