How to define a vim function on a single line

vim

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

Best Answer

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.

Related Question