5

So I want to be able to type something like:

:hello

in vim normal mode and then have it echo out 'hello sir'.

I made the below vimscript into a plugin, and I get the error:

Not an editor command

What am I doing wrong?

vimscript

if exists("g:hello_world") || &cp || v:version < 700 
  finish
endif
let g:hello_world=1 " your version number
let s:keepcpo = &cpo
set cpo&vim

fun! s:hellosir()
  echo 'hello sir'
endfun

command hello call hellosir()
1

3 Answers 3

11

steffen's answer is correct, but here is an example with an argument:

" a highlight color must be set up for the function to work
highlight blue ctermbg=blue guibg=blue

function! Highlight(text)
    :execute "match blue /" . a:text . "/"
endfunction

:command! -nargs=1 Highlight :call Highlight(<q-args>)

To run it and highlight all occurrences of a regex:

:Highlight foobar

Note that I try not to abbreviate commands/functions in .vimrc. Save abbreviations for when you're typing on the command line.

Sign up to request clarification or add additional context in comments.

Comments

9

Define your function (note the uppercase letter for user-defined functions):

:fun! Hellosir()
:    echo 'hello sir'
:endfun

Now call it:

:call Hellosir()

hello sir

It is also possible to define your own ex command:

:command Hello :call Hellosir()
:Hello

hello sir

EDIT

You can combine both: Make the function script-local and access it with your (global) ex command:

fun! s:hellosir()
  echo 'hello sir'
endfun
command Hello call s:hellosir()

1 Comment

Using a script local function is perfectly fine (actually preferred in this case). Using the command Hello call s:hellosir(). Now the command does need to be capitalized.
4

What is wrong relates with this line:

command hello call hellosir()

First, from :h user-cmd-ambiguous

All user defined commands must start with an uppercase letter, to avoid confusion with builtin commands. Exceptions are these builtin commands:

  • :Next
  • :X

They cannot be used for a user defined command. [...]

Second, that you have to call your function with the s: prefix in that command.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.