2

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?

Community
  • 1
  • 1
Maros
  • 1,825
  • 4
  • 25
  • 56

2 Answers2

2
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.

ZyX
  • 52,536
  • 7
  • 114
  • 135
1

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

Maros
  • 1,825
  • 4
  • 25
  • 56
  • 3
    Now try to do the same when filename contains space, dollar, quote, any other shell special symbol. What you need to do here is `au BufWritePost *.slim :silent call system('slimrb '.shellescape(expand('%')).' > '.shellescape(expand('%:r').'.html'))`. By the way, you can pass percent sign to shell, you just have to escape it with slash (when using `:execute`+`shellescape()`: with `shellescape(str, 1)`, note the second argument) or use `system()` which does not treat this sign in any special way. – ZyX Sep 10 '12 at 04:09
  • This seems like a much better solution. If you post it as an answer I'll accept it. – Maros Oct 15 '12 at 21:51