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?

Drew
  • 75,699
  • 9
  • 109
  • 225
Tianxiang Xiong
  • 3,848
  • 16
  • 27
  • 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 Feb 24 '17 at 16:40
  • 1
    3. Replace `(setq exists-next-sexp nil)` with `(setq arg nil)`. – npostavs Feb 24 '17 at 18:04

1 Answers1

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)))
glucas
  • 20,175
  • 1
  • 51
  • 83