From a111978de8fa28256a208d823b68a37188dfa7f0 Mon Sep 17 00:00:00 2001 From: Lars Ingebrigtsen Date: Mon, 5 Jul 2021 16:30:43 +0200 Subject: [PATCH] Count zero-length matches in `count-matches' correctly * lisp/replace.el (how-many): Count zero-length matches correctly (bug#27359). --- lisp/replace.el | 12 ++++++------ test/lisp/replace-tests.el | 11 +++++++++++ 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/lisp/replace.el b/lisp/replace.el index fe2cbc447a6..ed81097e149 100644 --- a/lisp/replace.el +++ b/lisp/replace.el @@ -1089,17 +1089,17 @@ a previously found match." rend (point-max))) (goto-char rstart)) (let ((count 0) - opoint (case-fold-search (if (and case-fold-search search-upper-case) (isearch-no-upper-case-p regexp t) case-fold-search))) (while (and (< (point) rend) - (progn (setq opoint (point)) - (re-search-forward regexp rend t))) - (if (= opoint (point)) - (forward-char 1) - (setq count (1+ count)))) + (re-search-forward regexp rend t)) + ;; Ensure forward progress on zero-length matches like "^$". + (when (and (= (match-beginning 0) (match-end 0)) + (not (eobp))) + (forward-char 1)) + (setq count (1+ count))) (when interactive (message (ngettext "%d occurrence" "%d occurrences" count) diff --git a/test/lisp/replace-tests.el b/test/lisp/replace-tests.el index 2db570c97dd..6d004e657d0 100644 --- a/test/lisp/replace-tests.el +++ b/test/lisp/replace-tests.el @@ -601,4 +601,15 @@ bound to HIGHLIGHT-LOCUS." (if (match-string 2) "R" "L"))) (should (equal (buffer-string) after))))) +(ert-deftest test-count-matches () + (with-temp-buffer + (insert "oooooooooo") + (goto-char (point-min)) + (should (= (count-matches "oo") 5)) + (should (= (count-matches "o+") 1))) + (with-temp-buffer + (insert "o\n\n\n\no\n\n") + (goto-char (point-min)) + (should (= (count-matches "^$") 4)))) + ;;; replace-tests.el ends here -- 2.39.2