cua-base.el 58.4 KB
Newer Older
1 2
;;; cua-base.el --- emulate CUA key bindings

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

;; Author: Kim F. Storm <storm@cua.dk>
6
;; Keywords: keyboard emulations convenience cua
7 8 9

;; This file is part of GNU Emacs.

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

;; 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
21
;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
22 23 24 25 26 27 28 29 30


;;; Commentary:

;; This is the CUA package which provides a complete emulation of the
;; standard CUA key bindings (Motif/Windows/Mac GUI) for selecting and
;; manipulating the region where S-<movement> is used to highlight &
;; extend the region.

31 32 33 34
;; CUA style key bindings for cut and paste
;; ----------------------------------------

;; This package allows the C-z, C-x, C-c, and C-v keys to be
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
;; bound appropriately according to the Motif/Windows GUI, i.e.
;;	C-z	-> undo
;;	C-x	-> cut
;;	C-c	-> copy
;;	C-v	-> paste
;;
;; The tricky part is the handling of the C-x and C-c keys which
;; are normally used as prefix keys for most of emacs' built-in
;; commands.  With CUA they still do!!!
;;
;; Only when the region is currently active (and highlighted since
;; transient-mark-mode is used), the C-x and C-c keys will work as CUA
;; keys
;; 	C-x -> cut
;; 	C-c -> copy
;; When the region is not active, C-x and C-c works as prefix keys!
;;
;; This probably sounds strange and difficult to get used to - but
;; based on my own experience and the feedback from many users of
;; this package, it actually works very well and users adapt to it
55
;; instantly - or at least very quickly.  So give it a try!
56 57 58 59 60 61
;; ... and in the few cases where you make a mistake and accidentally
;; delete the region - you just undo the mistake (with C-z).
;;
;; If you really need to perform a command which starts with one of
;; the prefix keys even when the region is active, you have three options:
;; - press the prefix key twice very quickly (within 0.2 seconds),
62
;; - press the prefix key and the following key within 0.2 seconds, or
63 64
;; - use the SHIFT key with the prefix key, i.e. C-X or C-C
;;
Glenn Morris's avatar
Glenn Morris committed
65
;; This behavior can be customized via the
66 67 68 69 70 71 72 73 74
;; cua-prefix-override-inhibit-delay variable.

;; In addition to using the shifted movement keys, you can also use
;; [C-space] to start the region and use unshifted movement keys to extend
;; it. To cancel the region, use [C-space] or [C-g].

;; If you prefer to use the standard emacs cut, copy, paste, and undo
;; bindings, customize cua-enable-cua-keys to nil.

75 76 77 78 79 80 81 82 83 84 85 86

;; Typing text replaces the region
;; -------------------------------

;; When the region is active, i.e. highlighted, the text in region is
;; replaced by the text you type.

;; The replaced text is saved in register 0 which can be inserted using
;; the key sequence M-0 C-v (see the section on register support below).

;; If you have just replaced a highlighted region with typed text,
;; you can repeat the replace with M-v.  This will search forward
Paul Eggert's avatar
Paul Eggert committed
87
;; for a stretch of text identical to the previous contents of the
88 89 90 91 92 93 94 95 96 97 98 99
;; region (i.e. the contents of register 0) and replace it with the
;; text you typed to replace the original region.  Repeating M-v will
;; replace the next matching region and so on.
;;
;; Example:  Suppose you have a line like this
;;   The redo operation will redo the last redoable command
;; which you want to change into
;;   The repeat operation will repeat the last repeatable command
;; This is done by highlighting the first occurrence of "redo"
;; and type "repeat" M-v M-v.


100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
;; CUA mode indications
;; --------------------
;; You can choose to let CUA use different cursor colors to indicate
;; overwrite mode and read-only buffers.  For example, the following
;; setting will use a RED cursor in normal (insertion) mode in
;; read-write buffers, a YELLOW cursor in overwrite mode in read-write
;; buffers, and a GREEN cursor read-only buffers:
;;
;;  (setq cua-normal-cursor-color "red")
;;  (setq cua-overwrite-cursor-color "yellow")
;;  (setq cua-read-only-cursor-color "green")
;;

;; CUA register support
;; --------------------
115
;; Emacs's standard register support is also based on a separate set of
116
;; "register commands".
117
;;
118 119 120 121
;; CUA's register support is activated by providing a numeric
;; prefix argument to the C-x, C-c, and C-v commands. For example,
;; to copy the selected region to register 2, enter [M-2 C-c].
;; Or if you have activated the keypad prefix mode, enter [kp-2 C-c].
122
;;
123 124
;; And CUA will copy and paste normal region as well as rectangles
;; into the registers, i.e. you use exactly the same command for both.
125
;;
126 127 128 129 130 131 132
;; In addition, the last highlighted text that is deleted (not
;; copied), e.g. by [delete] or by typing text over a highlighted
;; region, is automatically saved in register 0, so you can insert it
;; using [M-0 C-v].

;; CUA rectangle support
;; ---------------------
133
;; Emacs's normal rectangle support is based on interpreting the region
134 135 136
;; between the mark and point as a "virtual rectangle", and using a
;; completely separate set of "rectangle commands" [C-x r ...] on the
;; region to copy, kill, fill a.s.o. the virtual rectangle.
137
;;
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
;; cua-mode's superior rectangle support uses a true visual
;; representation of the selected rectangle, i.e. it highlights the
;; actual part of the buffer that is currently selected as part of the
;; rectangle.  Unlike emacs' traditional rectangle commands, the
;; selected rectangle always as straight left and right edges, even
;; when those are in the middle of a TAB character or beyond the end
;; of the current line.  And it does this without actually modifying
;; the buffer contents (it uses display overlays to visualize the
;; virtual dimensions of the rectangle).
;;
;; This means that cua-mode's rectangles are not limited to the actual
;; contents of the buffer, so if the cursor is currently at the end of a
;; short line, you can still extend the rectangle to include more columns
;; of longer lines in the same rectangle.  And you can also have the
;; left edge of a rectangle start in the middle of a TAB character.
;; Sounds strange? Try it!
;;
Kim F. Storm's avatar
Kim F. Storm committed
155
;; To start a rectangle, use [C-return] and extend it using the normal
156 157 158 159 160
;; movement keys (up, down, left, right, home, end, C-home,
;; C-end). Once the rectangle has the desired size, you can cut or
;; copy it using C-x and C-c (or C-w and M-w), and you can
;; subsequently insert it - as a rectangle - using C-v (or C-y).  So
;; the only new command you need to know to work with cua-mode
Kim F. Storm's avatar
Kim F. Storm committed
161
;; rectangles is C-return!
162 163 164 165 166
;;
;; Normally, when you paste a rectangle using C-v (C-y), each line of
;; the rectangle is inserted into the existing lines in the buffer.
;; If overwrite-mode is active when you paste a rectangle, it is
;; inserted as normal (multi-line) text.
167
;;
168 169 170
;; If you prefer the traditional rectangle marking (i.e. don't want
;; straight edges), [M-p] toggles this for the current rectangle,
;; or you can customize cua-virtual-rectangle-edges.
171 172 173 174 175 176 177 178

;; And there's more: If you want to extend or reduce the size of the
;; rectangle in one of the other corners of the rectangle, just use
;; [return] to move the cursor to the "next" corner.  Or you can use
;; the [M-up], [M-down], [M-left], and [M-right] keys to move the
;; entire rectangle overlay (but not the contents) in the given
;; direction.
;;
Kim F. Storm's avatar
Kim F. Storm committed
179
;; [C-return] cancels the rectangle
180 181 182 183 184 185 186 187 188 189
;; [C-space] activates the region bounded by the rectangle

;; If you type a normal (self-inserting) character when the rectangle is
;; active, the character is inserted on the "current side" of every line
;; of the rectangle.  The "current side" is the side on which the cursor
;; is currently located. If the rectangle is only 1 column wide,
;; insertion will be performed to the left when the cursor is at the
;; bottom of the rectangle.  So, for example, to comment out an entire
;; paragraph like this one, just place the cursor on the first character
;; of the first line, and enter the following:
Kim F. Storm's avatar
Kim F. Storm committed
190
;;     C-return M-} ; ; <space>  C-return
191

192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
;; cua-mode's rectangle support also includes all the normal rectangle
;; functions with easy access:
;;
;; [M-a] aligns all words at the left edge of the rectangle
;; [M-b] fills the rectangle with blanks (tabs and spaces)
;; [M-c] closes the rectangle by removing all blanks at the left edge
;;       of the rectangle
;; [M-f] fills the rectangle with a single character (prompt)
;; [M-i] increases the first number found on each line of the rectangle
;;       by the amount given by the numeric prefix argument (default 1)
;;       It recognizes 0x... as hexadecimal numbers
;; [M-k] kills the rectangle as normal multi-line text (for paste)
;; [M-l] downcases the rectangle
;; [M-m] copies the rectangle as normal multi-line text (for paste)
;; [M-n] fills each line of the rectangle with increasing numbers using
;;       a supplied format string (prompt)
208
;; [M-o] opens the rectangle by moving the highlighted text to the
209
;;       right of the rectangle and filling the rectangle with blanks.
210 211
;; [M-p] toggles virtual straight rectangle edges
;; [M-P] inserts tabs and spaces (padding) to make real straight edges
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
;; [M-q] performs text filling on the rectangle
;; [M-r] replaces REGEXP (prompt) by STRING (prompt) in rectangle
;; [M-R] reverse the lines in the rectangle
;; [M-s] fills each line of the rectangle with the same STRING (prompt)
;; [M-t] performs text fill of the rectangle with TEXT (prompt)
;; [M-u] upcases the rectangle
;; [M-|] runs shell command on rectangle
;; [M-'] restricts rectangle to lines with CHAR (prompt) at left column
;; [M-/] restricts rectangle to lines matching REGEXP (prompt)
;; [C-?] Shows a brief list of the above commands.

;; [M-C-up] and [M-C-down] scrolls the lines INSIDE the rectangle up
;; and down; lines scrolled outside the top or bottom of the rectangle
;; are lost, but can be recovered using [C-z].

;; CUA Global Mark
228
;; ---------------
229 230 231 232 233 234
;; The final feature provided by CUA is the "global mark", which
;; makes it very easy to copy bits and pieces from the same and other
;; files into the current text.  To enable and cancel the global mark,
;; use [S-C-space].  The cursor will blink when the global mark
;; is active.  The following commands behave differently when the global
;; mark is set:
235
;; <ch>  All characters (including newlines) you type are inserted
236 237 238 239 240 241 242 243 244
;;       at the global mark!
;; [C-x] If you cut a region or rectangle, it is automatically inserted
;;       at the global mark, and the global mark is advanced.
;; [C-c] If you copy a region or rectangle, it is immediately inserted
;;       at the global mark, and the global mark is advanced.
;; [C-v] Copies a single character to the global mark.
;; [C-d] Moves (i.e. deletes and inserts) a single character to the
;;       global mark.
;; [backspace] deletes the character before the global mark, while
245
;; [delete] deletes the character after the global mark.
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262

;; [S-C-space] Jumps to and cancels the global mark.
;; [C-u S-C-space] Cancels the global mark (stays in current buffer).

;; [TAB] Indents the current line or rectangle to the column of the
;;       global mark.

;;; Code:

;;; Customization

(defgroup cua nil
  "Emulate CUA key bindings including C-x and C-c."
  :prefix "cua"
  :group 'editing-basics
  :group 'convenience
  :group 'emulations
263
  :version "22.1"
264 265 266 267
  :link '(emacs-commentary-link :tag "Commentary" "cua-base.el")
  :link '(emacs-library-link :tag "Lisp File" "cua-base.el"))

(defcustom cua-enable-cua-keys t
268
  "Enable using C-z, C-x, C-c, and C-v for undo, cut, copy, and paste.
269
If the value is t, these mappings are always enabled.  If the value is
270
`shift', these keys are only enabled if the last region was marked with
271 272
a shifted movement key.  If the value is nil, these keys are never
enabled."
273
  :type '(choice (const :tag "Disabled" nil)
274
		 (const :tag "Shift region only" shift)
Kim F. Storm's avatar
Kim F. Storm committed
275
		 (other :tag "Enabled" t))
276 277
  :group 'cua)

Kim F. Storm's avatar
Kim F. Storm committed
278
(defcustom cua-remap-control-v t
279
  "If non-nil, C-v binding is used for paste (yank).
Kim F. Storm's avatar
Kim F. Storm committed
280 281 282 283 284
Also, M-v is mapped to `cua-repeat-replace-region'."
  :type 'boolean
  :group 'cua)

(defcustom cua-remap-control-z t
285
  "If non-nil, C-z binding is used for undo."
Kim F. Storm's avatar
Kim F. Storm committed
286 287 288
  :type 'boolean
  :group 'cua)

289
(defcustom cua-highlight-region-shift-only nil
290
  "If non-nil, only highlight region if marked with S-<move>.
291 292
When this is non-nil, CUA toggles `transient-mark-mode' on when the region
is marked using shifted movement keys, and off when the mark is cleared.
293
But when the mark was set using \\[cua-set-mark], Transient Mark mode
294 295 296 297
is not turned on."
  :type 'boolean
  :group 'cua)

298
(defcustom cua-prefix-override-inhibit-delay 0.2
299
  "If non-nil, time in seconds to delay before overriding prefix key.
300 301 302 303 304 305 306 307 308 309 310
If there is additional input within this time, the prefix key is
used as a normal prefix key.  So typing a key sequence quickly will
inhibit overriding the prefix key.
As a special case, if the prefix keys repeated within this time, the
first prefix key is discarded, so typing a prefix key twice in quick
succession will also inhibit overriding the prefix key.
If the value is nil, use a shifted prefix key to inhibit the override."
  :type '(choice (number :tag "Inhibit delay")
		 (const :tag "No delay" nil))
  :group 'cua)

311
(defcustom cua-delete-selection t
312
  "If non-nil, typed text replaces text in the active selection."
313 314 315 316
  :type '(choice (const :tag "Disabled" nil)
		 (other :tag "Enabled" t))
  :group 'cua)

317 318 319 320 321
(defcustom cua-keep-region-after-copy nil
  "If non-nil, don't deselect the region after copying."
  :type 'boolean
  :group 'cua)

322
(defcustom cua-toggle-set-mark t
323
  "If non-nil, the `cua-set-mark' command toggles the mark."
324 325 326 327
  :type '(choice (const :tag "Disabled" nil)
		 (other :tag "Enabled" t))
  :group 'cua)

Kim F. Storm's avatar
Kim F. Storm committed
328
(defcustom cua-auto-mark-last-change nil
329
  "If non-nil, set implicit mark at position of last buffer change.
Kim F. Storm's avatar
Kim F. Storm committed
330 331 332 333 334 335
This means that \\[universal-argument] \\[cua-set-mark] will jump to the position
of the last buffer change before jumping to the explicit marks on the mark ring.
See `cua-set-mark' for details."
  :type 'boolean
  :group 'cua)

336
(defcustom cua-enable-register-prefix 'not-ctrl-u
337
  "If non-nil, registers are supported via numeric prefix arg.
338
If the value is t, any numeric prefix arg in the range 0 to 9 will be
339
interpreted as a register number.
340
If the value is `not-ctrl-u', using C-u to enter a numeric prefix is not
341
interpreted as a register number.
342
If the value is `ctrl-u-only', only numeric prefix entered with C-u is
343
interpreted as a register number."
344
  :type '(choice (const :tag "Disabled" nil)
345 346
		 (const :tag "Enabled, but C-u arg is not a register" not-ctrl-u)
		 (const :tag "Enabled, but only for C-u arg" ctrl-u-only)
Kim F. Storm's avatar
Kim F. Storm committed
347
		 (other :tag "Enabled" t))
348 349 350
  :group 'cua)

(defcustom cua-delete-copy-to-register-0 t
351
  "If non-nil, save last deleted region or rectangle to register 0."
352 353 354 355
  :type 'boolean
  :group 'cua)

(defcustom cua-enable-region-auto-help nil
356
  "If non-nil, automatically show help for active region."
357 358 359 360
  :type 'boolean
  :group 'cua)

(defcustom cua-enable-modeline-indications nil
361
  "If non-nil, use minor-mode hook to show status in mode line."
362 363 364 365
  :type 'boolean
  :group 'cua)

(defcustom cua-check-pending-input t
366
  "If non-nil, don't override prefix key if input pending.
Paul Eggert's avatar
Paul Eggert committed
367
It is rumored that `input-pending-p' is unreliable under some window
368 369 370 371
managers, so try setting this to nil, if prefix override doesn't work."
  :type 'boolean
  :group 'cua)

Kim F. Storm's avatar
Kim F. Storm committed
372
(defcustom cua-paste-pop-rotate-temporarily nil
373
  "If non-nil, \\[cua-paste-pop] only rotates the kill-ring temporarily.
374 375 376 377 378
This means that both \\[yank] and the first \\[yank-pop] in a sequence always insert
the most recently killed text.  Each immediately following \\[cua-paste-pop] replaces
the previous text with the next older element on the `kill-ring'.
With prefix arg, \\[universal-argument] \\[yank-pop] inserts the same text as the most
recent \\[yank-pop] (or \\[yank]) command."
Kim F. Storm's avatar
Kim F. Storm committed
379 380
  :type 'boolean
  :group 'cua)
381 382 383

;;; Rectangle Customization

384
(defcustom cua-virtual-rectangle-edges t
385
  "If non-nil, rectangles have virtual straight edges.
386 387
Note that although rectangles are always DISPLAYED with straight edges, the
buffer is NOT modified, until you execute a command that actually modifies it.
388
M-p toggles this feature when a rectangle is active."
389 390 391
  :type 'boolean
  :group 'cua)

392
(defcustom cua-auto-tabify-rectangles 1000
393
  "If non-nil, automatically tabify after rectangle commands.
394 395
This basically means that `tabify' is applied to all lines that
are modified by inserting or deleting a rectangle.  If value is
396
an integer, CUA will look for existing tabs in a region around
397 398 399 400 401 402 403 404
the rectangle, and only do the conversion if any tabs are already
present.  The number specifies then number of characters before
and after the region marked by the rectangle to search."
  :type '(choice (number :tag "Auto detect (limit)")
		 (const :tag "Disabled" nil)
		 (other :tag "Enabled" t))
  :group 'cua)

405 406 407
(defvar cua-global-keymap)		; forward
(defvar cua--region-keymap)		; forward

408 409 410 411
(defcustom cua-rectangle-mark-key [(control return)]
  "Global key used to toggle the cua rectangle mark."
  :set #'(lambda (symbol value)
	   (set symbol value)
412 413
	   (when (and (boundp 'cua--keymaps-initialized)
		      cua--keymaps-initialized)
414 415 416 417 418 419 420 421 422 423
	     (define-key cua-global-keymap value
	       'cua-set-rectangle-mark)
	     (when (boundp 'cua--rectangle-keymap)
	       (define-key cua--rectangle-keymap value
		 'cua-clear-rectangle-mark)
	       (define-key cua--region-keymap value
		 'cua-toggle-rectangle-mark))))
  :type 'key-sequence
  :group 'cua)

424
(defcustom cua-rectangle-modifier-key 'meta
425
  "Modifier key used for rectangle commands bindings.
426 427 428
On non-window systems, always use the meta modifier.
Must be set prior to enabling CUA."
  :type '(choice (const :tag "Meta key" meta)
429 430
		 (const :tag "Alt key" alt)
		 (const :tag "Hyper key" hyper)
431 432 433
		 (const :tag "Super key" super))
  :group 'cua)

434
(defcustom cua-enable-rectangle-auto-help t
435
  "If non-nil, automatically show help for region, rectangle and global mark."
436 437 438
  :type 'boolean
  :group 'cua)

439
(defface cua-rectangle
Kim F. Storm's avatar
Kim F. Storm committed
440 441
  '((default :inherit region)
    (((class color)) :foreground "white" :background "maroon"))
442
  "Font used by CUA for highlighting the rectangle."
443 444
  :group 'cua)

445
(defface cua-rectangle-noselect
Kim F. Storm's avatar
Kim F. Storm committed
446 447
  '((default :inherit region)
    (((class color)) :foreground "white" :background "dimgray"))
448
  "Font used by CUA for highlighting the non-selected rectangle lines."
449 450 451 452 453 454
  :group 'cua)


;;; Global Mark Customization

(defcustom cua-global-mark-keep-visible t
455
  "If non-nil, always keep global mark visible in other window."
456 457 458
  :type 'boolean
  :group 'cua)

459
(defface cua-global-mark
460 461
  '((((min-colors 88)(class color)) :foreground "black" :background "yellow1")
    (((class color)) :foreground "black" :background "yellow")
462
    (t :weight bold))
463
  "Font used by CUA for highlighting the global mark."
464 465 466
  :group 'cua)

(defcustom cua-global-mark-blink-cursor-interval 0.20
467
  "Blink cursor at this interval when global mark is active."
468 469 470 471 472 473 474
  :type '(choice (number :tag "Blink interval")
		 (const :tag "No blink" nil))
  :group 'cua)


;;; Cursor Indication Customization

475
(defcustom cua-enable-cursor-indications nil
476
  "If non-nil, use different cursor colors for indications."
477 478 479
  :type 'boolean
  :group 'cua)

480 481 482 483 484 485 486 487 488
(defcustom cua-normal-cursor-color (or (and (boundp 'initial-cursor-color) initial-cursor-color)
				       (and (boundp 'initial-frame-alist)
					    (assoc 'cursor-color initial-frame-alist)
					    (cdr (assoc 'cursor-color initial-frame-alist)))
				       (and (boundp 'default-frame-alist)
					    (assoc 'cursor-color default-frame-alist)
					    (cdr (assoc 'cursor-color default-frame-alist)))
				       (frame-parameter nil 'cursor-color)
				       "red")
489
  "Normal (non-overwrite) cursor color.
490 491 492
Default is to load cursor color from initial or default frame parameters.

If the value is a COLOR name, then only the `cursor-color' attribute will be
493
affected.  If the value is a cursor TYPE (one of: box, hollow, bar, or hbar),
494 495
then only the `cursor-type' property will be affected.  If the value is
a cons (TYPE . COLOR), then both properties are affected."
496
  :initialize 'custom-initialize-default
497 498 499 500 501
  :type '(choice
	  (color :tag "Color")
	  (choice :tag "Type"
		  (const :tag "Filled box" box)
		  (const :tag "Vertical bar" bar)
502
		  (const :tag "Horizontal bar" hbar)
503
		  (const :tag "Hollow box" hollow))
504 505 506 507
	  (cons :tag "Color and Type"
		(choice :tag "Type"
			(const :tag "Filled box" box)
			(const :tag "Vertical bar" bar)
508
			(const :tag "Horizontal bar" hbar)
509
			(const :tag "Hollow box" hollow))
510
		(color :tag "Color")))
511 512 513
  :group 'cua)

(defcustom cua-read-only-cursor-color "darkgreen"
514
  "Cursor color used in read-only buffers, if non-nil.
515 516 517
Only used when `cua-enable-cursor-indications' is non-nil.

If the value is a COLOR name, then only the `cursor-color' attribute will be
518
affected.  If the value is a cursor TYPE (one of: box, hollow, bar, or hbar),
519 520 521 522 523 524 525
then only the `cursor-type' property will be affected.  If the value is
a cons (TYPE . COLOR), then both properties are affected."
  :type '(choice
	  (color :tag "Color")
	  (choice :tag "Type"
		  (const :tag "Filled box" box)
		  (const :tag "Vertical bar" bar)
526
		  (const :tag "Horizontal bar" hbar)
527
		  (const :tag "Hollow box" hollow))
528 529 530 531
	  (cons :tag "Color and Type"
		(choice :tag "Type"
			(const :tag "Filled box" box)
			(const :tag "Vertical bar" bar)
532
			(const :tag "Horizontal bar" hbar)
533
			(const :tag "Hollow box" hollow))
534
		(color :tag "Color")))
535 536 537
  :group 'cua)

(defcustom cua-overwrite-cursor-color "yellow"
538
  "Cursor color used when overwrite mode is set, if non-nil.
539 540 541
Only used when `cua-enable-cursor-indications' is non-nil.

If the value is a COLOR name, then only the `cursor-color' attribute will be
542
affected.  If the value is a cursor TYPE (one of: box, hollow, bar, or hbar),
543 544 545 546 547 548 549
then only the `cursor-type' property will be affected.  If the value is
a cons (TYPE . COLOR), then both properties are affected."
  :type '(choice
	  (color :tag "Color")
	  (choice :tag "Type"
		  (const :tag "Filled box" box)
		  (const :tag "Vertical bar" bar)
550
		  (const :tag "Horizontal bar" hbar)
551
		  (const :tag "Hollow box" hollow))
552 553 554 555
	  (cons :tag "Color and Type"
		(choice :tag "Type"
			(const :tag "Filled box" box)
			(const :tag "Vertical bar" bar)
556
			(const :tag "Horizontal bar" hbar)
557
			(const :tag "Hollow box" hollow))
558
		(color :tag "Color")))
559 560 561
  :group 'cua)

(defcustom cua-global-mark-cursor-color "cyan"
562
  "Indication for active global mark.
Kim F. Storm's avatar
Kim F. Storm committed
563
Will change cursor color to specified color if string.
564 565 566
Only used when `cua-enable-cursor-indications' is non-nil.

If the value is a COLOR name, then only the `cursor-color' attribute will be
567
affected.  If the value is a cursor TYPE (one of: box, hollow, bar, or hbar),
568 569 570 571 572 573 574
then only the `cursor-type' property will be affected.  If the value is
a cons (TYPE . COLOR), then both properties are affected."
  :type '(choice
	  (color :tag "Color")
	  (choice :tag "Type"
		  (const :tag "Filled box" box)
		  (const :tag "Vertical bar" bar)
575
		  (const :tag "Horizontal bar" hbar)
576
		  (const :tag "Hollow box" hollow))
577 578 579 580
	  (cons :tag "Color and Type"
		(choice :tag "Type"
			(const :tag "Filled box" box)
			(const :tag "Vertical bar" bar)
581
			(const :tag "Horizontal bar" hbar)
582
			(const :tag "Hollow box" hollow))
583
		(color :tag "Color")))
584 585 586 587 588
  :group 'cua)


;;; Rectangle support is in cua-rect.el

589 590
(autoload 'cua-set-rectangle-mark "cua-rect"
  "Start rectangle at mouse click position." t nil)
591 592

;; Stub definitions until it is loaded
593 594 595 596 597 598 599 600 601 602 603 604 605
(defvar cua--rectangle)
(defvar cua--last-killed-rectangle)
(unless (featurep 'cua-rect)
  (setq cua--rectangle nil
        cua--last-killed-rectangle nil))

;; All behind cua--rectangle tests.
(declare-function cua--rectangle-left   "cua-rect" (&optional val))
(declare-function cua--delete-rectangle "cua-rect" ())
(declare-function cua--insert-rectangle "cua-rect"
                  (rect &optional below paste-column line-count))
(declare-function cua--rectangle-corner "cua-rect" (&optional advance))
(declare-function cua--rectangle-assert "cua-rect" ())
606 607 608

;;; Global Mark support is in cua-gmrk.el

609
(autoload 'cua-toggle-global-mark "cua-gmrk" nil t nil)
610 611

;; Stub definitions until cua-gmrk.el is loaded
612 613
(defvar cua--global-mark-active)
(unless (featurep 'cua-gmrk)
614 615
  (setq cua--global-mark-active nil))

616 617
(declare-function cua--insert-at-global-mark    "cua-gmrk" (str &optional msg))
(declare-function cua--global-mark-post-command "cua-gmrk" ())
618

619 620 621 622

;;; Low-level Interface

(defvar cua-inhibit-cua-keys nil
623
  "Buffer-local variable that may disable the CUA keymappings.")
624 625
(make-variable-buffer-local 'cua-inhibit-cua-keys)

626 627 628 629
;;; Aux. variables

;; Current region was started using cua-set-mark.
(defvar cua--explicit-region-start nil)
630
(make-variable-buffer-local 'cua--explicit-region-start)
631 632 633 634 635 636 637 638 639 640

;; Latest region was started using shifted movement command.
(defvar cua--last-region-shifted nil)

;; buffer + point prior to current command when rectangle is active
;; checked in post-command hook to see if point was moved
(defvar cua--buffer-and-point-before-command nil)

;; status string for mode line indications
(defvar cua--status-string nil)
641
(make-variable-buffer-local 'cua--status-string)
642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705

(defvar cua--debug nil)


;;; Prefix key override mechanism

;; The prefix override (when mark-active) operates in three substates:
;; [1] Before using a prefix key
;; [2] Immediately after using a prefix key
;; [3] A fraction of a second later

;; In state [1], the cua--prefix-override-keymap is active.
;; This keymap binds the C-x and C-c prefix keys to the
;; cua--prefix-override-handler function.

;; When a prefix key is typed in state [1], cua--prefix-override-handler
;; will push back the keys already read to the event queue.  If input is
;; pending, it changes directly to state [3].  Otherwise, a short timer [T]
;; is started, and it changes to state [2].

;; In state [2], the cua--prefix-override-keymap is inactive.  Instead the
;; cua--prefix-repeat-keymap is active.  This keymap binds C-c C-c and C-x
;; C-x to the cua--prefix-repeat-handler function.

;; If the prefix key is repeated in state [2], cua--prefix-repeat-handler
;; will cancel [T], back the keys already read (except for the second prefix
;; keys) to the event queue, and changes to state [3].

;; The basic cua--cua-keys-keymap binds [C-x timeout] to kill-region and
;; [C-c timeout] to copy-region-as-kill, so if [T] times out in state [2],
;; the cua--prefix-override-timeout function will push a `timeout' event on
;; the event queue, and changes to state [3].

;; In state [3] both cua--prefix-override-keymap and cua--prefix-repeat-keymap
;; are inactive, so the timeout in cua-global-keymap binding is used, or the
;; normal prefix key binding from the global or local map will be used.

;; The pre-command hook (executed as a consequence of the timeout or normal
;; prefix key binding) will cancel [T] and change from state [3] back to
;; state [1].  So cua--prefix-override-handler and cua--prefix-repeat-handler
;; are always called with state reset to [1]!

;; State [1] is recognized by cua--prefix-override-timer is nil,
;; state [2] is recognized by cua--prefix-override-timer is a timer, and
;; state [3] is recognized by cua--prefix-override-timer is t.

(defvar cua--prefix-override-timer nil)
(defvar cua--prefix-override-length nil)

(defun cua--prefix-override-replay (arg repeat)
  (let* ((keys (this-command-keys))
	 (i (length keys))
	 (key (aref keys (1- i))))
    (setq cua--prefix-override-length (- i repeat))
    (setq cua--prefix-override-timer
	  (or
	   ;; In state [2], change to state [3]
	   (> repeat 0)
	   ;; In state [1], change directly to state [3]
	   (and cua-check-pending-input (input-pending-p))
	   ;; In state [1], [T] disabled, so change to state [3]
	   (not (numberp cua-prefix-override-inhibit-delay))
	   (<= cua-prefix-override-inhibit-delay 0)
	   ;; In state [1], start [T] and change to state [2]
706
	   (run-with-timer cua-prefix-override-inhibit-delay nil
707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729
			   'cua--prefix-override-timeout)))
    ;; Don't record this command
    (setq this-command last-command)
    ;; Restore the prefix arg
    (setq prefix-arg arg)
    (reset-this-command-lengths)
    ;; Push the key back on the event queue
    (setq unread-command-events (cons key unread-command-events))))

(defun cua--prefix-override-handler (arg)
  "Start timer waiting for prefix key to be followed by another key.
Repeating prefix key when region is active works as a single prefix key."
  (interactive "P")
  (cua--prefix-override-replay arg 0))

(defun cua--prefix-repeat-handler (arg)
  "Repeating prefix key when region is active works as a single prefix key."
  (interactive "P")
  (cua--prefix-override-replay arg 1))

(defun cua--prefix-copy-handler (arg)
  "Copy region/rectangle, then replay last key."
  (interactive "P")
730
  (cua-copy-region arg)
731
  (let ((keys (this-single-command-keys)))
732
    (setq unread-command-events
733 734 735 736 737
	  (cons (aref keys (1- (length keys))) unread-command-events))))

(defun cua--prefix-cut-handler (arg)
  "Cut region/rectangle, then replay last key."
  (interactive "P")
738
  (cua-cut-region arg)
739
  (let ((keys (this-single-command-keys)))
740
    (setq unread-command-events
741 742 743 744 745 746 747 748 749
	  (cons (aref keys (1- (length keys))) unread-command-events))))

(defun cua--prefix-override-timeout ()
  (setq cua--prefix-override-timer t)
  (when (= (length (this-command-keys)) cua--prefix-override-length)
    (setq unread-command-events (cons 'timeout unread-command-events))
    (if prefix-arg
      (reset-this-command-lengths)
      (setq overriding-terminal-local-map nil))
750
    (cua--select-keymaps)))
751 752 753 754 755 756 757 758


;;; Aux. functions

(defun cua--fallback ()
  ;; Execute original command
  (setq this-command this-original-command)
  (call-interactively this-command))
759

760 761 762 763 764 765 766 767 768 769 770
(defun cua--keep-active ()
  (setq mark-active t
	deactivate-mark nil))

(defun cua--deactivate (&optional now)
  (setq cua--explicit-region-start nil)
  (if (not now)
      (setq deactivate-mark t)
    (setq mark-active nil)
    (run-hooks 'deactivate-mark-hook)))

771 772 773 774
(defun cua--filter-buffer-noprops (start end)
  (let ((str (filter-buffer-substring start end)))
    (set-text-properties 0 (length str) nil str)
    str))
775 776 777 778 779

;; The current register prefix
(defvar cua--register nil)

(defun cua--prefix-arg (arg)
780
  (setq cua--register
781 782
	(and cua-enable-register-prefix
	     (integerp arg) (>= arg 0) (< arg 10)
783 784
	     (let* ((prefix (aref (this-command-keys) 0))
		    (ctrl-u-prefix (and (integerp prefix)
Kim F. Storm's avatar
Kim F. Storm committed
785
					(= prefix ?\C-u))))
786
	       (cond
Kim F. Storm's avatar
Kim F. Storm committed
787 788 789 790 791
		((eq cua-enable-register-prefix 'not-ctrl-u)
		 (not ctrl-u-prefix))
		((eq cua-enable-register-prefix 'ctrl-u-only)
		 ctrl-u-prefix)
		(t t)))
792 793 794 795 796 797
	     (+ arg ?0)))
  (if cua--register nil arg))


;;; Region specific commands

Kim F. Storm's avatar
Kim F. Storm committed
798 799 800
(defvar cua--last-deleted-region-pos nil)
(defvar cua--last-deleted-region-text nil)

801 802 803 804 805 806 807
(defun cua-delete-region ()
  "Delete the active region.
Save a copy in register 0 if `cua-delete-copy-to-register-0' is non-nil."
  (interactive)
  (let ((start (mark)) (end (point)))
    (or (<= start end)
	(setq start (prog1 end (setq end start))))
808 809
    (setq cua--last-deleted-region-text
          (funcall region-extract-function t))
810
    (if cua-delete-copy-to-register-0
Kim F. Storm's avatar
Kim F. Storm committed
811
	(set-register ?0 cua--last-deleted-region-text))
812
    (setq cua--last-deleted-region-pos
Kim F. Storm's avatar
Kim F. Storm committed
813 814 815
	  (cons (current-buffer)
		(and (consp buffer-undo-list)
		     (car buffer-undo-list))))
816 817
    (cua--deactivate)
    (/= start end)))
818 819 820 821 822 823 824 825 826 827

(defun cua-copy-region (arg)
  "Copy the region to the kill ring.
With numeric prefix arg, copy to register 0-9 instead."
  (interactive "P")
  (setq arg (cua--prefix-arg arg))
  (setq cua--last-killed-rectangle nil)
  (let ((start (mark)) (end (point)))
    (or (<= start end)
	(setq start (prog1 end (setq end start))))
828 829
    (cond
     (cua--register
830
      (copy-to-register cua--register start end nil 'region))
831
     ((eq this-original-command 'clipboard-kill-ring-save)
832
      (clipboard-kill-ring-save start end 'region))
833
     (t
834
      (copy-region-as-kill start end 'region)))
835 836 837 838 839 840 841 842 843 844 845 846 847 848 849
    (if cua-keep-region-after-copy
	(cua--keep-active)
      (cua--deactivate))))

(defun cua-cut-region (arg)
  "Cut the region and copy to the kill ring.
With numeric prefix arg, copy to register 0-9 instead."
  (interactive "P")
  (setq cua--last-killed-rectangle nil)
  (if buffer-read-only
      (cua-copy-region arg)
    (setq arg (cua--prefix-arg arg))
    (let ((start (mark)) (end (point)))
      (or (<= start end)
	  (setq start (prog1 end (setq end start))))
850 851
      (cond
       (cua--register
852
	(copy-to-register cua--register start end t 'region))
853
       ((eq this-original-command 'clipboard-kill-region)
854
	(clipboard-kill-region start end 'region))
855
       (t
856
	(kill-region start end 'region))))
857 858 859 860 861 862 863 864 865 866 867 868
    (cua--deactivate)))

;;; Generic commands for regions, rectangles, and global marks

(defun cua-cancel ()
  "Cancel the active region, rectangle, or global mark."
  (interactive)
  (setq mark-active nil)
  (setq cua--explicit-region-start nil)
  (if (fboundp 'cua--cancel-rectangle)
      (cua--cancel-rectangle)))

869
(declare-function x-clipboard-yank "../term/x-win" ())
870

871 872 873 874 875 876 877 878
(defun cua-paste (arg)
  "Paste last cut or copied region or rectangle.
An active region is deleted before executing the command.
With numeric prefix arg, paste from register 0-9 instead.
If global mark is active, copy from register or one character."
  (interactive "P")
  (setq arg (cua--prefix-arg arg))
  (let ((regtxt (and cua--register (get-register cua--register)))
879 880
	(count (prefix-numeric-value arg))
	paste-column paste-lines)
881 882 883 884 885 886 887
    (cond
     ((and cua--register (not regtxt))
      (message "Nothing in register %c" cua--register))
     (cua--global-mark-active
      (if regtxt
	  (cua--insert-at-global-mark regtxt)
	(when (not (eobp))
Kim F. Storm's avatar
Kim F. Storm committed
888
	  (cua--insert-at-global-mark (filter-buffer-substring (point) (+ (point) count)))
889 890
	  (forward-char count))))
     (buffer-read-only
891
      (error "Cannot paste into a read-only buffer"))
892 893 894 895
     (t
      ;; Must save register here, since delete may override reg 0.
      (if mark-active
	  (if cua--rectangle
896 897 898 899 900 901
	      (progn
		(goto-char (min (mark) (point)))
		(setq paste-column (cua--rectangle-left))
		(setq paste-lines (cua--delete-rectangle))
		(if (= paste-lines 1)
		    (setq paste-lines nil))) ;; paste all
902 903
	    ;; Before a yank command, make sure we don't yank the
	    ;; head of the kill-ring that really comes from the
904 905
	    ;; currently active region we are going to delete.
	    ;; That would make yank a no-op.
906 907
	    (if (and (string= (filter-buffer-substring (point) (mark))
			      (car kill-ring))
908
		     (fboundp 'mouse-region-match)
909
		     (mouse-region-match))
910 911 912 913 914
		(current-kill 1))
	    (cua-delete-region)))
      (cond
       (regtxt
	(cond
915
	 ;; This being a cons implies cua-rect is loaded?
916 917 918 919 920 921 922 923 924 925
	 ((consp regtxt) (cua--insert-rectangle regtxt))
	 ((stringp regtxt) (insert-for-yank regtxt))
	 (t (message "Unknown data in register %c" cua--register))))
       ((and cua--last-killed-rectangle
	     (eq (and kill-ring (car kill-ring)) (car cua--last-killed-rectangle)))
	(let ((pt (point)))
	  (when (not (eq buffer-undo-list t))
	    (setq this-command 'cua--paste-rectangle)
	    (undo-boundary)
	    (setq buffer-undo-list (cons pt buffer-undo-list)))
926 927
	  (cua--insert-rectangle (cdr cua--last-killed-rectangle)
				 nil paste-column paste-lines)
928
	  (if arg (goto-char pt))))
929 930
       ((eq this-original-command 'clipboard-yank)
	(clipboard-yank))
931 932
       ((eq this-original-command 'x-clipboard-yank)
	(x-clipboard-yank))
933 934
       (t (yank arg)))))))

Kim F. Storm's avatar
Kim F. Storm committed
935 936 937 938 939 940

;; cua-paste-pop-rotate-temporarily == t mechanism:
;;
;; C-y M-y M-y => only rotates kill ring temporarily,
;;                so next C-y yanks what previous C-y yanked,
;;
941 942 943
;; M-y M-y M-y => equivalent to C-y M-y M-y
;;
;; But: After another command, C-u M-y remembers the temporary
Kim F. Storm's avatar
Kim F. Storm committed
944
;;      kill-ring position, so
945
;; C-u M-y     => yanks what the last M-y yanked
Kim F. Storm's avatar
Kim F. Storm committed
946 947 948 949
;;

(defvar cua-paste-pop-count nil)

950 951
(defun cua-paste-pop (arg)
  "Replace a just-pasted text or rectangle with a different text.
952 953
See `yank-pop' for details about the default behavior.  For an alternative
behavior, see `cua-paste-pop-rotate-temporarily'."
954
  (interactive "P")
Kim F. Storm's avatar
Kim F. Storm committed
955 956 957 958 959 960 961 962 963 964 965 966 967 968 969
  (cond
   ((eq last-command 'cua--paste-rectangle)
    (undo)
    (yank arg))
   ((not cua-paste-pop-rotate-temporarily)
    (yank-pop (prefix-numeric-value arg)))
   (t
    (let ((rotate (if (consp arg) 1 (prefix-numeric-value arg))))
      (cond
       ((or (null cua-paste-pop-count)
	    (eq last-command 'yank)
	    (eq last-command 'cua-paste))
	(setq cua-paste-pop-count rotate)
	(setq last-command 'yank)
	(yank-pop cua-paste-pop-count))
970 971
       ((and (eq last-command 'cua-paste-pop) (not (consp arg)))
	(setq cua-paste-pop-count (+ cua-paste-pop-count rotate))
Kim F. Storm's avatar
Kim F. Storm committed
972 973 974
	(setq last-command 'yank)
	(yank-pop cua-paste-pop-count))
       (t
975 976
	(setq cua-paste-pop-count
	      (if (consp arg) (+ cua-paste-pop-count rotate -1) 1))
Kim F. Storm's avatar
Kim F. Storm committed
977 978 979
	(yank (1+ cua-paste-pop-count)))))
    ;; Undo rotating the kill-ring, so next C-y will
    ;; yank the original head.
980
    (setq kill-ring-yank-pointer kill-ring)
Kim F. Storm's avatar
Kim F. Storm committed
981
    (setq this-command 'cua-paste-pop))))
982 983

(defun cua-exchange-point-and-mark (arg)
984 985 986 987 988
  "Exchange point and mark.
Don't activate the mark if `cua-enable-cua-keys' is non-nil.
Otherwise, just activate the mark if a prefix ARG is given.

See also `exchange-point-and-mark'."
989
  (interactive "P")
990 991 992 993 994 995 996 997 998
  (cond ((null cua-enable-cua-keys)
	 (exchange-point-and-mark arg))
	(arg
	 (setq mark-active t))
	(t
	 (let (mark-active)
	   (exchange-point-and-mark)
	   (if cua--rectangle
	       (cua--rectangle-corner 0))))))
999

1000 1001 1002 1003 1004
;; Typed text that replaced the highlighted region.
(defvar cua--repeat-replace-text nil)

(defun cua-repeat-replace-region (arg)
  "Repeat replacing text of highlighted region with typed text.
1005 1006
Searches for the next stretch of text identical to the region last
replaced by typing text over it and replaces it with the same stretch
Kim F. Storm's avatar
Kim F. Storm committed
1007
of text."
1008
  (interactive "P")
Kim F. Storm's avatar
Kim F. Storm committed
1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
  (when cua--last-deleted-region-pos
    (save-excursion
      (save-restriction
	(set-buffer (car cua--last-deleted-region-pos))
	(widen)
	;; Find the text that replaced the region via the undo list.
	(let ((ul buffer-undo-list)
	      (elt (cdr cua--last-deleted-region-pos))
	      u s e)
	  (when elt
	    (while (consp ul)
	      (setq u (car ul) ul (cdr ul))
	      (cond
	       ((eq u elt) ;; got it
		(setq ul nil))
	       ((and (consp u) (integerp (car u)) (integerp (cdr u)))
		(if (and s (= (cdr u) s))
		    (setq s (car u))
		  (setq s (car u) e (cdr u)))))))
Kim F. Storm's avatar
Kim F. Storm committed
1028
	  (cond ((and s e (<= s e) (= s (mark t)))
1029
		 (setq cua--repeat-replace-text (cua--filter-buffer-noprops s e)))
Kim F. Storm's avatar
Kim F. Storm committed
1030 1031 1032 1033 1034
		((and (null s) (eq u elt)) ;; nothing inserted
		 (setq cua--repeat-replace-text
		       ""))
		(t
		 (message "Cannot locate replacement text"))))))
Kim F. Storm's avatar
Kim F. Storm committed
1035 1036 1037 1038 1039
    (setq cua--last-deleted-region-pos nil))
  (if (and cua--last-deleted-region-text
	   cua--repeat-replace-text
	   (search-forward cua--last-deleted-region-text nil t nil))
      (replace-match cua--repeat-replace-text arg t)))
1040

1041 1042 1043
(defun cua-help-for-region (&optional help)
  "Show region specific help in echo area."
  (interactive)
1044
  (message
1045 1046 1047 1048 1049 1050
   (concat (if help "C-?:help " "")
	   "C-z:undo C-x:cut C-c:copy C-v:paste S-ret:rect")))


;;; Shift activated / extended region

Kim F. Storm's avatar
Kim F. Storm committed
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
(defun cua-pop-to-last-change ()
  (let ((undo-list buffer-undo-list)
	pos elt)
    (while (and (not pos)
		(consp undo-list))
      (setq elt (car undo-list)
	    undo-list (cdr undo-list))
      (cond
       ((integerp elt)
	(setq pos elt))
       ((not (consp elt)))
       ((and (integerp (cdr elt))
	     (or (integerp (car elt)) (stringp (car elt))))
	(setq pos (cdr elt)))
       ((and (eq (car elt) 'apply) (consp (cdr elt)) (integerp (cadr elt)))
	(setq pos (nth 3 elt)))))
    (when (and pos
	       (/= pos (point))
	       (>= pos (point-min)) (<= pos (point-max)))
      (goto-char pos)
      t)))

1073 1074
(defun cua-set-mark (&optional arg)
  "Set mark at where point is, clear mark, or jump to mark.
Kim F. Storm's avatar
Kim F. Storm committed
1075 1076 1077

With no prefix argument, clear mark if already set.  Otherwise, set
mark, and push old mark position on local mark ring; also push mark on
Kim F. Storm's avatar
Kim F. Storm committed
1078
global mark ring if last mark was set in another buffer.
Kim F. Storm's avatar
Kim F. Storm committed
1079 1080

With argument, jump to mark, and pop a new position for mark off
Kim F. Storm's avatar
Kim F. Storm committed
1081
the local mark ring (this does not affect the global mark ring).
Kim F. Storm's avatar
Kim F. Storm committed
1082
Use \\[pop-global-mark] to jump to a mark off the global mark ring
Kim F. Storm's avatar
Kim F. Storm committed
1083 1084 1085 1086
\(see `pop-global-mark').

If `cua-auto-mark-last-change' is non-nil, this command behaves as if there
was an implicit mark at the position of the last buffer change.
1087