;;; syd-search.el -*- lexical-binding: t; -*-

(cl-defun syd-search-region (beg end &key initial)
  (save-restriction
    (narrow-to-region beg end)
    (consult-line initial)))

(defun syd-search--escape-regexp (str)
  (require 'syd-text)
  (replace-regexp-in-string " " "\\\\ "
                            (syd-pcre-quote str)))

(defun syd-search-buffer (buffer)
  "Conduct a text search on BUFFER.

If a selection is active and multi-line, perform a search restricted to that
region.

If a selection is active and not multi-line, use the selection as the initial
input and search the whole buffer for it."
  (interactive (list (current-buffer)))
  (save-restriction
    (let* ((beg (region-beginning))
           (end (region-end))
           (multiline-p (/= (line-number-at-pos beg)
                            (line-number-at-pos end))))
      (if (and beg end (region-active-p))
          (progn (deactivate-mark)
                 (if multiline-p
                     (syd-search-region beg end)
                   ;; Treat as a single pattern, not several
                   ;; space-separated patterns.
                   (consult-line (syd-search--escape-regexp
                                  (buffer-substring-no-properties beg end)))))
        (consult-line)))))

;;;###autoload
(defun syd-search-directory (dir)
  (interactive (list (read-directory-name
                      "Search directory: "
                      default-directory nil t)))
  (cond ((executable-find "rg")
         (consult-ripgrep dir))
        ((executable-find "grep")
         (message "Couldn't find ripgrep; using grep")
         (consult-grep dir))))

;;;###autoload
(defun syd-search-current-directory ()
  (interactive)
  (syd-search-directory default-directory))


(provide 'syd-search)
;;; syd-search.el ends here
