I have a a function

(defun display-ansi-colors ()
  (let ((inhibit-read-only t))
    (ansi-color-apply-on-region (point-min) (point-max))))

that I got from here: http://stackoverflow.com/questions/23378271/how-do-i-display-ansi-color-codes-in-emacs-for-any-mode

I'd like to run it automatically after org-babel-sh-evaluate or org-babel-execute:shell to strip the ANSI color codes from the output and colorize the org-mode #+RESULTS block.

Many thanks.

  • 1
    Maybe add it to the org-babel-after-execute-hook with appropriate precautions to apply it only to shell code blocks? Untested - and I don't know off the top of my head how to take those "appropriate precautions".
    – NickD
    Sep 10, 2017 at 2:48
  • @Nick: yep, and the odds are that ANSI codes are unique enough that it wouldn't matter whether you applied to to all code blocks. But that somewhat offends my aesthetics :), and I'm not sure how to filter for just org-babel-sh-evaluate or org-babel-execute:shell
    – E Bro
    Sep 12, 2017 at 2:54

1 Answer 1


Ok, this more or less works when put together in an org file:

#+BEGIN_SRC emacs-lisp :results none
(require 'cl)
(defun org-redisplay-ansi-source-blocks ()
  "Refresh the display of ANSI text source blocks."
  (org-element-map (org-element-parse-buffer) 'src-block
    (lambda (src)
      (when (equalp "ansi" (org-element-property :language src))
        (let ((begin (org-element-property :begin src))
              (end (org-element-property :end src)))
          (ansi-color-apply-on-region begin end))))))

(add-to-list 'org-babel-after-execute-hook #'org-redisplay-ansi-source-blocks)

(org-babel-do-load-languages 'org-babel-load-languages '((shell . t)))

#+BEGIN_SRC sh :results output verbatim drawer :wrap src ansi
echo "\e[33mTest text\e[0m"
echo Styles: '\e[3mitalic\e[0m' '\e[1mbold\e[0m' '\e[4munderline\e[0m' '\e[1m\e[3mbolditalics\e[0m'

#+BEGIN_src ansi
Test text
Styles: italic bold underline bolditalics

How it ends up looking like:


One issue I don't know how to fix yet is when the file is saved, all the ANSI information is lost.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.