Created
August 14, 2018 16:31
-
-
Save erinacio/b5b6bcd6b3875243192d012f1bab79b7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import sys | |
import os | |
import requests | |
import argparse | |
import base64 | |
from urllib.parse import quote | |
stdout = sys.stdout | |
IS_ITERM = os.getenv('TERM_PROGRAM', default='').startswith('iTerm') and os.isatty(1) | |
IS_SCREEN = os.getenv('TERM', default='').startswith('screen') | |
def b64encode(s): | |
if type(s) is str: | |
s = s.encode() | |
return base64.b64encode(s).decode() | |
# iTerm2 on macOS only | |
def print_image(image_data, extension='.png'): | |
if IS_SCREEN: | |
stdout.write('\033Ptmux;\033\033]') | |
else: | |
stdout.write('\033]') | |
stdout.write('1337;File=') | |
stdout.write('name=') | |
stdout.write(b64encode(f'webtex-output{extension}')) | |
stdout.write(';') | |
stdout.write(f'size={len(image_data)}') | |
stdout.write(';') | |
stdout.write('inline=1') | |
stdout.write(':') | |
stdout.write(b64encode(image_data)) | |
if IS_SCREEN: | |
stdout.write('\a\033\\') | |
else: | |
stdout.write('\a') | |
stdout.write('\n') | |
def webtex_google_chart(tex): | |
params = { | |
'cht': 'tx', | |
'chl': tex | |
} | |
r = requests.get('https://chart.googleapis.com/chart', params) | |
if r.status_code != 200: | |
raise Exception(f'status code is {r.status_code}') | |
return r.content | |
def webtex_codecogs(tex): | |
# webtex use a strange request format, will do manual urlencode here | |
r = requests.get('https://latex.codecogs.com/png.latex?' + quote(tex)) | |
if r.status_code != 200: | |
raise Exception(f'status code is {r.status_code}') | |
return r.content | |
def render_tex(tex, provider=webtex_codecogs, **kw): | |
return provider(tex, **kw) | |
def write_image(fp, img): | |
if fp is sys.stdout and IS_ITERM: | |
print_image(img) | |
elif fp.buffer is not None: | |
fp.buffer.write(img) | |
fp.flush() | |
else: | |
fp.write(img) | |
fp.flush() | |
def main(): | |
img = render_tex(sys.argv[1]) | |
write_image(stdout, img) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment