granth green sumo

turkey sandwiches!

Photo Photo Photo Photo Photo Photo

Trailing Whitespace 16 June 2008

textmate, whitespace, ruby

Useless whitespace bugs me. I recently read a post on how to make it more visible. Why make it even more annoying? So I’ll fix it!

The most common case I have is if I hit enter to make a blank line inside a block. TextMate leaves the indent, so you get space-space-newline instead of just newline.

To fix this, I made a macro to remove trailing whitespace when you hit enter. It’s much faster than the bit of Perl in the “Remove Trailing Spaces in Document” command in the Text bundle. It’s fast enough that I don’t notice it at all.

In order for the macro to have the correct scope at the end of a line, I added a punctuation.trailing-whitespace scope to match the newline. That way I can avoid colouring the newline – TextMate displays it as the rest of the line, to the edge of the screen. That’s a bit too ugly. Add this to the patterns section of TextMate’s Ruby language grammar:

{ name = 'punctuation.trailing-whitespace';
  match = '(\s+)$\n?';
  captures = { 1 = { name = 'invalid.trailing-whitespace'; }; };
},

The macro:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>bundleUUID</key>
  <string>467B298F-6227-11D9-BFB1-000D93589AF6</string>
  <key>commands</key>
  <array>
    <dict>
      <key>command</key>
      <string>insertNewline:</string>
    </dict>
    <dict>
      <key>command</key>
      <string>moveUp:</string>
    </dict>
    <dict>
      <key>command</key>
      <string>selectHardLine:</string>
    </dict>
    <dict>
      <key>argument</key>
      <dict>
        <key>action</key>
        <string>replaceAll</string>
        <key>findInProjectIgnoreCase</key>
        <false/>
        <key>findInProjectRegularExpression</key>
        <false/>
        <key>findString</key>
        <string>\s+$</string>
        <key>ignoreCase</key>
        <true/>
        <key>regularExpression</key>
        <true/>
        <key>replaceAllScope</key>
        <string>selection</string>
        <key>replaceString</key>
        <string>\n</string>
        <key>wrapAround</key>
        <true/>
      </dict>
      <key>command</key>
      <string>findWithOptions:</string>
    </dict>
    <dict>
      <key>command</key>
      <string>moveDown:</string>
    </dict>
    <dict>
      <key>command</key>
      <string>moveToEndOfParagraph:</string>
    </dict>
  </array>
  <key>keyEquivalent</key>
  <string>
</string>
  <key>name</key>
  <string>Remove Trailing Whitespace and Insert LF</string>
  <key>scope</key>
  <string>punctuation.trailing-whitespace, invalid.trailing-whitespace</string>
  <key>uuid</key>
  <string>CF85A6DA-30A7-4A67-A723-29CD631C6958</string>
</dict>
</plist>

previously: Sake Music Grab