14

Feature

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

Problem

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.

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

    (ansi-color-apply input)

#+end_src

#+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

Notes:

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

1 Answer 1

9

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)))
    (save-excursion
      (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"
#+END_SRC

I get nice red text in the result:

red-results

3
  • Any ideas on making this support 24-bit true color escape codes?
    – HappyFace
    May 16, 2021 at 11:53
  • I made [some progress ](github.com/atomontage/xterm-color/issues/40) on getting 24-bit colors, if anyone's interested.
    – HappyFace
    May 16, 2021 at 12:22
  • This removes the color attributes when you save the file and open it again, or when you export with results. Is there any way to store them but display them nicely?
    – Japhir
    Jul 18, 2023 at 17:44

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.