2

Emacs in -nw mode colors source code files, in this screenshot you see how emacs colors the .rb file I opened. Over the weeks/months I've gotten used to the coloring.

Despite how hard I try, there always comes a time when I'm not in emacs, and I'm doing a cat in the Terminal.app bash shell. So much like you can pipe a compact block of json to get nicely indented json, is it possible to pipe a .rb file to some scripts that runs Emacs and extracts the syntax coloring that Emacs uses?

enter image description here

Stefan
  • 26,404
  • 3
  • 48
  • 85
american-ninja-warrior
  • 3,903
  • 2
  • 24
  • 44
  • 2
    Please clarify how this is relevant to Emacs. I guess what you're really asking is "how to use Emacs in a pipe to color my file". If so, please says it. – Stefan May 08 '19 at 01:57
  • 3
    Yes, translate Emacs font-lock faces into ANSI escape code, see https://github.com/Lindydancer/e2ansi – xuchunyang May 08 '19 at 08:04
  • You can install/use the package highlight from homebrew - see discussion on this page: https://unix.stackexchange.com/questions/267361/syntax-highlighting-in-the-terminal#267362 - this package support colour customisation. – Ian May 08 '19 at 12:47
  • I really don't understand why this question is put on hold -- I've voted for it to be reopened. Anyway, I asked myself the same thing a couple of years ago -- when I didn't find any package I wrote my own (https://github.com/Lindydancer/e2ansi as @ xuchunyang already posted). Any text Emacs can highlight, it can render using ANSI sequences so it can be viewed in a terminal, using the command e2ansi-cat. It integrates with pagers like moreand less so anything you view with them becomes highlighted automatically. – Lindydancer May 09 '19 at 19:24
  • really don't understand why this question is closed – american-ninja-warrior May 15 '19 at 21:49
  • @xuchunyang can you post your suggestion as an answer? –  May 16 '19 at 20:12

1 Answers1

5

You can use the syntax coloring outside Emacs, two working examples are htmlize for the web and e2ansi for the terminal. For your need, you can use e2ansi-cat provided by e2ansi, here is a screenshot of it:

screenshot of cat and e2ansi-cat

By the way, if you use Eshell, you can easily get the syntax coloring:

(defun eshell/cat-with-syntax-highlight (filename)
  (let ((existing-buffer (get-file-buffer filename))
        (buffer (find-file-noselect filename)))
    (eshell-print
     (with-current-buffer buffer
       (font-lock-ensure)
       (buffer-string)))
    (unless existing-buffer
      (kill-buffer buffer))
    nil))

screenshot of cat-with-syntax-highlight

xuchunyang
  • 14,527
  • 1
  • 19
  • 39