vimvim-registers

Using a register in a .vimrc mapping


I'm doing a job involving multiple modifications of HTML template files in which values to be replaced are designated in the template with tokens such as "%%ARTICLE_DATE". I'd like to use the "+" or "*" (clipboard, X-clipboard) vim registers in a mapping in my .vimrc to set up a search using the value in the clipboard. For instance:

cmap <esc>q %s/%%ARTICLE_DATE/<something>/c

So if I had "June 12, 2016" in my X-clipboard from another app, I could key Esc-q and have

:%s/%%ARTICLE_DATE/June 12, 2016/c

in my vim command line, and I could press Enter and selectively replace the matched tokens. Is there a functional representation of clipboard contents which I could use for <something> which would do this?


Solution

  • There are two different ways you could do this.

    1. The easy way:

      cmap <esc>q %s/%%ARTICLE_DATE/<C-r>*/c
      

      This doesn't use any fancy tricks. It just uses the <C-r> key to insert the contents of a register.

    2. The robust way:

      cmap <expr> <esc>q "%s/\V%%ARTICLE_DATE/".escape(getreg("*"), "\\/")."/c"
      

      This uses an "expr" mapping, which means it will evaluate the vimscript to a string and run that string as a mapping. This has some extra things in place to make sure that if you have a slash (forward or backward) in your register, it won't screw up the search.