3

I want to create alert/prompt message in vim based on user's action. For example, if the user tries to save a changed config file, a message has to be shown like 'this is a config file and changing it might affect the project. Make sure you are confirm in saving it' and gthen show options like yes, no or quit.

Is it possible to make user defined alert/prompt messages in vim?

5

You could try the following code:

augroup CustomSaving
    autocmd!
    autocmd BufWriteCmd /tmp/* if &l:modified | call s:AskForConfirmation() | endif
augroup END

function! s:AskForConfirmation() abort
    echom 'This is a config file and changing it might affect the project.'
    echom 'Are you sure you want to save?'
    while 1
        let choice = inputlist(['1. yes', '2. no', '3. quit'])
        if choice == 0 || choice > 3
            redraw!
            echohl WarningMsg
            echo 'Please enter a number between 1 and 3'
            echohl None
            continue
        elseif choice == 1
            silent! write
        elseif choice == 3
            quit!
        endif
        break
    endwhile
endfunction

Currently it would only affect the files under the /tmp directory. If you wanted it to work for your project files, you would have to change the pattern /tmp/* inside the autocmd:

autocmd BufWriteCmd /tmp/* if &l:modified | call s:AskForConfirmation() | endif

Into something like /path/to/project/*, or if your config files have all the .conf extension, into /path/to/project/*.conf

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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