Emacs: Delete Backward Char or Bracket Text

By Xah Lee. Date: . Last updated: .

Here's a command that deletes char backward (⌫ Backspace), but if the char is a bracket, any type ()[]{}, or ASCII quote, delete the bracket/quote and the inner text.

(defun xah-delete-backward-char-or-bracket-text ()
  "Delete backward 1 character, but if it's a \"quote\" or bracket ()[]{}【】「」 etc, delete bracket and the inner text, push the deleted text to `kill-ring'.

What char is considered bracket or quote is determined by current syntax table.

If `universal-argument' is called first, do not delete inner text.

URL `http://ergoemacs.org/emacs/emacs_delete_backward_char_or_bracket_text.html'
Version 2017-04-25 26437"
  (interactive)
  (if (and delete-selection-mode (region-active-p))
      (delete-region (region-beginning) (region-end))
    (cond
     ((looking-back "\\s)" 1)
      (progn
        (backward-sexp)
        (xah-delete-matching-brackets (not current-prefix-arg))))
     ((looking-back "\\s(" 1)
      (progn
        (backward-char )
        (xah-delete-matching-brackets (not current-prefix-arg))))
     ((looking-back "\\s\"" 1)
      (if (nth 3 (syntax-ppss))
          (progn
            (backward-char )
            (xah-delete-matching-brackets (not current-prefix-arg)))
        (progn
          (backward-sexp)
          (xah-delete-matching-brackets (not current-prefix-arg)))))
     (t (delete-char -1)))))

(defun xah-delete-matching-brackets ( &optional *delete-inner-text-p)
  "Delete the matching brackets/quotes to the right of `point'.
If *delete-inner-text-p is true, also delete the inner text.
This command assumes that the char to the right of point is a bracket/quote, and have a matching one after.
2017-03-13"
  (interactive)
  (if *delete-inner-text-p
      (progn
        (mark-sexp)
        (kill-region (region-beginning) (region-end)))
    (let ((-pt (point)))
      (forward-sexp)
      (delete-char -1)
      (goto-char -pt)
      (delete-char 1))))

You can set the ⌫ Backspace key for it, like this:

(global-set-key (kbd "DEL") 'xah-delete-backward-char-or-bracket-text)

〔►see Emacs: How to Define Keys

Working with Brackets Topic

  1. Emacs: Select Line, between Quotes, Extend Selection
  2. Emacs: Insert Brackets by Pair
  3. Emacs: Move Cursor to Bracket/Quote
  4. Emacs: Delete Backward Char or Bracket Text
Like it? Buy Xah Emacs Tutorial. Thanks.

or, buy something from Best Keyboard for Emacs