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-functions
At 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 started
The solution given by the help is to set an option in your $MYVIMRC
:
set autoread
Two 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 e
So the previous mappings become :
nnoremap <leader>a :<c-u>call writefile([expand("<cword>")], "file", "a") \| windo e<cr>
and
nnoremap <leader>a :<c-u>call writefile([expand("<cword>")], expand("#"), "a") \| windo e<cr>