About the forward and backward a word behaviour in Emacs

Ok, just so we're clear, Im going to assume you are talking about the commands forward-word and backward-word these are bound by default to Alt+f and Alt+b

eg string: "Hello dolly I am here"

If your cursor is on the "H" of "Hello", and you do forward-word the cursor will move to the space between "Hello" and "dolly", but it sounds like you want the cursor to be on the letter "d" of "dolly" instead of in-front of it.

So, do forward-word twice, then backward-word once.

That will put your cursor on the "d" of "dolly".

This can be automated with a macro.

;; = comments, do not type them

Ctrl+x ( ;;start macro

Alt+f Alt+f Alt+b

Ctrl+x ) ;;end macro

Then to run last defined macro do this:

Ctrl+x e

EDIT: as pascal mentioned in a comment, this can also just be done with

Alt+f Ctrl+f

You could put that into a macro as well, either way the result is the same.


The macro solution described is a great way to get this behavior in a session, but it's a little inconvenient if that's the default behavior you want, since you have to define it every time you start emacs. If you want M-f to work like this all the time, you can define an elisp function and bind it to the key. Put this in your .emacs file:

(defun next-word (p)
   "Move point to the beginning of the next word, past any spaces"
   (interactive "d")
   (forward-word)
   (forward-word)
   (backward-word))
(global-set-key "\M-f" 'next-word)

Tags:

Emacs

Command