Vim Macro: cleaning up line endings

When development teams have people working on a variety of platforms, its pretty common to end up with wrong line endings. In vim these will look like ^M at the end of each line. To get rid of these line endings you can use the following command (in command mode)

:% s/^M$//

To type the correct ^M character, you'll need to press Ctrl + V followed by Ctrl + M (the first combination means "take the next combination literally).

To turn this into a macro you should do the following. In command mode, pressq, followed by any letter. This will be the shortcut to access the macro. Then type the command as above. Finally, press q again to stop recording and its done. You can use your macro by pressing @ and then the letter you chose.

6 thoughts on “Vim Macro: cleaning up line endings

  1. Hi Lorna.
    Cool tip but I think I can go one better!

    I have the following line in my ~/.vim/ftplugin/php.vim file

    autocmd BufWritePre *.php :%s/\s\+$//e

    This removes all trailing spaces in a .php file prior to writing it to disk and means I can concentrate on work rather that using macros ;-)

  2. Ken: Hello, thanks for dropping by and upstaging me with such an excellent tip :) I've also seen some nice pre-commit hooks for SVN that cleans up this kind of badness before the files go near the repo.

    • Have you tried using the svn:eol-style property? This seems more appropriate than using pre-commit hooks.

  3. Geoff: For line-endings the SVN property is really useful, but for more complex requirements, like the ones Ken mentioned, a hook is more functional I think. I must admit to usually specifying whitespace and line endings in coding standards and then shouting at people that do it wrong ... its a less technical solution but it works :)

  4. Lorna,
    If you're getting into hooks and coding standards you might want to have a look at triggering Greg Sherwood's php codesniffer when somebody attempts to check in changes.

    http://url.ie/hq6 is a redirect to his blog posting about doing this.

Leave a Reply

Please use [code] and [/code] around any source code you wish to share.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>