You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Eshell中高亮指定关键词?

嘿,这个需求我刚好折腾过!在Eshell里给errors、info这类关键词加高亮,其实有几种很实用的办法,给你拆解一下:

方法一:自定义输出过滤函数(最灵活)

这个办法是通过Eshell的输出过滤钩子,在内容显示到buffer之前就给指定关键词加上高亮属性,实时性拉满。

把这段代码加到你的Emacs配置文件里:

(defun my-eshell-highlight-keywords (output)
  "Highlight specific keywords in Eshell output."
  ;; 这里可以自定义关键词和对应的高亮样式
  (let ((keywords '(("errors" . font-lock-warning-face)
                    ("info" . font-lock-info-face)
                    ("warning" . font-lock-warning-face)
                    ("debug" . font-lock-comment-face))))
    (dolist (pair keywords)
      (setq output (replace-regexp-in-string (car pair)
                                             (lambda (match)
                                               (propertize match 'face (cdr pair)))
                                             output t t)))
    output))

;; 把过滤函数挂到Eshell的输出钩子上
(add-hook 'eshell-preoutput-filter-functions #'my-eshell-highlight-keywords)

小说明:

  • 你可以随便扩展keywords列表,比如加个"success"对应font-lock-string-face(绿色),完全按自己喜好来。
  • 如果默认的face不够用,还能自己定义专属高亮样式,比如:
    (defface my-eshell-error-face
      '((t (:foreground "dark red" :weight bold :underline t)))
      "自定义的Eshell错误关键词高亮样式")
    
    然后把("errors" . my-eshell-error-face)加到关键词列表里就行。

方法二:开启ANSI颜色支持(适合程序本身带颜色输出的情况)

如果你运行的程序本身就会输出带ANSI颜色码的内容(比如很多CLI工具会给错误标红),那直接开启Eshell的ANSI解析就行:

(add-hook 'eshell-mode-hook #'ansi-color-for-comint-mode-on)

这样Eshell就能正确识别并显示程序输出的颜色了,省得自己写过滤规则。

方法三:直接给Eshell buffer加font-lock规则

这个办法是利用Emacs的font-lock机制,直接在Eshell buffer里匹配关键词高亮,适合想要对已有输出也生效的场景:

(add-hook 'eshell-mode-hook
          (lambda ()
            (font-lock-add-keywords nil
                                    '(("\\<errors\\>" . font-lock-warning-face)
                                      ("\\<info\\>" . font-lock-info-face)
                                      ("\\<warning\\>" . font-lock-warning-face)))))

这里的\\<和\\>是正则的词边界,避免匹配到包含这些关键词的长单词(比如errorstest不会被误匹配)。

最后记得把配置代码加到你的init.el或者配置文件里,重启Eshell或者用M-x eval-buffer加载配置就能看到效果啦!

内容的提问来源于stack exchange,提问作者Wang Li

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:47:06