[Top][All Lists]

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

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

From: Pascal J. Bourguignon
Subject: Re: How to write the "interactive" form for a command acting on a region
Date: Tue, 13 Jan 2015 23:38:48 +0100
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/24.3 (gnu/linux)

Marcin Borkowski <> writes:

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

If you want a different behavior, then you should have different

    (defun my-FUNCTION (…)

    (defun my-COMMAND (…)
       (interactive …)
       (my-function …)

(defun my-command (start end)
   (interactive "r")
   (message "start=%s end=%s" start end))

A region is always defined, whether transient-mark-mode is on or off,
and whether the region is active or not.

Therefore interactive "r" will always give you start and end points.
You could have a command such as:

    (defun my-command (start end)
       (interactive "r")
       (if (use-region-p) ; region is active
          (my-function start end)
          (my-function (point-min) (point-max))))

Otherwise, if the behavior of your command and your function was the
same, you could write a single command, using (require 'cl) to deal with
the default values.  

But since you want to force the arguments when it's called interactively
without an active region, you will have to duplicate some code.
Separating the function and command is probablyh preferable in your

    (require 'cl)
    (defun* my-command (&optional (start (point-min)) (end (point-max)))
       (interactive "r")
       (when (and (called-interactively-p)
                  (not (use-region-p)))
          (setf start (point-min)
                end   (point-max)))

__Pascal Bourguignon__       
“The factory of the future will have only two employees, a man and a
dog. The man will be there to feed the dog. The dog will be there to
keep the man from touching the equipment.” -- Carl Bass CEO Autodesk

reply via email to

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