[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: Drew Adams
Subject: RE: How to write the "interactive" form for a command acting on a region
Date: Tue, 13 Jan 2015 19:49:27 -0800 (PST)

> >>     (defun my-command (start end)
> >>        (interactive "r")
> >>        (if (use-region-p)
> >>            (my-function start end)
> >>          (my-function (point-min) (point-max))))
> In any case, if the code of my-function was put inside my-command,
> instead of being factored out, it would become much harder to use
> my-command from other functions or commands (perhaps those other
> commands or functions really want to work on the whole buffer even
> when there's an active region).

It is more likely (typical) that the automatic choice (predefined
decision) to use (a) the region when it is active and nonempty,
versus (b) the current buffer limits otherwise (i.e., respecting
narrowing restrictions), is a behavior difference _only_ for
interactive use.

And in that (typical) case, the standard, simple approach is
to limit that behavior decision to the `interactive' spec.
Others have already shown the simple code used to do that.

In that way, the body of the command _is_ what you proposed
to "factor" out as a separate `my-function' for non-interactive
use.  Instead of having a command and a function, the typical
approach is to just put all of the "command" stuff in the
`interactive' spec and then use the one function, interactively
or not.

Your proposed dilemma ("it would become much harder...") then
evaporates.  Any non-interactive use of the command simply
specifies the limits to use, whether they correspond to the
region (active or not), the buffer limits, or anything else.

In sum, the typical approach in this common scenario is to
define a function that is useful both as a command and more
generally (from Lisp).

You could even say that this is a main raison d'etre for
the `interactive' spec: put all of the logic that pertains
only to interactive use in that one place, when possible.
That's the factoring that is usually done.

> The requirements of a functional API are not the same as
> of a user interface command set.

Yes, not necessarily the same, and not in general - true.

But sometimes (often) the interactive use of a function is
a simple specialization of its more general use.  When that
is the case it can make sense to factor out that difference
into an `interactive' spec.


In fact, there are probably more Emacs functions that it
wouldn't hurt to define as commands, IMHO.  I've been
surprised more than once to find that a function I intended
only for Lisp is useful bound to a key in some contexts.

reply via email to

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