complete-computing-environment/use_emacs_as_a_pager.org

3.0 KiB

Use Emacs as a Pager

(provide 'cce/emacs-pager)

uhoreg has a cool script they shared on Reddit which lets you use Emacs buffers as your pager.

[[ -z "$(which emacsclient)" ]] && less -
t=$(mktemp --suffix .emacs-pager) || exit 1
cat - >> $t
echo 'reading into emacs...'
emacsclient --alternate-editor=less "$t"
rm -f -- $t
export PAGER=emacs-pager
{ ... }:

{
  home.sessionVariables = {
    PAGER = "${../files/emacs-pager-bin}";
  };
}

Of course, if you feed random terminal shit in to your Emacs, you're gonna end up with ANSI escape codes. Luckily, xterm-color.el exists, and we can use that to automatically color our buffers as necessary.

We start with xterm-colorize-maybe, a function which searches the buffer for an ANSI control-code, and colorizes the buffer if it finds one.

(defun cce/xterm-colorize-maybe ()
  (interactive)
  (goto-char (point-min))
  (when (search-forward (char-to-string 27) nil t)
    (xterm-color-colorize-buffer)))
(add-hook 'find-file-hook #'cce/xterm-colorize-maybe)

I set TERM to xterm-256color everywhere that I can so that commands try to output the text and don't assume that Emacs (identifying as TERM=dumb) can't handle it. comint and compilation are handled a little bit differently due to one having a process filter and the other not.

(use-package xterm-color
  :commands xterm-color-colorize-buffer xterm-color-test
  :autoload xterm-color-filter
  :config
  (setenv "TERM" "xterm-256color")
  (setq compilation-environment '("TERM=xterm-256color"))
  (setq comint-output-filter-functions
        (remove 'ansi-color-process-output comint-output-filter-functions))
  (defun cce/compilation-start-hook (proc)
    (when (eq (process-filter proc) 'compilation-filter)
      (set-process-filter proc
                          (lambda (proc string)
                            (funcall 'compilation-filter proc
                                     (xterm-color-filter string))))))
  :hook
  (shell-mode . (lambda ()
                  (add-hook 'comint-preoutput-filter-functions
                            'xterm-color-filter nil t)))
  (compilation-start . cce/compilation-start-hook))