]> git.eshelyaron.com Git - emacs.git/commitdiff
Count zero-length matches in `count-matches' correctly
authorLars Ingebrigtsen <larsi@gnus.org>
Mon, 5 Jul 2021 14:30:43 +0000 (16:30 +0200)
committerLars Ingebrigtsen <larsi@gnus.org>
Mon, 5 Jul 2021 14:30:43 +0000 (16:30 +0200)
* lisp/replace.el (how-many): Count zero-length matches correctly
(bug#27359).

lisp/replace.el
test/lisp/replace-tests.el

index fe2cbc447a623f5f016ee401b604e51941392f68..ed81097e1499c3c7af6069dbc8e640db43cedeec 100644 (file)
@@ -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)
index 2db570c97dd5f4ebef0af4643f9e0118caa6feff..6d004e657d0476001628569f54a022391b6c35c3 100644 (file)
@@ -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