save-and-close-confirmation.vim 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. " This code sets shortcuts for close buffer and save.
  2. " They both work to let you know when a file has unsaved changes
  3. " and offers you to give it a filename. We take this granted on
  4. " modern text editors, but VIM does not have it by default.
  5. " Tested in NeoVim, but should work with VIM as well.
  6. " Put this on your ~/.vimrc for VIM and ~/.config/nvim/init.vim for
  7. " neovim.
  8. " Remaps 2 keyboard shortcuts
  9. " Ctrl+W: for closing the buffer (and ask for confirmation, filename etc.)
  10. " Ctrl+S: save (and ask for filename if not already saved
  11. " A "Save As" feature can also be built from this code if you want!
  12. " -- save related -- "
  13. function! SaveFile()
  14. let old_name = expand('%')
  15. if old_name != ''
  16. exec ':w'
  17. else
  18. let filename_input = input('Enter filename to save as: ')
  19. exec ':saveas ' . filename_input
  20. endif
  21. endfunction
  22. nnoremap <C-s> :call SaveFile()<cr>
  23. inoremap <C-s> <Esc>:call SaveFile()<cr>i
  24. vnoremap <C-s> <Esc>:call SaveFile()<cr>v
  25. " -- close buffer related -- "
  26. function! CloseFile()
  27. let old_name = expand('%')
  28. let unsaved_changes = &mod
  29. if unsaved_changes == 1
  30. " there are unsaved changes, so we offer to save
  31. let savechanges_input = input('Do you want to save changes? (y/n) ')
  32. if savechanges_input == 'y'
  33. :call SaveFile()
  34. endif
  35. endif
  36. exec ':q!'
  37. redraw!
  38. endfunction
  39. nnoremap <C-w> :call CloseFile()<cr>
  40. inoremap <C-w> <Esc>:call CloseFile()<cr>
  41. vnoremap <C-w> <Esc>:call CloseFile()<cr>