Add gist to restrict commands to a certain major mode

This commit is contained in:
Bram Schoenmakers 2023-07-30 21:27:19 +02:00
parent d2b0257c6b
commit 4af9999834
2 changed files with 49 additions and 0 deletions

View File

@ -674,6 +674,33 @@ Based on an answer at the [[https://emacs.stackexchange.com/a/77480/34645][Emacs
- else: Non-nil means case sensitive search.
#+end_src
* Restrict symbol / command completion to a major mode :emacs:
#+begin_src elisp :tangle gists/restrict-command-to-major-mode.el
(defun my/buffer-has-major-mode-p (major-mode _sym buffer)
"Return t if BUFFER has MAJOR-MODE set."
(eq (buffer-local-value 'major-mode buffer) major-mode))
(defun my/restrict-symbol (mode symbols)
"Restrict SYMBOLS to a certain major MODE.
Ideally, packages should restrict their own `interactive'
commands to their own mode (see the `interactive' help). However,
this is not common practice so this little facility makes it
easier to restrict symbols to a certain mode. Meaning, the
command will not appear in the M-x menu as a possible completion.
This may be handy if a command may be destructive for a major
mode it wasn't meant for.
Example:
(my/restrict-symbol 'ledger-mode '(ledger-occur))"
(dolist (sym symbols)
(put sym 'completion-predicate
(apply-partially #'my/buffer-has-major-mode-p mode))))
#+end_src
* Meta
** License

View File

@ -0,0 +1,22 @@
(defun my/buffer-has-major-mode-p (major-mode _sym buffer)
"Return t if BUFFER has MAJOR-MODE set."
(eq (buffer-local-value 'major-mode buffer) major-mode))
(defun my/restrict-symbol (mode symbols)
"Restrict SYMBOLS to a certain major MODE.
Ideally, packages should restrict their own `interactive'
commands to their own mode (see the `interactive' help). However,
this is not common practice so this little facility makes it
easier to restrict symbols to a certain mode. Meaning, the
command will not appear in the M-x menu as a possible completion.
This may be handy if a command may be destructive for a major
mode it wasn't meant for.
Example:
(my/restrict-symbol 'ledger-mode '(ledger-occur))"
(dolist (sym symbols)
(put sym 'completion-predicate
(apply-partially #'my/buffer-has-major-mode-p mode))))