0

I have the following custom implementation of insert-pair:

(defun *-insert-pair (&optional arg open close)
  "Wrap next ARG sexps in parentheses.

If there is no next sexp, insert a new pair of parentheses."
  (interactive "p")
  (let ((arg (or arg 1))
        (exists-next-sexp t))
    (save-excursion
      (condition-case nil
          (forward-sexp)
        (scan-error (setq exists-next-sexp nil))))
    (if exists-next-sexp
        (insert-pair arg open close)
      (insert-pair nil open close))))

However, I don't like the use of the boolean var exist-next-sexp. Is there a more idiomatic way to write this so I can get rid of it?

2
  • 1
    1. The last bit could be written as just (insert-pair (and exists-next-sexp arg) open close), which makes clear that insert-pair is used in any case. 2. Don't bother with a second ARG variable (confusing to use the same name, and nothing gained). Just (setq arg (or arg 1).
    – Drew
    Commented Feb 24, 2017 at 16:40
  • 1
    3. Replace (setq exists-next-sexp nil) with (setq arg nil).
    – npostavs
    Commented Feb 24, 2017 at 18:04

1 Answer 1

1

The use of let vs setq for optional argument defaults is subjective, see https://emacs.stackexchange.com/a/14203/780 for some discussion in the comments.

If you don't mind using setq here, you can combine the comments from @Drew and @npostavs for something fairly concise:

(defun *-insert-pair (&optional arg open close)
  (interactive "p")
  (setq arg (or arg 1))
  (save-excursion
    (condition-case nil
        (forward-sexp)
      (scan-error (setq arg nil))))
  (insert-pair arg open close))

You can also use let and combine things in to a single argument like this:

(defun *-insert-pair (&optional arg open close)
  (interactive "p")
  (let ((arg (save-excursion
               (condition-case nil
                   (progn
                     (forward-sexp)
                     (or arg 1))
                 (scan-error nil)))))

    (insert-pair arg open close)))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.