【问题标题】:How to have colors in the output of (emacs) shell-command?如何在(emacs)shell命令的输出中有颜色?
【发布时间】:2011-01-18 16:07:53
【问题描述】:

执行命令shell-command时,相关缓冲区中显示的输出未着色。

从 emacs 中调用测试框架(输出黄色/绿色/红色...)时,这尤其令人讨厌。

如何配置或扩展 emacs 以使 shell-command 允许在 shell 中进行彩色输出并在表示该输出时保留颜色?

谢谢!

ps。我在 UN*X 系统上使用 Bash shell。

【问题讨论】:

    标签: emacs xemacs


    【解决方案1】:

    这可能是你想要的:

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

    【讨论】:

    • 之前尝试过这个钩子,结合 (autoload 'ansi-color-for-comint-mode-on "ansi-color" nil t),但似乎只影响 shell-mode 而不是简单的 shell-command
    • @mgodinho:好吧,接受的答案不是执行 shell 命令,而是打开一个 shell 模式(带有重命名的缓冲区),没有这个附加钩子,接受的答案不会产生任何颜色。至少对我来说。
    【解决方案2】:

    您可以实现自己的 shell-execute,例如

    (defun my-shell-execute(cmd)
       (interactive "sShell command: ")
       (shell (get-buffer-create "my-shell-buf"))
       (process-send-string (get-buffer-process "my-shell-buf") (concat cmd "\n")))
    

    【讨论】:

    • 不错的 hack,我确实通过一点调整实现了它:(concat "reset\n" cmd "\nexit 0 &> /dev/null\n")
    • 非常酷,@mgodinho hack 可以防止在每次后续调用时触发 shell 初始化提示。我的 Emacs 现在看起来像一个 IDE :)
    【解决方案3】:

    这增加了一个建议,在 shell 命令完成后在 minibuffer 上运行 ansi-color-apply-on-region

    (require 'ansi-color)
    
    (defun ansi-color-apply-on-buffer ()
        (ansi-color-apply-on-region (point-min) (point-max)))
    
    (defun ansi-color-apply-on-minibuffer ()
      (let ((bufs (remove-if-not
                   (lambda (x) (string-starts-with (buffer-name x) " *Echo Area"))
                   (buffer-list))))
        (dolist (buf bufs)
          (with-current-buffer buf
            (ansi-color-apply-on-buffer)))))
    
    (defun ansi-color-apply-on-minibuffer-advice (proc &rest rest)
      (ansi-color-apply-on-minibuffer))
    
    (advice-add 'shell-command :after #'ansi-color-apply-on-minibuffer-advice)
    ;; (advice-remove 'shell-command #'ansi-color-apply-on-minibuffer-advice)
    

    它不依赖于 shell-mode 或 comint。我将它与以下内容一起使用以获得不错的测试输出(一个绿色的笑脸,其中包含成功的 doctests 计数。

    (defun add-test-function (cmd)
      (interactive "sCommand to run: ")
      (setq my-testall-test-function cmd)
      (defun my-testall ()
        (interactive)
        (shell-command my-testall-test-function))
      (local-set-key [f9] 'my-testall))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-18
      • 1970-01-01
      • 2019-02-10
      • 1970-01-01
      • 1970-01-01
      • 2021-12-04
      • 2014-02-07
      相关资源
      最近更新 更多