Emacs 复制匹配行

Emacs 复制匹配行,emacs,Emacs,在Emacs中,如何轻松复制与特定正则表达式匹配的所有行?最好在输入时突出显示匹配行 occure通过将它们添加到缓冲区中来实现,但这会增加很多额外的内容。这样如何: (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*" (interact

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

occure
通过将它们添加到缓冲区中来实现,但这会增加很多额外的内容。

这样如何:

(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)))

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

    (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)

您可以使用
保留行
获取所需内容,复制行,然后撤消。相反,还有
刷新行
来消除您不想要的行。

从Emacs 24开始,
出现
实际上提供了一个简单的解决方案:

C-uM-so
*模式。*
RET

当您单独使用C-u作为前缀参数时,每行的匹配部分都会插入到
*occure*
缓冲区中,而不带所有常规装饰

请注意,由于只使用与regexp匹配的行的一部分(与正常情况不同),因此需要使用前导和尾随
*
,以确保捕获整行


关于
发生
如何处理参数的详细信息有点棘手,因此如果您想了解更多信息,请仔细阅读C-hf
发生
RET。

您可以安装软件包
所有
。然后
M-xall
允许您编辑缓冲区中与regexp匹配的所有行。您也可以复制它们,而不是编辑它们。

您是如何如此快速地执行此操作的?这也是一个与我所期望的完全不同的解决方案。我假设它将使用发生模式。谢谢,嗯。。。这是一种常见的事情。这里真的只有三件事。1) 制作一个缓冲区,2)搜索当前缓冲区,3)在新的缓冲区中插入搜索结果……我刚刚在谷歌上搜索了一下,发现了我自己10多年前的问题。我真的应该把它放在我的
中。emacs.d
工作起来很有魅力!这应该是现在可以接受的答案。:)我不同意-我认为
occure
应该有一个选项,它不需要改变模式来匹配整行-它的基本目的是找到匹配行,应该有一种方法告诉它不要使用occure模式。