There is a nice built-in Emacs feature to colorize strings with ANSI color escape sequences. So evaluating the following Elisp code, will insert the "Test text" at the point with proper colors.

(require 'ansi-color)
(insert (ansi-color-apply "^[[33mTest text^[[0m"))

enter image description here


I tried to use the ansi-color-apply function to colorize the results of my Org Babel code blocks using :post with the following filter block.

#+begin_src emacs-lisp :var input="[33mTest text[0m" :results raw

    (ansi-color-apply input)


#+RESULTS: ansi-colorize
Test text

Which only removes the color escape sequences, but the inserted text has no proper face attributes.:

enter image description here


Since ansi-color-apply is a pure function, therefore does its job right and returns with:

#("Test text" 0 9 (font-lock-face (foreground-color . "#E6DB74")))

Which does not have the expected effect when the result is inserted by Org Babel


If I understand you question correctly you wish to interpret ansi color codes in the results of org babel code blocks.

I achieved this by adding a hook to org-babel-after-execute-hook:

(defun ek/babel-ansi ()
  (when-let ((beg (org-babel-where-is-src-block-result nil nil)))
      (goto-char beg)
      (when (looking-at org-babel-result-regexp)
        (let ((end (org-babel-result-end))
              (ansi-color-context-region nil))
          (ansi-color-apply-on-region beg end))))))
(add-hook 'org-babel-after-execute-hook 'ek/babel-ansi)

Now when I execute for example this code block

#+BEGIN_SRC shell
echo -e "\e[31mTest\e[0m"

I get nice red text in the result:



Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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