Subject: Re: bug#22763: 25.1.50; Feature Request -- A faster method to obtain line number at position.

From: Eli Zaretskii <[email-masked]>
Date: Mon, 22 Feb 2016 18:06:37 +0200

> Date: Sun, 21 Feb 2016 18:42:52 -0800
> From: Keith David Bershatsky <[email-masked]>
> 
> A while back, I posed a question on emacs.stackexchange.com for a faster method to obtain `line-number-at-pos`.  A user by the name of Constantine came up with `(format-mode-line "%l")`, which is indeed much faster.  I think the draft code below may be just a tad faster, with the added feature of the POS argument.
> 
> http://emacs.stackexchange.com/questions/3821/a-faster-method-to-obtain-line-number-at-pos-in-large-buffers
> 
> A user named wasamasa posted a comment: "Be aware that this method will give you "??" for lines exceeding line-number-display-limit-width which is set to a value of 200 per default as I found out here."
> 
> And Stefan posted a comment:  "IIRC the result may also be unreliable if there have been modifications in the buffer since the last redisplay."
> 
> The thread has received 555 hits in the past year, and several have star-ed it and up-voted the question and answer.
> 
> The following is a draft in C based on the existing function `decode_mode_spec` that lets the user input the POS as an argument without the necessity to use `goto-char`.  I'm not sure if it resolves either of the comments above.  The draft is not meant to be a patch per se, because I'm not a programmer and am just beginning my tinkering quest into the language of C.  I have been using it in my own setup for about a week and I haven't seen any ill effects.  It can of course use some TLC by someone more knowledgeable than myself.

This would overwrite the line number and position cached by each
window for redisplay purposes.  I think this is undesirable.  More
importantly, the gotchas pointed out above will still be true, AFAICT.

My suggestion is instead to expose display_count_lines to Lisp via a
simple wrapper (that would need to take care of narrowing and such
likes, something that your proposed API doesn't do, btw).  In my
limited testing I saw a 5- to 10-fold speedup as compared to
line-number-at-pos, when doing that.  I think this is good enough;
applications that need faster massive counting, if there are such
applications, can implement a cache in Lisp and speed this up even
more.

Thanks.