How to have colors in the output of (emacs) shell-command?
When executing the command shell-comman开发者_如何学编程d, the output shown in the associated buffer is not colorized.
This is particularly annoying when calling a testing framework (outputting yellow/green/red...) from within emacs.
How can I configure, or extend, emacs in order to have shell-command allowing colorized output in the shell and preserving the colors while representing that output?
Thanks!
ps. I'm using the Bash shell, on a UN*X system.
This is probably what you want :
(add-hook 'shell-mode-hook 'ansi-color-for-comint-mode-on)
You can implement your own shell-execute, something like
(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")))
This adds an advice to run ansi-color-apply-on-region
on the minibuffer after shell-command finishes:
(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)
It does not rely on shell-mode or comint. I accompany it with something like the following to get nice test output (a green smiley with the count of successful 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))
This solution is inspired by @ArneBabenhauserheide's but uses xterm-color
instead of ansi-color
. It also colorizes the *Shell Command Output*
buffer as well as the mini
(defun xterm-color-colorize-shell-command-output ()
"Colorize `shell-command' output."
(let ((bufs
(seq-remove
(lambda (x)
(not (or (string-prefix-p " *Echo Area" (buffer-name x))
(string-prefix-p "*Shell Command" (buffer-name x)))))
(buffer-list))))
(dolist (buf bufs)
(with-current-buffer buf
(xterm-color-colorize-buffer)))))
(defun xterm-color-colorize-shell-command-output-advice (proc &rest rest)
(xterm-color-colorize-shell-command-output))
(advice-add 'shell-command :after #'xterm-color-colorize-shell-command-output-advice)
;; (advice-remove 'shell-command #'xterm-color-colorize-shell-command-output-advice)
精彩评论