vimvim-registers

Duplicate % register and pass as an argument


I use the % register to compile the current .tex file using pdflatex. I have this mapped to ww, where the file is first saved and then compiled.

map :ww :w <CR> :!pdflatex % <CR>

This works fine. Now I tried copying % to another register and then create similar mapping using the new register, but that doesn't work.

let @a=@%
map :ww :w <CR> :!pdflatex a <CR>

When I compile, I get the following error message:

! I can't find file `a'.
<*> a

However, when I check the register a using echo @a, the register has been created correctly. So I don't understand why this doesn't work. Please help.

P.S. My ultimate goal is to create a conditional mapping:

if % contains 'chapter':
    map :ww :w <CR> :!pdflatex ../main.tex <CR>
else
    map :ww :w <CR> :!pdflatex % <CR>

So that vim can handle the directory structure:

.
├── chapter1
│   ├── chapter1.tex
├── chapter2
│   ├── chapter2.tex
├── chapter3
│   ├── chapter3.tex
├── main.tex

Solution

  • % is not a register itself, it is an "Ex special character" (see :h cmdline-special).

    In order to paste the contents of a register in insert or commandline/ex mode, you can press Ctrl+R, followed by the character that identifies the register. If you edit e.g. your .vimrc and would do that in insert mode, you'll paste the value that register has currently, which is no good for use in a mapping, so you need to escape it with Ctrl+V:

    map :ww :w <CR> :!pdflatex ^Ra <CR>
    

    Here, ^R is a single character that was created with the key sequence Ctrl+V, Ctrl+R.


    There might be a second issue I see with your approach, if I understand it correctly:

    Your let @a=@% is also evaluated on start of your editor, if it's in your .vimrc. To fix that, move that and the mapping into an autocommand (:h autocmd).