Subject: bug#14013: 24.3.50; dired-isearch-filenames-regexp is matching text outside filenames

From: Juri Linkov <[email-masked]>
Date: Sun, 03 Apr 2022 21:05:07 +0300

>> I wonder if it is realistic to use a temporary helper buffer to
>> implement ^.
>
> Good idea.  Maybe even not a buffer, but just a string.
> Are there any differences between buffer matching and string matching?
>
> Then first we could remove ^ from the search regexp, and when it finds
> something, then get the found buffer-substring using text properties
> and match it with the original regexp that contains ^.

This works surprisingly well.  Maybe there are more corner cases,
but something already works with quick tests:

diff --git a/lisp/dired-aux.el b/lisp/dired-aux.el
index c49e4e91d8..0832ea1ddb 100644
--- a/lisp/dired-aux.el
+++ b/lisp/dired-aux.el
@@ -3202,7 +3202,16 @@ dired-isearch-search-filenames
                          (if isearch-forward old (max (1- old) (point-min)))
                          property)
                     old))
-             end found)
+             end found regexp (i 0))
+        (when isearch-regexp
+          (setq regexp string)
+          (while (string-match "\\^\\|\\$\\|\\\\`\\|\\\\'" string i)
+            (setq i (- (match-end 0) (length (match-string 0 string))))
+            (if (save-match-data (not (subregexp-context-p
+                                       string (match-beginning 0))))
+                ;; The ^/$ is inside a char-range or escaped or something.
+                nil
+              (setq string (replace-match "" t t string)))))
         ;; Otherwise, try to search for the next property.
         (unless beg
           (setq beg (if isearch-forward
@@ -3221,6 +3230,9 @@ dired-isearch-search-filenames
                                                      (max bound end))
                                            end)
                        noerror count))
+          (when (and regexp (not (string-match-p
+                                  regexp (buffer-substring beg end))))
+            (setq found nil))
           (unless found
             (setq beg (if isearch-forward
                           (next-single-property-change end property)