Code Self Study Forum

How to print code in color from the terminal

This command will create a postscript file from a text file, colorizing the text. Replace with the name of the file that contains the code.

$ vim -me -e -c ":hardcopy >" -c ":q"

You can then open the .ps file with Evince or another Postscript/PDF reader.

I found the command here.

1 Like

I wanted to print multiple code files, so ended up using the command below. It looks for #elixir files and combines them into output.ex along with the filenames.

for f in $(find . -name *.ex*); do          
    # edit: don't use the next line as-it, see the post below.
    # echo "# $f\n\n$(cat $f)\n\n#######\n" >> output.ex

(That will also find vim’s backup files like fname.ex~, so it might not won’t work well as-is unless you clean the directories.)

Then the output can be converted to postscript with this (though the syntax highlighting didn’t work).

enscript --pretty-print --color output.ex -o

I ended up running the output.ex file through Vim to generate the postscript file with syntax highlighting:

vim -me -e -c ":hardcopy >" -c ":q" output.ex

If anyone has other tips for printing code, leave a comment below. :slight_smile:

See also Advanced Linux Printing guide.

Actually, looking at the output, that didn’t work perfectly, because \n in the regex was turned into a newline. It’s still readable, but that command needs some adjustment.

You might want to take a look at the Linux tput command. For example, here’s a code snippet from one of my scripts which uses it to temporarily adjust the tty:

        echo ""
        echo "Now that we have a tarball, run the following command FROM YOUR WORKSTATION to download it:"
        tput bold; echo "scp [email protected]:~/dot_octoprint.tar.gz ~/."; tput sgr0
        echo ""

In this case, the sandwiched echo command’s output will be in bold in the terminal. (In this script everything the user was expected to copy/paste/run was bolded to make a consistent interface.)

h t t p s : / / s t a c k o v e r f l o w . c o m / questions/2616906/how-do-i-output-coloured-text-to-a-linux-terminal

It might be necessary to adjust the current tty to allow this capability then set it back when you’re done.

old_stty_cfg=$(stty -g)
stty raw -echo
stty $old_stty_cfg
1 Like