From 4af99998349705cc4ced90cdbf4f51455c51ec95 Mon Sep 17 00:00:00 2001 From: Bram Schoenmakers Date: Sun, 30 Jul 2023 21:27:19 +0200 Subject: [PATCH] Add gist to restrict commands to a certain major mode --- gists.org | 27 +++++++++++++++++++++++++ gists/restrict-command-to-major-mode.el | 22 ++++++++++++++++++++ 2 files changed, 49 insertions(+) create mode 100644 gists/restrict-command-to-major-mode.el diff --git a/gists.org b/gists.org index 81126a8..f790533 100644 --- a/gists.org +++ b/gists.org @@ -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 diff --git a/gists/restrict-command-to-major-mode.el b/gists/restrict-command-to-major-mode.el new file mode 100644 index 0000000..da69a73 --- /dev/null +++ b/gists/restrict-command-to-major-mode.el @@ -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))))