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

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

How to write the "interactive" form for a command acting on a region


From: Marcin Borkowski
Subject: How to write the "interactive" form for a command acting on a region
Date: Tue, 13 Jan 2015 23:05:01 +0100

Hi all,

so I want to have a function which should do something on the region.
If no region is active, I want it to act on the whole buffer.  If called
from Lisp code, I want to be able to supply "begin" and/or "end"
parameters, which (if nil) should default to (point-min) and
(point-max).  Finally, I want my command to behave differently depending
on whether it was called interactively or programmatically.  I did some
RTFMing, and after a few iterations I came up with this:

(defun my-function (&optional begin end print-message)
  "Do something clever on region or buffer."
  (interactive
   (if (use-region-p)
       (list (region-beginning) (region-end) t)
     (list (point-min) (point-max) t)))
  (save-excursion
    (save-restriction
      (narrow-to-region (or begin (point-min)) (or end (point-max)))
      (let ((result))
        (ding) ; do something clever here
        (if print-message
            (message "Result: %s." result)
          result)))))

I'm wondering whether it can be made better?

Regards,

-- 
Marcin Borkowski               This email was proudly sent
http://mbork.pl                from my Emacs.



reply via email to

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