Sublime Text 2: Trim trailing white space on demand

107,617

Solution 1

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" }

Solution 2

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

Solution 3

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

Solution 4

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

Solution 5

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" }
Share:
107,617

Related videos on Youtube

José Luis
Author by

José Luis

Current role: Front-End Developer.

Updated on September 09, 2021

Comments

  • José Luis
    José Luis over 1 year

    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.

    • Paul Fioravanti
      Paul Fioravanti over 10 years
      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.
    • Nate Glenn
      Nate Glenn over 9 years
      For fellow Googlers: the non-ondemand way is to add this setting: "trim_trailing_white_space_on_save": true
    • tehfoo
      tehfoo about 9 years
      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.
    • slindsey3000
      slindsey3000 about 8 years
      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.
    • Frank Farmer
      Frank Farmer over 3 years
      "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.
  • Rob
    Rob almost 10 years
    Yeah, I like this answer the best ... upgrade safe + just works - thanks
  • Richard Marskell - Drackir
    Richard Marskell - Drackir over 9 years
    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.
  • dennisbot
    dennisbot over 9 years
    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?.
  • shanemgrey
    shanemgrey over 9 years
    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.
  • Richard Marskell - Drackir
    Richard Marskell - Drackir over 9 years
    Also, FYI \s in regex not only matches the space character, but also tabs and new lines (i.e. "whitespace") not just spaces. :)
  • Pawel
    Pawel over 8 years
    Ctrl + Shift + T is used to open last closed tab in Sublime already. So I prefer Ctrl + Alt + T
  • Joncom
    Joncom about 8 years
    This method works for all lines except the last one.
  • javifm
    javifm about 8 years
    The best solution for me, I don´t want to add a plugin for just simply do this. Thanks.
  • dspacejs
    dspacejs about 7 years
    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
  • compie
    compie over 6 years
    Warning: scrolling through large files becomes significantly slower with this plugin installed.
  • Kaia Leahy
    Kaia Leahy almost 6 years
    @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
    Kaia Leahy almost 6 years
    ([\t ]+\n|\s+\z) <-- does not remove blank lines.
  • Vikrame
    Vikrame over 5 years
    For me this is the Perfect solution, Thx
  • Codesmith
    Codesmith almost 5 years
    The correct regex should be [ \t]+$ and replace it with nothing.
  • Dustin Oprea
    Dustin Oprea almost 2 years
    Extra points for the big red arrow. I've been using Sublime for eight years and I'd somehow missed that.
  • Noka
    Noka about 1 year
    Don't forget that you need to have your find replace option set to Regex for this to work.