While editing buffer A, I would like to append some text to buffer B without leaving buffer A. How can I achieve that?My ultimate goal is to form a collection of words that I cherry-pick from the buffer I am currently editing without having to switch buffers or windows.My plan was to write a mapping to yank <cword> and append it to another buffer in its own line, but I can't figure out how to write to a different buffer.
How can I append text to another buffer?
key bindings;buffers
As you said in your post, you can grab the word under the cursor with the special keyword <cword> (or <cWORD> if you want a big word), but before writing it inside a buffer you need to expand it :expand(<cword>)Next, you need a function to write into a buffer.When you are looking for a function, type :help function-list.It will give you a list of all the functions available sorted by category.In this buffer of the help, if you search for the word file, you will find a category of functions that allow you to manipulate files ::help file-functionsAt the bottom of this category, there's a function that seems to do what you want (write into another buffer) : writefile().For more details on how to use it, read :h writefile(.To write a word inside a buffer and append it to its existing content here is the syntax given by the help :call writefile([foo], event.log, a)You just need to replace foo with the word under the cursor and event.log with the name of the buffer in which you want to append some text (let's say for example file).It gives something like this :call writefile([expand(<cword>)], file, a)Next, you need a mapping to do it automatically :nnoremap <leader>a :<c-u>call writefile([expand(<cword>)], file, a)<cr>Here I've chosen <leader>a as a mapping, but you can choose another one.Finally, you could have the following message error :Warning: File {filename} has changed since editing startedThe solution given by the help is to set an option in your $MYVIMRC :set autoreadTwo possible improvements :To write in the alternate file (the file that was last edited in the current window) instead of file :nnoremap <leader>a :<c-u>call writefile([expand(<cword>)], expand(#), a)<cr>In case you use a split window, to update all the splits, you can use the following command :windo eSo the previous mappings become :nnoremap <leader>a :<c-u>call writefile([expand(<cword>)], file, a) \| windo e<cr>andnnoremap <leader>a :<c-u>call writefile([expand(<cword>)], expand(#), a) \| windo e<cr>