Elisp: Using thing-at-point
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 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.
Writing Emacs Command
Patreon me $5. Ask me question on patreon