Taming closing delimiters in my s-expressions


As I explained when I wrote about my daily Clojure workflow, I rely heavily on Smartparens for my editing. With Lisp-like languages in particular, I enable smartparens-strict-mode to keep my s-expressions balanced even when I happen to use delete-char or kill-word dangerously near a closing parenthesis.

I have sp-kill-sexp bound to C-M-k, however out of habit I often use C-k to kill a line, which in my configuration is set up as Artur Malabarba explained in his Kill Entire Line with Prefix Argument. Doing that in the middle of an s-expression creates unnerving chaos.

Smartparens comes with a handy binding to temporarily disable the enforced balancing and let me insert a closing delimiter. Just pressing C-q followed by the desired matching parenthesis brings the order back.

Unfortunately, it’s not always that easy. Take this snippet which appears at the end of a ClojureScript function:

(when-not (empty? @data)
            [:div
             {:style {:padding "1em" :text-align "center"}}
             [graph]])]]))))

Carelessly hitting C-k near [graph] disrupts an otherwise elegant s-expression. I could undo, of course, but what if after C-k I do other kill-and-yank edits?

This is exactly why I have come to love syntactic-close.

(use-package syntactic-close            ; Automatically insert closing delimiter
  :ensure t
  :bind ("C-c x c" . syntactic-close))

As soon as I discover an unbalanced s-expression, I can use C-c x c as many times as needed to add back the right closing delimiters.