Skip to content
Brandon R. Stoner edited this page Jun 15, 2013 · 4 revisions

Your first command.

Vimpy provides a simple abstraction around Vim commands, allowing plugin developers to write complete commands in Python. These commands should be located in your package's commands module in order to be automatically imported by Vimpy.

Here is an example of how you could create a simple command:

from vimpy import Command

class HelloWorld(Command):
  def run(self):
    print('Hello, world.')

After saving this in your project package's commands.py, you will be able to open vim and run the following command in command mode:

:HelloWorld

If it all worked as expected, you should see the text 'Hello, world.' in your command line.

Handling arguments.

Now that you've created a command, you might be wondering how to pass information to it. Well, that's as simple as it seemed. If you add arguments to your run function, Vimpy will intelligently figure out how to funnel them from Vim and into your command.

For instance, let's look at this command:

class HelloWorld(Command):
  def run(self, name):
    echo 'Hello, {name}.'.format(name)

Now, you can use your command like this:

:HelloWorld Jake

This should cause your application to print "Hello, Jake." into the command line area. Not only can we use normal arguments, but keyword arguments are also supported. So, we could also do the following:

class HelloWorld(Command):
  def run(self, name='world'):
    echo 'Hello, {name}.'.format(name)

Now, we can use the comand with or without a name argument. For instance, we can try the following:

:HelloWorld

The output will be "Hello, world." - or we can try this method of providing a name:

:HelloWorld name=Jake

The output here would be 'Hello, Jake.'. In Python, you can use keyword arguments as normal arguments as long as the proper ordering is retained, so the same result can also come from:

:HelloWorld Jake

Optionally, you can provide quotes for any arguments. This is useful if your arguments have spaces in them. For instance, the following also produce the same output:

:HelloWorld name="Jake"
:HelloWorld 'name=Jake'
:HelloWorld 'Jake'
Clone this wiki locally