[Top][All Lists]

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

Re: (interactive) and &optional

From: Emanuel Berg
Subject: Re: (interactive) and &optional
Date: Thu, 23 Mar 2023 21:01:51 +0100
User-agent: Gnus/5.13 (Gnus v5.13)

Rainer Woitok wrote:

> In an attempt to write a function with and optional argument
> which is both, callable from Lisp and via "M-x", I ran into
> some unexpected (by me) problems. Consider the following
> function:
>    (defun fun (&optional arg)
>    (interactive "Sarg: ")
>    (message "%s:%s.\n" 'val (symbol-name arg)))

See this file. The lines like this

(or beg (setq beg (point-min)))

are what does it.

If you do it like this, it always work both interactively and
from Lisp and you are able to set a default value that is the
same for both methods.

;;; -*- lexical-binding: t -*-
;; this file:
;; DWIM code helpers and examples.
;; Advantages to this style:
;; - the same default interactively and from Lisp
;; - the default is the whole buffer
;; - the region is never used from Lisp
;; - the variables are always set, to the default if not explicitely
;; - one can still have preceding, non-optional arguments

(defun use-region (&optional both)
  (if (use-region-p)
      (list (region-beginning) (region-end))
    (when both
      (list nil nil) )))

(defun test-dwim (&optional beg end)
  (interactive (use-region))
  (or beg (setq beg (point-min)))
  (or end (setq end (point-max)))
  (message "%d %d" beg end) )

(defun test-dwim-2 (re &optional beg end)
  (interactive `(,(read-regexp "regexp: ") ,@(use-region)))
  (or beg (setq beg (point-min)))
  (or end (setq end (point-max)))
  (message "%s %d %d" re beg end) )

(provide 'dwim)

underground experts united

reply via email to

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