Search code examples
emacsansi-escape

emacs shell command output not showing ANSI colors but the code


When I do M-! in my emacs 21.4 the ANSI codes gets literal. Eg: ls --color

^[[0m^[[0m05420273.pdf^[[0m
^[[0m100829_Baño1.pdf^[[0m 

Is there a way of having it with color and UTF8?

The same question has been answered in SO before but with not totally satisfactory results (the solution given was to open a shell-mode). I know how to have colors in a shell. I only want to know how I can have color with M! (shell-command) or if it is not possible at all.

A shell mode is too intrusive when you want only to show something quick and don't want to move to this buffer and you would like to have it disappear automatically without C-x-k. Obviously there are situations where a shell buffer is more convenient but thanks to the other question I found how to put color to the shell-mode.

[note] emacs in use GNU Emacs 21.4.1 (x86_64-redhat-linux-gnu, X toolkit, Xaw3d scroll bars) of 2008-06-15 on builder6.centos.org


Solution

  • ansi-color.el contains the functions to process ANSI color codes. Unfortunately, there's not really a good way to hook it into shell-command. This is something of a hack, but it works:

    (require 'ansi-color)
    
    (defadvice display-message-or-buffer (before ansi-color activate)
      "Process ANSI color codes in shell output."
      (let ((buf (ad-get-arg 0)))
        (and (bufferp buf)
             (string= (buffer-name buf) "*Shell Command Output*")
             (with-current-buffer buf
               (ansi-color-apply-on-region (point-min) (point-max))))))