lemzwerg
lemzwerg

Reputation: 822

emacs isearch with automatic application of a regex between characters

I would like to have a hook into Emacs's isearch-forward function to make it automatically apply a regex between the input characters while searching a string. For example, I would like to set this regex to [-=<>]. If I now type foobar into isearch, it should match foo<bar, fo=ob=>ar, f-o-o-b-a-r, etc.

Is such a functionality already available? I looked into ELPA and MELPA without success. In case this is not available, and since my Elisp abilities are very limited: How could this be implemented?

Upvotes: 1

Views: 241

Answers (2)

jpkotta
jpkotta

Reputation: 9417

I wrote a package called flex-isearch, that basically inserts ".*" in between each character of the search string (it's a bit more complicated than that) and switches to regexp searching. It does this automatically when the isearch fails.

Upvotes: 0

lemzwerg
lemzwerg

Reputation: 822

OK, I found a solution by myself after inspecting hexl.el from Emacs.

Here's the code.

(defun my-isearch-function ()
  "Make isearch skip characters -=<> while searching."
  (if (not isearch-regexp)
      (lambda (string &optional bound noerror count)
        (funcall
         (if isearch-forward
             're-search-forward
           're-search-backward)
         (mapconcat (lambda (c) (regexp-quote (string c))) string
                    "\\(?:[-=<>]*\\)?")
         bound
         noerror
         count))
    (isearch-search-fun-default)))


(defun toggle-my-isearch ()
  "Toggle my search mode.
If activated, incremental search skips characters -=<> while
searching.

For example, searching `foobar' matches `foo-bar' or `f-o-o=b<a>r'."
  (interactive)
  (if (eq isearch-search-fun-function 'isearch-search-fun-default)
      (progn
        (setq isearch-search-fun-function 'my-isearch-function)
        (message "my isearch on"))
    (setq isearch-search-fun-function 'isearch-search-fun-default)
    (message "my isearch off")))


(global-set-key (kbd "s-s") 'toggle-my-isearch)

Upvotes: 0

Related Questions