How do I define a vim function on a single line?

Since | is used to separate commands, I thought I could just do this:

:function! SomeFunc() | return 0 | endfunction

It works fine when I type it on separate lines (entering the first line causes it to prompt for the remaining lines):

:function! SomeFunc() return 0
endfunction

I now see this caveat at :help :bar:

These commands see the '|' as their argument, and can therefore not be followed by another Vim command:

:function

Is there any way around that?

I see where it says...

You can also use to separate commands in the same way as with '|'. To insert a use CTRL-V CTRL-J. "^@" will be shown.

But this doesn't work either:

:function! SomeFunc() <NL> return 0 <NL> endfunction

It gives this error:

E488: Trailing characters

This works if I manually type in the CTRL-V CTRL-J sequence:

:function! SomeFunc() ^@ return 0 ^@ endfunction

But that still isn't a acceptable solution because I want to be able to simply copy and paste the function! command and press Enter...

5

2 Answers

One option would be to use exe:

exe ":function! SomeFunc() \n return 0 \n endfunction"

The \n characters are interpreted as newlines by the double-quoted strings. This does mean you should be careful to escape any special sequences.

That said,

I want to be able to simply copy and paste the function! command and press Enter...

As romainl mentioned, your ultimate goal is not clear. If this is something you do often for some reason, maybe there's a better way to get what you want. It's a good idea to describe your problem in terms of why you need this functionality.

2

I was looking into this because I wanted to test out functions I copied online in a vim session before adding to my .vimrc. I tried source but that requires a file name.

One of the comments in the answer section says to use :@". That runs whatever is in the unnamed register.

If you want to run something you copied from online, you can do :@+. But it won't work if you don't have vim installed with system clipboard integration.

Another method that works without clipboard integration is :normal :<PASTE YOUR COMMAND HERE WITH YOUR SYSTEM HOTKEY>. That runs everything in normal mode as if you were typing it yourself, each newline would continue onto the next line fo the function.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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

You Might Also Like