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'.

When cursor is inside a string or comment, just delete backward 1 char.

URL `http://ergoemacs.org/emacs/emacs_delete_backward_char_or_bracket_text.html'
Version 2017-02-13"
  (interactive)
  (let ((-temp-syn-table (make-syntax-table)))

    (modify-syntax-entry ?\« "(»" -temp-syn-table)
    (modify-syntax-entry ?\» ")«" -temp-syn-table)
    (modify-syntax-entry ?\‹ "(›" -temp-syn-table)
    (modify-syntax-entry ?\› ")‹" -temp-syn-table)
    (modify-syntax-entry ?\“ "(”" -temp-syn-table)
    (modify-syntax-entry ?\” ")“" -temp-syn-table)

    (with-syntax-table -temp-syn-table
      (if (and delete-selection-mode (region-active-p))
          (delete-region (region-beginning) (region-end))
        (cond
         ((looking-back "\\s)" 1)
          (progn
            (backward-sexp)
            (mark-sexp)
            (kill-region (region-beginning) (region-end))))
         ((looking-back "\\s(" 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