consult 构建正则的函数不再在外部接收参数后,如何使用 advice 处理其在内部 lambda 接收的参数?

今天在 consult 的 issue 区看到了提出的类似问题,作者回复:可以修改 *-builder 返回的值,但更推荐的是既然是修改正则,不如直接修改 consult--default-regexp-compiler 返回的结果

这样改的确可以说是一劳永逸了


顺便附上修改之后的结果

(defcustom my-consult-py-prefix ?:
  "The prefix character when using consult to search Pinyin."
  :group 'consult
  :type 'character)

(defun my--consult-py-regexp-compiler (input type ignore-case)
  "Compile the INPUT string to a list of regular expressions.

The function should return a pair, the list of regular expressions and a
highlight function. The highlight function should take a single
argument, the string to highlight given the INPUT. TYPE is the desired
type of regular expression, which can be `basic', `extended', `emacs' or
`pcre'. If IGNORE-CASE is non-nil return a highlight function which
matches case insensitively."
  (require 'pinyinlib)
  (setq input (consult--split-escaped
               (if (char-equal my-consult-py-prefix (string-to-char input))
                   ;; Detect the first entered character. If it matches
                   ;; `my-consult-py-prefix', convert the subsequent
                   ;; characters into Pinyin regexp.
                   (pinyinlib-build-regexp-string (substring input 1))
                 input)))
  (cons (mapcar (lambda (x) (consult--convert-regexp x type)) input)
        (when-let (regexps (seq-filter #'consult--valid-regexp-p input))
          (apply-partially #'consult--highlight-regexps regexps ignore-case))))

(advice-add 'consult--default-regexp-compiler :override #'my--consult-py-regexp-compiler)

实际上就是 cireu 大佬所说的复制出来后 override,但毕竟只需要维护一个,就轻松多了

唯一的问题是在 Windows 下使用 consult-findconsult-grep 有些小毛病,会把不匹配的结果也输出出来,匹配到的结果会做高亮处理(在 wsl 下测试一切正常,未出现 Windows 上的这些问题)

但常用的 consult-ripgrepconsult-fd 使用都正常,所以上面那些小毛病就不处理了(估计是 Windows 的问题,折腾也白耗心神。。。)