2

What's the most reliable way to get the start and end positions of the symbol at the cursor location (point)?

2 Answers 2

6

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!

1
  • Note that, unless someone takes steps to make it do otherwise, (forward-thing 'symbol) calls forward-symbol which certainly does the right thing in terms of the buffer's syntax table and the syntax-based definition of "symbol".
    – phils
    Jun 21, 2017 at 13:00
1

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?

5
  • symbol-at-point or thing-at-point returns current symbol at point, but I'd like to get the start/end point(the exact boundary) of this symbol...😅 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 of thing-at-point (and hence the thingatpt.el library in general), so are you specifically questioning its reliability, or was it simply that you hadn't noticed the function in question?
    – phils
    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. 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.
    – wasamasa
    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 than symbol, though? I would expect the handling of symbol 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).
    – phils
    Jun 21, 2017 at 22:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.