How to have colors in the output of (emacs) shell-

2019-05-27 13:55发布

问题:

When executing the command shell-command, 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.

回答1:

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")))


回答2:

This is probably what you want :

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


回答3:

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))


标签: emacs xemacs