As a software engineer I found myself pretty often in needs of showcasing a piece of code in a document or presentation. While coding, we have IDE and editor tools like VSCode for highlighting the syntax, to make it more readable. However, for the software not designed for developers, usually there’s no such syntax highlighting feature for code. I think explaining your code and idea is critical for software engineering, so syntax highlighting in documents and presentations is as important as for development. With that in mind, I wrote a piece shell script that helps you syntax highlighting code snippets for MacOS:

function shl() {
pbpaste | pygmentize -l \$1 -f html -O style=monokai -O full=True > /tmp/highlighted-code.html
open /tmp/highlighted-code.html
}


To use it, you need to install Pygments first, you can run

pip install Pygments


Next, all you need to do is put the piece of shell script into your ~/.bash_profile. You can now reload the bash profile via

source ~/.bash_profile


Then you can then copy the code you want to highligh and run this

shl shell


And here you go!

It will output an HTML file in temporary folder and open it. As long as your editor supports copy paste from browser, you should now be able to copy the code and paste it wherever you want. And you can change the shell to whatever programming language Pygments supports, like cpp, python:

shl python
shl cpp
# ...


Now, with this script, it’s super simple. Just copy the code, run the command, and that’s it. Hope this is helpful, enjoy code highlighting for your doc writing and presentation :)