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

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

Re: Functions with multiple optional arguments


From: Emanuel Berg
Subject: Re: Functions with multiple optional arguments
Date: Mon, 17 Oct 2022 03:48:00 +0200
User-agent: Gnus/5.13 (Gnus v5.13)

Heime via Users list for the GNU Emacs text editor wrote:

> Have been writing a function that has two optional
> arguments. It is turning out to be a difficult task in
> situations when one in missing an argument. Anybody has
> experience about this, as I have not seen much code with
> multiple optional arguments.

Yes, you have to have them all to the right of &optional.

Optional args default to nil so if you want to use one to the
right of another that is also optional it can be explicitly
ignored by calling the function with nil for the optional
argument (all of them) that are desired to be left unset ...

If you intend to use them in the function, and nil doesn't
make sense to use, you have to check for nil and set them
manually to what will in practice be their default value ...

See these examples

;;; -*- lexical-binding: t -*-
;;
;; this file:
;;   https://dataswamp.org/~incal/emacs-init/dwim.el
;;
;; DWIM code examples.
;;
;; Advantages:
;;
;; * the same defaults interactively and from Lisp
;; * that default is the whole buffer
;; * the default is always set unless other data is set explicitely
;; * the region is never used from Lisp
;; * it works with preceding, non-optional arguments as well
;;
;; re: `use-region', see lines 6873-6879 in simple.el for
;; `use-region-beginning' and `use-region-end'.

(defun use-region ()
  (when (use-region-p)
    (list (region-beginning) (region-end)) ))

(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 "re: ")
                 ,@(use-region) ))
  (or beg (setq beg (point-min)))
  (or end (setq end (point-max)))
  (message "%d %d %s" beg end re) )

;; test

(when nil

  (save-mark-and-excursion
    (set-mark   10)
    (goto-char 500)
    (call-interactively #'test-dwim) ) ; 10  500

  (call-interactively #'test-dwim)     ;  1 1282

  (test-dwim)                          ;  1 1282
  (test-dwim 30)                       ; 30 1282
  (test-dwim nil 90)                   ;  1   90
  (test-dwim 30  90)                   ; 30   90

  (test-dwim-2 "a" 30 90)              ; 30   90 a
)

-- 
underground experts united
https://dataswamp.org/~incal




reply via email to

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