Originally posted to OpenQuestions.
Is there an easy way to do “search near” in Emacs? This should take three arguments, ‘word1’, ‘word2’ and ‘distance’, and should return all occurences of ‘word2’ that occur within distane ‘distance’ from an occurence of ‘word1’. It would also be nice if there was a new buffer that should contain a “clickable” and “returnable” list of these occurences like “M-x grep”, does. I am trying to convince somebody for the benefits of Emacs over other editors AND (gasp) “word processors” and he put the existence of such a utility as a requirement. So you understand, this is for a sacred purpose
.
‘n’ is the number of characters between the two words. – AnselmHelbig\(\<word1\>\(\w+\W*\)\{,n\}\<word2\>\|\<word2\>\(\w+\W*\)\{,n\}\<word1\>\) \<word1\>\W\(\w+\W+\)\{,n\}\<word2\>\|\<word2\>\W\(\w+\W+\)\{,n\}\<word1\>
(defun find-near (word1 word2 num)
"Find all occurences of word1 within distance num of word2."
(occur (concat "\\<"
word1 "\\>\\(\\W\\<\\w+\\>\\)\\{,"
(number-to-string num) "\\}\\W+\\<" word2 "\\>\\|\\<"
word2 "\\>\\(\\W+\\<\\w+\\>\\)\\{,"
(number-to-string num) "\\}\\W+\\<" word1 "\\>")))
(defun near-search ()
"It finds all occurences of a word within a given distance of an other word."
(interactive)
(let ( (word1 (read-string "First word:"))
(word2 (read-string "Second word:"))
(num (read-number "Distance:" 1)))
(find-near word1 word2 num)))