Emacs Lisp: Using thing-at-point

By Xah Lee. Date: . Last updated: .

This page shows you how to use emacs lisp's thing-at-point function to get text from buffer into a string.


When writing interactive commands, one of the most useful function is thing-at-point.

thing-at-point lets you get the current word under cursor into a string. (or, current line, current sentence, paragraph, file, URL, defun, ….)

Here's a example.

(defun xx ()
  "print current word."
  (message "%s" (thing-at-point 'word)))

Evaluate the code, then try it. 〔►see How to Evaluate Emacs Lisp Code

Finding the Positions of a Thing's Boundary

Sometimes you also need to know a thing's boundary, because you may need to delete it (using (delete-region position1 position2)).

bounds-of-thing-at-point returns the boundary positions of the text unit under cursor.

(defun my-get-boundary-and-thing ()
  "example of using `bounds-of-thing-at-point'"
  (let (bounds pos1 pos2 mything)
    (setq bounds (bounds-of-thing-at-point 'symbol))
    (setq pos1 (car bounds))
    (setq pos2 (cdr bounds))
    (setq mything (buffer-substring-no-properties pos1 pos2))

     "thing begin at [%s], end at [%s], thing is [%s]"
     pos1 pos2 mything)))
Like it? Buy Xah Emacs Tutorial. Thanks.

or, buy something from Best Keyboard for Emacs