Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search for the nth occurence of a pattern in Emacs?

Tags:

emacs

I am trying to avoid elisp as much as possible. I think I am able to implement a solution to my problem in Elisp, but that's not what I am looking for.

I am looking for the nth occurence of a string in a buffer. For instance looking after the 4th occurence of foo, I've tried C-u C-s foo. But C-s does not interpret prefixes.

Is there a simple/elegant key sequence in Emacs to perform that job?

like image 326
yves Baumes Avatar asked Apr 03 '14 12:04

yves Baumes


1 Answers

search-forward is a simple function to search the next occurrence of a string. It also accepts an optional COUNT argument searching for the next COUNT successive occurrences.

Unfortunately you cannot call it with a prefix argument, because it queries for input.

You already guessed the answer: throw together some elisp.

This function queries you for a string and a count and performs the search:

(defun search-forward-count (string count)
  (interactive "sString: \nnCount: ")
  (re-search-forward string nil nil count))

This function queries you for a string and uses the prefix argument as its count:

(defun search-forward-prefix (count string)
  (interactive "p\nsString: ")
  (re-search-forward string nil nil count))
like image 151
pmr Avatar answered Oct 16 '22 05:10

pmr