Function: line-number-at-pos

line-number-at-pos is a function defined in fns.c.

Signature

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

Documentation

Return the line number at POSITION in the current buffer.

If POSITION is nil or omitted, it defaults to point's position in the current buffer.

If the buffer is narrowed, the return value by default counts the lines from the beginning of the accessible portion of the buffer. But if the second optional argument ABSOLUTE is non-nil, the value counts the lines from the absolute start of the buffer, disregarding the narrowing.

View in manual

Probably introduced at or before Emacs version 22.1.

Source Code

// Defined in /usr/src/emacs/src/fns.c
{
  ptrdiff_t pos_byte, start_byte = BEGV_BYTE;

  if (!BUFFER_LIVE_P (current_buffer))
    error ("Attempt to count lines in a dead buffer");

  if (MARKERP (position))
    {
      /* We don't trust the byte position if the marker's buffer is
         not the current buffer.  */
      if (XMARKER (position)->buffer != current_buffer)
	pos_byte = CHAR_TO_BYTE (marker_position (position));
      else
	pos_byte = marker_byte_position (position);
    }
  else if (NILP (position))
    pos_byte = PT_BYTE;
  else
    {
      CHECK_FIXNUM (position);
      ptrdiff_t pos = XFIXNUM (position);
      /* Check that POSITION is valid. */
      if (pos < BEG || pos > Z)
	args_out_of_range_3 (position, make_int (BEG), make_int (Z));
      pos_byte = CHAR_TO_BYTE (pos);
    }

  if (!NILP (absolute))
    start_byte = BEG_BYTE;
  else if (NILP (absolute))
    pos_byte = clip_to_bounds (BEGV_BYTE, pos_byte, ZV_BYTE);

  /* Check that POSITION is valid. */
  if (pos_byte < BEG_BYTE || pos_byte > Z_BYTE)
    args_out_of_range_3 (make_int (BYTE_TO_CHAR (pos_byte)),
			 make_int (BEG), make_int (Z));

  return make_int (count_lines (start_byte, pos_byte) + 1);
}