Vim Recipes GUI (GVim) Creating Menus and Toolbar Buttons

Creating Menus and Toolbar Buttons

Problem

You want to add your own commands to Gvim's menus, or toolbar, for quick access.

For example, you've written a function that automatically writes bestselling novels for you, but you're not willing to use it if you have to type its name every time; you want to invoke it by selecting a menu option.

Solution

Use :set amenu menu command to map a menu item to a command. This is the GUI equivalent of :map.

For example, :amenu Help.Op&ions :help options<cr> adds a new item called Options to the Help menu, which invokes :help options. The ampersand (&) signifies that the character it prefixes can be used as a keyboard shortcut, so in this case <Alt>+h+t selects this command.

Discussion

You're not restricted to adding items to existing menus; you can create a new top-level menu simply by specifying a name not currently in use. For example:

:amenu <silent>&Vim.vim\.org :!xdg-open http://www.vim.org/<cr>

will create a new top-level menu called Vim with the shortcut key V. It will contain one entry named vim.org (we escape the . because otherwise it would create a vim entry which in turn contain an org item). When invoked it will open the Vim website on systems adhering to the Free Desktop Specification. The <silent> prefix prevents the command from being echoed on the command-line.

If you want to add a dashed separator line between menu items use a menu item named -SEP- and an empty command, e.g. :amenu Help.-SEP- :.

To control where a top-level menu appears relative to its neighbours you need to prefix amenu with a numeric priority: the lower the number the further right the menu's position. For example, :5amenu First.first :echo 'first'<cr> creates a top-level menu named First that appears before all of the others.

The same approach can be used to position menu items. For example, :amenu 9999.1 Help.first :echo 'first'<cr> adds a first item to the Help menu, which appears before the other items.

You can also use :amenu to add a new toolbar icon:

:amenu icon=image-path Toolbar.item-name
command

For example:

:amenu icon=options.png ToolBar.OptionsHelp :help<cr>

If the image-path consists only of a filename, as above, Vim prepends $VIMRUNTIME/bitmaps/ to it.