help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Custom searches, like interactively searching palindromes


From: Andreas Politz
Subject: Re: Custom searches, like interactively searching palindromes
Date: Wed, 08 Dec 2010 15:30:35 -0000
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/24.0.50 (gnu/linux)

Karan Bathla <karan_goku@yahoo.com> writes:

>
> I would like to know how one can interactively search for patterns
> that are not captured by regexes, like palindromes.
>

I had a similar desire and wrote this 2 functions, which can be
used to do what you want, though not for replacing.

(defun isearch-with-predicate (predicate indicator &optional backward regexp)
  (lexical-let ((predicate predicate))
    (let ((isearch-search-fun-function
           (lambda nil
             (lambda (string &optional bound no-error)
               (let (isearch-search-fun-function)
                 (search-with-predicate
                  string (isearch-search-fun)
                  predicate bound no-error)))))
          (isearch-message-prefix-add indicator)
          isearch-with-predicate-success
          (isearch-mode-end-hook
           (lambda nil
             (setq isearch-with-predicate-success
                   (not isearch-mode-end-hook-quit)))))
      (funcall (if backward
                   (if regexp
                       'isearch-backward-regexp
                     'isearch-backward)
                 (if regexp
                     'isearch-forward-regexp
                   'isearch-forward)))
      (isearch-clean-overlays)
      isearch-with-predicate-success)))

(defun search-with-predicate (string
                              search-fn
                              predicate
                              &optional
                              bound noerror count)
  (let (found
        limit
        (count (or count 1)))
    (save-excursion
      (while (and (setq found
                        (funcall search-fn string bound noerror))
                  (or (not (setq found
                                 (and (funcall predicate)
                                      found)))
                      (> (decf count) 0))))
      (setq limit (point)))
    (if found
        (goto-char found)
      (unless (eq noerror t)
        (goto-char limit)
        nil))))

(defun isearch-palindrome (&optional regexp)
  (interactive "P")
  (isearch-with-predicate
   (lambda ()
     (let* ((word (buffer-substring (match-beginning 0) (match-end 0)))
            (prefix (append (substring word 0 (/ (length word) 2)) nil))
            (suffix (nreverse (append (substring word (/ (length word) 2)) 
nil))))
       (every '= prefix suffix)))
   "(Palindrome)" nil regexp))

-ap


reply via email to

[Prev in Thread] Current Thread [Next in Thread]