Sublime Text 2: Trim trailing white space on demand
Asked Answered
C

5

120

I know that Sublime Text 2 can delete the trailing white space on files upon saving.

When working in a team and commiting a change to a file this tends to produce huge diffs which make peer code review more cumbersome. For that reason I prefer to only do the white space cleaning when I'm commiting huge changes to a file anyway and leave whitespace as it is for the minor changes.

I would like to know if there's any command for executing the trimming of the white space on demand on a file, other than "Activate trimming on save > Save file > Deactivate trimming".

Searching in the Documentation and on stackoverflow didn't show anything relevant, all the links seem to talk about the auto trimming on save.

Cortisone answered 6/9, 2012 at 9:38 Comment(5)
This doesn't directly answer your question, but it may help if you're using Git for version control: $ mv .git/hooks/pre-commit.sample .git/hooks/pre-commit which I got from this blog.Shadowy
For fellow Googlers: the non-ondemand way is to add this setting: "trim_trailing_white_space_on_save": trueTurnsole
As an enhancement for @Nate Glenn's comment, note that trimming whitespace from Markdown could get you in trouble, especially if you trim someone else's intentional white space and commit it without noticing. You can edit Markdown.sublime-settings and disable the global trim on save and prevent mishaps.Vacation
IMPORTANT : If there is more than 1 line in between the { } braces make sure you put a ',' on the line above or you will get an error when you try to save.Metric
"When working in a team and commiting a change to a file this tends to produce huge diffs which make peer code review more cumbersome" The deeper issue here is commits with trailing whitespace shouldn't be making it into the repo in the first place, ideally -- precisely because it creates the sort of dirty patches you allude to. Ban trailing whitespace in your coding standards, and catch commits with bad whitespace in your linter/commit hooks.Radioactivity
A
76

Beware: using this plugin makes Sublime Text significantly slower

I use TrailingSpaces plugin for this.

Highlight trailing spaces and delete them in a flash.

ST2 provides a way to automatically delete trailing spaces upon file save. Depending on your settings, it may be more handy to just highlight them and/or delete them by hand. This plugin provides just that!

Usage: click "Edit / Trailing Spaces / Delete".

To add a key binding, open "Preferences / Key Bindings - User" and add:

{ "keys": ["ctrl+alt+t"], "command": "delete_trailing_spaces" }
Albata answered 10/9, 2012 at 9:11 Comment(5)
Yeah, I like this answer the best ... upgrade safe + just works - thanksBarmy
I've notice that the ctrl + F feature to find words becomes slow after I've installed this plugin so I removed it, can you tell me if the same situation happens to you?.Trey
Ctrl + Shift + T is used to open last closed tab in Sublime already. So I prefer Ctrl + Alt + TWimmer
There is an option called trailing_spaces_trim_on_save, which you can set to true in Preferences > Package Settings > Trailing Spaces > Settings - User. You can use this instead of binding a keyboard shortcut, I find it to be better for my needsMucker
Warning: scrolling through large files becomes significantly slower with this plugin installed.Trimetrogon
G
88

I use these steps for a quick on-demand solution within Sublime Text:

  1. Find > Replace...
  2. Find What: [ \t]+\n
  3. Replace With: \n
  4. Replace All

You could also do this for a large set of files via

  1. Find > Find in Files...
  2. Find: [ \t]+\n
  3. Where:
  4. Replace: \n
  5. Replace
Gracielagracile answered 15/10, 2013 at 21:27 Comment(5)
This method works for all lines except the last one.Blalock
@Blalock is correct about the last line. In Sublime Text 3, \t doesn't seem to match spaces, so the answer as written only removes trailing tabs. I think I prefer \s+\n, but note that it deletes blank lines as well. If you want to remove whitespace on the final line as well you can add \s+\z as so: (\s+\n|\s+\z).Terrier
([\t ]+\n|\s+\z) <-- does not remove blank lines.Terrier
The correct regex should be [ \t]+$ and replace it with nothing.Springhead
Don't forget that you need to have your find replace option set to Regex for this to work.Neuroticism
A
76

Beware: using this plugin makes Sublime Text significantly slower

I use TrailingSpaces plugin for this.

Highlight trailing spaces and delete them in a flash.

ST2 provides a way to automatically delete trailing spaces upon file save. Depending on your settings, it may be more handy to just highlight them and/or delete them by hand. This plugin provides just that!

Usage: click "Edit / Trailing Spaces / Delete".

To add a key binding, open "Preferences / Key Bindings - User" and add:

{ "keys": ["ctrl+alt+t"], "command": "delete_trailing_spaces" }
Albata answered 10/9, 2012 at 9:11 Comment(5)
Yeah, I like this answer the best ... upgrade safe + just works - thanksBarmy
I've notice that the ctrl + F feature to find words becomes slow after I've installed this plugin so I removed it, can you tell me if the same situation happens to you?.Trey
Ctrl + Shift + T is used to open last closed tab in Sublime already. So I prefer Ctrl + Alt + TWimmer
There is an option called trailing_spaces_trim_on_save, which you can set to true in Preferences > Package Settings > Trailing Spaces > Settings - User. You can use this instead of binding a keyboard shortcut, I find it to be better for my needsMucker
Warning: scrolling through large files becomes significantly slower with this plugin installed.Trimetrogon
R
49

You can simply use a regex to remove trailing whitespaces:

  1. Find > Replace...
  2. Find what: [^\S\r\n]+$
  3. Replace with: leave empty.
  4. Click 'Replace All'

[^\S\r\n]+$ is Regex for "at least one whitespace character (so spaces and tabs but not newlines, using a double negation) followed by the end of the line"

Regular Expression must be enabled: Enable regex is search dialog

Raneeraney answered 24/10, 2016 at 8:48 Comment(1)
Extra points for the big red arrow. I've been using Sublime for eight years and I'd somehow missed that.Swing
S
23

This method isn't perfect, but uses no plugins or settings and works in most situations.

  1. Multi-Select and move cursor to the end of every line
  2. Hold CTRL-Shift, Press Left, Right
  3. The spaces and tabs at the end of the lines should now be selected. Press Delete or Backspace

Note - Special characters such as ( and + may also be selected at the end of the line at this point, not just spaces.

How to Multi-Select all lines:

One way is to use the middle mouse key to select vertically then hit the End Key if it's a small selection.

With hot-keys:

  1. CTRL-A (select all)
  2. CTRL-SHIFT-L (place cursor on all lines selected)
  3. END (Go to end of lines)

You can also use the find function to find something that will be in every line, like the space character:

  1. \s (using regex)
  2. Click Find All
  3. Press the "End" key to get multiple cursors at the end of each line

Sample Text:

text and number     44  more text and a space  
text and number 44  more text and 2 tabs        
text and number 44  more text and no space or tab

text and number 44  more text after a line feed
Shrewsbury answered 8/5, 2013 at 23:18 Comment(3)
Note: To highlight all lines with the multi-cursor in the last position you can use CTRL+A followed by CTRL+SHIFT+L followed by END.Evieevil
Using this technique on other datasets I've found that it's not perfect. Sublime Text will also highlight special characters such as ) and + along with trailing spaces. Be careful if some of the data ends in special characters.Shrewsbury
Also, FYI \s in regex not only matches the space character, but also tabs and new lines (i.e. "whitespace") not just spaces. :)Evieevil
E
14

I found a soulution here: http://www.sublimetext.com/forum/viewtopic.php?f=4&t=4958

You can modify the package

trim_trailing_white_space.py

located in the default packages directory, this way:

import sublime, sublime_plugin

def trim_trailing_white_space(view):
    trailing_white_space = view.find_all("[\t ]+$")
    trailing_white_space.reverse()
    edit = view.begin_edit()
    for r in trailing_white_space:
        view.erase(edit, r)
    view.end_edit(edit)

class TrimTrailingWhiteSpaceCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        trim_trailing_white_space(self.view)

class TrimTrailingWhiteSpace(sublime_plugin.EventListener):
    def on_pre_save(self, view):
        if view.settings().get("trim_trailing_white_space_on_save") == True:
            trim_trailing_white_space(view)

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)

Now you can add the command to your keymap configuration:

{ "keys": ["your_shortcut"], "command": "trim_trailing_white_space" }
Eyebolt answered 6/9, 2012 at 11:54 Comment(2)
The best solution for me, I don´t want to add a plugin for just simply do this. Thanks.Cuneal
For me this is the Perfect solution, ThxTranscript

© 2022 - 2024 — McMap. All rights reserved.