Last active
January 19, 2019 09:31
-
-
Save adnan360/5471769a683b03d996c0caebafab52c2 to your computer and use it in GitHub Desktop.
Ask if changes are unsaved and requests a filename to save it if the buffer was not saved anywhere (for VIM/NVIM). Convenient and neat!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
" This code sets shortcuts for close buffer and save. | |
" They both work to let you know when a file has unsaved changes | |
" and offers you to give it a filename. We take this granted on | |
" modern text editors, but VIM does not have it by default. | |
" Tested in NeoVim, but should work with VIM as well. | |
" Put this on your ~/.vimrc for VIM and ~/.config/nvim/init.vim for | |
" neovim. | |
" Remaps 2 keyboard shortcuts | |
" Ctrl+W: for closing the buffer (and ask for confirmation, filename etc.) | |
" Ctrl+S: save (and ask for filename if not already saved | |
" A "Save As" feature can also be built from this code if you want! | |
" -- save related -- " | |
function! SaveFile() | |
let old_name = expand('%') | |
if old_name != '' | |
exec ':w' | |
else | |
let filename_input = input('Enter filename to save as: ') | |
exec ':saveas ' . filename_input | |
endif | |
endfunction | |
nnoremap <C-s> :call SaveFile()<cr> | |
inoremap <C-s> <Esc>:call SaveFile()<cr>i | |
vnoremap <C-s> <Esc>:call SaveFile()<cr>v | |
" -- close buffer related -- " | |
function! CloseFile() | |
let old_name = expand('%') | |
let unsaved_changes = &mod | |
if unsaved_changes == 1 | |
" there are unsaved changes, so we offer to save | |
let savechanges_input = input('Do you want to save changes? (y/n) ') | |
if savechanges_input == 'y' | |
SaveFile() | |
endif | |
endif | |
exec ':q!' | |
redraw! | |
endfunction | |
nnoremap <C-w> :call CloseFile()<cr> | |
inoremap <C-w> <Esc>:call CloseFile()<cr> | |
vnoremap <C-w> <Esc>:call CloseFile()<cr> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment