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:
menu : reference to the context menu
click : a mouse event
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:
The context is determined by a predicate which can take into account different things, among them:
use-region-p)
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.
It is recommended to use the customize-variable command to configure context-menu-functions instead of using add-hook for the following reasons: