Fixes: debbugs:19335
[emacs.git] / lisp / rect.el
blob75585d2f080c7ff55b5213a97bca862059b9830c
1 ;;; rect.el --- rectangle functions for GNU Emacs -*- lexical-binding:t -*-
3 ;; Copyright (C) 1985, 1999-2015 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 <http://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 (= c col)
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 (defvar killed-rectangle nil
261 "Rectangle for `yank-rectangle' to insert.")
263 ;;;###autoload
264 (defun kill-rectangle (start end &optional fill)
265 "Delete the region-rectangle and save it as the last killed one.
267 When called from a program the rectangle's corners are START and END.
268 You might prefer to use `delete-extract-rectangle' from a program.
270 With a prefix (or a FILL) argument, also fill lines where nothing has to be
271 deleted.
273 If the buffer is read-only, Emacs will beep and refrain from deleting
274 the rectangle, but put it in the kill ring anyway. This means that
275 you can use this command to copy text from a read-only buffer.
276 \(If the variable `kill-read-only-ok' is non-nil, then this won't
277 even beep.)"
278 (interactive "r\nP")
279 (condition-case nil
280 (setq killed-rectangle (delete-extract-rectangle start end fill))
281 ((buffer-read-only text-read-only)
282 (setq deactivate-mark t)
283 (setq killed-rectangle (extract-rectangle start end))
284 (if kill-read-only-ok
285 (progn (message "Read only text copied to kill ring") nil)
286 (barf-if-buffer-read-only)
287 (signal 'text-read-only (list (current-buffer)))))))
289 ;;;###autoload
290 (defun copy-rectangle-as-kill (start end)
291 "Copy the region-rectangle and save it as the last killed one."
292 (interactive "r")
293 (setq killed-rectangle (extract-rectangle start end))
294 (setq deactivate-mark t)
295 (if (called-interactively-p 'interactive)
296 (indicate-copied-region (length (car killed-rectangle)))))
298 ;;;###autoload
299 (defun yank-rectangle ()
300 "Yank the last killed rectangle with upper left corner at point."
301 (interactive "*")
302 (insert-rectangle killed-rectangle))
304 ;;;###autoload
305 (defun insert-rectangle (rectangle)
306 "Insert text of RECTANGLE with upper left corner at point.
307 RECTANGLE's first line is inserted at point, its second
308 line is inserted at a point vertically under point, etc.
309 RECTANGLE should be a list of strings.
310 After this command, the mark is at the upper left corner
311 and point is at the lower right corner."
312 (let ((lines rectangle)
313 (insertcolumn (current-column))
314 (first t))
315 (push-mark)
316 (while lines
317 (or first
318 (progn
319 (forward-line 1)
320 (or (bolp) (insert ?\n))
321 (move-to-column insertcolumn t)))
322 (setq first nil)
323 (insert-for-yank (car lines))
324 (setq lines (cdr lines)))))
326 ;;;###autoload
327 (defun open-rectangle (start end &optional fill)
328 "Blank out the region-rectangle, shifting text right.
330 The text previously in the region is not overwritten by the blanks,
331 but instead winds up to the right of the rectangle.
333 When called from a program the rectangle's corners are START and END.
334 With a prefix (or a FILL) argument, fill with blanks even if there is
335 no text on the right side of the rectangle."
336 (interactive "*r\nP")
337 (apply-on-rectangle 'open-rectangle-line start end fill)
338 (goto-char start))
340 (defun open-rectangle-line (startcol endcol fill)
341 (when (= (move-to-column startcol (if fill t 'coerce)) startcol)
342 (unless (and (not fill)
343 (= (point) (point-at-eol)))
344 (indent-to endcol))))
346 (defun delete-whitespace-rectangle-line (startcol _endcol fill)
347 (when (= (move-to-column startcol (if fill t 'coerce)) startcol)
348 (unless (= (point) (point-at-eol))
349 (delete-region (point) (progn (skip-syntax-forward " ") (point))))))
351 ;;;###autoload
352 (defalias 'close-rectangle 'delete-whitespace-rectangle) ;; Old name
354 ;;;###autoload
355 (defun delete-whitespace-rectangle (start end &optional fill)
356 "Delete all whitespace following a specified column in each line.
357 The left edge of the rectangle specifies the position in each line
358 at which whitespace deletion should begin. On each line in the
359 rectangle, all continuous whitespace starting at that column is deleted.
361 When called from a program the rectangle's corners are START and END.
362 With a prefix (or a FILL) argument, also fill too short lines."
363 (interactive "*r\nP")
364 (apply-on-rectangle 'delete-whitespace-rectangle-line start end fill))
366 (defvar string-rectangle-history nil)
367 (defun string-rectangle-line (startcol endcol string delete)
368 (move-to-column startcol t)
369 (if delete
370 (delete-rectangle-line startcol endcol nil))
371 (insert string))
373 (defvar-local rectangle--string-preview-state nil)
374 (defvar-local rectangle--string-preview-window nil)
376 (defun rectangle--string-flush-preview ()
377 (mapc #'delete-overlay (nthcdr 3 rectangle--string-preview-state))
378 (setf (nthcdr 3 rectangle--string-preview-state) nil))
380 (defun rectangle--string-erase-preview ()
381 (with-selected-window rectangle--string-preview-window
382 (rectangle--string-flush-preview)))
384 (defun rectangle--space-to (col)
385 (propertize " " 'display `(space :align-to ,col)))
387 (defface rectangle-preview-face '((t :inherit region))
388 "The face to use for the `string-rectangle' preview.")
390 (defcustom rectangle-preview t
391 "If non-nil, `string-rectangle' will show an-the-fly preview."
392 :type 'boolean)
394 (defun rectangle--string-preview ()
395 (let ((str (minibuffer-contents)))
396 (when (equal str "")
397 (setq str (or (car-safe minibuffer-default)
398 (if (stringp minibuffer-default) minibuffer-default))))
399 (when str (setq str (propertize str 'face 'region)))
400 (with-selected-window rectangle--string-preview-window
401 (unless (or (null rectangle--string-preview-state)
402 (equal str (car rectangle--string-preview-state)))
403 (rectangle--string-flush-preview)
404 (apply-on-rectangle
405 (lambda (startcol endcol)
406 (let* ((sc (move-to-column startcol))
407 (start (if (<= sc startcol) (point)
408 (forward-char -1)
409 (setq sc (current-column))
410 (point)))
411 (ec (move-to-column endcol))
412 (end (point))
413 (ol (make-overlay start end)))
414 (push ol (nthcdr 3 rectangle--string-preview-state))
415 ;; FIXME: The extra spacing doesn't interact correctly with
416 ;; the extra spacing added by the rectangular-region-highlight.
417 (when (< sc startcol)
418 (overlay-put ol 'before-string (rectangle--space-to startcol)))
419 (let ((as (when (< endcol ec)
420 ;; (rectangle--space-to ec)
421 (spaces-string (- ec endcol))
423 (if (= start end)
424 (overlay-put ol 'after-string (if as (concat str as) str))
425 (overlay-put ol 'display str)
426 (if as (overlay-put ol 'after-string as))))))
427 (nth 1 rectangle--string-preview-state)
428 (nth 2 rectangle--string-preview-state))))))
430 ;; FIXME: Should this be turned into inhibit-region-highlight and made to apply
431 ;; to non-rectangular regions as well?
432 (defvar rectangle--inhibit-region-highlight nil)
434 ;;;###autoload
435 (defun string-rectangle (start end string)
436 "Replace rectangle contents with STRING on each line.
437 The length of STRING need not be the same as the rectangle width.
439 Called from a program, takes three args; START, END and STRING."
440 (interactive
441 (progn
442 (make-local-variable 'rectangle--string-preview-state)
443 (make-local-variable 'rectangle--inhibit-region-highlight)
444 (let* ((buf (current-buffer))
445 (win (if (eq (window-buffer) buf) (selected-window)))
446 (start (region-beginning))
447 (end (region-end))
448 (rectangle--string-preview-state `(nil ,start ,end))
449 ;; Rectangle-region-highlighting doesn't work well in the presence
450 ;; of the preview overlays. We could work harder to try and make
451 ;; it work better, but it's easier to just disable it temporarily.
452 (rectangle--inhibit-region-highlight t))
453 (barf-if-buffer-read-only)
454 (list start end
455 (minibuffer-with-setup-hook
456 (lambda ()
457 (setq rectangle--string-preview-window win)
458 (add-hook 'minibuffer-exit-hook
459 #'rectangle--string-erase-preview nil t)
460 (add-hook 'post-command-hook
461 #'rectangle--string-preview nil t))
462 (read-string (format "String rectangle (default %s): "
463 (or (car string-rectangle-history) ""))
464 nil 'string-rectangle-history
465 (car string-rectangle-history)))))))
466 (goto-char
467 (apply-on-rectangle 'string-rectangle-line start end string t)))
469 ;;;###autoload
470 (defalias 'replace-rectangle 'string-rectangle)
472 ;;;###autoload
473 (defun string-insert-rectangle (start end string)
474 "Insert STRING on each line of region-rectangle, shifting text right.
476 When called from a program, the rectangle's corners are START and END.
477 The left edge of the rectangle specifies the column for insertion.
478 This command does not delete or overwrite any existing text."
479 (interactive
480 (progn (barf-if-buffer-read-only)
481 (list
482 (region-beginning)
483 (region-end)
484 (read-string (format "String insert rectangle (default %s): "
485 (or (car string-rectangle-history) ""))
486 nil 'string-rectangle-history
487 (car string-rectangle-history)))))
488 (apply-on-rectangle 'string-rectangle-line start end string nil))
490 ;;;###autoload
491 (defun clear-rectangle (start end &optional fill)
492 "Blank out the region-rectangle.
493 The text previously in the region is overwritten with blanks.
495 When called from a program the rectangle's corners are START and END.
496 With a prefix (or a FILL) argument, also fill with blanks the parts of the
497 rectangle which were empty."
498 (interactive "*r\nP")
499 (apply-on-rectangle 'clear-rectangle-line start end fill))
501 (defun clear-rectangle-line (startcol endcol fill)
502 (let ((pt (point-at-eol)))
503 (when (= (move-to-column startcol (if fill t 'coerce)) startcol)
504 (if (and (not fill)
505 (<= (save-excursion (goto-char pt) (current-column)) endcol))
506 (delete-region (point) pt)
507 ;; else
508 (setq pt (point))
509 (move-to-column endcol t)
510 (setq endcol (current-column))
511 (delete-region pt (point))
512 (indent-to endcol)))))
514 ;; Line numbers for `rectangle-number-line-callback'.
515 (defvar rectangle-number-line-counter)
517 (defun rectangle-number-line-callback (start _end format-string)
518 (move-to-column start t)
519 (insert (format format-string rectangle-number-line-counter))
520 (setq rectangle-number-line-counter
521 (1+ rectangle-number-line-counter)))
523 (defun rectangle--default-line-number-format (start end start-at)
524 (concat "%"
525 (int-to-string (length (int-to-string (+ (count-lines start end)
526 start-at))))
527 "d "))
529 ;;;###autoload
530 (defun rectangle-number-lines (start end start-at &optional format)
531 "Insert numbers in front of the region-rectangle.
533 START-AT, if non-nil, should be a number from which to begin
534 counting. FORMAT, if non-nil, should be a format string to pass
535 to `format' along with the line count. When called interactively
536 with a prefix argument, prompt for START-AT and FORMAT."
537 (interactive
538 (if current-prefix-arg
539 (let* ((start (region-beginning))
540 (end (region-end))
541 (start-at (read-number "Number to count from: " 1)))
542 (list start end start-at
543 (read-string "Format string: "
544 (rectangle--default-line-number-format
545 start end start-at))))
546 (list (region-beginning) (region-end) 1 nil)))
547 (unless format
548 (setq format (rectangle--default-line-number-format start end start-at)))
549 (let ((rectangle-number-line-counter start-at))
550 (apply-on-rectangle 'rectangle-number-line-callback
551 start end format)))
553 ;;; New rectangle integration with kill-ring.
555 ;; FIXME: known problems with the new rectangle support:
556 ;; - lots of commands handle the region without paying attention to its
557 ;; rectangular shape.
559 (add-function :around redisplay-highlight-region-function
560 #'rectangle--highlight-for-redisplay)
561 (add-function :around redisplay-unhighlight-region-function
562 #'rectangle--unhighlight-for-redisplay)
563 (add-function :around region-extract-function
564 #'rectangle--extract-region)
566 (defvar rectangle-mark-mode-map
567 (let ((map (make-sparse-keymap)))
568 (define-key map [?\C-o] 'open-rectangle)
569 (define-key map [?\C-t] 'string-rectangle)
570 (define-key map [remap exchange-point-and-mark]
571 'rectangle-exchange-point-and-mark)
572 (dolist (cmd '(right-char left-char forward-char backward-char
573 next-line previous-line))
574 (define-key map (vector 'remap cmd)
575 (intern (format "rectangle-%s" cmd))))
576 map)
577 "Keymap used while marking a rectangular region.")
579 ;;;###autoload
580 (define-minor-mode rectangle-mark-mode
581 "Toggle the region as rectangular.
582 Activates the region if needed. Only lasts until the region is deactivated."
583 nil nil nil
584 (rectangle--reset-crutches)
585 (when rectangle-mark-mode
586 (add-hook 'deactivate-mark-hook
587 (lambda () (rectangle-mark-mode -1)))
588 (unless (region-active-p)
589 (push-mark (point) t t)
590 (message "Mark set (rectangle mode)"))))
592 (defun rectangle-exchange-point-and-mark (&optional arg)
593 "Like `exchange-point-and-mark' but cycles through the rectangle's corners."
594 (interactive "P")
595 (if arg
596 (progn
597 (setq this-command 'exchange-point-and-mark)
598 (exchange-point-and-mark arg))
599 (let* ((p (point))
600 (repeat (eq this-command last-command))
601 (m (mark))
602 (p<m (< p m))
603 (cols (if p<m (rectangle--pos-cols p m) (rectangle--pos-cols m p)))
604 (cp (if p<m (car cols) (cdr cols)))
605 (cm (if p<m (cdr cols) (car cols))))
606 (if repeat (setq this-command 'exchange-point-and-mark))
607 (rectangle--reset-crutches)
608 (goto-char p)
609 (rectangle--col-pos (if repeat cm cp) 'mark)
610 (set-mark (point))
611 (goto-char m)
612 (rectangle--col-pos (if repeat cp cm) 'point))))
614 (defun rectangle--*-char (cmd n &optional other-cmd)
615 ;; Part of the complexity here is that I'm trying to avoid making assumptions
616 ;; about the L2R/R2L direction of text around point, but this is largely
617 ;; useless since the rectangles implemented in this file are "logical
618 ;; rectangles" and not "visual rectangles", so in the presence of
619 ;; bidirectional text things won't work well anyway.
620 (if (< n 0) (rectangle--*-char other-cmd (- n))
621 (let ((col (rectangle--point-col (point))))
622 (while (> n 0)
623 (let* ((bol (line-beginning-position))
624 (eol (line-end-position))
625 (curcol (current-column))
626 (nextcol
627 (condition-case nil
628 (save-excursion
629 (funcall cmd 1)
630 (cond
631 ((> bol (point)) (- curcol 1))
632 ((< eol (point)) (+ col (1+ n)))
633 (t (current-column))))
634 (end-of-buffer (+ col (1+ n)))
635 (beginning-of-buffer (- curcol 1))))
636 (diff (abs (- nextcol col))))
637 (cond
638 ((and (< nextcol curcol) (< curcol col))
639 (let ((curdiff (- col curcol)))
640 (if (<= curdiff n)
641 (progn (cl-decf n curdiff) (setq col curcol))
642 (setq col (- col n) n 0))))
643 ((< nextcol 0) (ding) (setq n 0 col 0)) ;Bumping into BOL!
644 ((= nextcol curcol) (funcall cmd 1))
645 (t ;; (> nextcol curcol)
646 (if (<= diff n)
647 (progn (cl-decf n diff) (setq col nextcol))
648 (setq col (if (< col nextcol) (+ col n) (- col n)) n 0))))))
649 ;; FIXME: This rectangle--col-pos's move-to-column is wasted!
650 (rectangle--col-pos col 'point))))
652 (defun rectangle-right-char (&optional n)
653 "Like `right-char' but steps into wide chars and moves past EOL."
654 (interactive "p") (rectangle--*-char #'right-char n #'left-char))
655 (defun rectangle-left-char (&optional n)
656 "Like `left-char' but steps into wide chars and moves past EOL."
657 (interactive "p") (rectangle--*-char #'left-char n #'right-char))
659 (defun rectangle-forward-char (&optional n)
660 "Like `forward-char' but steps into wide chars and moves past EOL."
661 (interactive "p") (rectangle--*-char #'forward-char n #'backward-char))
662 (defun rectangle-backward-char (&optional n)
663 "Like `backward-char' but steps into wide chars and moves past EOL."
664 (interactive "p") (rectangle--*-char #'backward-char n #'forward-char))
666 (defun rectangle-next-line (&optional n)
667 "Like `next-line' but steps into wide chars and moves past EOL.
668 Ignores `line-move-visual'."
669 (interactive "p")
670 (let ((col (rectangle--point-col (point))))
671 (forward-line n)
672 (rectangle--col-pos col 'point)))
673 (defun rectangle-previous-line (&optional n)
674 "Like `previous-line' but steps into wide chars and moves past EOL.
675 Ignores `line-move-visual'."
676 (interactive "p")
677 (let ((col (rectangle--point-col (point))))
678 (forward-line (- n))
679 (rectangle--col-pos col 'point)))
682 (defun rectangle--extract-region (orig &optional delete)
683 (if (not rectangle-mark-mode)
684 (funcall orig delete)
685 (let* ((strs (funcall (if delete
686 #'delete-extract-rectangle
687 #'extract-rectangle)
688 (region-beginning) (region-end)))
689 (str (mapconcat #'identity strs "\n")))
690 (when (eq last-command 'kill-region)
691 ;; Try to prevent kill-region from appending this to some
692 ;; earlier element.
693 (setq last-command 'kill-region-dont-append))
694 (when strs
695 (put-text-property 0 (length str) 'yank-handler
696 `(rectangle--insert-for-yank ,strs t)
697 str)
698 str))))
700 (defun rectangle--insert-for-yank (strs)
701 (push (point) buffer-undo-list)
702 (let ((undo-at-start buffer-undo-list))
703 (insert-rectangle strs)
704 (setq yank-undo-function
705 (lambda (_start _end)
706 (undo-start)
707 (setcar undo-at-start nil) ;Turn it into a boundary.
708 (while (not (eq pending-undo-list (cdr undo-at-start)))
709 (undo-more 1))))))
711 (defun rectangle--place-cursor (leftcol left str)
712 (let ((pc (window-parameter nil 'rectangle--point-crutches)))
713 (if (and (eq left (car pc)) (eq leftcol (cdr pc)))
714 (put-text-property 0 1 'cursor 1 str))))
716 (defun rectangle--highlight-for-redisplay (orig start end window rol)
717 (cond
718 ((not rectangle-mark-mode)
719 (funcall orig start end window rol))
720 (rectangle--inhibit-region-highlight
721 (funcall redisplay-unhighlight-region-function rol)
722 nil)
723 ((and (eq 'rectangle (car-safe rol))
724 (eq (nth 1 rol) (buffer-chars-modified-tick))
725 (eq start (nth 2 rol))
726 (eq end (nth 3 rol))
727 (equal (rectangle--crutches) (nth 4 rol)))
728 rol)
730 (save-excursion
731 (let* ((nrol nil)
732 (old (if (eq 'rectangle (car-safe rol))
733 (nthcdr 5 rol)
734 (funcall redisplay-unhighlight-region-function rol)
735 nil)))
736 (cl-assert (eq (window-buffer window) (current-buffer)))
737 ;; `rectangle--pos-cols' looks up the `selected-window's parameter!
738 (with-selected-window window
739 (apply-on-rectangle
740 (lambda (leftcol rightcol)
741 (let* ((mleft (move-to-column leftcol))
742 (left (point))
743 ;; BEWARE: In the presence of other overlays with
744 ;; before/after/display-strings, this happens to move to
745 ;; the column "as if the overlays were not applied", which
746 ;; is sometimes what we want, tho it can be
747 ;; considered a bug in move-to-column (it should arguably
748 ;; pay attention to the before/after-string/display
749 ;; properties when computing the column).
750 (mright (move-to-column rightcol))
751 (right (point))
753 (if (not old)
754 (let ((ol (make-overlay left right)))
755 (overlay-put ol 'window window)
756 (overlay-put ol 'face 'region)
758 (let ((ol (pop old)))
759 (move-overlay ol left right (current-buffer))
760 ol))))
761 ;; `move-to-column' may stop before the column (if bumping into
762 ;; EOL) or overshoot it a little, when column is in the middle
763 ;; of a char.
764 (cond
765 ((< mleft leftcol) ;`leftcol' is past EOL.
766 (overlay-put ol 'before-string (rectangle--space-to leftcol))
767 (setq mright (max mright leftcol)))
768 ((and (> mleft leftcol) ;`leftcol' is in the middle of a char.
769 (eq (char-before left) ?\t))
770 (setq left (1- left))
771 (move-overlay ol left right)
772 (goto-char left)
773 (overlay-put ol 'before-string (rectangle--space-to leftcol)))
774 ((overlay-get ol 'before-string)
775 (overlay-put ol 'before-string nil)))
776 (cond
777 ;; While doing rectangle--string-preview, the two sets of
778 ;; overlays steps on the other's toes. I fixed some of the
779 ;; problems, but others remain. The main one is the two
780 ;; (rectangle--space-to rightcol) below which try to virtually
781 ;; insert missing text, but during "preview", the text is not
782 ;; missing (it's provided by preview's own overlay).
783 (rectangle--string-preview-state
784 (if (overlay-get ol 'after-string)
785 (overlay-put ol 'after-string nil)))
786 ((< mright rightcol) ;`rightcol' is past EOL.
787 (let ((str (rectangle--space-to rightcol)))
788 (put-text-property 0 (length str) 'face 'region str)
789 ;; If cursor happens to be here, draw it at the right place.
790 (rectangle--place-cursor leftcol left str)
791 (overlay-put ol 'after-string str)))
792 ((and (> mright rightcol) ;`rightcol's in the middle of a char.
793 (eq (char-before right) ?\t))
794 (setq right (1- right))
795 (move-overlay ol left right)
796 (if (= rightcol leftcol)
797 (overlay-put ol 'after-string nil)
798 (goto-char right)
799 (let ((str (rectangle--space-to rightcol)))
800 (put-text-property 0 (length str) 'face 'region str)
801 (when (= left right)
802 (rectangle--place-cursor leftcol left str))
803 (overlay-put ol 'after-string str))))
804 ((overlay-get ol 'after-string)
805 (overlay-put ol 'after-string nil)))
806 (when (and (= leftcol rightcol) (display-graphic-p))
807 ;; Make zero-width rectangles visible!
808 (overlay-put ol 'after-string
809 (concat (propertize " "
810 'face '(region (:height 0.2)))
811 (overlay-get ol 'after-string))))
812 (push ol nrol)))
813 start end))
814 (mapc #'delete-overlay old)
815 `(rectangle ,(buffer-chars-modified-tick)
816 ,start ,end ,(rectangle--crutches)
817 ,@nrol))))))
819 (defun rectangle--unhighlight-for-redisplay (orig rol)
820 (if (not (eq 'rectangle (car-safe rol)))
821 (funcall orig rol)
822 (mapc #'delete-overlay (nthcdr 5 rol))
823 (setcar (cdr rol) nil)))
825 (provide 'rect)
827 ;;; rect.el ends here