cua-rect.el 51.6 KB
Newer Older
1 2
;;; cua-rect.el --- CUA unified rectangle support

3
;; Copyright (C) 1997-2013 Free Software Foundation, Inc.
4 5 6

;; Author: Kim F. Storm <storm@cua.dk>
;; Keywords: keyboard emulations convenience CUA
7
;; Package: cua-base
8 9 10

;; This file is part of GNU Emacs.

11
;; GNU Emacs is free software: you can redistribute it and/or modify
12
;; it under the terms of the GNU General Public License as published by
13 14
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
15 16 17 18 19 20 21

;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
22
;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
23

24
;;; Acknowledgments
25 26

;; The rectangle handling and display code borrows from the standard
Juanma Barranquero's avatar
Juanma Barranquero committed
27
;; GNU emacs rect.el package and the rect-mark.el package by Rick
28 29
;; Sladkey <jrs@world.std.com>.

Pavel Janík's avatar
Pavel Janík committed
30 31 32 33
;;; Commentary:

;;; Code:

34
(eval-when-compile
35
  (require 'cua-base))
36 37 38 39 40 41

;;; Rectangle support

(require 'rect)

;; If non-nil, restrict current region to this rectangle.
42
;; Value is a vector [top bot left right corner ins virt select].
43 44
;; CORNER specifies currently active corner 0=t/l 1=t/r 2=b/l 3=b/r.
;; INS specifies whether to insert on left(nil) or right(t) side.
45
;; If VIRT is non-nil, virtual straight edges are enabled.
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
;; If SELECT is a regexp, only lines starting with that regexp are affected.")
(defvar cua--rectangle nil)
(make-variable-buffer-local 'cua--rectangle)

;; Most recent rectangle geometry.  Note: car is buffer.
(defvar cua--last-rectangle nil)

;; Rectangle restored by undo.
(defvar cua--restored-rectangle nil)

;; Last rectangle copied/killed; nil if last kill was not a rectangle.
(defvar cua--last-killed-rectangle nil)

;; List of overlays used to display current rectangle.
(defvar cua--rectangle-overlays nil)
(make-variable-buffer-local 'cua--rectangle-overlays)
62
(put 'cua--rectangle-overlays 'permanent-local t)
63

64 65 66 67
(defvar cua--overlay-keymap
  (let ((map (make-sparse-keymap)))
    (define-key map "\r" 'cua-rotate-rectangle)))

68 69
(defvar cua--virtual-edges-debug nil)

70 71 72
;; Undo rectangle commands.

(defvar cua--rect-undo-set-point nil)
73 74 75

(defun cua--rectangle-undo-boundary ()
  (when (listp buffer-undo-list)
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
    (let ((s (cua--rect-start-position))
	  (e (cua--rect-end-position)))
      (undo-boundary)
      (push (list 'apply 0 s e
		  'cua--rect-undo-handler
		  (copy-sequence cua--rectangle) t s e)
	  buffer-undo-list))))

(defun cua--rect-undo-handler (rect on s e)
  (if (setq on (not on))
      (setq cua--rect-undo-set-point s)
    (setq cua--restored-rectangle (copy-sequence rect))
    (setq cua--buffer-and-point-before-command nil))
  (push (list 'apply 0 s (if on e s)
	      'cua--rect-undo-handler rect on s e)
	buffer-undo-list))
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137

;;; Rectangle geometry

(defun cua--rectangle-top (&optional val)
  ;; Top of CUA rectangle (buffer position on first line).
  (if (not val)
      (aref cua--rectangle 0)
    (setq val (line-beginning-position))
    (if (<= val (aref cua--rectangle 1))
        (aset cua--rectangle 0 val)
      (aset cua--rectangle 1 val)
      (cua--rectangle-corner 2))))

(defun cua--rectangle-bot (&optional val)
  ;; Bot of CUA rectangle (buffer position on last line).
  (if (not val)
      (aref cua--rectangle 1)
    (setq val (line-end-position))
    (if (>= val (aref cua--rectangle 0))
        (aset cua--rectangle 1 val)
      (aset cua--rectangle 0 val)
      (cua--rectangle-corner 2))))

(defun cua--rectangle-left (&optional val)
  ;; Left column of CUA rectangle.
  (if (integerp val)
      (if (<= val (aref cua--rectangle 3))
          (aset cua--rectangle 2 val)
        (aset cua--rectangle 3 val)
        (cua--rectangle-corner (if (cua--rectangle-right-side) -1 1)))
    (aref cua--rectangle 2)))

(defun cua--rectangle-right (&optional val)
  ;; Right column of CUA rectangle.
  (if (integerp val)
      (if (>= val (aref cua--rectangle 2))
          (aset cua--rectangle 3 val)
        (aset cua--rectangle 2 val)
        (cua--rectangle-corner (if (cua--rectangle-right-side) -1 1)))
    (aref cua--rectangle 3)))

(defun cua--rectangle-corner (&optional advance)
  ;; Currently active corner of rectangle.
  (let ((c (aref cua--rectangle 4)))
    (if (not (integerp advance))
        c
138
      (aset cua--rectangle 4
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
            (if (= advance 0)
                (- 3 c) ; opposite corner
              (mod (+ c 4 advance) 4)))
      (aset cua--rectangle 5 0))))

(defun cua--rectangle-right-side (&optional topbot)
  ;; t if point is on right side of rectangle.
  (if (and topbot (= (cua--rectangle-left) (cua--rectangle-right)))
      (< (cua--rectangle-corner) 2)
    (= (mod (cua--rectangle-corner) 2) 1)))

(defun cua--rectangle-column ()
  (if (cua--rectangle-right-side)
      (cua--rectangle-right)
    (cua--rectangle-left)))

(defun cua--rectangle-insert-col (&optional col)
  ;; Currently active corner of rectangle.
  (if (integerp col)
      (aset cua--rectangle 5 col)
    (if (cua--rectangle-right-side t)
        (if (= (aref cua--rectangle 5) 0)
            (1+ (cua--rectangle-right))
          (aref cua--rectangle 5))
      (cua--rectangle-left))))

165 166
(defun cua--rectangle-virtual-edges (&optional set val)
  ;; Current setting of rectangle virtual-edges
167 168
  (if set
      (aset cua--rectangle 6 val))
169
  (and ;(not buffer-read-only)
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
       (aref cua--rectangle 6)))

(defun cua--rectangle-restriction (&optional val bounded negated)
  ;; Current rectangle restriction
  (if val
      (aset cua--rectangle 7
            (and (stringp val)
             (> (length val) 0)
             (list val bounded negated)))
    (aref cua--rectangle 7)))

(defun cua--rectangle-assert ()
  (message "%S (%d)" cua--rectangle (point))
  (if (< (cua--rectangle-right) (cua--rectangle-left))
      (message "rectangle right < left"))
  (if (< (cua--rectangle-bot) (cua--rectangle-top))
      (message "rectangle bot < top")))

188
(defun cua--rectangle-get-corners ()
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
  ;; Calculate the rectangular region represented by point and mark,
  ;; putting start in the upper left corner and end in the
  ;; bottom right corner.
  (let ((top (point)) (bot (mark)) r l corner)
    (save-excursion
      (goto-char top)
      (setq l (current-column))
      (goto-char bot)
      (setq r (current-column))
      (if (<= top bot)
          (setq corner (if (<= l r) 0 1))
        (setq top (prog1 bot (setq bot top)))
        (setq corner (if (<= l r) 2 3)))
      (if (<= l r)
          (if (< l r)
              (setq r (1- r)))
        (setq l (prog1 r (setq r l)))
        (goto-char top)
207
        (move-to-column l)
208 209
        (setq top (point))
        (goto-char bot)
210
        (move-to-column r)
211
        (setq bot (point))))
212
    (vector top bot l r corner 0 cua-virtual-rectangle-edges nil)))
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230

(defun cua--rectangle-set-corners ()
  ;; Set mark and point in opposite corners of current rectangle.
  (let (pp pc mp mc (c (cua--rectangle-corner)))
    (cond
     ((= c 0)  ; top/left -> bot/right
      (setq pp (cua--rectangle-top) pc (cua--rectangle-left)
            mp (cua--rectangle-bot) mc (cua--rectangle-right)))
     ((= c 1)  ; top/right -> bot/left
      (setq pp (cua--rectangle-top) pc (cua--rectangle-right)
            mp (cua--rectangle-bot) mc (cua--rectangle-left)))
     ((= c 2)  ; bot/left -> top/right
      (setq pp (cua--rectangle-bot) pc (cua--rectangle-left)
            mp (cua--rectangle-top) mc (cua--rectangle-right)))
     ((= c 3)  ; bot/right -> top/left
      (setq pp (cua--rectangle-bot) pc (cua--rectangle-right)
            mp (cua--rectangle-top) mc (cua--rectangle-left))))
    (goto-char mp)
231
    (move-to-column mc)
232 233
    (set-mark (point))
    (goto-char pp)
Juanma Barranquero's avatar
Juanma Barranquero committed
234
    ;; Move cursor inside rectangle, except if char at right edge is a tab.
235
    (if (and (if (cua--rectangle-right-side)
236 237
		 (and (= (move-to-column pc) (- pc tab-width))
		      (not (eolp)))
238 239 240
	       (> (move-to-column pc) pc))
	     (not (bolp)))
	(backward-char 1))
241
    ))
242

243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
(defun cua--rect-start-position ()
  ;; Return point of top left corner
  (save-excursion
    (goto-char (cua--rectangle-top))
    (and (> (move-to-column (cua--rectangle-left))
	    (cua--rectangle-left))
	 (not (bolp))
	 (backward-char 1))
    (point)))

(defun cua--rect-end-position ()
  ;; Return point of bottom right cornet
  (save-excursion
    (goto-char (cua--rectangle-bot))
    (and (= (move-to-column (cua--rectangle-right))
	    (- (cua--rectangle-right) tab-width))
	 (not (eolp))
	 (not (bolp))
	 (backward-char 1))
    (point)))

264 265
;;; Rectangle resizing

266
(defun cua--forward-line (n)
267
  ;; Move forward/backward one line.  Returns t if movement.
268 269 270 271 272
  (let ((pt (point)))
    (and (= (forward-line n) 0)
	 ;; Deal with end of buffer
	 (or (not (eobp))
	     (goto-char pt)))))
273 274 275 276 277 278 279 280 281 282 283

(defun cua--rectangle-resized ()
  ;; Refresh state after resizing rectangle
  (setq cua--buffer-and-point-before-command nil)
  (cua--rectangle-insert-col 0)
  (cua--rectangle-set-corners)
  (cua--keep-active))

(defun cua-resize-rectangle-right (n)
  "Resize rectangle to the right."
  (interactive "p")
284
  (let ((resized (> n 0)))
285 286 287 288
    (while (> n 0)
      (setq n (1- n))
      (cond
       ((cua--rectangle-right-side)
289 290
        (cua--rectangle-right (1+ (cua--rectangle-right)))
        (move-to-column (cua--rectangle-right)))
291
       (t
292 293
        (cua--rectangle-left (1+ (cua--rectangle-left)))
        (move-to-column (cua--rectangle-right)))))
294 295 296 297 298 299
    (if resized
        (cua--rectangle-resized))))

(defun cua-resize-rectangle-left (n)
  "Resize rectangle to the left."
  (interactive "p")
300
  (let (resized)
301 302 303 304 305 306 307
    (while (> n 0)
      (setq n (1- n))
      (if (or (= (cua--rectangle-right) 0)
              (and (not (cua--rectangle-right-side)) (= (cua--rectangle-left) 0)))
          (setq n 0)
        (cond
         ((cua--rectangle-right-side)
308 309
          (cua--rectangle-right (1- (cua--rectangle-right)))
          (move-to-column (cua--rectangle-right)))
310
         (t
311 312
          (cua--rectangle-left (1- (cua--rectangle-left)))
          (move-to-column (cua--rectangle-right))))
313 314 315 316 317 318 319
        (setq resized t)))
    (if resized
        (cua--rectangle-resized))))

(defun cua-resize-rectangle-down (n)
  "Resize rectangle downwards."
  (interactive "p")
320
  (let (resized)
321 322 323 324 325
    (while (> n 0)
      (setq n (1- n))
      (cond
       ((>= (cua--rectangle-corner) 2)
        (goto-char (cua--rectangle-bot))
326 327
        (when (cua--forward-line 1)
          (move-to-column (cua--rectangle-column))
328 329 330 331
          (cua--rectangle-bot t)
          (setq resized t)))
       (t
        (goto-char (cua--rectangle-top))
332 333
        (when (cua--forward-line 1)
          (move-to-column (cua--rectangle-column))
334 335 336 337 338 339 340 341
          (cua--rectangle-top t)
          (setq resized t)))))
    (if resized
        (cua--rectangle-resized))))

(defun cua-resize-rectangle-up (n)
  "Resize rectangle upwards."
  (interactive "p")
342
  (let (resized)
343 344 345 346 347
    (while (> n 0)
      (setq n (1- n))
      (cond
       ((>= (cua--rectangle-corner) 2)
        (goto-char (cua--rectangle-bot))
348 349
        (when (cua--forward-line -1)
          (move-to-column (cua--rectangle-column))
350 351 352 353
          (cua--rectangle-bot t)
          (setq resized t)))
       (t
        (goto-char (cua--rectangle-top))
354 355
        (when (cua--forward-line -1)
          (move-to-column (cua--rectangle-column))
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
          (cua--rectangle-top t)
          (setq resized t)))))
    (if resized
        (cua--rectangle-resized))))

(defun cua-resize-rectangle-eol ()
  "Resize rectangle to end of line."
  (interactive)
  (unless (eolp)
    (end-of-line)
    (if (> (current-column) (cua--rectangle-right))
        (cua--rectangle-right (current-column)))
    (if (not (cua--rectangle-right-side))
        (cua--rectangle-corner 1))
    (cua--rectangle-resized)))

(defun cua-resize-rectangle-bol ()
  "Resize rectangle to beginning of line."
  (interactive)
  (unless (bolp)
    (beginning-of-line)
    (cua--rectangle-left (current-column))
    (if (cua--rectangle-right-side)
        (cua--rectangle-corner -1))
    (cua--rectangle-resized)))

(defun cua-resize-rectangle-bot ()
  "Resize rectangle to bottom of buffer."
  (interactive)
  (goto-char (point-max))
386
  (move-to-column (cua--rectangle-column))
387 388 389 390 391 392 393
  (cua--rectangle-bot t)
  (cua--rectangle-resized))

(defun cua-resize-rectangle-top ()
  "Resize rectangle to top of buffer."
  (interactive)
  (goto-char (point-min))
394
  (move-to-column (cua--rectangle-column))
395 396 397 398 399 400
  (cua--rectangle-top t)
  (cua--rectangle-resized))

(defun cua-resize-rectangle-page-up ()
  "Resize rectangle upwards by one scroll page."
  (interactive)
401 402 403 404 405 406
  (scroll-down)
  (move-to-column (cua--rectangle-column))
  (if (>= (cua--rectangle-corner) 2)
      (cua--rectangle-bot t)
    (cua--rectangle-top t))
  (cua--rectangle-resized))
407 408 409 410

(defun cua-resize-rectangle-page-down ()
  "Resize rectangle downwards by one scroll page."
  (interactive)
411 412 413 414 415 416
  (scroll-up)
  (move-to-column (cua--rectangle-column))
  (if (>= (cua--rectangle-corner) 2)
      (cua--rectangle-bot t)
    (cua--rectangle-top t))
  (cua--rectangle-resized))
417 418 419 420 421 422 423 424 425

;;; Mouse support

;; This is pretty simplistic, but it does the job...

(defun cua-mouse-resize-rectangle (event)
  "Set rectangle corner at mouse click position."
  (interactive "e")
  (mouse-set-point event)
426 427
  ;; FIX ME -- need to calculate virtual column.
  (if (cua--rectangle-virtual-edges)
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
      (move-to-column (car (posn-col-row (event-end event))) t))
  (if (cua--rectangle-right-side)
      (cua--rectangle-right (current-column))
    (cua--rectangle-left (current-column)))
  (if (>= (cua--rectangle-corner) 2)
      (cua--rectangle-bot t)
    (cua--rectangle-top t))
  (cua--rectangle-resized))

(defvar cua--mouse-last-pos nil)

(defun cua-mouse-set-rectangle-mark (event)
  "Start rectangle at mouse click position."
  (interactive "e")
  (when cua--rectangle
    (cua--deactivate-rectangle)
    (cua--deactivate t))
  (setq cua--last-rectangle nil)
  (mouse-set-point event)
447
  ;; FIX ME -- need to calculate virtual column.
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
  (cua-set-rectangle-mark)
  (setq cua--buffer-and-point-before-command nil)
  (setq cua--mouse-last-pos nil))

(defun cua-mouse-save-then-kill-rectangle (event arg)
  "Expand rectangle to mouse click position and copy rectangle.
If command is repeated at same position, delete the rectangle."
  (interactive "e\nP")
  (if (and (eq this-command last-command)
           (eq (point) (car-safe cua--mouse-last-pos))
           (eq cua--last-killed-rectangle (cdr-safe cua--mouse-last-pos)))
      (progn
        (unless buffer-read-only
          (cua--delete-rectangle))
        (cua--deactivate))
    (cua-mouse-resize-rectangle event)
    (let ((cua-keep-region-after-copy t))
      (cua-copy-rectangle arg)
      (setq cua--mouse-last-pos (cons (point) cua--last-killed-rectangle)))))
467

468
(defun cua--mouse-ignore (_event)
469 470 471 472
  (interactive "e")
  (setq this-command last-command))

(defun cua--rectangle-move (dir)
473
  (let ((moved t)
474 475 476 477 478 479 480
        (top (cua--rectangle-top))
        (bot (cua--rectangle-bot))
        (l (cua--rectangle-left))
        (r (cua--rectangle-right)))
    (cond
     ((eq dir 'up)
      (goto-char top)
481
      (when (cua--forward-line -1)
482 483 484 485 486 487
        (cua--rectangle-top t)
        (goto-char bot)
        (forward-line -1)
        (cua--rectangle-bot t)))
     ((eq dir 'down)
      (goto-char bot)
488
      (when (cua--forward-line 1)
489 490
        (cua--rectangle-bot t)
        (goto-char top)
491
        (cua--forward-line 1)
492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
        (cua--rectangle-top t)))
     ((eq dir 'left)
      (when (> l 0)
        (cua--rectangle-left (1- l))
        (cua--rectangle-right (1- r))))
     ((eq dir 'right)
      (cua--rectangle-right (1+ r))
      (cua--rectangle-left (1+ l)))
     (t
      (setq moved nil)))
    (when moved
      (setq cua--buffer-and-point-before-command nil)
      (cua--rectangle-set-corners)
      (cua--keep-active))))


;;; Operations on current rectangle

510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
(defun cua--tabify-start (start end)
  ;; Return position where auto-tabify should start (or nil if not required).
  (save-excursion
    (save-restriction
      (widen)
      (and (not buffer-read-only)
	   cua-auto-tabify-rectangles
	   (if (or (not (integerp cua-auto-tabify-rectangles))
		   (= (point-min) (point-max))
		   (progn
		     (goto-char (max (point-min)
				     (- start cua-auto-tabify-rectangles)))
		     (search-forward "\t" (min (point-max)
					       (+ end cua-auto-tabify-rectangles)) t)))
	       start)))))

(defun cua--rectangle-operation (keep-clear visible undo pad tabify &optional fct post-fct)
527 528 529
  ;; Call FCT for each line of region with 4 parameters:
  ;; Region start, end, left-col, right-col
  ;; Point is at start when FCT is called
530 531
  ;; Call fct with (s,e) = whole lines if VISIBLE non-nil.
  ;; Only call fct for visible lines if VISIBLE==t.
532
  ;; Set undo boundary if UNDO is non-nil.
533 534
  ;; Rectangle is padded if PAD = t or numeric and (cua--rectangle-virtual-edges)
  ;; Perform auto-tabify after operation if TABIFY is non-nil.
535
  ;; Mark is kept if keep-clear is 'keep and cleared if keep-clear is 'clear.
536 537
  (let* ((inhibit-field-text-motion t)
	 (start (cua--rectangle-top))
538 539 540 541 542
         (end   (cua--rectangle-bot))
         (l (cua--rectangle-left))
         (r (1+ (cua--rectangle-right)))
         (m (make-marker))
         (tabpad (and (integerp pad) (= pad 2)))
543 544
         (sel (cua--rectangle-restriction))
	 (tabify-start (and tabify (cua--tabify-start start end))))
545 546 547
    (if undo
        (cua--rectangle-undo-boundary))
    (if (integerp pad)
548
        (setq pad (cua--rectangle-virtual-edges)))
549 550 551 552 553 554 555
    (save-excursion
      (save-restriction
        (widen)
        (when (> (cua--rectangle-corner) 1)
          (goto-char end)
          (and (bolp) (not (eolp)) (not (eobp))
               (setq end (1+ end))))
556
        (when (eq visible t)
557 558 559 560
          (setq start (max (window-start) start))
          (setq end   (min (window-end) end)))
        (goto-char end)
        (setq end (line-end-position))
561 562
	(if (and visible (bolp) (not (eobp)))
	    (setq end (1+ end)))
563 564 565 566 567 568 569 570 571 572 573 574
        (goto-char start)
        (setq start (line-beginning-position))
        (narrow-to-region start end)
        (goto-char (point-min))
        (while (< (point) (point-max))
          (move-to-column r pad)
          (and (not pad) (not visible) (> (current-column) r)
               (backward-char 1))
          (if (and tabpad (not pad) (looking-at "\t"))
              (forward-char 1))
          (set-marker m (point))
          (move-to-column l pad)
575
          (if (and fct (or visible (and (>= (current-column) l) (<= (current-column) r))))
576 577 578 579 580 581 582 583 584
              (let ((v t) (p (point)))
                (when sel
                  (if (car (cdr sel))
                      (setq v (looking-at (car sel)))
                    (setq v (re-search-forward (car sel) m t))
                    (goto-char p))
                  (if (car (cdr (cdr sel)))
                      (setq v (null v))))
                (if visible
585
		    (funcall fct p m l r v)
586 587 588 589 590 591 592
                  (if v
                      (funcall fct p m l r)))))
          (set-marker m nil)
          (forward-line 1))
        (if (not visible)
            (cua--rectangle-bot t))
        (if post-fct
593 594 595
            (funcall post-fct l r))
	(when tabify-start
	  (tabify tabify-start (point)))))
596 597 598 599 600 601 602 603 604 605 606 607 608
    (cond
     ((eq keep-clear 'keep)
      (cua--keep-active))
     ((eq keep-clear 'clear)
      (cua--deactivate))
     ((eq keep-clear 'corners)
      (cua--rectangle-set-corners)
      (cua--keep-active)))
    (setq cua--buffer-and-point-before-command nil)))

(put 'cua--rectangle-operation 'lisp-indent-function 4)

(defun cua--delete-rectangle ()
609 610 611
  (let ((lines 0))
    (if (not (cua--rectangle-virtual-edges))
	(cua--rectangle-operation nil nil t 2 t
612
	  (lambda (s e _l _r _v)
613 614 615
            (setq lines (1+ lines))
            (if (and (> e s) (<= e (point-max)))
                (delete-region s e))))
616
      (cua--rectangle-operation nil 1 t nil t
617
	(lambda (s e _l _r _v)
618 619 620 621
	   (setq lines (1+ lines))
	   (when (and (> e s) (<= e (point-max)))
	     (delete-region s e)))))
    lines))
622 623 624

(defun cua--extract-rectangle ()
  (let (rect)
625 626
    (if (not (cua--rectangle-virtual-edges))
	(cua--rectangle-operation nil nil nil nil nil ; do not tabify
627
	  (lambda (s e _l _r)
628
	     (setq rect (cons (cua--filter-buffer-noprops s e) rect))))
629
      (cua--rectangle-operation nil 1 nil nil nil ; do not tabify
630
	(lambda (s e l r _v)
631 632 633 634 635 636 637
	   (let ((copy t) (bs 0) (as 0) row)
	     (if (= s e) (setq e (1+ e)))
	     (goto-char s)
	     (move-to-column l)
	     (if (= (point) (line-end-position))
		 (setq bs (- r l)
		       copy nil)
638
	       (skip-chars-forward "\s\t" e)
639 640 641
	       (setq bs (- (min r (current-column)) l)
		     s (point))
	       (move-to-column r)
642
	       (skip-chars-backward "\s\t" s)
643 644 645
	       (setq as (- r (max (current-column) l))
		     e (point)))
       	     (setq row (if (and copy (> e s))
646
			   (cua--filter-buffer-noprops s e)
647 648 649 650 651 652 653 654 655
			 ""))
    	     (when (> bs 0)
    	       (setq row (concat (make-string bs ?\s) row)))
    	     (when (> as 0)
    	       (setq row (concat row (make-string as ?\s))))
    	     (setq rect (cons row rect))))))
    (nreverse rect)))

(defun cua--insert-rectangle (rect &optional below paste-column line-count)
656 657 658
  ;; Insert rectangle as insert-rectangle, but don't set mark and exit with
  ;; point at either next to top right or below bottom left corner
  ;; Notice: In overwrite mode, the rectangle is inserted as separate text lines.
659
  (if (eq below 'auto)
660 661
      (setq below (and (bolp)
                       (or (eolp) (eobp) (= (1+ (point)) (point-max))))))
662 663
  (unless paste-column
    (setq paste-column (current-column)))
664 665
  (let ((lines rect)
        (first t)
666 667
	(tabify-start (cua--tabify-start (point) (point)))
	last-column
668 669 670 671 672 673
        p)
    (while (or lines below)
      (or first
          (if overwrite-mode
              (insert ?\n)
            (forward-line 1)
674 675 676
            (or (bolp) (insert ?\n))))
      (unless overwrite-mode
	(move-to-column paste-column t))
677 678 679
      (if (not lines)
          (setq below nil)
        (insert-for-yank (car lines))
680 681
	(unless last-column
	  (setq last-column (current-column)))
682 683 684
        (setq lines (cdr lines))
        (and first (not below)
             (setq p (point))))
685 686 687 688 689 690 691 692 693 694 695 696 697
      (setq first nil)
      (if (and line-count (= (setq line-count (1- line-count)) 0))
	  (setq lines nil)))
    (when (and line-count last-column (not overwrite-mode))
      (while (> line-count 0)
	(forward-line 1)
	(or (bolp) (insert ?\n))
	(move-to-column paste-column t)
        (insert-char ?\s (- last-column paste-column -1))
	(setq line-count (1- line-count))))
    (when (and tabify-start
	       (not overwrite-mode))
      (tabify tabify-start (point)))
698 699 700 701 702 703 704 705 706 707 708 709 710
    (and p (not overwrite-mode)
         (goto-char p))))

(defun cua--copy-rectangle-as-kill (&optional ring)
  (if cua--register
      (set-register cua--register (cua--extract-rectangle))
    (setq killed-rectangle (cua--extract-rectangle))
    (setq cua--last-killed-rectangle (cons (and kill-ring (car kill-ring)) killed-rectangle))
    (if ring
        (kill-new (mapconcat
                   (function (lambda (row) (concat row "\n")))
                   killed-rectangle "")))))

711
(defun cua--activate-rectangle ()
712 713 714
  ;; Turn on rectangular marking mode by disabling transient mark mode
  ;; and manually handling highlighting from a post command hook.
  ;; Be careful if we are already marking a rectangle.
715 716
  (setq cua--rectangle
        (if (and cua--last-rectangle
717 718 719
                 (eq (car cua--last-rectangle) (current-buffer))
                 (eq (car (cdr cua--last-rectangle)) (point)))
            (cdr (cdr cua--last-rectangle))
720 721
          (cua--rectangle-get-corners))
        cua--status-string (if (cua--rectangle-virtual-edges) " [R]" "")
722 723 724 725 726 727
        cua--last-rectangle nil))

;; (defvar cua-save-point nil)

(defun cua--deactivate-rectangle ()
  ;; This is used to clean up after `cua--activate-rectangle'.
728
  (mapc (function delete-overlay) cua--rectangle-overlays)
729
  (setq cua--last-rectangle (cons (current-buffer)
730 731 732 733 734 735 736 737 738 739 740 741 742
                                  (cons (point) ;; cua-save-point
                                        cua--rectangle))
        cua--rectangle nil
        cua--rectangle-overlays nil
        cua--status-string nil
        cua--mouse-last-pos nil))

(defun cua--highlight-rectangle ()
  ;; This function is used to highlight the rectangular region.
  ;; We do this by putting an overlay on each line within the rectangle.
  ;; Each overlay extends across all the columns of the rectangle.
  ;; We try to reuse overlays where possible because this is more efficient
  ;; and results in less flicker.
743
  ;; If cua--rectangle-virtual-edges is nil and the buffer contains tabs or short lines,
Paul Eggert's avatar
Paul Eggert committed
744
  ;; the highlighted region may not be perfectly rectangular.
745 746 747 748 749 750 751
  (let ((deactivate-mark deactivate-mark)
        (old cua--rectangle-overlays)
        (new nil)
        (left (cua--rectangle-left))
        (right (1+ (cua--rectangle-right))))
    (when (/= left right)
      (sit-for 0)  ; make window top/bottom reliable
752
      (cua--rectangle-operation nil t nil nil nil ; do not tabify
753
        (lambda (s e l r v)
754
           (let ((rface (if v 'cua-rectangle 'cua-rectangle-noselect))
755
                 overlay bs ms as)
756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778
	     (when (cua--rectangle-virtual-edges)
	       (let ((lb (line-beginning-position))
		     (le (line-end-position))
		     cl cl0 pl cr cr0 pr)
		 (goto-char s)
		 (setq cl (move-to-column l)
		       pl (point))
		 (setq cr (move-to-column r)
		       pr (point))
		 (if (= lb pl)
		     (setq cl0 0)
		   (goto-char (1- pl))
		   (setq cl0 (current-column)))
		 (if (= lb le)
		     (setq cr0 0)
		   (goto-char (1- pr))
		   (setq cr0 (current-column)))
		 (unless (and (= cl l) (= cr r))
		   (when (/= cl l)
		     (setq bs (propertize
			       (make-string
				(- l cl0 (if (and (= le pl) (/= le lb)) 1 0))
				(if cua--virtual-edges-debug ?. ?\s))
779
			       'face (or (get-text-property (1- s) 'face) 'default)))
780 781 782 783
		     (if (/= pl le)
			 (setq s (1- s))))
		   (cond
		    ((= cr r)
784 785 786 787
		     (if (and (/= pr le)
			      (/= cr0 (1- cr))
			      (or bs (/= cr0 (- cr tab-width)))
			      (/= (mod cr tab-width) 0))
788 789
			 (setq e (1- e))))
		    ((= cr cl)
790 791 792 793 794 795
		     (setq ms (propertize
			       (make-string
				(- r l)
				(if cua--virtual-edges-debug ?, ?\s))
			       'face rface))
		     (if (cua--rectangle-right-side)
796 797
			 (put-text-property (1- (length ms)) (length ms) 'cursor 2 ms)
		       (put-text-property 0 1 'cursor 2 ms))
798
		     (setq bs (concat bs ms))
799
		     (setq rface nil))
800
 		    (t
801 802 803 804 805
		     (setq as (propertize
			       (make-string
				(- r cr0 (if (= le pr) 1 0))
				(if cua--virtual-edges-debug ?~ ?\s))
			       'face rface))
806
		     (if (cua--rectangle-right-side)
807 808
			 (put-text-property (1- (length as)) (length as) 'cursor 2 as)
		       (put-text-property 0 1 'cursor 2 as))
809 810 811
		     (if (/= pr le)
			 (setq e (1- e))))))))
	     ;; Trim old leading overlays.
812 813 814 815 816 817 818 819 820 821 822 823 824 825 826
             (while (and old
                         (setq overlay (car old))
                         (< (overlay-start overlay) s)
                         (/= (overlay-end overlay) e))
               (delete-overlay overlay)
               (setq old (cdr old)))
             ;; Reuse an overlay if possible, otherwise create one.
             (if (and old
                      (setq overlay (car old))
                      (or (= (overlay-start overlay) s)
                          (= (overlay-end overlay) e)))
                 (progn
                   (move-overlay overlay s e)
                   (setq old (cdr old)))
               (setq overlay (make-overlay s e)))
827
 	     (overlay-put overlay 'before-string bs)
828 829
	     (overlay-put overlay 'after-string as)
	     (overlay-put overlay 'face rface)
830
	     (overlay-put overlay 'keymap cua--overlay-keymap)
831
	     (overlay-put overlay 'window (selected-window))
832
	     (setq new (cons overlay new))))))
833
    ;; Trim old trailing overlays.
834
    (mapc (function delete-overlay) old)
835 836 837 838 839
    (setq cua--rectangle-overlays (nreverse new))))

(defun cua--indent-rectangle (&optional ch to-col clear)
  ;; Indent current rectangle.
  (let ((col (cua--rectangle-insert-col))
840
        (pad (cua--rectangle-virtual-edges))
841
        indent)
842
    (cua--rectangle-operation (if clear 'clear 'corners) nil t pad nil
843
      (lambda (_s _e l _r)
844 845 846 847 848 849
         (move-to-column col pad)
         (if (and (eolp)
                  (< (current-column) col))
             (move-to-column col t))
	 (cond
	  (to-col (indent-to to-col))
850
	  ((and ch (not (eq ch ?\t))) (insert ch))
851 852 853 854
	  (t (tab-to-tab-stop)))
         (if (cua--rectangle-right-side t)
             (cua--rectangle-insert-col (current-column))
           (setq indent (- (current-column) l))))
855
      (lambda (l r)
856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907
         (when (and indent (> indent 0))
           (aset cua--rectangle 2 (+ l indent))
           (aset cua--rectangle 3 (+ r indent -1)))))))

;;
;; rectangle functions / actions
;;

(defvar cua--rectangle-initialized nil)

(defun cua-set-rectangle-mark (&optional reopen)
  "Set mark and start in CUA rectangle mode.
With prefix argument, activate previous rectangle if possible."
  (interactive "P")
  (unless cua--rectangle-initialized
    (cua--init-rectangles))
  (when (not cua--rectangle)
    (if (and reopen
             cua--last-rectangle
             (eq (car cua--last-rectangle) (current-buffer)))
        (goto-char (car (cdr cua--last-rectangle)))
      (if (not mark-active)
          (push-mark nil nil t)))
    (cua--activate-rectangle)
    (cua--rectangle-set-corners)
    (setq mark-active t
          cua--explicit-region-start t)
    (if cua-enable-rectangle-auto-help
        (cua-help-for-rectangle t))))

(defun cua-clear-rectangle-mark ()
  "Cancel current rectangle."
  (interactive)
  (when cua--rectangle
    (setq mark-active nil
          cua--explicit-region-start nil)
    (cua--deactivate-rectangle)))

(defun cua-toggle-rectangle-mark ()
  (interactive)
  (if cua--rectangle
      (cua--deactivate-rectangle)
    (unless cua--rectangle-initialized
      (cua--init-rectangles))
    (cua--activate-rectangle))
  (if cua--rectangle
      (if cua-enable-rectangle-auto-help
          (cua-help-for-rectangle t))
    (if cua-enable-region-auto-help
        (cua-help-for-region t))))

(defun cua-restrict-regexp-rectangle (arg)
908 909
  "Restrict rectangle to lines (not) matching regexp.
With prefix argument, toggle restriction."
910
  (interactive "P")
911
  (let ((r (cua--rectangle-restriction)))
912 913 914 915 916 917 918 919 920 921
    (if (and r (null (car (cdr r))))
      (if arg
          (cua--rectangle-restriction (car r) nil (not (car (cdr (cdr r)))))
        (cua--rectangle-restriction "" nil nil))
      (cua--rectangle-restriction
       (read-from-minibuffer "Restrict rectangle (regexp): "
                             nil nil nil nil) nil arg))))

(defun cua-restrict-prefix-rectangle (arg)
  "Restrict rectangle to lines (not) starting with CHAR.
922
With prefix argument, toggle restriction."
923
  (interactive "P")
924
  (let ((r (cua--rectangle-restriction)))
925 926 927 928 929
    (if (and r (car (cdr r)))
      (if arg
          (cua--rectangle-restriction (car r) t (not (car (cdr (cdr r)))))
        (cua--rectangle-restriction "" nil nil))
      (cua--rectangle-restriction
930
       (format "[%c]"
931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977
               (read-char "Restrictive rectangle (char): ")) t arg))))

(defun cua-move-rectangle-up ()
  (interactive)
  (cua--rectangle-move 'up))

(defun cua-move-rectangle-down ()
  (interactive)
  (cua--rectangle-move 'down))

(defun cua-move-rectangle-left ()
  (interactive)
  (cua--rectangle-move 'left))

(defun cua-move-rectangle-right ()
  (interactive)
  (cua--rectangle-move 'right))

(defun cua-copy-rectangle (arg)
  (interactive "P")
  (setq arg (cua--prefix-arg arg))
  (cua--copy-rectangle-as-kill arg)
  (if cua-keep-region-after-copy
      (cua--keep-active)
    (cua--deactivate)))

(defun cua-cut-rectangle (arg)
  (interactive "P")
  (if buffer-read-only
      (cua-copy-rectangle arg)
    (setq arg (cua--prefix-arg arg))
    (goto-char (min (mark) (point)))
    (cua--copy-rectangle-as-kill arg)
    (cua--delete-rectangle))
  (cua--deactivate))

(defun cua-delete-rectangle ()
  (interactive)
  (goto-char (min (point) (mark)))
  (if cua-delete-copy-to-register-0
      (set-register ?0 (cua--extract-rectangle)))
  (cua--delete-rectangle)
  (cua--deactivate))

(defun cua-rotate-rectangle ()
  (interactive)
  (cua--rectangle-corner (if (= (cua--rectangle-left) (cua--rectangle-right)) 0 1))
978 979 980
  (cua--rectangle-set-corners)
  (if (cua--rectangle-virtual-edges)
      (setq cua--buffer-and-point-before-command nil)))
981

982
(defun cua-toggle-rectangle-virtual-edges ()
983
  (interactive)
984 985 986
  (cua--rectangle-virtual-edges t (not (cua--rectangle-virtual-edges)))
  (cua--rectangle-set-corners)
  (setq cua--status-string (and (cua--rectangle-virtual-edges) " [R]"))
987 988 989 990 991
  (cua--keep-active))

(defun cua-do-rectangle-padding ()
  (interactive)
  (if buffer-read-only
992
      (message "Cannot do padding in read-only buffer")
993
    (cua--rectangle-operation nil nil t t t)
994 995 996 997 998 999 1000 1001
    (cua--rectangle-set-corners))
  (cua--keep-active))

(defun cua-open-rectangle ()
  "Blank out CUA rectangle, shifting text right.
The text previously in the region is not overwritten by the blanks,
but instead winds up to the right of the rectangle."
  (interactive)
1002
  (cua--rectangle-operation 'corners nil t 1 nil
1003
   (lambda (_s _e l r)
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
      (skip-chars-forward " \t")
      (let ((ws (- (current-column) l))
            (p (point)))
        (skip-chars-backward " \t")
        (delete-region (point) p)
        (indent-to (+ r ws))))))

(defun cua-close-rectangle (arg)
  "Delete all whitespace starting at left edge of CUA rectangle.
On each line in the rectangle, all continuous whitespace starting
at that column is deleted.
With prefix arg, also delete whitespace to the left of that column."
  (interactive "P")
1017
  (cua--rectangle-operation 'clear nil t 1 nil
1018
   (lambda (s _e _l _r)
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028
      (when arg
        (skip-syntax-backward " " (line-beginning-position))
        (setq s (point)))
      (skip-syntax-forward " " (line-end-position))
      (delete-region s (point)))))

(defun cua-blank-rectangle ()
  "Blank out CUA rectangle.
The text previously in the rectangle is overwritten by the blanks."
  (interactive)
1029
  (cua--rectangle-operation 'keep nil nil 1 nil
1030
   (lambda (s e _l _r)
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
      (goto-char e)
      (skip-syntax-forward " " (line-end-position))
      (setq e (point))
      (let ((column (current-column)))
        (goto-char s)
        (skip-syntax-backward " " (line-beginning-position))
        (delete-region (point) e)
        (indent-to column)))))

(defun cua-align-rectangle ()
  "Align rectangle lines to left column."
  (interactive)
1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
  (cua--rectangle-operation 'clear nil t t nil
   (lambda (s _e l _r)
      (let ((b (line-beginning-position)))
	(skip-syntax-backward "^ " b)
	(skip-syntax-backward " " b)
	(setq s (point)))
      (skip-syntax-forward " " (line-end-position))
      (delete-region s (point))
      (indent-to l))
   (lambda (l _r)
      (move-to-column l)
      ;; (setq cua-save-point (point))
      )))
1056

1057 1058 1059
(declare-function cua--cut-rectangle-to-global-mark  "cua-gmrk" (as-text))
(declare-function cua--copy-rectangle-to-global-mark "cua-gmrk" (as-text))

1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
(defun cua-copy-rectangle-as-text (&optional arg delete)
  "Copy rectangle, but store as normal text."
  (interactive "P")
  (if cua--global-mark-active
      (if delete
          (cua--cut-rectangle-to-global-mark t)
        (cua--copy-rectangle-to-global-mark t))
    (let* ((rect (cua--extract-rectangle))
           (text (mapconcat
                  (function (lambda (row) (concat row "\n")))
                  rect "")))
      (setq arg (cua--prefix-arg arg))
      (if cua--register
          (set-register cua--register text)
        (kill-new text)))
    (if delete
        (cua--delete-rectangle))
    (cua--deactivate)))

(defun cua-cut-rectangle-as-text (arg)
  "Kill rectangle, but store as normal text."
  (interactive "P")
  (cua-copy-rectangle-as-text arg (not buffer-read-only)))

(defun cua-string-rectangle (string)
  "Replace CUA rectangle contents with STRING on each line.
The length of STRING need not be the same as the rectangle width."
  (interactive "sString rectangle: ")
1088
  (cua--rectangle-operation 'keep nil t t nil
1089
     (lambda (s e l _r)
1090 1091 1092 1093 1094 1095 1096
        (delete-region s e)
        (skip-chars-forward " \t")
        (let ((ws (- (current-column) l)))
          (delete-region s (point))
          (insert string)
          (indent-to (+ (current-column) ws))))
     (unless (cua--rectangle-restriction)
1097
       (lambda (l _r)
1098 1099
          (cua--rectangle-right (max l (+ l (length string) -1)))))))

1100
(defun cua-fill-char-rectangle (character)
1101 1102
  "Replace CUA rectangle contents with CHARACTER."
  (interactive "cFill rectangle with character: ")
1103
  (cua--rectangle-operation 'clear nil t 1 nil
1104
   (lambda (s e l r)
1105 1106
      (delete-region s e)
      (move-to-column l t)
1107
      (insert-char character (- r l)))))
1108 1109 1110 1111 1112 1113

(defun cua-replace-in-rectangle (regexp newtext)
  "Replace REGEXP with NEWTEXT in each line of CUA rectangle."
  (interactive "sReplace regexp: \nsNew text: ")
  (if buffer-read-only
      (message "Cannot replace in read-only buffer")
1114
    (cua--rectangle-operation 'keep nil t 1 nil
1115
     (lambda (_s e _l _r)
1116 1117 1118 1119 1120 1121
        (if (re-search-forward regexp e t)
            (replace-match newtext nil nil))))))

(defun cua-incr-rectangle (increment)
  "Increment each line of CUA rectangle by prefix amount."
  (interactive "p")
1122
  (cua--rectangle-operation 'keep nil t 1 nil
1123
     (lambda (_s e _l _r)
1124 1125
        (cond
         ((re-search-forward "0x\\([0-9a-fA-F]+\\)" e t)
1126
          (let* ((txt (cua--filter-buffer-noprops (match-beginning 1) (match-end 1)))
1127 1128 1129 1130
                 (n (string-to-number txt 16))
                 (fmt (format "0x%%0%dx" (length txt))))
            (replace-match (format fmt (+ n increment)))))
         ((re-search-forward "\\( *-?[0-9]+\\)" e t)
1131
          (let* ((txt (cua--filter-buffer-noprops (match-beginning 1) (match-end 1)))
1132 1133 1134 1135 1136 1137 1138
                 (prefix (if (= (aref txt 0) ?0) "0" ""))
                 (n (string-to-number txt 10))
                 (fmt (format "%%%s%dd" prefix (length txt))))
            (replace-match (format fmt (+ n increment)))))
         (t nil)))))

(defvar cua--rectangle-seq-format "%d"
1139
  "Last format used by `cua-sequence-rectangle'.")
1140

1141
(defun cua-sequence-rectangle (first incr format)
1142 1143
  "Resequence each line of CUA rectangle starting from FIRST.
The numbers are formatted according to the FORMAT string."
1144
  (interactive
1145 1146 1147 1148 1149 1150 1151
   (list (if current-prefix-arg
             (prefix-numeric-value current-prefix-arg)
           (string-to-number
            (read-string "Start value: (0) " nil nil "0")))
         (string-to-number
          (read-string "Increment: (1) " nil nil "1"))
         (read-string (concat "Format: (" cua--rectangle-seq-format ") "))))
1152 1153 1154
  (if (= (length format) 0)
      (setq format cua--rectangle-seq-format)
    (setq cua--rectangle-seq-format format))
1155
  (cua--rectangle-operation 'clear nil t 1 nil
1156
     (lambda (s e _l _r)
1157
         (delete-region s e)
1158
         (insert (format format first))
1159 1160
         (setq first (+ first incr)))))

1161 1162
(defmacro cua--convert-rectangle-as (command tabify)
  `(cua--rectangle-operation 'clear nil nil nil ,tabify
1163
    (lambda (s e _l _r)
1164 1165
       (,command s e))))

1166 1167 1168
(defun cua-upcase-rectangle ()
  "Convert the rectangle to upper case."
  (interactive)