[Top][All Lists]

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

Re: paren-close-dwim: elisp function of a newbie; feedback welcome

From: Davis Herring
Subject: Re: paren-close-dwim: elisp function of a newbie; feedback welcome
Date: Wed, 25 Sep 2013 11:32:21 -0600
User-agent: Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv: Gecko/20110717 Lanikai/3.1.11

> (defun paren-close-dwim ()
>   "Insert the next missing closing paranthesis based on the syntax table.

Typo: "parenthesis".

>    Otherwise insert a normal closing ?\)"

Don't indent docstring lines.

>   (interactive)

Use "*" to get an immediate error if read-only.  You might also consider
allowing a prefix count like `self-insert-command'.

>   (save-excursion
>     (setq fallback-char ?\))

Use `let' to introduce local variables.  However, here you'll be able to
do without any...

>     ;; go backward up a level in the parenthesis hierarchy (which
>     ;; jumps to the next not yet closed (seen from point) open
>     ;; parenthesis). Catch unbalanced paranthesis error etc.
>     (setq closing-paren
>           (condition-case nil
>               (progn (backward-up-list)
>                      ;; get character at point
>                      (setq open-paren (point))
>                      ;; get corresponding closing character from the
>                      ;; syntax table. (syntax-after open-paren)
>                      ;; delivers a cons cell with (OPEN . CLOSE), so
>                      ;; we need the cdr to match open-paren.
>                      (setq syntax-cons (syntax-after open-paren))

Since you only assign and use `open-paren' once, just insert the
expression for it in place of the variable.

>                      (if (cdr syntax-cons)
>                          (cdr syntax-cons)
>                        ;; if cdr is nil use the fallback-char
>                        fallback-char))

(or (cdr syntax-cons) fallback-char)

This then allows you to drop the `syntax-cons' variable.

>             (error fallback-char))))

Use `ignore-errors' and promote the `or`:

(or (ignore-errors (backward-up-list) (cdr (syntax-after (point))))

Then you can get rid of `fallback-char' too.

>     ;; insert dwim parenthesis
>     (insert closing-paren))

Similarly, you can do without the `closing-paren' variable.

Indentation error: the `insert' is not inside the `save-excursion'.

The final version I get (narrowly wrapped for email):

(defun paren-close-dwim ()
  "Insert closing parenthesis from syntax table.
Use a normal parenthesis if not inside any."
  (interactive "*")
  (insert (or (ignore-errors
                (save-excursion (backward-up-list)
                                (cdr (syntax-after (point)))))


This product is sold by volume, not by mass.  If it appears too dense or
too sparse, it is because mass-energy conversion has occurred during

reply via email to

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