2

From my two previous questions, I learned about using :source %, @", and other tricks to execute vimscript.

But as I noticed, :source % needs the file to be saved first, furthermore, @" and any other trick using registers don't always work.

Not needing to save first to execute something is very important for debugging/testing your code (as I'm sure many are already aware).

So is there truly no way to execute Vimscript (without as much restrictions as using registers has) without saving first?

10
  • 1
    There is, of course, the hack of remapping something to :w | source %. This answers your use case, but for the sake of knowledge (much more important :P), it does not answer question. I am searching for a way to use something like the source command on a buffer instead of a file, now. Cool question :) Commented Sep 16, 2020 at 20:50
  • 1
    Try this: 0x0.st/iIUL.txt ; to use it, visually select the code you want to run, then execute :@*.
    – user938271
    Commented Sep 16, 2020 at 20:51
  • 1
    Thanks! had to search first if this question was asked before...seems it wasn't (afaik). @AriSweedler Commented Sep 16, 2020 at 20:58
  • 1
    Short of looping and doing execute getline('.') (or joining the lines and exec’ing), I’m not aware of anything. And those two usually have issues with line continuations/command separators.
    – D. Ben Knoble
    Commented Sep 16, 2020 at 21:07
  • 1
    It does execute :source; it's just written in the short form so. In my experience, writing the code in a tempfile does not cause issues; they should be automatically removed as soon as you quit Vim. There are other similar techniques. If you use tmux, you can run the code in another pane, which is especially useful when you're trying to debug a crash (I'm doing it right now); you don't want your main Vim instance to crash.
    – user938271
    Commented Sep 16, 2020 at 21:10

2 Answers 2

5

vim9 has updated :source command and now you can:

  1. :%source whole buffer without saving it, or just :source
  2. :'<,'>source a visually selected lines
  3. and basically range of lines, e.g. :3,10source
1
  • It also works with Neovim 0.8.2 Commented Feb 8, 2023 at 12:20
1

Here ya go, sorry it's late:

function! RunVimscript()
    new
    setlocal buftype=nofile bufhidden=wipe noswapfile
    let l:input = getbufline("#", 0, "$")
    call append(0, split(execute(l:input), "\n"))
endfunction

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.