0

I am trying to do a shortcut to resave a file with cmd-S. And if the file is of type vim, it will also re-source %. Here is what I have:

function SaveFile()
    w
    if &filetype ==? 'vim'
        so %
    endif
endfunction
nnoremap  <leader>S         :silent call SaveFile()<CR>

However, I get the following error:

E127: Cannot redefine function SaveFile: It is in use

Why is this so? What do I need to do to fix this issue? Is :so % not allowed in a function?

1
  • Check what error means with :h E127 Jul 15 '20 at 21:43
1

Your issue is that functions cannot be redefined without ! (as in function!). This is only partially true:

                                *E127* *E122*
            When a function by this name already exists and [!] is
            not used an error message is given.  There is one
            exception: When sourcing a script again, a function
            that was previously defined in that script will be
            silently replaced.
            When [!] is used, an existing function is silently
            replaced.  Unless it is currently being executed, that
            is an error.
            NOTE: Use ! wisely.  If used without care it can cause
            an existing function to be replaced unexpectedly,
            which is hard to debug.

I actually do not use ! anymore, but I believe in old versions of vim it was required to be able to re-source a script at runtime and have function/command definitions work. You might want to check on your version.


A more idiomatic way to accomplish your setup is to split the two (this is effectively what I do):

" ~/.vim/vimrc, or some other globally-sourced file
nnoremap <leader>fs :write<CR>

and

" ~/.vim/after/ftplugin/vim.vim

" two options: a dedicated map
nnoremap <buffer> <localleader>ef :source %<CR>
" or an autocommand
augroup SourceVim
  autocmd! * <buffer>
  autocmd BufWritePost <buffer> source %
augroup END

(I do something similar in clojure with fireplace's :Require)

2
  • Why not :update instead of :write?
    – Matt
    Jul 16 '20 at 5:46
  • OP used write @Matt , but also sometimes you want the effect of a write (such as something that watches your code and runs tests or some such)
    – D. Ben Knoble
    Jul 16 '20 at 11:13

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.