lkahtz
lkahtz

Reputation: 4796

Emacs - mark the word forward and backward

Basically what I am asking is the equivalent function to vim's vb(bbww...) and vw(wwbb...):

I want to bind my meta-j and meta-k to mark the word before and after current point. Simple.el provided the mark-word function, which I bind to meta-k. And I changed the mark-word function a bit to:

 (defun mark-backward (&optional arg   allow-extend) ;   
      (interactive "P\np")
      (cond ((and allow-extend
               (or (and (eq last-command this-command) (mark t))
                   (and transient-mark-mode mark-active)))
      (setq arg (if arg (prefix-numeric-value arg)
               (if (< (mark) (point)) -1 1)))
                   (set-mark
                       (save-excursion
                           (goto-char (mark))
                           (forward-word arg)
                           (point))))   
      (t   (push-mark  
        (save-excursion
        (backward-word (prefix-numeric-value arg))
        (point))      nil t)))) 
(global-set-key (kbd "M-k") 'mark-word) 
(global-set-key (kbd "M-j") 'mark-backward)

This kinda worked. I want to undo some marking use the other key, how can I do that? (i.e. after I marked some word with M-k, I want to use M-j to unmark some word to left. Currently, when I hit M-j, emacs continue to mark forward).

Upvotes: 1

Views: 2617

Answers (2)

phimuemue
phimuemue

Reputation: 35983

(defun my-mark-word (N)
  (interactive "p")
  (if (and 
       (not (eq last-command this-command))
       (not (eq last-command 'my-mark-word-backward)))
      (set-mark (point)))
  (forward-word N))


(defun my-mark-word-backward (N)
  (interactive "p")
  (if (and
       (not (eq last-command this-command))
       (not (eq last-command 'my-mark-word)))
      (set-mark (point)))
  (backward-word N))

(local-set-key (kbd "M-k") 'my-mark-word)

(local-set-key (kbd "M-j") 'my-mark-word-backward)

This should emulate VIMs behaviour (with other keystrokes, of course).

Remark: M-j is by default bound to indent-new-comment-line which is quite handy when writing commented blocks in source code. M-k is by default bound to kill-sentence.

Upvotes: 3

Lindydancer
Lindydancer

Reputation: 26104

You should replace forward-word with backward-word in one more place.

The code, however, still have problems selecting words to the left of the point.

Ps. Please edit your post -- the code posted is barely readable.

Upvotes: 0

Related Questions