With the help of @Drew, I figure out a solution. I am not good at elisp. The code may not be a good design but at least is working. I use this code to add 4 white space so I can copy a highlighted code and paste to web like stackoverflow and remove 4 white space afterward easily.

(defun shift-region (distance)
  (let ((beg (save-excursion (goto-char (region-beginning))(line-beginning-position)))
        (end (save-excursion (goto-char (region-end))(line-end-position))))
    (goto-char beg)
    (set-mark end)
    (indent-rigidly beg end distance)
    (setq deactivate-mark nil)))

(defun shift-right ()
  (shift-region 4))

(defun shift-left ()
  (shift-region -4))

(global-set-key (kbd "C-<tab>") 'shift-right)
(global-set-key (kbd "<backtab>") 'shift-left)


I have this code

(defun shift-region (distance)
  (let ((mark (mark)))
      (indent-rigidly (region-beginning) (region-end) distance)
      (push-mark mark t t)
      (setq deactivate-mark nil))))

I want to expand the region-beginning to the beginning of that line while the region-end to the end of that line.

Visual representation (I use [ ] to represent the region mark)

abcde [ fghi
abc ] defg

will become

[ abcdefghi
abcdefg ]
  • Expand region is a fine extension in the same spirit as your request. However, there is no explicit mention there for expanding to lines. Worth trying though.
    – Juancho
    Dec 20, 2015 at 15:10

1 Answer 1


Instead of the position (region-beginning) use the position of the beginning of the same line:

(save-excursion (goto-char (region-beginning)) (line-beginning-position))

For example:

(defun shift-region (distance)
  (let ((mark  (mark))
        (beg   (save-excursion (goto-char (region-beginning))
        (end   (region-end)))
    (indent-rigidly beg end distance)
    (push-mark mark t t)
    (setq deactivate-mark  nil)))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.