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.

thing-at-point

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."
  (interactive)
  (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'"
  (interactive)
  (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))

    (message
     "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]

Elisp: Writing Command

  1. Writing Command, Basics
  2. Mark and Region
  3. Get Buffer String
  4. Work with Lines
  5. Copy Cut Paste kill-ring
  6. Get User Input
  7. Interactive Form
  8. Get universal-argument
  9. Find Replace Text
  10. 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.