Vim programmatically save with different file extension
I'm writing slim files in Vim and I want them to compile and save as html files when I save. Adding this to my .vimrc makes it happen for files in the current directory:
au BufWritePost *.slim silent !slimrb % > $(echo % | cut -d'.' -f1).html
It doesn't work for files with a path like ../file.slim since the cut command turns it into ./file.slim.
I need to use parameter expansions but the % character is reserved for the current filepath when executing an external command in Vim.
How do I compile and save a slim file to a html file regardless of the directory of the file?
au BufWritePost *.slim :silent call system('slimrb '.shellescape(expand('%')).' > '.shellescape(expand('%:r').'.html'))
. In gvim with filenames not containing special characters this works just like silent !slimrb % > %:r.html, but in terminal vim it does not blank the screen (silent does not prevent this) and works when filenames contain any special character except newline. To handle newline you have to use the following:
au BufWritePost *.slim :execute 'silent !slimrb' shellescape(@%, 1) '>' shellescape(expand('%:r').'.html', 1) | redraw!
or write custom shellescape function.
I realized I can trim the extension in Vim using %:r. To auto-compile and save a slim file as an html file I use
au BufWritePost *.slim silent !slimrb % > %:r.html