How can vim be configured to automatically execute a command line command when executing: W Save Command?

  question, vim

I am writinga.lessFile, I want to be in execution:wCalled automatically when a command is savedlesscCommand to compile the file intoa.cssDocuments.lesscThe format of the command islessc a.less a.css.
How should I set it up?


Don’t know why.autocmd BufWritePostIt doesn’t work, then it only worksautocmd BufWriteCmdHere we go.

function!  CompileLess()
 exec "w"
 exec "!  lessc % > %:t:r.css"
 endfunction
 
 if executable("lessc")
 autocmd BufWriteCmd *.less call CompileLess()
 endif

The general code is as follows. cmd has perfected itself. system can be used to retrieve the compilation results. If there is an error, it will be output, so as to locate the error well.

function!  CompileLess()
 let cmd = 'lessc + ' +  expand('<afile>:p:h')
 let output = system(cmd)
 if v:shell_error
 echohl WarningMsg | echo output
 endif
 endfunction
 if executable('lessc')
 autocmd BufWritePost *.less call CompileLess()
 endif