Invalidsearch
Invalidsearch

Reputation: 235

Search and replace contents of yanked text in vim

In my vimrc, I have a shortcut to copy the filename with its path to the clipboard.

:nmap cp :let @* = expand("%")

This works fine. Now, I want to replace the contents of this yanked text to

1) replace \ with /  
2) remove certain words from the yanked text.

I am familiar with search and replace on regular text but I don't know how to change my vimrc entry to do this every time on the yanked text when I use my shortcut.

So, something like this?

:nmap cp :let @* = expand("%") || %s/\\/\/ || %s/<word>//

I am using gvim on windows.

Upvotes: 4

Views: 879

Answers (1)

Ingo Karkat
Ingo Karkat

Reputation: 172510

The :substitute command works on the buffer contents itself; that's not so useful here. (You could temporarily :put the register / file name, transform it, and then :delete it (back) into a register.) Fortunately, there's an equivalent low-level :help substitute() function that you can apply on a String:

:nnoremap cp :let @* = substitute(expand("%"), '\\', '/', 'g')<CR>

In fact, expand() directly supports a special substitution :help filename-modifiers, so this would be a (rather obscure) solution, too:

:nnoremap cp :let @* = expand("%:gs?\\?/?")<CR>

For the additional removal of <word>, you can use another layer of substitute() / append another :gs???. I'll leave that to you.

Additional critique

  • Your mapping is missing the trailing <CR> to conclude command-line mode.
  • You should use :noremap; it makes the mapping immune to remapping and recursion.
  • % is relative to the current working dir. If you need the full absolute path, you can get that via %:p.
  • Starting your mapping with c is unconventional. It's fine here, because the change command wants a {motion}, and p is not a valid one. In general, I'd rather avoid such clever overloading (as long as you have other unused mapping prefixes still available).

Upvotes: 6

Related Questions