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))))