FYI, I'm taking a "Vim learning" approach and demonstrating how to take what OP has already (for the most part) and properly move much of it into a function. As a couple of the comments above show, though, there certainly could be nice alternative approaches that also solve the problem in question.
There are a few ways you could go about it. They mainly differ in how much you want to do prior to the function call. I might be inclined to extract the register value sooner rather than later in which case you could do
vnoremap <C-C> y:call YourFunc(getreg('"', 1, 1))
This would probably be my preference because it leaves behind buffer specific things when we call the function. IOW, in the function we just process a list containing strings and don't have to worry about yanking and registers and visually selected text. That makes the function more general and reusable.
(There are other ways to get visually selected text into usuable form but for simplicity's sake and since
getreg() nicely transforms buffer lines to a list of strings I'm sticking with your choice.)
Speaking of registers and yanking, I'd avoid a letter register since you're more likely to overwrite something you previously saved. I'm using the "unnamed" register which automatically receives text yanked with
So the function just looks like this:
let l:clipboard = $HOME . "/.vim_clipboard"
call writefile(a:lofs, l:clipboard)
call system("xclip -r -sel c " . l:clipboard)
You may be wondering about the
a: that precedes
lofs. Vimscript requires that those two characters be prepended to a function parameter name when referencing the parameter from within the body of the function.
To avoid repeating the path string I put it in a local variable. Though not required like
a: I'm using the prefix
l: (for "local"). This is just a convention which is meant to improve clarity/readability. (This is a tiny function so it doesn't help much here but it doesn't hurt to practice good habits all the time.) The local variable is being passed as the second parameter to
writefile() and is also being concatenated to the string passed to
Regarding your question about environment variables, Vim inherits them from the runtime environment and you can access them similar to shell scripting:
As far as
$HOME goes this should be set if you're using *nix. On Windows it's set based on a couple rules which you can find here:
Are you not interested in the output of the
system call? If you were you could replace
return and get the output from the function directly. Or you could replace
echo or equivalent.