如何使用单个热键在 Emacs 中获取字符串/正则表达式替换预览(如 VS Code 中)?

问题描述 投票:0回答:1

我想要什么

在 VS Code 中,我可以按

Ctrl + Shift + h
并获得替换候选的便捷预览(参见屏幕截图)。它允许导航所有匹配项,并使用热键进行替换。

vs code replace preview

已经有效的

在 Emacs 中,要获得相同的功能,我可以运行:

  1. 运行 coach-rg (或其他搜索)
  2. 从迷你缓冲区切换到常春藤发生
  3. 将 ivy-occurr 转换为 wgrep 缓冲区

这是 3 个关键要素,如果按照 Emacs 指南完成的话,每个要素都比 VS Code 更详细。

emacs replace preview

我尝试过的事情

我想在 Emacs 中运行步骤 1-3,仅使用 1 个热键。我能得到的最接近的是这段代码:

(defun counsel-rg-to-wgrep ()
  (interactive)
  ;; (counsel-rg)
  (run-at-time nil nil (lambda ()
                         (ivy-wgrep-change-to-wgrep-mode)))
  (ivy-occur))

但它仍然必须从搜索迷你缓冲区中调用(此外,这里需要逆序和

run-at-time
,相信我)。如果我取消注释
(counsel-rg)
调用,则包含搜索结果的缓冲区不会打开,并且我在 Messages 缓冲区中收到此错误:

ivy-occur: No completion session is active

问题

如何使用一个热键完成所有 3 个步骤?

visual-studio-code replace emacs ripgrep
1个回答
0
投票

我能够通过以下代码得到我想要的东西。我是 Elisp 的新人,所以欢迎重构建议。

有一件事我无法工作 - 当输入搜索字符串时,ivy 的迷你缓冲区中的交互式匹配列表。

(add-to-list 'load-path "~/.emacs.d/elisp/")
(load "~/.emacs.d/elisp/replace+.el")

(defun get-initial-input-for-replace ()
      nil)
(setq-and-tell-customize 'search/replace-default-fn
                         'get-initial-input-for-replace)

(defun query-replace-regexp-with-initial-input (input)
  (eval
   '(let ((original-fn (symbol-function 'initial-input-for-replace)))
      (fset 'get-initial-input-for-replace (lambda () (regexp-quote input)))
      (unwind-protect
          (call-interactively 'query-replace-regexp)
        (fset 'get-initial-input-for-replace original-fn)))
   t))

(defun rapid-replace-across-git-repo ()
  "Opens up wgrep buffer with query-replace-regexp started"
  (interactive)
  (eval 
   '(let* ((thing (ivy-thing-at-point))
           (search-str (read-string "Enter at least 3 chars to replace: " thing)))
      (run-at-time
       nil nil
       (lambda ()
         (run-at-time
          nil nil
          (lambda ()
            (run-at-time
             nil nil
             (lambda ()
               (query-replace-regexp-with-initial-input search-str)
               ))
            (ivy-wgrep-change-to-wgrep-mode)))
         (ivy-occur)))
      (counsel-git-grep search-str))
   t))

(global-set-key (kbd "C-S-h") 'rapid-replace-across-git-repo)

这个解决方案需要3个包:ivy、council、replace+.el。

© www.soinside.com 2019 - 2024. All rights reserved.