1

From time to time I accidentally create files with names like ":w" or ":q". This happens when instead of writing :wq I type :w:q and sometimes, for some reason, even :w:w or :w :w. And this has become too frequent to ignore.

My solution to this problem would be to make vim throw an error if :w is given a filename that starts with a colon. Are there ways to force vim to behave like that? Or maybe there is another obvious solution I am missing?

2 Answers 2

2

Disallow writing files matching :* pattern (no matter which command is used):

autocmd BufWritePre :* throw "Invalid name"
3
  • 1
    Such comments will probably be deleted, but just wanted to confirm that this works and is doing exactly what I wanted. On top of that files that contain : are allowed, and only the ones starting with : show the error. Perfect, thank you. Feb 12, 2023 at 22:24
  • Why would it be deleted? :-) Thanks for the feedback and thanks to @Matt for the perfect solution :-) Feb 13, 2023 at 6:06
  • 1
    @VivianDeSmedt I think it's SO policy to delete simple "thank you" comments. BTW thanks for your answer as well - but I really wanted it to be an error, so then it would force me to notice it happened and maybe stop doing it. Feb 13, 2023 at 13:00
1

I would introduce an abbreviation:

cnoreabbrev <expr> :w (getcmdtype() == ':' && getcmdline() =~ '^w\s*') ? '' : ':w'

With this abbreviation if you type :w in the command line (getcmdtype() == ':') that match w\s* (getcmdline() =~ '^w\s*') it is abbreviated as '' and the not wanted extra :w are removed.

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.