代码之家  ›  专栏  ›  技术社区  ›  Singletoned

Emacs复制匹配行

  •  15
  • Singletoned  · 技术社区  · 15 年前

    在emacs中,如何轻松地复制与特定regex匹配的所有行?最好在我打字时突出显示匹配的行。

    occur 通过将它们放入缓冲区来达到一定程度,但这会增加很多额外的东西。

    5 回复  |  直到 9 年前
        1
  •  12
  •   Trey Jackson    15 年前

    这个怎么样:

    (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
  •  27
  •   phils    11 年前

    从Emacs24开始, occur 实际上是否提供了一个简单的解决方案:

    C-U 小精灵 o .*pattern.* 雷特

    当你使用 C-U 作为前缀参数,每行的匹配部分插入到 *Occur* 缓冲区,没有所有正常的装饰。

    注意,因为只使用了与regexp匹配的行的一部分(与普通的occure不同),所以需要前导和尾随 .* 以确保捕获整条线。

    关于如何 发生 treats参数有点棘手,所以请阅读 C-H f 发生 雷特 如果你想知道更多,请小心。

        3
  •  9
  •   scottfrazer    15 年前

    你可以使用 keep-lines 要得到你想要的,复制它们,然后撤消。相反,也有 flush-lines 把你不想要的线去掉。

        4
  •  2
  •   offby1    15 年前

    我一直很高兴地用这个:

        (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)
    
        5
  •  2
  •   doublep    9 年前

    您可以安装程序包 all . 然后 M-x all 允许您编辑缓冲区中与regexp匹配的所有行。不用编辑,你也可以复制它们。