5

I'm trying to find out if it's possible to make the write ":w" command perform a forced validation for certain file types.

My use case is that I want to prevent small typos and idention errors in python source code. So VIM should not even allow me to save a file with errors.

I can run "python -m py_compile filename" on a file to see if it compiles. This command returns nothing, if all is well, otherwise and error message like "Sorry: IndentationError: expected an indented block (hello.py, line 2)" Alas this requires me to save the file "filename, which I only want done if it passes.

So I'd need to automate these steps:

  • save the current file with a temporary filename, like filename.insert_uuid_here.py
  • run "python -m py_compile filename.insert_uuid_here.py

on success:

  • remove both the filename.insert_uuid_here.py and the __python_cache__/filename.insert_uuid_here.py file.

  • allow save

on fail:

  • remove the filename.insert_uuid_here.py

  • display error from compile attempt

Is this something, that's possible?

How could I link this to any ":w" attempt to write a python file?

3
  • 1
    Might be possible using a custom BufWriteCmd autocommand. I would however not recommend doing that. Commented Jun 9, 2018 at 9:26
  • It might be a better approach to allow writing while linting on save, but automate the checks to block at the build or deploy phase.
    – LEI
    Commented Jun 10, 2018 at 15:20
  • Does the python command follow basic shell command execution conventions? Specifically does it optionally allow input via stdin rather than a file and does it return 0 when input is clean and non-zero otherwise? If both of these are true I have a function for you.
    – B Layer
    Commented Jun 10, 2018 at 15:46

1 Answer 1

1

You can use ALE to asynchronously lint (i.e. check for style/syntax errors) while you type. This will not prevent vim from saving the buffer when you instruct it to do so but that might be what actually you need/want.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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