Search code examples
vimkey-bindings

How to bind q to close a readonly buffer in Vim?


How do I bind q to close a read-only buffer forcefully without any promptings?

Fugitive plugin for example does this when you do :Gst. In that buffer q closes everything and returns back to the file. It's a handy feature.

How do I extend this to any RO buffers because it makes sense to bind q to close it and I don't see why Macros are useful in RO buffers. Also do you have any alternative suggestions for this? I do find myself closing RO buffers so many times with :close! etc.


Solution

  • You can do that with a conditional mapping, see :help :map-expression:

    :nnoremap <expr> q (&readonly ? ':close!<CR>' : 'q')
    

    I still wouldn't recommend to overload a command with two such drastically different meanings; how about <Leader>q for closing?