What's the most reliable way to get the start and end positions of the symbol at the cursor location (point)?
2 Answers
The thingatpt.el
API works as follows:
(thing-at-point 'symbol) ;=> foo
(beginning-of-thing 'symbol) ;=> 42
(end-of-thing 'symbol) ;=> 45
(bounds-of-thing-at-point 'symbol) ;=> (42 . 45)
While it's not 100% reliable as it relies on (forward-thing 'symbol)
to do the right thing, it's pretty good and one of the better APIs in Emacs. Give it a try!
-
Note that, unless someone takes steps to make it do otherwise,
(forward-thing 'symbol)
callsforward-symbol
which certainly does the right thing in terms of the buffer's syntax table and the syntax-based definition of "symbol".– philsCommented Jun 21, 2017 at 13:00
I would expect symbol-at-point
to be reliable.
Given that you yourself tagged this question with thing-at-point
, are you asking in particular whether there are flaws with this method?
-
symbol-at-point
orthing-at-point
returns current symbol at point, but I'd like to get the start/endpoint
(the exact boundary) of this symbol...😅 Commented Jun 21, 2017 at 11:43 -
Oh yes. I ought to have said
(bounds-of-thing-at-point 'symbol)
. But the same question applies -- you seem to already be aware ofthing-at-point
(and hence thethingatpt.el
library in general), so are you specifically questioning its reliability, or was it simply that you hadn't noticed the function in question?– philsCommented Jun 21, 2017 at 12:39 -
I hadn't noticed the function, though I use
thing-at-point
quite often ...And as @wasamasa pointed out, the function may not be 100% reliable, though I've not encountered such situations. Thanks for you information. Commented Jun 21, 2017 at 12:52 -
I've run into it being unreliable with Evil and other modes doing weird things, see github.com/emacs-evil/evil/issues/844 for example.– wasamasaCommented Jun 21, 2017 at 16:46
-
That particular instance sounds like an issue with the evil library's thing-at-point handler(s) for
evil-defun
rather thansymbol
, though? I would expect the handling ofsymbol
to be reliable. For the standard "things" I would expect this to be as reliable as other methods for obtaining the same information (but certainly there may be bugs for more complex "things" where the behaviour may be down to individual modes to define).– philsCommented Jun 21, 2017 at 22:07