Emacs: Calling cua-mode cua-set-rectangle-mark from within custom function

701 views Asked by At

Currently I use cua-mode for its column/rectangle facilities like so (I don't used it for copy/pasting):

M-x cua-mode ; Enable cua-mode
<C-return>   ; Call cua-set-rectangle-mark

Then when I'm done with my rectangle:

C-g          ; Call cua-cancel

The bindings for CUA mode clash with other mode bindings (e.g. in org mode) so I sometimes find myself having to turn cua-mode on/off. I only ever use it for its rectangles - so I would like to solve this nuisance by doing two thing:

1) Bind a key (say f6) to a function which enables cua-mode if it is not already enabled and calls cua-set-rectangle-mark so I can create my rectangle.

2) Override C-g whilst cua-mode is active so that when pressed not only does it exit any rectangle but it also exits cua-mode.

So then my workflow would be:

<f6> ; Enter cua-mode and call cua-set-rectangle-mark
C-g  ; Call cua-cancel and disable cua-mode

That way I would not need constantly toggle cua-mode on/off when there are clashes.

For part 1 I've come up with:

(defun cua-activate-plus-set-rectangle-mark()
 (interactive)
 (cua-set-rectangle-mark))

(global-set-key (kbd "<f6>") 'cua-activate-plus-set-rectangle-mark)

Pressing f6 works when cua-mode is already enabled but does not when cua-mode is not enabled. If I change it to be like so:

(defun cua-activate-plus-set-rectangle-mark()
 (interactive)
 (cua-mode)
 (cua-set-rectangle-mark))

then it doesn't work at all regardless of whether I started with cua-mode enabled or not.

For part 2 I have:

(defun cua-mode-off()
 "Cancels any open active region/rectangle and turns CUA mode off"
 (interactive)
 (cua-cancel)
 (setq cua-mode nil))

The function does exactly what I want it to but I do not know how to bind it to C-g when cua-mode is enabled.

So my questions:

1) How can I write the function to enter cua-mode and call cua-set-rectangle-mark so it works as expected?

2) How can I override C-g only whilst cua-mode is active to call my custom function?

1

There are 1 answers

0
Aaron Harris On BEST ANSWER

I think the behavior you're looking for already exists. Take a look at cua-rectangle-mark-mode. From the manual:

CUA mode provides enhanced rectangle support with visible rectangle highlighting. Use C-RET to start a rectangle, extend it using the movement commands, and cut or copy it using C-x or C-c. RET moves the cursor to the next (clockwise) corner of the rectangle, so you can easily expand it in any direction. Normal text you type is inserted to the left or right of each line in the rectangle (on the same side as the cursor).

You can use this rectangle support without activating CUA by calling the cua-rectangle-mark-mode command. But see also the standard rectangle-mark-mode. See Rectangles.