Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a mapping for Vim's command-line that escapes the contents of a register before inserting it

Tags:

vim

escaping

Suppose that I have a document like this, and I want to search for all occurences of the URL:

Vim resources: [http://example.com/search?q=vim][q]
...
[q]: http://example.com/search?q=vim

I don't want to type it out in full, so I'll place my cursor on the first URL, and run "uyi[ to yank it into the 'u' register. Now to search for it, I'd like to just paste the contents of that register into the search field by running:

/\V<c-r>u<CR> 

This results in Vim searching for the string 'http:' - because the '/' character terminates the search field.

I can get around the problem by running this instead:

/\V<c-r>=escape(@u, '\/')<CR><CR>

But it's a lot of typing!

How can I create a mapping for Vim's commandline that simplifies this workflow?

My ideal workflow would go something like this:

  • press /\V to bring up the search prompt, and use very nomagic mode
  • hit ctrl-x to trigger the custom mapping (ctrl-x is available)
  • Vim listens for the next key press... (pressing <Esc> would cancel)
  • pressing 'u' would escape the contents of the 'u' register, and insert on the command line
like image 237
nelstrom Avatar asked Sep 13 '11 10:09

nelstrom


1 Answers

Try this:

cnoremap <c-x> <c-r>=<SID>PasteEscaped()<cr>
function! s:PasteEscaped()
  " show some kind of feedback
  echo ":".getcmdline()."..."

  " get a character from the user
  let char = getchar()

  if char == "\<esc>"
    return ''
  else
    let register_content = getreg(nr2char(char))
    return escape(register_content, '\/')
  endif
endfunction

By the way, something that might be useful to know (if you don't already) is that you can use ? as the delimiter for :s. Which means that you could write a search-and-replace for an url like so:

:s?http://foo.com?http://bar.com?g
like image 86
Andrew Radev Avatar answered Oct 05 '22 13:10

Andrew Radev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!