help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: DWIM region (was: Re: count regexp hits)


From: Kaushal Modi
Subject: Re: DWIM region (was: Re: count regexp hits)
Date: Thu, 04 Jan 2018 22:48:42 +0000

On Thu, Jan 4, 2018 at 4:35 PM Emanuel Berg <moasen@zoho.com> wrote:

> BTW this method on acting on the region (if
> any) I have found very useful and it has
> recurred many times in my code:
>
> Is it the canonical way of doing it as well?
>

I don't think there's a canonical way.. here's how I dealt with the same
problem:


;;; Operate on Region or Whole Buffer
(defvar modi/region-or-whole-fns '(indent-region
                                   eval-region)
  "List of functions to act on the whole buffer if no region is selected.")

(defun modi/advice-region-or-whole (orig-fun &rest args)
  "Advice function that applies ORIG-FUN to the whole buffer if no region is
selected.
http://thread.gmane.org/gmane.emacs.help/109025/focus=109102 "
  ;; Required to override the "r" argument of `interactive' in functions
like
  ;; `indent-region' so that they can be called without an active region.
  (interactive (if (use-region-p)
                   (list (region-beginning) (region-end))
                 (list (point-min) (point-max))))
  (prog1 ; Return value of the advising fn needs to be the same as ORIG-FUN
      (apply orig-fun args)
    (when (and (called-interactively-p 'interactive)
               (not (use-region-p)))
      (message "Executed %s on the whole buffer."
               (propertize (symbol-name this-command)
                           'face 'font-lock-function-name-face)))))

(dolist (fn modi/region-or-whole-fns)
  (advice-add fn :around #'modi/advice-region-or-whole))


Now with that setup, I simply need to add functions, where I want the same
whole buffer or region behavior, to the modi/region-or-whole-fns variable.

Ref:
https://github.com/kaushalmodi/.emacs.d/blob/c7e3d5bae08105a7a1853566b44ea65c73c80e69/setup-files/setup-editing.el#L1001-L1028


-- 

Kaushal Modi


reply via email to

[Prev in Thread] Current Thread [Next in Thread]