* admin/gitmerge.el (gitmerge-missing):
[emacs.git] / lisp / rect.el
bloba62ed95b715f521a1d7a5c4812b447cb65cab7cc
1 ;;; rect.el --- rectangle functions for GNU Emacs -*- lexical-binding:t -*-
3 ;; Copyright (C) 1985, 1999-2017 Free Software Foundation, Inc.
5 ;; Maintainer: Didier Verna <didier@xemacs.org>
6 ;; Keywords: internal
7 ;; Package: emacs
9 ;; 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 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
24 ;;; Commentary:
26 ;; This package provides the operations on rectangles that are documented
27 ;; in the Emacs manual.
29 ;; ### NOTE: this file was almost completely rewritten by Didier Verna
30 ;; <didier@xemacs.org> in July 1999.
32 ;;; Code:
34 (eval-when-compile (require 'cl-lib))
36 (defgroup rectangle nil
37 "Operations on rectangles."
38 :version "25.1"
39 :group 'editing)
41 ;; FIXME: this function should be replaced by `apply-on-rectangle'
42 (defun operate-on-rectangle (function start end coerce-tabs)
43 "Call FUNCTION for each line of rectangle with corners at START, END.
44 If COERCE-TABS is non-nil, convert multi-column characters
45 that span the starting or ending columns on any line
46 to multiple spaces before calling FUNCTION.
47 FUNCTION is called with three arguments:
48 position of start of segment of this line within the rectangle,
49 number of columns that belong to rectangle but are before that position,
50 number of columns that belong to rectangle but are after point.
51 Point is at the end of the segment of this line within the rectangle."
52 (apply-on-rectangle
53 (lambda (startcol endcol)
54 (let (startpos begextra endextra)
55 (move-to-column startcol coerce-tabs)
56 (setq begextra (- (current-column) startcol))
57 (setq startpos (point))
58 (move-to-column endcol coerce-tabs)
59 ;; If we overshot, move back one character
60 ;; so that endextra will be positive.
61 (if (and (not coerce-tabs) (> (current-column) endcol))
62 (backward-char 1))
63 (setq endextra (- endcol (current-column)))
64 (if (< begextra 0)
65 (setq endextra (+ endextra begextra)
66 begextra 0))
67 (funcall function startpos begextra endextra)))
68 start end))
70 ;;; Crutches to let rectangle's corners be where point can't be
71 ;; (e.g. in the middle of a TAB, or past the EOL).
73 (defvar-local rectangle--mark-crutches nil
74 "(POS . COL) to override the column to use for the mark.")
76 (defun rectangle--pos-cols (start end &optional window)
77 ;; At this stage, we don't know which of start/end is point/mark :-(
78 ;; And in case start=end, it might still be that point and mark have
79 ;; different crutches!
80 (let ((cw (window-parameter window 'rectangle--point-crutches)))
81 (cond
82 ((eq start (car cw))
83 (let ((sc (cdr cw))
84 (ec (if (eq end (car rectangle--mark-crutches))
85 (cdr rectangle--mark-crutches)
86 (if rectangle--mark-crutches
87 (setq rectangle--mark-crutches nil))
88 (goto-char end) (current-column))))
89 (if (eq start end) (cons (min sc ec) (max sc ec)) (cons sc ec))))
90 ((eq end (car cw))
91 (if (eq start (car rectangle--mark-crutches))
92 (cons (cdr rectangle--mark-crutches) (cdr cw))
93 (if rectangle--mark-crutches (setq rectangle--mark-crutches nil))
94 (cons (progn (goto-char start) (current-column)) (cdr cw))))
95 ((progn
96 (if cw (setf (window-parameter nil 'rectangle--point-crutches) nil))
97 (eq start (car rectangle--mark-crutches)))
98 (let ((sc (cdr rectangle--mark-crutches))
99 (ec (progn (goto-char end) (current-column))))
100 (if (eq start end) (cons (min sc ec) (max sc ec)) (cons sc ec))))
101 ((eq end (car rectangle--mark-crutches))
102 (cons (progn (goto-char start) (current-column))
103 (cdr rectangle--mark-crutches)))
105 (if rectangle--mark-crutches (setq rectangle--mark-crutches nil))
106 (cons (progn (goto-char start) (current-column))
107 (progn (goto-char end) (current-column)))))))
109 (defun rectangle--col-pos (col kind)
110 (let ((c (move-to-column col)))
111 (if (and (= c col) (not (eolp)))
112 (if (eq kind 'point)
113 (if (window-parameter nil 'rectangle--point-crutches)
114 (setf (window-parameter nil 'rectangle--point-crutches) nil))
115 (if rectangle--mark-crutches (setq rectangle--mark-crutches nil)))
116 ;; If move-to-column overshot, move back one char so we're
117 ;; at the position where rectangle--highlight-for-redisplay
118 ;; will add the overlay (so that the cursor can be drawn at the
119 ;; right place).
120 (when (> c col) (forward-char -1))
121 (setf (if (eq kind 'point)
122 (window-parameter nil 'rectangle--point-crutches)
123 rectangle--mark-crutches)
124 (cons (point) col)))))
126 (defun rectangle--point-col (pos)
127 (let ((pc (window-parameter nil 'rectangle--point-crutches)))
128 (if (eq pos (car pc)) (cdr pc)
129 (goto-char pos)
130 (current-column))))
132 (defun rectangle--crutches ()
133 (cons rectangle--mark-crutches
134 (window-parameter nil 'rectangle--point-crutches)))
135 (defun rectangle--reset-crutches ()
136 (kill-local-variable 'rectangle--mark-crutches)
137 (if (window-parameter nil 'rectangle--point-crutches)
138 (setf (window-parameter nil 'rectangle--point-crutches) nil)))
140 ;;; Rectangle operations.
142 (defun apply-on-rectangle (function start end &rest args)
143 "Call FUNCTION for each line of rectangle with corners at START, END.
144 FUNCTION is called with two arguments: the start and end columns of the
145 rectangle, plus ARGS extra arguments. Point is at the beginning of line when
146 the function is called.
147 The final point after the last operation will be returned."
148 (save-excursion
149 (let* ((cols (rectangle--pos-cols start end))
150 (startcol (car cols))
151 (endcol (cdr cols))
152 (startpt (progn (goto-char start) (line-beginning-position)))
153 (endpt (progn (goto-char end)
154 (copy-marker (line-end-position))))
155 final-point)
156 ;; Ensure the start column is the left one.
157 (if (< endcol startcol)
158 (let ((col startcol))
159 (setq startcol endcol endcol col)))
160 ;; Start looping over lines.
161 (goto-char startpt)
162 (while
163 (progn
164 (apply function startcol endcol args)
165 (setq final-point (point))
166 (and (zerop (forward-line 1)) (bolp)
167 (<= (point) endpt))))
168 final-point)))
170 (defun delete-rectangle-line (startcol endcol fill)
171 (when (= (move-to-column startcol (if fill t 'coerce)) startcol)
172 (delete-region (point)
173 (progn (move-to-column endcol 'coerce)
174 (point)))))
176 (defun delete-extract-rectangle-line (startcol endcol lines fill)
177 (let ((pt (point-at-eol)))
178 (if (< (move-to-column startcol (if fill t 'coerce)) startcol)
179 (setcdr lines (cons (spaces-string (- endcol startcol))
180 (cdr lines)))
181 ;; else
182 (setq pt (point))
183 (move-to-column endcol t)
184 (setcdr lines (cons (filter-buffer-substring pt (point) t) (cdr lines))))
187 ;; This is actually the only function that needs to do complicated
188 ;; stuff like what's happening in `operate-on-rectangle', because the
189 ;; buffer might be read-only.
190 (defun extract-rectangle-line (startcol endcol lines)
191 (let (start end begextra endextra line)
192 (move-to-column startcol)
193 (setq start (point)
194 begextra (- (current-column) startcol))
195 (move-to-column endcol)
196 (setq end (point)
197 endextra (- endcol (current-column)))
198 (setq line (buffer-substring start (point)))
199 (if (< begextra 0)
200 (setq endextra (+ endextra begextra)
201 begextra 0))
202 (if (< endextra 0)
203 (setq endextra 0))
204 (goto-char start)
205 (while (search-forward "\t" end t)
206 (let ((width (- (current-column)
207 (save-excursion (forward-char -1)
208 (current-column)))))
209 (setq line (concat (substring line 0 (- (point) end 1))
210 (spaces-string width)
211 (substring line (+ (length line)
212 (- (point) end)))))))
213 (if (or (> begextra 0) (> endextra 0))
214 (setq line (concat (spaces-string begextra)
215 line
216 (spaces-string endextra))))
217 (setcdr lines (cons line (cdr lines)))))
219 (defconst spaces-strings
220 '["" " " " " " " " " " " " " " " " "])
222 (defun spaces-string (n)
223 "Return a string with N spaces."
224 (if (<= n 8) (aref spaces-strings n)
225 (make-string n ?\s)))
227 ;;;###autoload
228 (defun delete-rectangle (start end &optional fill)
229 "Delete (don't save) text in the region-rectangle.
230 The same range of columns is deleted in each line starting with the
231 line where the region begins and ending with the line where the region
232 ends.
234 When called from a program the rectangle's corners are START and END.
235 With a prefix (or a FILL) argument, also fill lines where nothing has
236 to be deleted."
237 (interactive "*r\nP")
238 (apply-on-rectangle 'delete-rectangle-line start end fill))
240 ;;;###autoload
241 (defun delete-extract-rectangle (start end &optional fill)
242 "Delete the contents of the rectangle with corners at START and END.
243 Return it as a list of strings, one for each line of the rectangle.
245 When called from a program the rectangle's corners are START and END.
246 With an optional FILL argument, also fill lines where nothing has to be
247 deleted."
248 (let ((lines (list nil)))
249 (apply-on-rectangle 'delete-extract-rectangle-line start end lines fill)
250 (nreverse (cdr lines))))
252 ;;;###autoload
253 (defun extract-rectangle (start end)
254 "Return the contents of the rectangle with corners at START and END.
255 Return it as a list of strings, one for each line of the rectangle."
256 (let ((lines (list nil)))
257 (apply-on-rectangle 'extract-rectangle-line start end lines)
258 (nreverse (cdr lines))))
260 (defun extract-rectangle-bounds (start end)
261 "Return the bounds of the rectangle with corners at START and END.
262 Return it as a list of (START . END) positions, one for each line of
263 the rectangle."
264 (let (bounds)
265 (apply-on-rectangle
266 (lambda (startcol endcol)
267 (move-to-column startcol)
268 (push (cons (prog1 (point) (move-to-column endcol)) (point))
269 bounds))
270 start end)
271 (nreverse bounds)))
273 (defvar killed-rectangle nil
274 "Rectangle for `yank-rectangle' to insert.")
276 ;;;###autoload
277 (defun kill-rectangle (start end &optional fill)
278 "Delete the region-rectangle and save it as the last killed one.
280 When called from a program the rectangle's corners are START and END.
281 You might prefer to use `delete-extract-rectangle' from a program.
283 With a prefix (or a FILL) argument, also fill lines where nothing has to be
284 deleted.
286 If the buffer is read-only, Emacs will beep and refrain from deleting
287 the rectangle, but put it in `killed-rectangle' anyway. This means that
288 you can use this command to copy text from a read-only buffer.
289 \(If the variable `kill-read-only-ok' is non-nil, then this won't
290 even beep.)"
291 (interactive "r\nP")
292 (condition-case nil
293 (setq killed-rectangle (delete-extract-rectangle start end fill))
294 ((buffer-read-only text-read-only)
295 (setq deactivate-mark t)
296 (setq killed-rectangle (extract-rectangle start end))
297 (if kill-read-only-ok
298 (progn (message "Read only text copied to `killed-rectangle'") nil)
299 (barf-if-buffer-read-only)
300 (signal 'text-read-only (list (current-buffer)))))))
302 ;;;###autoload
303 (defun copy-rectangle-as-kill (start end)
304 "Copy the region-rectangle and save it as the last killed one."
305 (interactive "r")
306 (setq killed-rectangle (extract-rectangle start end))
307 (setq deactivate-mark t)
308 (if (called-interactively-p 'interactive)
309 (indicate-copied-region (length (car killed-rectangle)))))
311 ;;;###autoload
312 (defun yank-rectangle ()
313 "Yank the last killed rectangle with upper left corner at point."
314 (interactive "*")
315 (insert-rectangle killed-rectangle))
317 ;;;###autoload
318 (defun insert-rectangle (rectangle)
319 "Insert text of RECTANGLE with upper left corner at point.
320 RECTANGLE's first line is inserted at point, its second
321 line is inserted at a point vertically under point, etc.
322 RECTANGLE should be a list of strings.
323 After this command, the mark is at the upper left corner
324 and point is at the lower right corner."
325 (let ((lines rectangle)
326 (insertcolumn (current-column))
327 (first t))
328 (push-mark)
329 (while lines
330 (or first
331 (progn
332 (forward-line 1)
333 (or (bolp) (insert ?\n))
334 (move-to-column insertcolumn t)))
335 (setq first nil)
336 (insert-for-yank (car lines))
337 (setq lines (cdr lines)))))
339 ;;;###autoload
340 (defun open-rectangle (start end &optional fill)
341 "Blank out the region-rectangle, shifting text right.
343 The text previously in the region is not overwritten by the blanks,
344 but instead winds up to the right of the rectangle.
346 When called from a program the rectangle's corners are START and END.
347 With a prefix (or a FILL) argument, fill with blanks even if there is
348 no text on the right side of the rectangle."
349 (interactive "*r\nP")
350 (apply-on-rectangle 'open-rectangle-line start end fill)
351 (goto-char start))
353 (defun open-rectangle-line (startcol endcol fill)
354 (when (= (move-to-column startcol (if fill t 'coerce)) startcol)
355 (unless (and (not fill)
356 (= (point) (point-at-eol)))
357 (indent-to endcol))))
359 (defun delete-whitespace-rectangle-line (startcol _endcol fill)
360 (when (= (move-to-column startcol (if fill t 'coerce)) startcol)
361 (unless (= (point) (point-at-eol))
362 (delete-region (point) (progn (skip-syntax-forward " " (point-at-eol))
363 (point))))))
365 ;;;###autoload
366 (defalias 'close-rectangle 'delete-whitespace-rectangle) ;; Old name
368 ;;;###autoload
369 (defun delete-whitespace-rectangle (start end &optional fill)
370 "Delete all whitespace following a specified column in each line.
371 The left edge of the rectangle specifies the position in each line
372 at which whitespace deletion should begin. On each line in the
373 rectangle, all contiguous whitespace starting at that column is deleted.
375 When called from a program the rectangle's corners are START and END.
376 With a prefix (or a FILL) argument, also fill too short lines."
377 (interactive "*r\nP")
378 (apply-on-rectangle 'delete-whitespace-rectangle-line start end fill))
380 (defvar string-rectangle-history nil)
381 (defun string-rectangle-line (startcol endcol string delete)
382 (move-to-column startcol t)
383 (if delete
384 (delete-rectangle-line startcol endcol nil))
385 (insert string))
387 (defvar-local rectangle--string-preview-state nil)
388 (defvar-local rectangle--string-preview-window nil)
390 (defun rectangle--string-flush-preview ()
391 (mapc #'delete-overlay (nthcdr 3 rectangle--string-preview-state))
392 (setf (nthcdr 3 rectangle--string-preview-state) nil))
394 (defun rectangle--string-erase-preview ()
395 (with-selected-window rectangle--string-preview-window
396 (rectangle--string-flush-preview)))
398 (defun rectangle--space-to (col)
399 (propertize " " 'display `(space :align-to ,col)))
401 (defface rectangle-preview '((t :inherit region))
402 "The face to use for the `string-rectangle' preview."
403 :version "25.1")
405 (defcustom rectangle-preview t
406 "If non-nil, `string-rectangle' will show an on-the-fly preview."
407 :version "25.1"
408 :type 'boolean)
410 (defun rectangle--string-preview ()
411 (when rectangle-preview
412 (let ((str (minibuffer-contents)))
413 (when str (setq str (propertize str 'face 'rectangle-preview)))
414 (with-selected-window rectangle--string-preview-window
415 (unless (or (null rectangle--string-preview-state)
416 (equal str (car rectangle--string-preview-state)))
417 (rectangle--string-flush-preview)
418 (apply-on-rectangle
419 (lambda (startcol endcol)
420 (let* ((sc (move-to-column startcol))
421 (start (if (<= sc startcol) (point)
422 (forward-char -1)
423 (setq sc (current-column))
424 (point)))
425 (ec (move-to-column endcol))
426 (end (point))
427 (ol (make-overlay start end)))
428 (push ol (nthcdr 3 rectangle--string-preview-state))
429 ;; FIXME: The extra spacing doesn't interact correctly with
430 ;; the extra spacing added by the rectangular-region-highlight.
431 (when (< sc startcol)
432 (overlay-put ol 'before-string (rectangle--space-to startcol)))
433 (let ((as (when (< endcol ec)
434 ;; (rectangle--space-to ec)
435 (spaces-string (- ec endcol))
437 (if (= start end)
438 (overlay-put ol 'after-string (if as (concat str as) str))
439 (overlay-put ol 'display str)
440 (if as (overlay-put ol 'after-string as))))))
441 (nth 1 rectangle--string-preview-state)
442 (nth 2 rectangle--string-preview-state)))))))
444 ;; FIXME: Should this be turned into inhibit-region-highlight and made to apply
445 ;; to non-rectangular regions as well?
446 (defvar rectangle--inhibit-region-highlight nil)
448 ;;;###autoload
449 (defun string-rectangle (start end string)
450 "Replace rectangle contents with STRING on each line.
451 The length of STRING need not be the same as the rectangle width.
453 When called interactively and option `rectangle-preview' is
454 non-nil, display the result as the user enters the string into
455 the minibuffer.
457 Called from a program, takes three args; START, END and STRING."
458 (interactive
459 (progn
460 (make-local-variable 'rectangle--string-preview-state)
461 (make-local-variable 'rectangle--inhibit-region-highlight)
462 (let* ((buf (current-buffer))
463 (win (if (eq (window-buffer) buf) (selected-window)))
464 (start (region-beginning))
465 (end (region-end))
466 (rectangle--string-preview-state `(nil ,start ,end))
467 ;; Rectangle-region-highlighting doesn't work well in the presence
468 ;; of the preview overlays. We could work harder to try and make
469 ;; it work better, but it's easier to just disable it temporarily.
470 (rectangle--inhibit-region-highlight t))
471 (barf-if-buffer-read-only)
472 (list start end
473 (minibuffer-with-setup-hook
474 (lambda ()
475 (setq rectangle--string-preview-window win)
476 (add-hook 'minibuffer-exit-hook
477 #'rectangle--string-erase-preview nil t)
478 (add-hook 'post-command-hook
479 #'rectangle--string-preview nil t))
480 (read-string (format "String rectangle (default %s): "
481 (or (car string-rectangle-history) ""))
482 nil 'string-rectangle-history
483 (car string-rectangle-history)))))))
484 ;; If we undo this change, we want to have the point back where we
485 ;; are now, and not after the first line in the rectangle (which is
486 ;; the first line to be changed by the following command).
487 (unless (eq buffer-undo-list t)
488 (push (point) buffer-undo-list))
489 (goto-char
490 (apply-on-rectangle 'string-rectangle-line start end string t)))
492 ;;;###autoload
493 (defalias 'replace-rectangle 'string-rectangle)
495 ;;;###autoload
496 (defun string-insert-rectangle (start end string)
497 "Insert STRING on each line of region-rectangle, shifting text right.
499 When called from a program, the rectangle's corners are START and END.
500 The left edge of the rectangle specifies the column for insertion.
501 This command does not delete or overwrite any existing text."
502 (interactive
503 (progn (barf-if-buffer-read-only)
504 (list
505 (region-beginning)
506 (region-end)
507 (read-string (format "String insert rectangle (default %s): "
508 (or (car string-rectangle-history) ""))
509 nil 'string-rectangle-history
510 (car string-rectangle-history)))))
511 (apply-on-rectangle 'string-rectangle-line start end string nil))
513 ;;;###autoload
514 (defun clear-rectangle (start end &optional fill)
515 "Blank out the region-rectangle.
516 The text previously in the region is overwritten with blanks.
518 When called from a program the rectangle's corners are START and END.
519 With a prefix (or a FILL) argument, also fill with blanks the parts of the
520 rectangle which were empty."
521 (interactive "*r\nP")
522 (apply-on-rectangle 'clear-rectangle-line start end fill))
524 (defun clear-rectangle-line (startcol endcol fill)
525 (let ((pt (point-at-eol)))
526 (when (= (move-to-column startcol (if fill t 'coerce)) startcol)
527 (if (and (not fill)
528 (<= (save-excursion (goto-char pt) (current-column)) endcol))
529 (delete-region (point) pt)
530 ;; else
531 (setq pt (point))
532 (move-to-column endcol t)
533 (setq endcol (current-column))
534 (delete-region pt (point))
535 (indent-to endcol)))))
537 ;; Line numbers for `rectangle-number-line-callback'.
538 (defvar rectangle-number-line-counter)
540 (defun rectangle-number-line-callback (start _end format-string)
541 (move-to-column start t)
542 (insert (format format-string rectangle-number-line-counter))
543 (setq rectangle-number-line-counter
544 (1+ rectangle-number-line-counter)))
546 (defun rectangle--default-line-number-format (start end start-at)
547 (concat "%"
548 (int-to-string (length (int-to-string (+ (count-lines start end)
549 start-at))))
550 "d "))
552 ;;;###autoload
553 (defun rectangle-number-lines (start end start-at &optional format)
554 "Insert numbers in front of the region-rectangle.
556 START-AT, if non-nil, should be a number from which to begin
557 counting. FORMAT, if non-nil, should be a format string to pass
558 to `format' along with the line count. When called interactively
559 with a prefix argument, prompt for START-AT and FORMAT."
560 (interactive
561 (if current-prefix-arg
562 (let* ((start (region-beginning))
563 (end (region-end))
564 (start-at (read-number "Number to count from: " 1)))
565 (list start end start-at
566 (read-string "Format string: "
567 (rectangle--default-line-number-format
568 start end start-at))))
569 (list (region-beginning) (region-end) 1 nil)))
570 (unless format
571 (setq format (rectangle--default-line-number-format start end start-at)))
572 (let ((rectangle-number-line-counter start-at))
573 (apply-on-rectangle 'rectangle-number-line-callback
574 start end format)))
576 ;;; New rectangle integration with kill-ring.
578 ;; FIXME: known problems with the new rectangle support:
579 ;; - lots of commands handle the region without paying attention to its
580 ;; rectangular shape.
582 (add-function :around redisplay-highlight-region-function
583 #'rectangle--highlight-for-redisplay)
584 (add-function :around redisplay-unhighlight-region-function
585 #'rectangle--unhighlight-for-redisplay)
586 (add-function :around region-extract-function
587 #'rectangle--extract-region)
588 (add-function :around region-insert-function
589 #'rectangle--insert-region)
591 (defvar rectangle-mark-mode-map
592 (let ((map (make-sparse-keymap)))
593 (define-key map [?\C-o] 'open-rectangle)
594 (define-key map [?\C-t] 'string-rectangle)
595 (define-key map [remap exchange-point-and-mark]
596 'rectangle-exchange-point-and-mark)
597 (dolist (cmd '(right-char left-char forward-char backward-char
598 next-line previous-line))
599 (define-key map (vector 'remap cmd)
600 (intern (format "rectangle-%s" cmd))))
601 map)
602 "Keymap used while marking a rectangular region.")
604 ;;;###autoload
605 (define-minor-mode rectangle-mark-mode
606 "Toggle the region as rectangular.
607 Activates the region if needed. Only lasts until the region is deactivated."
608 nil nil nil
609 (rectangle--reset-crutches)
610 (when rectangle-mark-mode
611 (add-hook 'deactivate-mark-hook
612 (lambda () (rectangle-mark-mode -1)))
613 (unless (region-active-p)
614 (push-mark (point) t t)
615 (message "Mark set (rectangle mode)"))))
617 (defun rectangle-exchange-point-and-mark (&optional arg)
618 "Like `exchange-point-and-mark' but cycles through the rectangle's corners."
619 (interactive "P")
620 (if arg
621 (progn
622 (setq this-command 'exchange-point-and-mark)
623 (exchange-point-and-mark arg))
624 (let* ((p (point))
625 (repeat (eq this-command last-command))
626 (m (mark))
627 (p<m (< p m))
628 (cols (if p<m (rectangle--pos-cols p m) (rectangle--pos-cols m p)))
629 (cp (if p<m (car cols) (cdr cols)))
630 (cm (if p<m (cdr cols) (car cols))))
631 (if repeat (setq this-command 'exchange-point-and-mark))
632 (rectangle--reset-crutches)
633 (goto-char p)
634 (rectangle--col-pos (if repeat cm cp) 'mark)
635 (set-mark (point))
636 (goto-char m)
637 (rectangle--col-pos (if repeat cp cm) 'point))))
639 (defun rectangle--*-char (cmd n &optional other-cmd)
640 ;; Part of the complexity here is that I'm trying to avoid making assumptions
641 ;; about the L2R/R2L direction of text around point, but this is largely
642 ;; useless since the rectangles implemented in this file are "logical
643 ;; rectangles" and not "visual rectangles", so in the presence of
644 ;; bidirectional text things won't work well anyway.
645 (if (< n 0) (rectangle--*-char other-cmd (- n))
646 (let ((col (rectangle--point-col (point)))
647 (step 1))
648 (while (> n 0)
649 (let* ((bol (line-beginning-position))
650 (eol (line-end-position))
651 (curcol (current-column))
652 (nextcol
653 (condition-case nil
654 (save-excursion
655 (funcall cmd step)
656 (cond
657 ((> bol (point)) (- curcol 1))
658 ((< eol (point)) (+ col (1+ n)))
659 (t (current-column))))
660 (end-of-buffer (+ col (1+ n)))
661 (beginning-of-buffer (- curcol 1))))
662 (diff (abs (- nextcol col))))
663 (cond
664 ((and (< nextcol curcol) (< curcol col))
665 (let ((curdiff (- col curcol)))
666 (if (<= curdiff n)
667 (progn (cl-decf n curdiff) (setq col curcol))
668 (setq col (- col n) n 0))))
669 ((< nextcol 0) (ding) (setq n 0 col 0)) ;Bumping into BOL!
670 ((= nextcol curcol) (funcall cmd 1))
671 (t ;; (> nextcol curcol)
672 (if (<= diff n)
673 (progn (cl-decf n diff) (setq col nextcol))
674 (setq col (if (< col nextcol) (+ col n) (- col n)) n 0))))
675 (setq step (1+ step))))
676 ;; FIXME: This rectangle--col-pos's move-to-column is wasted!
677 (rectangle--col-pos col 'point))))
679 (defun rectangle-right-char (&optional n)
680 "Like `right-char' but steps into wide chars and moves past EOL."
681 (interactive "p") (rectangle--*-char #'right-char n #'left-char))
682 (defun rectangle-left-char (&optional n)
683 "Like `left-char' but steps into wide chars and moves past EOL."
684 (interactive "p") (rectangle--*-char #'left-char n #'right-char))
686 (defun rectangle-forward-char (&optional n)
687 "Like `forward-char' but steps into wide chars and moves past EOL."
688 (interactive "p") (rectangle--*-char #'forward-char n #'backward-char))
689 (defun rectangle-backward-char (&optional n)
690 "Like `backward-char' but steps into wide chars and moves past EOL."
691 (interactive "p") (rectangle--*-char #'backward-char n #'forward-char))
693 (defun rectangle-next-line (&optional n)
694 "Like `next-line' but steps into wide chars and moves past EOL.
695 Ignores `line-move-visual'."
696 (interactive "p")
697 (let ((col (rectangle--point-col (point))))
698 (forward-line n)
699 (rectangle--col-pos col 'point)))
700 (defun rectangle-previous-line (&optional n)
701 "Like `previous-line' but steps into wide chars and moves past EOL.
702 Ignores `line-move-visual'."
703 (interactive "p")
704 (let ((col (rectangle--point-col (point))))
705 (forward-line (- n))
706 (rectangle--col-pos col 'point)))
709 (defun rectangle--extract-region (orig &optional delete)
710 (cond
711 ((not rectangle-mark-mode)
712 (funcall orig delete))
713 ((eq delete 'bounds)
714 (extract-rectangle-bounds (region-beginning) (region-end)))
716 (let* ((strs (funcall (if delete
717 #'delete-extract-rectangle
718 #'extract-rectangle)
719 (region-beginning) (region-end)))
720 (str (mapconcat #'identity strs "\n")))
721 (when (eq last-command 'kill-region)
722 ;; Try to prevent kill-region from appending this to some
723 ;; earlier element.
724 (setq last-command 'kill-region-dont-append))
725 (when strs
726 (put-text-property 0 (length str) 'yank-handler
727 `(rectangle--insert-for-yank ,strs t)
728 str)
729 str)))))
731 (defun rectangle--insert-region (orig strings)
732 (cond
733 ((not rectangle-mark-mode)
734 (funcall orig strings))
736 (funcall #'insert-rectangle strings))))
738 (defun rectangle--insert-for-yank (strs)
739 (push (point) buffer-undo-list)
740 (let ((undo-at-start buffer-undo-list))
741 (insert-rectangle strs)
742 (setq yank-undo-function
743 (lambda (_start _end)
744 (undo-start)
745 (setcar undo-at-start nil) ;Turn it into a boundary.
746 (while (not (eq pending-undo-list (cdr undo-at-start)))
747 (undo-more 1))))))
749 (defun rectangle--place-cursor (leftcol left str)
750 (let ((pc (window-parameter nil 'rectangle--point-crutches)))
751 (if (and (eq left (car pc)) (eq leftcol (cdr pc)))
752 (put-text-property 0 1 'cursor 1 str))))
754 (defun rectangle--highlight-for-redisplay (orig start end window rol)
755 (cond
756 ((not rectangle-mark-mode)
757 (funcall orig start end window rol))
758 (rectangle--inhibit-region-highlight
759 (funcall redisplay-unhighlight-region-function rol)
760 nil)
761 ((and (eq 'rectangle (car-safe rol))
762 (eq (nth 1 rol) (buffer-chars-modified-tick))
763 (eq start (nth 2 rol))
764 (eq end (nth 3 rol))
765 (equal (rectangle--crutches) (nth 4 rol)))
766 rol)
768 (save-excursion
769 (let* ((nrol nil)
770 (old (if (eq 'rectangle (car-safe rol))
771 (nthcdr 5 rol)
772 (funcall redisplay-unhighlight-region-function rol)
773 nil)))
774 (cl-assert (eq (window-buffer window) (current-buffer)))
775 ;; `rectangle--pos-cols' looks up the `selected-window's parameter!
776 (with-selected-window window
777 (apply-on-rectangle
778 (lambda (leftcol rightcol)
779 (let* ((mleft (move-to-column leftcol))
780 (left (point))
781 ;; BEWARE: In the presence of other overlays with
782 ;; before/after/display-strings, this happens to move to
783 ;; the column "as if the overlays were not applied", which
784 ;; is sometimes what we want, tho it can be
785 ;; considered a bug in move-to-column (it should arguably
786 ;; pay attention to the before/after-string/display
787 ;; properties when computing the column).
788 (mright (move-to-column rightcol))
789 (right (point))
791 (if (not old)
792 (let ((ol (make-overlay left right)))
793 (overlay-put ol 'window window)
794 (overlay-put ol 'face 'region)
796 (let ((ol (pop old)))
797 (move-overlay ol left right (current-buffer))
798 ol))))
799 ;; `move-to-column' may stop before the column (if bumping into
800 ;; EOL) or overshoot it a little, when column is in the middle
801 ;; of a char.
802 (cond
803 ((< mleft leftcol) ;`leftcol' is past EOL.
804 (overlay-put ol 'before-string (rectangle--space-to leftcol))
805 (setq mright (max mright leftcol)))
806 ((and (> mleft leftcol) ;`leftcol' is in the middle of a char.
807 (eq (char-before left) ?\t))
808 (setq left (1- left))
809 (move-overlay ol left right)
810 (goto-char left)
811 (overlay-put ol 'before-string (rectangle--space-to leftcol)))
812 ((overlay-get ol 'before-string)
813 (overlay-put ol 'before-string nil)))
814 (cond
815 ;; While doing rectangle--string-preview, the two sets of
816 ;; overlays steps on the other's toes. I fixed some of the
817 ;; problems, but others remain. The main one is the two
818 ;; (rectangle--space-to rightcol) below which try to virtually
819 ;; insert missing text, but during "preview", the text is not
820 ;; missing (it's provided by preview's own overlay).
821 (rectangle--string-preview-state
822 (if (overlay-get ol 'after-string)
823 (overlay-put ol 'after-string nil)))
824 ((< mright rightcol) ;`rightcol' is past EOL.
825 (let ((str (rectangle--space-to rightcol)))
826 (put-text-property 0 (length str) 'face 'region str)
827 ;; If cursor happens to be here, draw it at the right place.
828 (rectangle--place-cursor leftcol left str)
829 (overlay-put ol 'after-string str)))
830 ((and (> mright rightcol) ;`rightcol's in the middle of a char.
831 (eq (char-before right) ?\t))
832 (setq right (1- right))
833 (move-overlay ol left right)
834 (if (= rightcol leftcol)
835 (overlay-put ol 'after-string nil)
836 (goto-char right)
837 (let ((str (rectangle--space-to rightcol)))
838 (put-text-property 0 (length str) 'face 'region str)
839 (when (= left right)
840 (rectangle--place-cursor leftcol left str))
841 (overlay-put ol 'after-string str))))
842 ((overlay-get ol 'after-string)
843 (overlay-put ol 'after-string nil)))
844 (when (and (= leftcol rightcol) (display-graphic-p))
845 ;; Make zero-width rectangles visible!
846 (overlay-put ol 'after-string
847 (concat (propertize " "
848 'face '(region (:height 0.2)))
849 (overlay-get ol 'after-string))))
850 (push ol nrol)))
851 start end))
852 (mapc #'delete-overlay old)
853 `(rectangle ,(buffer-chars-modified-tick)
854 ,start ,end ,(rectangle--crutches)
855 ,@nrol))))))
857 (defun rectangle--unhighlight-for-redisplay (orig rol)
858 (if (not (eq 'rectangle (car-safe rol)))
859 (funcall orig rol)
860 (mapc #'delete-overlay (nthcdr 5 rol))
861 (setcar (cdr rol) nil)))
863 (provide 'rect)
865 ;;; rect.el ends here