Own JS/CSS options

Friday, March 9, 2012

Emacs Snippets: Kill Region or Line, Toggle Case

Two code snippets that solved problems random people on #emacs had. The first implements a specific behavior for C-w, the other toggles case at point.

Kill Region or to Beginning of Line

One user was confused by the behavior of kill-region (by default on C-w), which deletes the current region and appends it to the kill ring. Emacs traditionally differs from modern systems by always having a region (the equivalent to a “selection”) active.

Emacs monitors two special positions in any buffer. The first is called “point.” It’s the place where you enter text. The second is “mark,” and is some other place in the buffer. You can set mark using C-SPC. The text between point and mark is called “the region,” and many commands work on the region.

What confuses newer users not used to this is that you can not usually see the region. To alleviate this and add some other features, Emacs has for some time now added the so-called transient mark mode, in which the region is highlighted until a non-region moving command is issued. This implements most of the effects that newer users expect. Except, well, when they use C-w when no region is selected, (apparently) random parts of text vanish.

The following code changes that behavior. When the region is “active,” i.e. highlighted, it is deleted and appended to the kill ring as usual. When it is not active, the command will delete the current line (from point to the beginning of the line) and append it to the kill ring.

Not something I would use, but it seems to have solved that user’s problem.

(defun weird-c-w-command ()
  "Kill the region if active. Else, kill to beginning of line."
  (interactive)
  (if (region-active-p)
      (call-interactively 'kill-region)
    (kill-region (point-at-bol)
                 (point))))

Add that and the following to your .emacs to use it instead of the default for C-w:

(global-set-key (kbd "C-w") 'weird-c-w-command)

Toggle Case at Point

Another user was used to vi’s command to toggle case at point. While Emacsers usually would use M-c or M-l to capitalize or lower-case the current word starting at the current char, Emacs is customizeable to accomodate user’s wishes.

(defun toggle-case ()
  "Toggle the case of the char at point."
  (interactive)
  (let ((char (buffer-substring (point)
                                (1+ (point)))))
    (if (equal (upcase char)
               char)
        (downcase-region (point)
                         (1+ (point)))
      (upcase-region (point)
                     (1+ (point))))))

Bind to a key of your preference. Note that this is not exactly equivalent to the vi command ~, but the differences can be implemented if needed.