occur is an interactive compiled Lisp function in ‘replace.el’. The definition is as follows:

(defun occur (regexp &optional nlines region)
   (nconc (occur-read-primary-args)
          (and (use-region-p) (list (region-bounds)))))
  (let* ((start (and (caar region) (max (caar region) (point-min))))
         (end (and (cdar region) (min (cdar region) (point-max))))
         (in-region-p (or start end)))
    (when in-region-p
      (or start (setq start (point-min)))
      (or end (setq end (point-max))))
    (let ((occur--region-start start)
          (occur--region-end end)
           (and in-region-p
                (line-number-at-pos (min start end))))
           (line-number-at-pos (point)))
      (save-excursion ; If no matches `occur-1' doesn't restore the point.
        (and in-region-p (narrow-to-region start end))
        (occur-1 regexp nlines (list (current-buffer)))
        (and in-region-p (widen))))))

When the above function is invoked, the user is prompted to input a regexp for searching.

What I want is to make a new function myoccur by hard-coding a regexp in the above function and make it non-interactive, so that I can conveniently invoke it. If a wrapper over the original occur can make it non-interactive, that would also be great. How should I do?


1 Answer 1


I finally found a solution:

(global-set-key (kbd "C-x j") (lambda () (interactive) (occur "regexp" nil)))

I also found that \ needs to be escaped by another \ in the regexp, which is different from the regexp inputted in interactive mode. For example, to match all functions and subroutines defined in a Fortran code, the regexp should be:

^ *\\(\\(subroutine\\)\\|\\(function\\)\\)

while in the interactive mode, the regexp is:

^ *\(\(subroutine\)\|\(function\)\)

Update: The reason is that, which I found at emacs website, the string syntax for a backslash is \\

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.