Skip to content

Instantly share code, notes, and snippets.

@judy2k
Last active March 30, 2017 09:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save judy2k/757945d9e7ab6b07ba673dfe82da6f69 to your computer and use it in GitHub Desktop.
Save judy2k/757945d9e7ab6b07ba673dfe82da6f69 to your computer and use it in GitHub Desktop.
Generate a syntax-highlighted code snippet for Twitter
#!/bin/bash -e
#
# tweet-syntax - Create a syntax-highighted PNG file of your code and save in /tmp
#
# Prerequisites:
# pip install --upgrade pygments pillow
# 'Source Code Pro' font (or change the script below)
#
# Usage: cat code.ext | tweet-syntax [<syntax>]
# Default to python if input syntax not specified:
if [[ -z ${1} ]]; then
# If you don't provide syntax, attempt to guess from content:
# (this usually doesn't work)
syntax_flag="-g"
else
syntax_flag="-l ${1}"
fi
# Create a uniqifier:
uu=$(uuidgen | tr '[:upper:]' '[:lower:]' | cut -c '1-8')
# Work out where to store the output:
path=/tmp/code-example-${uu}.png
# Generate an image at $path from stdin:
pygmentize \
${syntax_flag} \
-f img \
-O "font_name=Source Code Pro,line_numbers=False,font_size=28,style=vs" \
-o "$path"
open "$path" # Display the resulting image (on OSX)
open -R "$path" # Show the image file in the Finder (on OSX)
echo -n "$path" | pbcopy # Copy the path into the pasteboard (on OSX)
echo "$path copied to clipboard"
@judy2k
Copy link
Author

judy2k commented Mar 30, 2017

This script was written for OSX, but by replacing calls to pbcopy and open with equivalents on other platforms (or just removing the calls) it should be easily portable to other systems.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment