Sven [email protected] ©1995-2001

Last update: Sun Oct 08 20:39:33 MET DST 2000

VIM Challenges

"Can you do it?" - Some challenges on hacking with Vim.

Every now and then I think about some problem and I think it can be done with a simple mapping. But I am not always pleased with my solution. Maybe you can think of a better solution? Let me know!

Collecting Matches

Goal: Scan current buffer for occurrences of a word and put all matching lines in a new buffer. [Assume that the word is in the unnamed register '"'.]

Analysis: This is a job for the "global" command. Now, we could easily copy all matching lines after the end of the current buffer with g:#foo#co $, but creating a new buffer to display the result is nice - and also easy done with :new. A mark to remember the former end-of-buffer is necessary for deleting the resulting lines, of course. The last two commands simply delete the resulting empty line.

Solution:

map ## Gma :g#<c-r>"#co $<cr> 'a j dG :new<cr> p k dd I am not happy with the result - for these reasons: I'd rather append the matches to some unused named register and have the pasted into the new edit buffer. Is that possible with an ex command?

000505: Yes - it certainly is possible with an ex command:

map ## :g#<c-r>"#y A<cr> :new "Ap The ex command y A appends every match to the register 'A'. (Note the space between the command an the register name here. Otherwise vim would see the command "yA" which is, of course, no an ex command.)

Now all that is missing is a simple emthod to make sure that the register A is cleared before using the mapped commands. Anyone?

000515: Frank Baruch [email protected] pointed me at the Vim's "let" command which allows to fill the contents of a register:

let @a=""<cr> Adding this will give us the following mapping: map ## let @a=""<cr> :g#<c-r>"#y A<cr> :new "Ap Or in one line: map ## :let @a=""<cr>:g#<c-r>"#y A<cr>:new<cr>"Apdk0 Unfortunately, this solution is specific to Vim. Does anyone have a Vi solution, ie a solution using Vi commands only?

Comments? Improvements? Send them to me!


URL:         http://www.math.fu-berlin.de/~guckes/vim/chall.html
URL:         https://www.vim8.org/chall.html (mirror)
Created:     Sun Oct 08 12:00:00 MET DST 2000
Send feedback on this page to
Sven Guckes [email protected]