Elisp: 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, etc.)

Here's a example.

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

Evaluate the code, then try it. [see 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)))

thing-at-point and Syntax Table

The exact meaning of “thing”, depends on current buffer's syntax table.

[see Elisp: Syntax Table Tutorial]

Writing Emacs Command

  1. Elisp: How to Write Commands
  2. Elisp: Region, Active Region
  3. Elisp: Get Buffer String
  4. Elisp: Functions on Line
  5. Elisp: Cut Copy Paste to/from kill-ring
  6. Elisp: Get User Input
  7. Elisp: Get universal-argument
  8. Elisp: Find Replace String in Buffer
  9. Elisp: Using thing-at-point
Patreon me $5 patreon

Or Buy Xah Emacs Tutorial

Or buy a nice keyboard: Best Keyboard for Emacs

If you have a question, put $5 at patreon and message me.