Emacs Lisp: Using thing-at-point

By Xah Lee. Date: . Last updated: .

This page shows you how to use thing-at-point function to get text unit such as current {word, line, text block, file path, buffer, etc} 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
(thing-at-point THING &optional NO-PROPERTIES)
Return a string that's the current THING under cursor. Thing is a word, file path, url, line, etc. THING should be any of 'symbol, 'list, 'sexp, 'defun, 'filename, 'url, 'email, 'uuid, 'word, 'sentence, 'whitespace, 'line, 'number, 'page.

Here's a example.

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

Evaluate the code, then try it. [see Evaluate Emacs Lisp Code]

Get Boundary Positions of a Thing

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
Return a cons cell (cons pos1 pos2) that's 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 Emacs Lisp: Syntax Table]

Problems of thing-at-point

Emacs Lisp: Problems of thing-at-point


Practical Elisp ⭐

Writing Command

Text Processing

Get User Input

File/Buffer

Writing Script