Implementing commands - adamallaf/lime GitHub Wiki

Implementing a command

The Command interface describes the basic autonomy of a Command with specific interfaces for TextCommands, WindowCommands and ApplicationCommands.

The most important method to implement here are the different Run methods (depending on the specific type of command) which will be called to actually execute whatever the command is supposed to be doing. If the default implementation provided by the DefaultCommand type is ok for your particular command, the Run method will then be the only method you'll need to write any code for if your command's type embeds DefaultCommand.

Command arguments

Any arguments that the command will take should be struct members of the command type, as for example shown by the MoveCommand type definition. The members of the type should be named in UpperCamelCase in the struct, but in its serialized text form should be in snake_case.

If no special handling is required, the backend will match the snake_cased serialized form of the argument to the UpperCamelCased name automatically without the need of writing any custom code. If you want to parse the serialized string data yourself for specific members of your command struct, you can make that member's type implement the CustomSet interface for which an example is shown by the MoveByType type (click Set to jump into the source code). If you want to completely bypass the default deserialization code for your command, you can make it implement the CustomInit interface.

Registering your command with the backend

Commands need to be registered with the backend to show up via the CommandHandler's Register method, which takes the name of the command, as well as an instance of your command type.

Typically this is done in the go source file's niladic init function like so:

func init() {
  e := backend.GetEditor()
  // Note for those of you coming from C/C++, it is perfectly fine
  // in Go to return the address of a local variable
  if err := e.CommandHandler().Register("my_command", &MyCommand{}); err != nil {
    log4go.Error("Failed to register command my_command: %s", err)
  }
}

Testing your command

Go comes with unit testing functionality built in and every command should implement a test (or more) to ensure that it is functioning as expected and to prevent any regressions.

See the *_test.go files for a couple of examples of how commands can be tested.

Other references