117

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.

José Luis
  • 1,816
  • 8
  • 24
  • 26
  • 1
    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](http://codeimpossible.com/2012/04/02/Trailing-whitespace-is-evil-Don-t-commit-evil-into-your-repo-/). – Paul Fioravanti Sep 06 '12 at 09:51
  • 106
    For fellow Googlers: the non-ondemand way is to add this setting: `"trim_trailing_white_space_on_save": true` – Nate Glenn May 06 '13 at 20:21
  • 3
    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. – tehfoo Dec 03 '13 at 19:11
  • 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. – slindsey3000 Nov 20 '14 at 16:51
  • 1
    "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. – Frank Farmer Mar 29 '19 at 22:02

5 Answers5

85

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
Jason Favors
  • 1,131
  • 9
  • 4
  • 5
    This method works for all lines except the last one. – Joncom Oct 21 '14 at 22:59
  • 1
    @Joncom 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)`. – Kaia Leahy Jan 27 '17 at 15:20
  • 3
    `([\t ]+\n|\s+\z)` <-- does not remove blank lines. – Kaia Leahy Jan 27 '17 at 15:45
  • 4
    The correct regex should be `[ \t]+$` and replace it with nothing. – Codesmith Feb 05 '18 at 17:21
  • Don't forget that you need to have your find replace option set to Regex for this to work. – Noka Nov 12 '21 at 16:39
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" }
compie
  • 10,135
  • 15
  • 54
  • 78
Sridhar Katakam
  • 1,206
  • 13
  • 53
  • 1
    Yeah, I like this answer the best ... upgrade safe + just works - thanks – Rob Feb 04 '13 at 22:44
  • 1
    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?. – dennisbot Jul 05 '13 at 15:57
  • Ctrl + Shift + T is used to open last closed tab in Sublime already. So I prefer Ctrl + Alt + T – Pawel Jul 08 '14 at 10:31
  • 7
    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 needs – Daniel Nov 28 '15 at 06:38
  • 1
    Warning: scrolling through large files becomes significantly slower with this plugin installed. – compie Jul 19 '16 at 20:08
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

Spangen
  • 4,420
  • 5
  • 37
  • 42
antou
  • 706
  • 6
  • 12
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
shanemgrey
  • 2,280
  • 1
  • 26
  • 33
  • 2
    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. – Richard Marskell - Drackir Jun 04 '13 at 05:07
  • 2
    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. – shanemgrey Jul 24 '13 at 14:26
  • 2
    Also, FYI `\s` in regex not only matches the space character, but also tabs and new lines (i.e. "whitespace") not just spaces. :) – Richard Marskell - Drackir Jul 24 '13 at 17:48
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" }
Riccardo Marotti
  • 20,218
  • 7
  • 70
  • 53