Emacs Shift-Tab to left shift the block

Viewed 20957

How can I get Emacs to ShiftTab to move the selected text to the left by 4 spaces?

4 Answers

This removes 4 spaces from the front of the current line (provided the spaces exist).

(global-set-key (kbd "<S-tab>") 'un-indent-by-removing-4-spaces)
(defun un-indent-by-removing-4-spaces ()
  "remove 4 spaces from beginning of of line"
  (interactive)
  (save-excursion
    (save-match-data
      (beginning-of-line)
      ;; get rid of tabs at beginning of line
      (when (looking-at "^\\s-+")
        (untabify (match-beginning 0) (match-end 0)))
      (when (looking-at "^    ")
        (replace-match "")))))

If your variable tab-width happens to be 4 (and that's what you want to "undo"), then you can replace the (looking-at "^ ") with something more general like (concat "^" (make-string tab-width ?\ )).

Also, the code will convert the tabs at the front of the line to spaces using untabify.

Related