5.2 Context Menu Customization

Anju uses context-menu-mode (introduced in Emacs 28) to define its context menu behavior. This is accomplished through the customizable hook variable context-menu-functions.

context-menu-functions is a list of functions where each function has two arguments:

When the context menu is raised, typically via right-click (mouse-3), each function in context-menu-functions is run, populating the context menu.

The following example Elisp illustrates an implementation of a context menu function.

(defun anju-context-menu-wordcount (menu click)
  "Context menu hook function for wordcount commands.

- MENU: menu
- CLICK: event

This function is intended to be hooked into `context-menu-functions'."

  (save-excursion
    (mouse-set-point click)

    (when (derived-mode-p 'text-mode) ; context predicate
      (anju-context-menu-item-separator menu count-words-separator)
      (easy-menu-add-item menu nil ["Count Words"
                                    count-words
                                    :help "Count words"])))
  menu)

Defining how a menu item is context-sensitive can be determined in multiple places:

  1. At the time of menu item definition
  2. At a higher level.

The context is determined by a predicate which can take into account different things, among them:

In the example above, the context predicate is (derived-mode-p 'text-mode). Note that it is defined at a higher level to avoid instantiating menu items if the context does not apply.

The context predicate can be embedded in the menu item definition itself. See more about this with the :visible and :active keywords for the macro easy-menu-define.

It is up to the implementer to determine where to best apply the context predicate.

Customizing context-menu-functions

It is recommended to use the customize-variable command to configure context-menu-functions instead of using add-hook for the following reasons:

  1. A visual UI is provided showing what choices for built-in context menu functions are available.
  2. Users can insert their own custom function.
  3. Top-down ordering of functions will similarly determine the order of menu items in the context menu.