I have functions that run re-search-forward
and gather its output into a buffer.
(defun my-search (pattern)
"Uses `re-search-forward` to return matching lines."
(let ((src)
(rslt))
(progn
(goto-char (re-search-forward pattern))
(save-excursion
(setq rslt (buffer-substring (progn (beginning-of-line-text)(point))
(progn (end-of-line) (point)))))
(format "%s\n\n" rslt))))
(defun my-search-results ()
"Iterate through buffer with `my-search` and gather matching lines into a buffer."
(interactive)
(let ((pattern (read-regexp "Regex Pattern to Search for: "))
(rslt (generate-new-buffer "*Search Results*"))
(match 0)
(nlines 0)
(current-line 0))
(while (not (eq (ignore-errors (save-excursion (re-search-forward pattern))) nil))
(princ (my-search pattern) rslt)
(incf match))
(switch-to-buffer "*Search Results*")))
We all know that Occur
will display "%d matches in %d lines."
in its search result. How do we do the same for these functions without repetition when there is more than one match in a line?
Currently, match
would keep track of the number of iteration cycles, which should be equivalent to the number of matching pattern found.
Adding an if
clause to my-search-results
doesn't solve the problem.
(defun my-search-results ()
(interactive)
(let ((pattern (read-regexp "Regex Pattern to Search for: "))
(rslt (generate-new-buffer "*Search Results*"))
(match 0)
(nlines 0)
(current-line 0))
(beginning-of-buffer)
(while (not (eq (ignore-errors (save-excursion (re-search-forward pattern))) nil))
(princ (my-search pattern) rslt)
(incf nlines)
(incf match)
(if (= (line-number-at-pos)
(save-excursion
(progn
(re-search-forward pattern)
(point))))
(progn (re-search-forward pattern)
(incf match))))
(message "%d matches in %d lines." match nlines)
(switch-to-buffer "*Search Results*")))
Test Data:
abacd
efgja
ogjfh
Desired Outcome:
M-xmy-search-results a
;; Result:
;; abacd
;; efgja
;; 3 matches in 2 lines.