1

I have a code linter (https://github.com/symplify/easy-coding-standard) that I can run manually from the command line, but which I'd like to run automatically in vim whenever I save a file that I've been working on.

This is what I have so far:

autocmd BufWritePost * execute '! /var/www/sites/mysite/vendor/bin/ecs check %'

Very basic, but kind of works. I'd like to improve it in lots of ways though

1) don't save the file if ecs is unhappy, unless I confirm in some way

2) don't allow vim to quit if I've used :x and there's a problem

3) only run ecs in certain project directories

I've tried googling this problem but didn't come up with much, especially for the first point. Any help appreciated, thank you!

  • 4
    There are a lot of different ways of doing linting on vim. Have you checked this wikia page? ALE is a pretty popular option, I think coc can also do some linting. The choice is pretty much a matter of personal preferences. – statox May 13 at 12:47
3

To prevent the saving, you first need to switch from BufWritePost to BufWritePre. But then, the updated file contents are not available yet on the file system, so you'd have to find another way (pipe, temp file) to get them to your linter. In general, this is a non-trivial problem, and I second the recommendation for generic tools like ALE already given in the comments.

If you still want to build a solution yourself:

  1. You can abort a write (in BufWritePre) by :throwing an exception (:echoerr might also work).
  2. When the buffer isn't persisted, Vim will automatically prevent a non-forceful quit.
  3. To limit this to certain directories, the autocmd pattern can be used; instead of *, you can put in file or path globs. But again, this scoping functionality often already is provided by plugins (directly as plugin configuration or indirectly by offering a command to turn off checking for a buffer, which you can then set up via a separate autocmd).
| improve this answer | |
  • Thanks for taking the time to reply! – Codemonkey May 14 at 16:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.