3

Each of M-x shell, M-x eshell, and M-x term in Emacs lets me save the buffer to a text file. But the terminal colors are not saved. How do I save the raw ANSI escape sequences too?

  • 1
    I'm afraid that the codes are removed before displaying the text, so there's no way to save them afterwards (maybe you can infer them from the faces, but that won't work all the time). – wvxvw Aug 2 '17 at 10:08
  • @wvxvw if that's the case, I don't think it would be easy to make this possible. term and others would require substantial rewrites to give them this capability. – DoMiNeLa10 Aug 2 '17 at 11:06
  • @DoMiNeLa10: it would be extra work to re-create the escape sequences afterwards, indeed, but there's a simpler option: save the program's output directly into a file before decoding the escape sequences. – Stefan Aug 2 '17 at 12:57
  • Maybe enriched-mode could be used to save the colors? (not the original ANSI escape sequences though). – npostavs Aug 2 '17 at 14:10
  • 1
    @GerryLufwansa: I was thinking of saving the data received by Emacs rather than piping through something like tee: that should work in all cases. – Stefan Aug 3 '17 at 19:51
2

You can try something like the 100% guaranteed untested code below:

;;; -*- lexical-binding:t -*-
(defun sm-save-proc-output ()
  (interactive)
  (let ((buf (get-buffer-create "*SM-Saved-Proc-Output*"))
        (proc (get-buffer-process (current-buffer))))
    (add-function :before (process-filter proc)
      (lambda (_proc string)
        (with-current-buffer buf
          (save-excursion
            (goto-char (point-max))
            (insert string)))))))

It won't let you save the current content, but instead, sets up the buffer *SM-Saved-Proc-Output* to receive a copy of all the output of the process running in the current buffer. You can then later save that buffer's content with M-x write-region or M-x write-file.

  • get-buffer-process requires an argument so I changed it to get-buffer-process "*shell*" (testing it with M-x shell first). There's another error (or warning?) Symbol's value as variable is void: v and the *SM-Saved-Proc-Output* buffer is still empty. I'm stumped at this point. – Gerry Lufwansa Aug 7 '17 at 2:54
  • I fixed the call to get-buffer-process and the other problem is probably because your file probably doesn't have the lexical-binding set (see the comment I added as first line). – Stefan Aug 7 '17 at 15:37

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.