10

In emacs there are the functions forward-word and backward-word. Are there also functions which move the point to the next/last whitespace?

Julia
  • 415

2 Answers2

11

Use forward-whitespace to advance by spaces, tabs or newlines. Multiple spaces are treated as one delimiter. With a negative argument, go backwards by that number of whitespaces.

  • 1
    Any idea how to advance to the first whitespace after a block of text, without skipping any? forward-whitespace seems to skip to the end of the line when I have trailing spaces on a line. I really just want to find the first trailing space. Thanks for any help. – Dave Nov 13 '15 at 08:03
  • 1
    @Dave : (lambda () (forward-whitespace) (forward-whitespace -1)) – Dean Serenevy May 19 '17 at 10:27
  • Any idea how to do backward-whitespace? – Noah May 08 '21 at 21:07
  • 1
    @Noah See https://emacs.stackexchange.com/a/26098/7059 for how to define backward-whitespace. – gsgx Aug 15 '22 at 00:14
  • @Noah (forward-whitespace -1) or C-u -1 M-x forward-whitespace – Philipp Ludwig Aug 18 '23 at 11:47
7

You can modify the syntactical properties of characters using the modify-syntax-entry function (C-h f modify-syntax-entry in emacs for more info):

For instance, if you are writing .tex documents, you might add the following to your .emacs:

(add-hook
 'TeX-mode-hook
 '(lambda ()
    (modify-syntax-entry ?_ "w")
    (modify-syntax-entry ?- "w")
))

This tells emacs to treat _ and - as "word" characters when you are in TeX mode, thus forward-word and backward-word will do what you want.

Dean Serenevy
  • 516
  • 2
  • 6
  • Does this break emacs packages that rely on what a word is? – ritchie Mar 16 '23 at 17:29
  • @ritchie It will only modify the syntax table for the chosen mode, so will have limited scope for mischief. I'd expect most packages to behave fine (I use this trick in other modes, not TeX), so "try it and find out"? :) – Dean Serenevy Mar 17 '23 at 18:35