4

Solution:

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 ()
  (interactive)
  (shift-region 4))

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

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

Question:

I have this code

(defun shift-region (distance)
  (let ((mark (mark)))
    (save-excursion
      (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
abcde [ fghi
abcdefghi
abc ] defg
abcde

will become

abcde
[ abcdefghi
abcdefghi
abcdefg ]
abcde
tom
  • 365
  • 2
  • 7

1 Answers1

2

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))
                               (line-beginning-position)))
        (end   (region-end)))
    (indent-rigidly beg end distance)
    (push-mark mark t t)
    (setq deactivate-mark  nil)))
rofrol
  • 196
  • 2
  • 8
Drew
  • 77,472
  • 10
  • 114
  • 243