1

I like using <cr> to save a file, except in a quickfix window where I want <cr> to enter the directory or file shown.

Here's one way to achieve this (works as a .vimrc by itself). I'm using the test described in this answer to check for quickfix windows.

" takes: nothing
" returns: nothing                               
function! RunEnter()                                                                          
        let l:isqf = getwininfo(win_getid())[0]['quickfix']                                   
        if l:isqf                                                                             
                execute '<cr>'                                                                
        else                                                                                  
                execute ':w!'                                                                 
        endif                                                                                 
endfunction 

noremap <cr> :call RunEnter()<cr>

This kind of command is easier to test, though, if it returns a string with the command to be executed rather than calling into execute.

" This vimrc does NOT work.

" takes: nothing
" returns: command to be executed
function! RunEnter()
        let l:isqf = getwininfo(win_getid())[0]['quickfix'] 
        if l:isqf                                                                             
                return '<cr>'                                                               
        else                                                                                  
                return ':w!<cr>'                                                                 
        endif    
endfunction

nnoremap <expr> <cr> RunEnter()

This .vimrc, however, doesn't have the expected behavior when you press <cr>.

For example, if you visit the .vimrc itself and then press <cr>, you get :w!<cr> verbatim as the command line. The <cr> is being treated as "<cr>" rather than as a literal naming a key.

1 Answer 1

4

<expr> merely interprets the string as a command, it does not perform conversion of "escape codes" like <cr>. This is a feature only of whatever is written in the map line.

Instead you need to create escape codes like this: "\<cr>" e.g.,

return ":w!\<cr>" 

You must use " in this context for vim to interpret it specially, which won't happen with '.

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.