Sunday, May 12, 2013

Re: Substitution gets broken when mapped

On Sun, May 12, 2013 at 10:01:37PM +0200, Sylvia Ganush wrote:
> Hello.

> I'm lost: one same substitution command works fine if executed from the
> command line, but gets broken if executed via a mapping.

> To remove trailing spaces I do:

> :%s/\s\+$//

> And it works perfectly. Since it's such a useful command I add this
> mapping to my .vimrc:

> nmap <leader>w :%s/\s\+$// <cr>

> But when I use the mapping, many extra lines get deleted and the text is
> mangled.

> I expect the mapping to yield the same result as the direct command, but
> it doesn't. What gives?

I'd start by checking mappings as Tim suggested -- then I'd use a
function so I can (a) save and restore the current cursor position and
(b) save and restore the last search register so I'm not blinded by
highlighted spaces every time I insert one at the end of future lines:

let mapleader = ','
nnoremap <Leader>a :call StripTrailingWhitespace()<CR>
function! StripTrailingWhitespace()
let _s=@/
let l = line(".")
let c = col(".")
%s/\s\+$//e
let @/=_s
call cursor(l, c)
endfunction

also I added the 'e' option so as not to be harassed with warnings if
there are no trailing spaces

sc

--
--
You received this message from the "vim_use" maillist.
Do not top-post! Type your reply below the text you are replying to.
For more information, visit http://www.vim.org/maillist.php

---
You received this message because you are subscribed to the Google Groups "vim_use" group.
To unsubscribe from this group and stop receiving emails from it, send an email to vim_use+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

No comments: