bram85's Blog

bram85's Avatar Image
Tooting mostly about #emacs.
← All posts

The small #elisp linked below demonstrates how to limit the completion of certain commands to a specific major mode in #emacs E.g. to make ledger-occur only available when you’re in a buffer with ledger-mode.

Packages which define (interactive) commands may handle this themselves. See the MODES argument in the (interactive) help text. However, it’s not a common practice, so you can achieve this from your own configuration with a few lines of elisp.

Why do this? I maintain my ledger in an #orgmode file with ledger source blocks in between. ledger-occur does not behave well when used in a different mode, and it resulted in data loss when executed in an Org buffer. To prevent accidentally selecting ledger-occur in other contexts, I put a restriction in place:

(my/restrict-symbol ‘ledger-mode ‘(ledger-copy-transaction-at-point ledger-occur))

Now, I can’t accidentally invoke ledger-occur or ledger-copy-transaction-at-point outside ledger-mode.

The restriction only affects the completion options in the command list invoked by M-x. Therefore, if you bind a restricted command to a key, it would still be invokable.

https://apps.bram85.nl/git/bram/gists/src/commit/4af99998349705cc4ced90cdbf4f51455c51ec95/gists/restrict-command-to-major-mode.el

To like or reply, open original post on Emacs.ch