0

I'd like to write an elisp function that tells me the line number of the closest regex match above my current cursor position.

For example, if my cursor is on line 9 of the following file and my regex pattern is ^george, then the line number is 6.

 1  john
 2  paul
 3  george
 4  ringo
 5  hello world
 6  george ringo
 7  john paul
 8  hello george
 9  paul
10  george
1

1 Answer 1

1

You can use re-search-backward for the search and count-lines to get the line number.

Code example:

(defun re-match-line-backward (regexp &optional bound noerror count)
  "Return line number of match for REGEXP before point.
This uses `re-search-backward' with REGEXP, BOUND, NOERROR and COUNT.
It does not move point."
  (interactive (list (read-regexp "Regexp: ")))
  (save-excursion
    (when (re-search-backward regexp bound noerror count)
      (let ((line (1+ (count-lines (point-min) (line-beginning-position)))))
        (when (called-interactively-p 'any)
        (message "Regexp %s found at line %d" regexp line))
        line))))
1
  • 1
    line-number-at-pos rather than count-lines, I think
    – rpluim
    Jul 19, 2022 at 9:26

Your Answer

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

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