Search code examples
emacsnarrowing

Emacs narrow-by-regex


There are functions like M-x narrow-to-line and M-x narrow-to-page. Which routines can help me achieve functionality of non-existing M-x narrow-by-regex?

Thanks.


Solution

  • this seems to work. will prompt the user for the begin and end regex. (not tested very thoroughly!):

    (defun narrow-to-regex ()
      "narrow the buffer visibility to the section between two regexes the user provides"
      (interactive)
      (let* ((beginRegex (read-regexp "begin pattern"))
             (endRegex (read-regexp "end pattern"))
             (beg)
             (end))
        (goto-char (point-min)) ;; go to the start of the buffer
        (if (re-search-forward beginRegex nil t nil)
            (setq beg (- (point) (length beginRegex))))
        (if (re-search-forward endRegex nil t nil)
            (setq end (point)))
        (if (and beg end (> end beg))
            (narrow-to-region beg end)
          (message "did not find both instances of the regex, %s %s, no narrow" beg end))))
    

    you will have too install it by putting it into a buffer (scratch etc) and going CTRL+X followed by CTRL+E