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.
If it's bracket, push the deleted text to `kill-ring'

URL `http://ergoemacs.org/emacs/emacs_delete_backward_char_or_bracket_text.html'
Version 2017-01-16"
  (interactive)
  (let (
        (-right-brackets (regexp-opt '(")" "]" "}" "〕" "】" "〗" "〉" "》" "」" "』" "›" "»")))
        (-left-brackets (regexp-opt '("(" "{" "[" "〔" "【" "〖" "〈" "《" "「" "『" "‹" "«" ))))
    (if (and delete-selection-mode (region-active-p))
        (delete-region (region-beginning) (region-end))
      (cond
       ((looking-back -right-brackets 1)
        (progn
          (backward-sexp)
          (mark-sexp)
          (kill-region (region-beginning) (region-end))))
       ((looking-back -left-brackets 1)
        (progn
          (backward-char )
          (mark-sexp)
          (kill-region (region-beginning) (region-end))))
       ((looking-back "\\s\"" 1)
        (if (nth 3 (syntax-ppss))
            (progn
              (backward-char )
              (mark-sexp)
              (kill-region (region-beginning) (region-end)))
          (progn
            (backward-sexp)
            (mark-sexp)
            (kill-region (region-beginning) (region-end)))))
       (t (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