Subject: Re: bug#65877: 29.1; line-number-at-pos crashes with args-out-of-range when ran using emacsclient

From: Eli Zaretskii <[email-masked]>
Date: Tue, 12 Sep 2023 14:28:59 +0300

tags 65877 notabug
thanks

> From: Michaël Cadilhac <[email-masked]>
> Date: Mon, 11 Sep 2023 16:07:42 -0500
> 
> How to reproduce: start with
> 
> $ emacs -Q
> 
> M-x server-start
> 
> Open a file with say 200 lines, scroll at the bottom, so that the
> first line of the file is not at the top of the window.
> 
> Then in a shell, run:
> 
> $ emacsclient -e '(line-number-at-pos (window-start))'
> *ERROR*: Args out of range: 146, 1, 1

This is a cockpit error, not a bug.  The doc string of
line-number-at-pos says:

  line-number-at-pos is a built-in function in ‘src/fns.c’.

  (line-number-at-pos &optional POSITION ABSOLUTE)

  Return the line number at POSITION in the current buffer.
                                     ^^^^^^^^^^^^^^^^^^^^^

So the correct form to evaluate is this:

  $ emacsclient -e "(with-current-buffer (window-buffer) (line-number-at-pos (window-start)))"

IOW, you must make sure the buffer of the selected window is current
when the server evaluates the expression.  It is not guaranteed by
default:

  $ emacsclient -e "(message \"%s\" (current-buffer))"
  " *server*"