Emacs复制匹配行

时间:2010-02-18 15:45:45

标签: emacs

在Emacs中,如何轻松复制与特定正则表达式匹配的所有行?最好在我输入时突出显示匹配的行。

occur通过将它们复制到一个缓冲区中来到那里,但它增加了许多额外的东西。

5 个答案:

答案 0 :(得分:27)

从Emacs 24开始,occur确实提供了一个简单的解决方案:

C-u M-s o .*pattern.* RET

当您自己使用 C-u 作为前缀参数时,每行的匹配部分将插入*Occur*缓冲区,而不包含所有正常的装饰。

请注意,因为只使用与正则表达式匹配的行的部分(与正常情况不同),所以需要前导和尾随.*以确保捕获整行。

occur如何处理参数的细节有点棘手,所以阅读 Ch f occur RET 如果你想了解更多,请仔细。

答案 1 :(得分:12)

这个怎么样:

(defun copy-lines-matching-re (re)
  "find all lines matching the regexp RE in the current buffer
putting the matching lines in a buffer named *matching*"
  (interactive "sRegexp to match: ")
  (let ((result-buffer (get-buffer-create "*matching*")))
    (with-current-buffer result-buffer 
      (erase-buffer))
    (save-match-data 
      (save-excursion
        (goto-char (point-min))
        (while (re-search-forward re nil t)
          (princ (buffer-substring-no-properties (line-beginning-position) 
                                                 (line-beginning-position 2))
                 result-buffer))))
    (pop-to-buffer result-buffer)))

答案 2 :(得分:9)

您可以使用keep-lines获取所需内容,复制它们,然后撤消。相反,还有flush-lines来摆脱你不想要的行。

答案 3 :(得分:2)

很长一段时间我一直在愉快地使用它:

    (defun occur-mode-clean-buffer ()
  "Removes all commentary from the *Occur* buffer, leaving the
unadorned lines."
  (interactive)
  (if (get-buffer "*Occur*")
      (save-excursion
        (set-buffer (get-buffer "*Occur*"))
        (fundamental-mode)
        (goto-char (point-min))
        (toggle-read-only 0)
        (set-text-properties (point-min) (point-max) nil)
        (if (looking-at (rx bol (one-or-more digit)
                            (or " lines matching \""
                                " matches for \"")))
            (kill-line 1))
        (while (re-search-forward (rx bol
                                      (zero-or-more blank)
                                      (one-or-more digit)
                                      ":")
                                  (point-max)
                                  t)
          (replace-match "")
          (forward-line 1)))

    (message "There is no buffer named \"*Occur*\".")))

(define-key occur-mode-map (kbd "C-c C-x") 'occur-mode-clean-buffer)

答案 4 :(得分:2)

您可以安装包all。然后M-x all允许您编辑缓冲区中与正则表达式匹配的所有行。您也可以复制它们,而不是编辑。