0

I have a shortcut -- s to save a file. If it's not a vim file it will just run a :w, and if it hasn't been saved to a file yet it will ask the user for a filepath or name. However, if it's a vim file, I want it to do :w | so %. However, I'm having trouble sourcing a file from within a function. Here is what I have so far:

" Cmd-s to save, if a new file, prompt for the name
function SaveFile()
   " If the filename doesn't exist, prompt the use to enter one
    if len(expand('%')) == 0
        execute 'w ' . input('Save File As: ')
    else
        w
    endif
endfunction
noremap <expr> <leader>S    &filetype ==? 'vim' ? ":silent call SaveFile() | source $MYVIMRC<CR>" : ':silent call SaveFile()<CR>'

What is wrong with the above function, or is there a rule against re-sourcing a file from within a function/command or something? If so, what would be the best way to accomplish the above?

1
  • 1
    For a (maybe) better solution see your own question and its answer by filbranden.
    – Ralf
    Commented Jun 28, 2020 at 8:58

2 Answers 2

1

Why don't you do the test in your function?

My experience is that the less code there is in the declaration of mappings, autocommands, commands, abbreviations... the less troubles we have.

function s:SaveFile() abort
   " If the filename doesn't exist, prompt the use to enter one
    if empty(expand('%'))
        let fn = input('Save File As: ')
        if empty(fn)
            echomsg "aborting..."
            return
        endif
        execute 'w ' . fn
    else
        w
    endif
    if &ft == 'vim'
        " TODO: handle possible anti-reinclusion guards
        exe 'source ' . fn
    endif
endfunction

nnoremap <silent> <leader>S :<c-u>call <sid>SaveFile()<cr>
" the call shall not be silenced in case of errors, but the mapping yes
" and <c-u> is required to possible remove counts

BTW, $MYVIMRC is the .vimrc, not the file saved. I would have understood why you'd want to source the file that has just been saved, but why sourcing an unrelated file?

You may also have to struggle with anti-(re)inclusion guards that aren't handled by the current function and neutralize them to reload scripts

0

If you are running this within an <expr> you have to escape the | in the command. It should be:

":silent call SaveFile() \| source $MYVIMRC<CR>"

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.