I don't think electric-pair-mode
will be of much help to you here. You could add (?\s . ?\s)
to electric-pair-pairs
(its alist of characters to automatically double-insert), but that would affect every space you type (there is no way to add conditions as to when it will/won't insert a pair) and will probably play havoc with skipping over whitespace. Also, w.r.t. automatically deleting a matching space, electric-pair-mode
doesn't do anything magical. It simply scans its list of characters to insert as pairs and removes the next character if it finds a match with the one you've deleted. Again, adding (?\s . ?\s)
to electric-pair-pairs
would be a poor solution.
So, I solved this by adding my own functions for the purpose...
(defun my/c-mode-insert-space (arg)
(interactive "*P")
(let ((prev (char-before))
(next (char-after)))
(self-insert-command (prefix-numeric-value arg))
(if (and prev next
(string-match-p "[[({]" (string prev))
(string-match-p "[])}]" (string next)))
(save-excursion (self-insert-command 1)))))
(defun my/c-mode-delete-space (arg &optional killp)
(interactive "*p\nP")
(let ((prev (char-before))
(next (char-after))
(pprev (char-before (- (point) 1))))
(if (and prev next pprev
(char-equal prev ?\s) (char-equal next ?\s)
(string-match "[[({]" (string pprev)))
(delete-char 1))
(backward-delete-char-untabify arg killp)))
You can bind them in c-mode (and its derivatives) like this:
(add-hook 'c-mode-common-hook
(lambda ()
(local-set-key " " 'my/c-mode-insert-space)
(local-set-key "\177" 'my/c-mode-delete-space)))