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

3
;; Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002, 2005
Kim F. Storm's avatar
Kim F. Storm committed
4
;;        Free Software Foundation, Inc.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33

;; Author: Kim F. Storm <storm@cua.dk>
;; Keywords: keyboard emulation convenience cua

;; This file is part of GNU Emacs.

;; GNU Emacs is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 2, or (at your option)
;; any later version.

;; 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
;; along with GNU Emacs; see the file COPYING.  If not, write to the
;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
;; Boston, MA 02111-1307, USA.


;;; 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.

34 35 36 37
;; CUA style key bindings for cut and paste
;; ----------------------------------------

;; This package allows the C-z, C-x, C-c, and C-v keys to be
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
;; 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
58
;; instantly - or at least very quickly.  So give it a try!
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
;; ... 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),
;; - press the prefix key and the following key within 0.2 seconds), or
;; - use the SHIFT key with the prefix key, i.e. C-X or C-C
;;
;; This behaviour can be customized via the
;; 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.

78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106

;; 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
;; for a streach of text identical to the previous contents of the
;; 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.

;; Note: Since CUA-mode duplicates the functionality of the
;; delete-selection-mode, that mode is automatically disabled when
;; CUA-mode is enabled.


107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
;; 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
;; --------------------
;; Emacs' standard register support is also based on a separate set of
;; "register commands".
124
;;
125 126 127 128
;; 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].
129
;;
130 131
;; 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.
132
;;
133 134 135 136 137 138 139 140 141 142 143
;; 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
;; ---------------------
;; Emacs' normal rectangle support is based on interpreting the region
;; 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.
144
;;
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
;; 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
162
;; To start a rectangle, use [C-return] and extend it using the normal
163 164 165 166 167
;; 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
168
;; rectangles is C-return!
169 170 171 172 173
;;
;; 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.
174
;;
175 176 177
;; 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.
178 179 180 181 182 183 184 185

;; 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
186
;; [C-return] cancels the rectangle
187 188 189 190 191 192 193 194 195 196
;; [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
197
;;     C-return M-} ; ; <space>  C-return
198

199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
;; 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)
215
;; [M-o] opens the rectangle by moving the highlighted text to the
216
;;       right of the rectangle and filling the rectangle with blanks.
217 218
;; [M-p] toggles virtual straight rectangle edges
;; [M-P] inserts tabs and spaces (padding) to make real straight edges
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
;; [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
235
;; ---------------
236 237 238 239 240 241
;; 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:
242
;; <ch>  All characters (including newlines) you type are inserted
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
;;       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
;; [delete] deltes the character after the global mark.

;; [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
270
  :version "22.1"
271 272 273 274 275 276 277 278 279
  :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
  "*Enable using C-z, C-x, C-c, and C-v for undo, cut, copy, and paste.
If the value is t, these mappings are always enabled.  If the value is
'shift, these keys are only enabled if the last region was marked with
a shifted movement key.  If the value is nil, these keys are never
enabled."
280
  :type '(choice (const :tag "Disabled" nil)
281
		 (const :tag "Shift region only" shift)
Kim F. Storm's avatar
Kim F. Storm committed
282
		 (other :tag "Enabled" t))
283 284 285 286 287 288 289 290 291 292 293
  :group 'cua)

(defcustom cua-highlight-region-shift-only nil
  "*If non-nil, only highlight region if marked with S-<move>.
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.
But when the mark was set using \\[cua-set-mark], transient-mark-mode
is not turned on."
  :type 'boolean
  :group 'cua)

294
(defcustom cua-prefix-override-inhibit-delay
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
  (if (featurep 'lisp-float-type) (/ (float 1) (float 5)) nil)
  "*If non-nil, time in seconds to delay before overriding prefix key.
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)

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

(defcustom cua-enable-register-prefix 'not-ctrl-u
  "*If non-nil, registers are supported via numeric prefix arg.
If the value is t, any numeric prefix arg in the range 0 to 9 will be
316
interpreted as a register number.
317
If the value is not-ctrl-u, using C-u to enter a numeric prefix is not
318
interpreted as a register number.
319 320
If the value is ctrl-u-only, only numeric prefix entered with C-u is
interpreted as a register number."
321
  :type '(choice (const :tag "Disabled" nil)
322 323
		 (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
324
		 (other :tag "Enabled" t))
325 326 327 328 329 330 331 332
  :group 'cua)

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

(defcustom cua-use-hyper-key nil
Kim F. Storm's avatar
Kim F. Storm committed
333 334
  "*If non-nil, bind rectangle commands to H-... instead of M-....
If set to 'also, toggle region command is also on C-return.
335
Must be set prior to enabling CUA."
Kim F. Storm's avatar
Kim F. Storm committed
336
  :type '(choice (const :tag "Meta key and C-return" nil)
337
		 (const :tag "Hyper key only" only)
Kim F. Storm's avatar
Kim F. Storm committed
338
		 (const :tag "Hyper key and C-return" also))
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
  :group 'cua)

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

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

(defcustom cua-check-pending-input t
  "*If non-nil, don't override prefix key if input pending.
It is rumoured that input-pending-p is unreliable under some window
managers, so try setting this to nil, if prefix override doesn't work."
  :type 'boolean
  :group 'cua)


;;; Rectangle Customization

361 362 363 364 365
(defcustom cua-virtual-rectangle-edges t
  "*If non-nil, rectangles have virtual straight edges.
Note that although rectangles are always DISPLAYED with straight edges, the
buffer is NOT modified, until you execute a command that actually modifies it.
\[M-p] toggles this feature when a rectangle is active."
366 367 368
  :type 'boolean
  :group 'cua)

369 370 371 372 373 374 375 376 377 378 379 380 381
(defcustom cua-auto-tabify-rectangles 1000
  "*If non-nil, automatically tabify after rectangle commands.
This basically means that `tabify' is applied to all lines that
are modified by inserting or deleting a rectangle.  If value is
an integer, cua will look for existing tabs in a region around
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)

382 383 384 385 386
(defcustom cua-enable-rectangle-auto-help t
  "*If non-nil, automatically show help for region, rectangle and global mark."
  :type 'boolean
  :group 'cua)

Kim F. Storm's avatar
Kim F. Storm committed
387 388 389
(defface cua-rectangle-face
  '((default :inherit region)
    (((class color)) :foreground "white" :background "maroon"))
390 391 392
  "*Font used by CUA for highlighting the rectangle."
  :group 'cua)

Kim F. Storm's avatar
Kim F. Storm committed
393 394 395
(defface cua-rectangle-noselect-face
  '((default :inherit region)
    (((class color)) :foreground "white" :background "dimgray"))
396 397 398 399 400 401 402 403 404 405 406
  "*Font used by CUA for highlighting the non-selected rectangle lines."
  :group 'cua)


;;; Global Mark Customization

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

Kim F. Storm's avatar
Kim F. Storm committed
407
(defface cua-global-mark-face
408 409
  '((((min-colors 88)(class color)) :foreground "black" :background "yellow1")
    (((class color)) :foreground "black" :background "yellow")
Kim F. Storm's avatar
Kim F. Storm committed
410
    (t :bold t))
411 412 413 414 415 416 417 418 419 420 421 422
  "*Font used by CUA for highlighting the global mark."
  :group 'cua)

(defcustom cua-global-mark-blink-cursor-interval 0.20
  "*Blink cursor at this interval when global mark is active."
  :type '(choice (number :tag "Blink interval")
		 (const :tag "No blink" nil))
  :group 'cua)


;;; Cursor Indication Customization

423
(defcustom cua-enable-cursor-indications nil
424 425 426 427
  "*If non-nil, use different cursor colors for indications."
  :type 'boolean
  :group 'cua)

428 429 430 431 432 433 434 435 436
(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")
437
  "Normal (non-overwrite) cursor color.
438 439 440
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
441
affected.  If the value is a cursor TYPE (one of: box, hollow, bar, or hbar),
442 443
then only the `cursor-type' property will be affected.  If the value is
a cons (TYPE . COLOR), then both properties are affected."
444
  :initialize 'custom-initialize-default
445 446 447 448 449 450
  :type '(choice
	  (color :tag "Color")
	  (choice :tag "Type"
		  (const :tag "Filled box" box)
		  (const :tag "Vertical bar" bar)
		  (const :tag "Horisontal bar" hbar)
451
		  (const :tag "Hollow box" hollow))
452 453 454 455 456
	  (cons :tag "Color and Type"
		(choice :tag "Type"
			(const :tag "Filled box" box)
			(const :tag "Vertical bar" bar)
			(const :tag "Horisontal bar" hbar)
457
			(const :tag "Hollow box" hollow))
458
		(color :tag "Color")))
459 460 461
  :group 'cua)

(defcustom cua-read-only-cursor-color "darkgreen"
Kim F. Storm's avatar
Kim F. Storm committed
462
  "*Cursor color used in read-only buffers, if non-nil.
463 464 465
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
466
affected.  If the value is a cursor TYPE (one of: box, hollow, bar, or hbar),
467 468 469 470 471 472 473 474
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)
		  (const :tag "Horisontal bar" hbar)
475
		  (const :tag "Hollow box" hollow))
476 477 478 479 480
	  (cons :tag "Color and Type"
		(choice :tag "Type"
			(const :tag "Filled box" box)
			(const :tag "Vertical bar" bar)
			(const :tag "Horisontal bar" hbar)
481
			(const :tag "Hollow box" hollow))
482
		(color :tag "Color")))
483 484 485 486
  :group 'cua)

(defcustom cua-overwrite-cursor-color "yellow"
  "*Cursor color used when overwrite mode is set, if non-nil.
487 488 489
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
490
affected.  If the value is a cursor TYPE (one of: box, hollow, bar, or hbar),
491 492 493 494 495 496 497 498
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)
		  (const :tag "Horisontal bar" hbar)
499
		  (const :tag "Hollow box" hollow))
500 501 502 503 504
	  (cons :tag "Color and Type"
		(choice :tag "Type"
			(const :tag "Filled box" box)
			(const :tag "Vertical bar" bar)
			(const :tag "Horisontal bar" hbar)
505
			(const :tag "Hollow box" hollow))
506
		(color :tag "Color")))
507 508 509 510
  :group 'cua)

(defcustom cua-global-mark-cursor-color "cyan"
  "*Indication for active global mark.
Kim F. Storm's avatar
Kim F. Storm committed
511
Will change cursor color to specified color if string.
512 513 514
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
515
affected.  If the value is a cursor TYPE (one of: box, hollow, bar, or hbar),
516 517 518 519 520 521 522 523
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)
		  (const :tag "Horisontal bar" hbar)
524
		  (const :tag "Hollow box" hollow))
525 526 527 528 529
	  (cons :tag "Color and Type"
		(choice :tag "Type"
			(const :tag "Filled box" box)
			(const :tag "Vertical bar" bar)
			(const :tag "Horisontal bar" hbar)
530
			(const :tag "Hollow box" hollow))
531
		(color :tag "Color")))
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
  :group 'cua)


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

(autoload 'cua-set-rectangle-mark "cua-rect" nil t nil)

;; Stub definitions until it is loaded

(when (not (featurep 'cua-rect))
  (defvar cua--rectangle)
  (setq cua--rectangle nil)
  (defvar cua--last-killed-rectangle)
  (setq cua--last-killed-rectangle nil))



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

(autoload 'cua-toggle-global-mark "cua-gmrk.el" nil t nil)

;; Stub definitions until cua-gmrk.el is loaded

(when (not (featurep 'cua-gmrk))
  (defvar cua--global-mark-active)
  (setq cua--global-mark-active nil))


(provide 'cua-base)

(eval-when-compile
  (require 'cua-rect)
  (require 'cua-gmrk)
  )

567 568 569 570 571 572 573

;;; Low-level Interface

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

574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651
;;; Aux. variables

;; Current region was started using cua-set-mark.
(defvar cua--explicit-region-start nil)

;; 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)

(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]
652
	   (run-with-timer cua-prefix-override-inhibit-delay nil
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
			   '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")
  (if cua--rectangle
      (cua-copy-rectangle arg)
    (cua-copy-region arg))
  (let ((keys (this-single-command-keys)))
680
    (setq unread-command-events
681 682 683 684 685 686 687 688 689
	  (cons (aref keys (1- (length keys))) unread-command-events))))

(defun cua--prefix-cut-handler (arg)
  "Cut region/rectangle, then replay last key."
  (interactive "P")
  (if cua--rectangle
      (cua-cut-rectangle arg)
    (cua-cut-region arg))
  (let ((keys (this-single-command-keys)))
690
    (setq unread-command-events
691 692 693 694 695 696 697 698 699
	  (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))
700
    (cua--select-keymaps)))
701 702 703 704 705 706 707 708


;;; Aux. functions

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

710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725
(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)))


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

(defun cua--prefix-arg (arg)
726
  (setq cua--register
727 728
	(and cua-enable-register-prefix
	     (integerp arg) (>= arg 0) (< arg 10)
729 730
	     (let* ((prefix (aref (this-command-keys) 0))
		    (ctrl-u-prefix (and (integerp prefix)
Kim F. Storm's avatar
Kim F. Storm committed
731
					(= prefix ?\C-u))))
732
	       (cond
Kim F. Storm's avatar
Kim F. Storm committed
733 734 735 736 737
		((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)))
738 739 740 741 742 743
	     (+ arg ?0)))
  (if cua--register nil arg))


;;; Region specific commands

Kim F. Storm's avatar
Kim F. Storm committed
744 745 746
(defvar cua--last-deleted-region-pos nil)
(defvar cua--last-deleted-region-text nil)

747 748 749 750 751 752 753
(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))))
Kim F. Storm's avatar
Kim F. Storm committed
754
    (setq cua--last-deleted-region-text (buffer-substring start end))
755
    (if cua-delete-copy-to-register-0
Kim F. Storm's avatar
Kim F. Storm committed
756
	(set-register ?0 cua--last-deleted-region-text))
757
    (delete-region start end)
758
    (setq cua--last-deleted-region-pos
Kim F. Storm's avatar
Kim F. Storm committed
759 760 761
	  (cons (current-buffer)
		(and (consp buffer-undo-list)
		     (car buffer-undo-list))))
762 763 764 765 766 767
    (cua--deactivate)))

(defun cua-replace-region ()
  "Replace the active region with the character you type."
  (interactive)
  (cua-delete-region)
Kim F. Storm's avatar
Kim F. Storm committed
768 769
  (unless (eq this-original-command this-command)
    (cua--fallback)))
770 771 772 773 774 775 776 777 778 779

(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))))
780 781 782 783 784 785 786
    (cond
     (cua--register
      (copy-to-register cua--register start end nil))
     ((eq this-original-command 'clipboard-kill-ring-save)
      (clipboard-kill-ring-save start end))
     (t
      (copy-region-as-kill start end)))
787 788 789 790 791 792 793 794 795 796 797 798 799 800 801
    (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))))
802 803 804 805 806 807 808
      (cond
       (cua--register
	(copy-to-register cua--register start end t))
       ((eq this-original-command 'clipboard-kill-region)
	(clipboard-kill-region start end))
       (t
	(kill-region start end))))
809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828
    (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)))

(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)))
829 830
	(count (prefix-numeric-value arg))
	paste-column paste-lines)
831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848
    (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))
	  (cua--insert-at-global-mark (buffer-substring (point) (+ (point) count)))
	  (forward-char count))))
     (buffer-read-only
      (message "Cannot paste into a read-only buffer"))
     (t
      ;; Must save register here, since delete may override reg 0.
      (if mark-active
	  ;; Before a yank command, make sure we don't yank
	  ;; the same region that we are going to delete.
	  ;; That would make yank a no-op.
	  (if cua--rectangle
849 850 851 852 853 854
	      (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
855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871
	    (if (string= (buffer-substring (point) (mark))
			 (car kill-ring))
		(current-kill 1))
	    (cua-delete-region)))
      (cond
       (regtxt
	(cond
	 ((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)))
872 873
	  (cua--insert-rectangle (cdr cua--last-killed-rectangle)
				 nil paste-column paste-lines)
874
	  (if arg (goto-char pt))))
875 876
       ((eq this-original-command 'clipboard-yank)
	(clipboard-yank))
877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899
       (t (yank arg)))))))

(defun cua-paste-pop (arg)
  "Replace a just-pasted text or rectangle with a different text.
See `yank-pop' for details."
  (interactive "P")
  (if (eq last-command 'cua--paste-rectangle)
      (progn
	(undo)
	(yank arg))
    (yank-pop (prefix-numeric-value arg))))

(defun cua-exchange-point-and-mark (arg)
  "Exchanges point and mark, but don't activate the mark.
Activates the mark if a prefix argument is given."
  (interactive "P")
  (if arg
      (setq mark-active t)
    (let (mark-active)
      (exchange-point-and-mark)
      (if cua--rectangle
	  (cua--rectangle-corner 0)))))

900 901 902 903 904 905 906
;; 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.
Searches for the next streach of text identical to the region last
replaced by typing text over it and replaces it with the same streach
Kim F. Storm's avatar
Kim F. Storm committed
907
of text."
908
  (interactive "P")
Kim F. Storm's avatar
Kim F. Storm committed
909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940
  (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)))))))
	  (setq cua--repeat-replace-text
		(cond ((and s e (<= s e) (= s (mark t)))
		       (buffer-substring-no-properties s e))
		      ((and (null s) (eq u elt)) ;; nothing inserted
		       "")
		      (t
		       (message "Cannot locate replacement text")
		       nil))))))
    (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)))
941

942 943 944
(defun cua-help-for-region (&optional help)
  "Show region specific help in echo area."
  (interactive)
945
  (message
946 947 948 949 950 951 952 953
   (concat (if help "C-?:help " "")
	   "C-z:undo C-x:cut C-c:copy C-v:paste S-ret:rect")))


;;; Shift activated / extended region

(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
954 955 956

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
957
global mark ring if last mark was set in another buffer.
Kim F. Storm's avatar
Kim F. Storm committed
958 959 960 961

With argument, jump to mark, and pop a new position for mark off
the local mark ring \(this does not affect the global mark ring\).
Use \\[pop-global-mark] to jump to a mark off the global mark ring
962 963 964 965
\(see `pop-global-mark'\).

Repeating the command without the prefix jumps to the next position
off the local \(or global\) mark ring.
Kim F. Storm's avatar
Kim F. Storm committed
966 967

With a double \\[universal-argument] prefix argument, unconditionally set mark."
968 969
  (interactive "P")
  (cond
Kim F. Storm's avatar
Kim F. Storm committed
970 971
   ((and (consp arg) (> (prefix-numeric-value arg) 4))
    (push-mark-command nil))
972
   ((eq last-command 'pop-to-mark-command)
Kim F. Storm's avatar
Kim F. Storm committed
973 974
    (setq this-command 'pop-to-mark-command)
    (pop-to-mark-command))
975
   ((and (eq last-command 'pop-global-mark) (not arg))
Kim F. Storm's avatar
Kim F. Storm committed
976 977
    (setq this-command 'pop-global-mark)
    (pop-global-mark))
978
   (arg
979 980
    (setq this-command 'pop-to-mark-command)
    (pop-to-mark-command))
981 982 983 984
   (mark-active
    (cua--deactivate)
    (message "Mark Cleared"))
   (t
985
    (push-mark-command nil nil)
986 987 988 989 990
    (setq cua--explicit-region-start t)
    (setq cua--last-region-shifted nil)
    (if cua-enable-region-auto-help
	(cua-help-for-region t)))))

991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
;;; Scrolling commands which does not signal errors at top/bottom
;;; of buffer at first key-press (instead moves to top/bottom
;;; of buffer).

(defun cua-scroll-up (&optional arg)
  "Scroll text of current window upward ARG lines; or near full screen if no ARG.
If window cannot be scrolled further, move cursor to bottom line instead.
A near full screen is `next-screen-context-lines' less than a full screen.
Negative ARG means scroll downward.
If ARG is the atom `-', scroll downward by nearly full screen."
  (interactive "P")
  (cond
   ((eq arg '-) (cua-scroll-down nil))
   ((< (prefix-numeric-value arg) 0)
    (cua-scroll-down (- (prefix-numeric-value arg))))
   ((eobp)
    (scroll-up arg))  ; signal error
   (t
    (condition-case nil
	(scroll-up arg)
      (end-of-buffer (goto-char (point-max)))))))

1013 1014
(put 'cua-scroll-up 'CUA 'move)

1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
(defun cua-scroll-down (&optional arg)
  "Scroll text of current window downward ARG lines; or near full screen if no ARG.
If window cannot be scrolled further, move cursor to top line instead.
A near full screen is `next-screen-context-lines' less than a full screen.
Negative ARG means scroll upward.
If ARG is the atom `-', scroll upward by nearly full screen."
  (interactive "P")
  (cond
   ((eq arg '-) (cua-scroll-up nil))
   ((< (prefix-numeric-value arg) 0)
    (cua-scroll-up (- (prefix-numeric-value arg))))
   ((bobp)
    (scroll-down arg))  ; signal error
   (t
    (condition-case nil
	(scroll-down arg)
      (beginning-of-buffer (goto-char (point-min)))))))

1033
(put 'cua-scroll-down 'CUA 'move)
1034

1035 1036 1037
;;; Cursor indications

(defun cua--update-indications ()
1038 1039 1040 1041 1042 1043 1044 1045
  (let* ((cursor
	  (cond
	   ((and cua--global-mark-active
		 cua-global-mark-cursor-color)
	    cua-global-mark-cursor-color)
	   ((and buffer-read-only
		 cua-read-only-cursor-color)
	    cua-read-only-cursor-color)
1046
	   ((and cua-overwrite-cursor-color overwrite-mode)
1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
	    cua-overwrite-cursor-color)
	   (t cua-normal-cursor-color)))
	 (color (if (consp cursor) (cdr cursor) cursor))
	 (type (if (consp cursor) (car cursor) cursor)))
    (if (and color
	     (stringp color)
	     (not (equal color (frame-parameter nil 'cursor-color))))
	(set-cursor-color color))
    (if (and type
	     (symbolp type)
1057
	     (not (eq type default-cursor-type)))
1058
	(setq default-cursor-type type))))
1059 1060 1061 1062 1063 1064


;;; Pre-command hook

(defun cua--pre-command-handler ()
  (condition-case nil
1065
      (let ((movement (eq (get this-command 'CUA) 'move)))
1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078

	;; Cancel prefix key timeout if user enters another key.
	(when cua--prefix-override-timer
	  (if (timerp cua--prefix-override-timer)
	      (cancel-timer cua--prefix-override-timer))
	  (setq cua--prefix-override-timer nil))

	;; Handle shifted cursor keys and other movement commands.
	;; If region is not active, region is activated if key is shifted.
	;; If region is active, region is cancelled if key is unshifted (and region not started with C-SPC).
	;; If rectangle is active, expand rectangle in specified direction and ignore the movement.
	(if movement
	    (cond
1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
	     ((if window-system
		  (memq 'shift (event-modifiers
				(aref (this-single-command-raw-keys) 0)))
		(or
		 (memq 'shift (event-modifiers
			       (aref (this-single-command-keys) 0)))
		 ;; See if raw escape sequence maps to a shifted event, e.g. S-up or C-S-home.
		 (and (boundp 'function-key-map)
		      function-key-map
		      (let ((ev (lookup-key function-key-map
					   (this-single-command-raw-keys))))
			(and (vector ev)
			     (symbolp (setq ev (aref ev 0)))
			     (string-match "S-" (symbol-name ev)))))))
1093
	      (unless mark-active
1094
		(push-mark-command nil t))
1095 1096 1097 1098
	      (setq cua--last-region-shifted t)
	      (setq cua--explicit-region-start nil))
	     ((or cua--explicit-region-start cua--rectangle)
	      (unless mark-active
1099
		(push-mark-command nil nil)))
1100
	     (t
1101
	      ;; If we set mark-active to nil here, the region highlight will not be
1102 1103 1104 1105
	      ;; removed by the direct_output_ commands.
	      (setq deactivate-mark t)))

	  ;; Handle delete-selection property on other commands
1106 1107 1108 1109 1110
	  (if (and mark-active (not deactivate-mark))
	      (let* ((ds (or (get this-command 'delete-selection)
			     (get this-command 'pending-delete)))
		     (nc (cond
			  ((not ds) nil)
1111
			  ((eq ds 'yank)
1112 1113 1114 1115 1116 1117 1118
			   'cua-paste)
			  ((eq ds 'kill)
			   (if cua--rectangle
			       'cua-copy-rectangle
			     'cua-copy-region))
			  ((eq ds 'supersede)
			   (if cua--rectangle
1119 1120
			       'cua-delete-rectangle
			     'cua-delete-region))
1121 1122
			  (t
			   (if cua--rectangle
1123 1124
			       'cua-delete-rectangle ;; replace?
			     'cua-replace-region)))))
1125 1126 1127
		(if nc
		    (setq this-original-command this-command
			  this-command nc)))))
1128

1129
	;; Detect extension of rectangles by mouse or other movement
1130
	(setq cua--buffer-and-point-before-command
1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149
	      (if cua--rectangle (cons (current-buffer) (point))))
	)
    (error nil)))

;;; Post-command hook

(defun cua--post-command-handler ()
  (condition-case nil
      (progn
	(when cua--global-mark-active
	  (cua--global-mark-post-command))
	(when (fboundp 'cua--rectangle-post-command)
	  (cua--rectangle-post-command))
	(setq cua--buffer-and-point-before-command nil)
	(if (or (not mark-active) deactivate-mark)
	    (setq cua--explicit-region-start nil))

	;; Debugging
	(if cua--debug
1150
	    (cond
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163
	     (cua--rectangle (cua--rectangle-assert))
	     (mark-active (message "Mark=%d Point=%d Expl=%s"
				   (mark t) (point) cua--explicit-region-start))))

	;; Disable transient-mark-mode if rectangle active in current buffer.
	(if (not (window-minibuffer-p (selected-window)))
	    (setq transient-mark-mode (and (not cua--rectangle)
					   (if cua-highlight-region-shift-only
					       (not cua--explicit-region-start)
					     t))))
	(if cua-enable-cursor-indications
	    (cua--update-indications))

1164
	(cua--select-keymaps)
1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177
	)

    (error nil)))


;;; Keymaps

(defun cua--M/H-key (map key fct)
  ;; bind H-KEY or M-KEY to FCT in MAP
  (if (eq key 'space) (setq key ? ))
  (unless (listp key) (setq key (list key)))
  (define-key map (vector (cons (if cua-use-hyper-key 'hyper 'meta) key)) fct))

1178 1179 1180 1181 1182 1183 1184
(defun cua--self-insert-char-p (def)
  ;; Return DEF if current key sequence is self-inserting in
  ;; global-map.
  (if (memq (global-key-binding (this-single-command-keys))
	    '(self-insert-command self-insert-iso))
      def nil))

1185 1186 1187
(defvar cua-global-keymap (make-sparse-keymap)
  "Global keymap for cua-mode; users may add to this keymap.")

1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
(defvar cua--cua-keys-keymap (make-sparse-keymap))
(defvar cua--prefix-override-keymap (make-sparse-keymap))
(defvar cua--prefix-repeat-keymap (make-sparse-keymap))
(defvar cua--global-mark-keymap (make-sparse-keymap)) ; Initalized when cua-gmrk.el is loaded
(defvar cua--rectangle-keymap (make-sparse-keymap))   ; Initalized when cua-rect.el is loaded
(defvar cua--region-keymap (make-sparse-keymap))

(defvar cua--ena-cua-keys-keymap nil)
(defvar cua--ena-prefix-override-keymap nil)
(defvar cua--ena-prefix-repeat-keymap nil)
(defvar cua--ena-region-keymap nil)
(defvar cua--ena-global-mark-keymap nil)

1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211
(defvar cua--keymap-alist
  `((cua--ena-prefix-override-keymap . ,cua--prefix-override-keymap)
    (cua--ena-prefix-repeat-keymap . ,cua--prefix-repeat-keymap)
    (cua--ena-cua-keys-keymap . ,cua--cua-keys-keymap)
    (cua--ena-global-mark-keymap . ,cua--global-mark-keymap)
    (cua--rectangle . ,cua--rectangle-keymap)
    (cua--ena-region-keymap . ,cua--region-keymap)
    (cua-mode . ,cua-global-keymap)))

(defun cua--select-keymaps ()
  ;; Setup conditions for selecting the proper keymaps in cua--keymap-alist.
1212 1213 1214 1215 1216
  (setq cua--ena-region-keymap
	(and mark-active (not deactivate-mark)))
  (setq cua--ena-prefix-override-keymap
	(and cua--ena-region-keymap
	     cua-enable-cua-keys
1217
	     (not cua-inhibit-cua-keys)
1218 1219 1220 1221 1222 1223 1224 1225 1226
	     (or (eq cua-enable-cua-keys t)
		 (not cua--explicit-region-start))
	     (not executing-kbd-macro)
	     (not cua--prefix-override-timer)))
  (setq cua--ena-prefix-repeat-keymap
	(and cua--ena-region-keymap
	     (timerp cua--prefix-override-timer)))
  (setq cua--ena-cua-keys-keymap
	(and cua-enable-cua-keys
1227
	     (not cua-inhibit-cua-keys)
1228 1229 1230 1231 1232 1233 1234 1235 1236 1237
	     (or (eq cua-enable-cua-keys t)
		 cua--last-region-shifted)))
  (setq cua--ena-global-mark-keymap
	(and cua--global-mark-active
	     (not (window-minibuffer-p)))))

(defvar cua--keymaps-initalized nil)

(defun cua--init-keymaps ()
  (unless (eq cua-use-hyper-key 'only)
Kim F. Storm's avatar
Kim F. Storm committed
1238
    (define-key cua-global-keymap [(control return)]	'cua-set-rectangle-mark))
1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252
  (when cua-use-hyper-key
    (cua--M/H-key cua-global-keymap 'space	'cua-set-rectangle-mark)
    (define-key cua-global-keymap [(hyper mouse-1)] 'cua-mouse-set-rectangle-mark))

  (define-key cua-global-keymap [(shift control ? )]	'cua-toggle-global-mark)

  ;; replace region with rectangle or element on kill ring
  (define-key cua-global-keymap [remap yank]		'cua-paste)
  (define-key cua-global-keymap [remap clipboard-yank]	'cua-paste)
  ;; replace current yank with previous kill ring element
  (define-key cua-global-keymap [remap yank-pop]		'cua-paste-pop)
  ;; set mark
  (define-key cua-global-keymap [remap set-mark-command]	'cua-set-mark)

1253 1254 1255 1256
  ;; scrolling
  (define-key cua-global-keymap [remap scroll-up]	'cua-scroll-up)
  (define-key cua-global-keymap [remap scroll-down]	'cua-scroll-down)

1257 1258 1259 1260
  (define-key cua--cua-keys-keymap [(control x) timeout] 'kill-region)
  (define-key cua--cua-keys-keymap [(control c) timeout] 'copy-region-as-kill)
  (define-key cua--cua-keys-keymap [(control z)] 'undo)
  (define-key cua--cua-keys-keymap [(control v)] 'yank)
1261
  (define-key cua--cua-keys-keymap [(meta v)] 'cua-repeat-replace-region)
1262 1263 1264 1265
  (define-key cua--cua-keys-keymap [remap exchange-point-and-mark] 'cua-exchange-point-and-mark)

  (define-key cua--prefix-override-keymap [(control x)] 'cua--prefix-override-handler)
  (define-key cua--prefix-override-keymap [(control c)] 'cua--prefix-override-handler)
1266

1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277
  (define-key cua--prefix-repeat-keymap [(control x) (control x)] 'cua--prefix-repeat-handler)
  (define-key cua--prefix-repeat-keymap [(control x) up]    'cua--prefix-cut-handler)
  (define-key cua--prefix-repeat-keymap [(control x) down]  'cua--prefix-cut-handler)
  (define-key cua--prefix-repeat-keymap [(control x) left]  'cua--prefix-cut-handler)
  (define-key cua--prefix-repeat-keymap [(control x) right] 'cua--prefix-cut-handler)
  (define-key cua--prefix-repeat-keymap [(control c) (control c)] 'cua--prefix-repeat-handler)
  (define-key cua--prefix-repeat-keymap [(control c) up]    'cua--prefix-copy-handler)
  (define-key cua--prefix-repeat-keymap [(control c) down]  'cua--prefix-copy-handler)
  (define-key cua--prefix-repeat-keymap [(control c) left]  'cua--prefix-copy-handler)
  (define-key cua--prefix-repeat-keymap [(control c) right] 'cua--prefix-copy-handler)

1278
  ;; Enable shifted fallbacks for C-x and C-c when region is active
1279 1280
  (define-key cua--region-keymap [(shift control x)] 'Control-X-prefix)
  (define-key cua--region-keymap [(shift control c)] 'mode-specific-command-prefix)
1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294
  ;; replace current region
  (define-key cua--region-keymap [remap self-insert-command]	'cua-replace-region)
  (define-key cua--region-keymap [remap self-insert-iso]	'cua-replace-region)
  (define-key cua--region-keymap [remap insert-register]	'cua-replace-region)
  (define-key cua--region-keymap [remap newline-and-indent]	'cua-replace-region)
  (define-key cua--region-keymap [remap newline]		'cua-replace-region)
  (define-key cua--region-keymap [remap open-line]		'cua-replace-region)
  ;; delete current region
  (define-key cua--region-keymap [remap delete-backward-char]	'cua-delete-region)
  (define-key cua--region-keymap [remap backward-delete-char]	'cua-delete-region)
  (define-key cua--region-keymap [remap backward-delete-char-untabify] 'cua-delete-region)
  (define-key cua--region-keymap [remap delete-char]		'cua-delete-region)
  ;; kill region
  (define-key cua--region-keymap [remap kill-region]		'cua-cut-region)
1295
  (define-key cua--region-keymap [remap clipboard-kill-region]	'cua-cut-region)
1296 1297 1298
  ;; copy region
  (define-key cua--region-keymap [remap copy-region-as-kill]	'cua-copy-region)
  (define-key cua--region-keymap [remap kill-ring-save]		'cua-copy-region)
1299
  (define-key cua--region-keymap [remap clipboard-kill-ring-save] 'cua-copy-region)
1300 1301 1302 1303 1304
  ;; cancel current region/rectangle
  (define-key cua--region-keymap [remap keyboard-escape-quit]	'cua-cancel)
  (define-key cua--region-keymap [remap keyboard-quit]		'cua-cancel)
  )

1305 1306 1307 1308 1309 1310 1311 1312

;; Setup standard movement commands to be recognized by CUA.

(dolist (cmd
 '(forward-char backward-char
   next-line previous-line
   forward-word backward-word
   end-of-line beginning-of-line
1313
   move-end-of-line move-beginning-of-line
1314 1315 1316 1317 1318 1319
   end-of-buffer beginning-of-buffer
   scroll-up scroll-down
   forward-sentence backward-sentence
   forward-paragraph backward-paragraph))
  (put cmd 'CUA 'move))

1320 1321 1322 1323 1324 1325 1326
;; State prior to enabling cua-mode
;; Value is a list with the following elements:
;;   transient-mark-mode
;;   delete-selection-mode
;;   pc-selection-mode

(defvar cua--saved-state nil)
1327 1328

;;;###autoload
1329
(define-minor-mode cua-mode
1330 1331 1332 1333 1334
  "Toggle CUA key-binding mode.
When enabled, using shifted movement keys will activate the region (and
highlight the region using `transient-mark-mode'), and typed text replaces
the active selection.  C-z, C-x, C-c, and C-v will undo, cut, copy, and
paste (in addition to the normal emacs bindings)."
1335
  :global t
Lute Kamstra's avatar
Lute Kamstra committed
1336
  :group 'cua
1337 1338 1339
  :set-after '(cua-enable-modeline-indications cua-use-hyper-key)
  :require 'cua-base
  :link '(emacs-commentary-link "cua-base.el")
1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354
  (setq mark-even-if-inactive t)
  (setq highlight-nonselected-windows nil)
  (make-variable-buffer-local 'cua--explicit-region-start)
  (make-variable-buffer-local 'cua--status-string)

  (unless cua--keymaps-initalized
    (cua--init-keymaps)
    (setq cua--keymaps-initalized t))

  (if cua-mode
      (progn
	(add-hook 'pre-command-hook 'cua--pre-command-handler)
	(add-hook 'post-command-hook 'cua--post-command-handler)
	(if (and cua-enable-modeline-indications (not (assoc 'cua-mode minor-mode-alist)))
	    (setq minor-mode-alist (cons '(cua-mode cua--status-string) minor-mode-alist)))
Kim F. Storm's avatar