简体   繁体   中英

AND operator for text search in Emacs

I am new to Emacs. I can search for text and show all lines in a separate buffer using "Mx occur". I can also search for multiple text items using OR operator as : one\\|two , which will find lines with "one" or "two" (as explained on Emacs occur mode search for multiple strings ). How can I search for lines with both "one" and "two"? I tried using \\& and \\&& but they do not work. Will I need to create a macro or function for this?

Edit:

I tried writing a function for above in Racket (a Scheme derivative). Following works:

#lang racket

(define text '("this is line number one"
               "this line contains two keyword"
               "this line has both one and two keywords"
               "this line contains neither"
               "another two & one words line"))

(define (srch . lst)    ; takes variable number of arguments
  (for ((i lst))
    (set! text (filter (λ (x) (string-contains? x i)) text)))
  text)

(srch "one" "two")

Ouput:

'("this line has both one and two keywords" "another two & one words line")

But how can I put this in Emacs Lisp?

Regex doesn't support "and" because it has very limited usefulness and weird semantics when you try to use it in any nontrivial regex. The usual fix is to just search for one.*two\\|two.*one ... or in the case of *Occur* maybe just search for one and then Mx delete-non-matching-lines two .

(You have to mark the *Occur* buffer as writable before you can do this. read-only-mode is a toggle; the default keybinding is Cx Cq . At least in my Emacs, you have to move the cursor away from the first line or you'll get "Text is read-only".)

(defun occur2 (regex1 regex2)
  "Search for lines matching both REGEX1 and REGEX2 by way of `occur'.
We first (occur regex1) and then do (delete-non-matching-lines regex2) in the
*Occur* buffer."
  (interactive "sFirst term: \nsSecond term: ")
  (occur regex1)
  (save-excursion
    (other-window 1)
    (let ((buffer-read-only nil))
      (forward-line 1)
      (delete-non-matching-lines regex2))))

The save-excursion and other-window is a bit of a wart but it seemed easier than hardcoding the name of the *Occur* buffer (which won't always be true; you can have several occur buffers) or switching there just to fetch the buffer name, then Doing the Right Thing with set-buffer etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM