1

Is there a way to automatically insert parenthesis (or other s-expressions) around a highlighted region by only typing (, {, ", etc.? I don't want to have to use a key bind (M-() for that. It's a common feature in modern text editors like VSCode, so I'm wondering if there is a way to do it in emacs.

Edit: I have delete-selection-mode on, but in general I want this behavior to trump all others. So if a region is selected, no matter if delete-selection-mode is on or off, typing the start symbol of an s-expression would wrap the region in the s-expression. I also just realized that electric-pair-mode includes this feature. But I don't want the other features of electric-pair-mode, namely that it inserts a pair whenever you type the starting pair, no matter if a region is selected.

3
  • Please specify the behavior you're looking for - it's not clear. If you just mean typing a ( etc. whenever the region is selected, that seems very limiting. With delete-selection-mode ON it prevents replacing the selected text with that char. With it off, it prevents inserting the char at point. Please give a recipe, saying what you do at each step, what you see now when doing that, and what you want to see instead. Commented Mar 17, 2024 at 16:06
  • @Drew sorry I wasn't clear. I've updated the question, hopefully that's clear enough Commented Mar 17, 2024 at 16:13
  • Thx............ Commented Mar 18, 2024 at 2:37

1 Answer 1

1

Electric pair mode is the closest built-in feature to what you're looking for. It inserts both an opening and a closing parentheses when you type one, with customizations to sometimes only insert what you type if there is already a matching unbalanced parenthesis. If the region is active, the parentheses are inserted around the region, even if Delete selection mode is active.

It doesn't appear to have an option to only trigger when the region is active. You can disable the insertion of the matching parenthesis when the region is inactive with a few lines of code, advising the function that is called (via post-self-insert-hook) after typing a character when Electric pair mode is active.

(electric-pair-mode) (defun only-if-use-region (func &rest args) (if (use-region-p) (apply func args))) (advice-add 'electric-pair-post-self-insert-function :around 'only-if-use-region) 
0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.