Skip to content

Instantly share code, notes, and snippets.

@tscholak
Forked from terencezl/jekyll.py
Last active August 29, 2015 14:16
Show Gist options
  • Save tscholak/8e1d1687d64cb2f05584 to your computer and use it in GitHub Desktop.
Save tscholak/8e1d1687d64cb2f05584 to your computer and use it in GitHub Desktop.
try:
from urllib.parse import quote # Py 3
except ImportError:
from urllib2 import quote # Py 2
import os
import sys
try:
BLOG_DIR = os.environ['BLOG_DIR']
except KeyError:
BLOG_DIR = '.'
print("Cannot find environment variable $BLOG_DIR. Use the current directory to output.")
f = None
for arg in sys.argv:
if arg.endswith('.ipynb'):
f = arg.split('.ipynb')[0]
break
c = get_config()
c.NbConvertApp.export_format = 'markdown'
home = os.path.expanduser("~")
c.MarkdownExporter.template_path = [os.path.join(home, '.ipython/templates')]
c.MarkdownExporter.template_file = 'jekyll'
#c.Exporter.file_extension = 'md'
def path2support(path):
"""Turn a file path into a URL"""
parts = path.split(os.path.sep)
return os.path.join("{{ '/notebooks/' | prepend: site.baseurl }}", *[quote(part) for part in parts])
c.MarkdownExporter.filters = {'path2support': path2support}
if f:
c.NbConvertApp.output_base = f.lower().replace(' ', '-')
c.FilesWriter.build_directory = os.path.join(BLOG_DIR, 'notebooks')
{% extends 'display_priority.tpl' %}
{%- block header -%}
---
layout: post
title: "{{resources['metadata']['name']}}"
tags: python
---
{%- endblock header -%}
{% block in_prompt %}
**In [{{ cell.prompt_number }}]:**
{% endblock in_prompt %}
{% block output_prompt %}
{%- endblock output_prompt %}
{% block input %}
{{ '{% highlight python linenos %}' }}
{{ cell.input }}
{{ '{% endhighlight %}' }}
{% endblock input %}
{% block pyerr %}
{{ super() }}
{% endblock pyerr %}
{% block traceback_line %}
{{ line | indent | strip_ansi }}
{% endblock traceback_line %}
{% block pyout %}
{% block data_priority scoped %}
{{ super() }}
{% endblock %}
{% endblock pyout %}
{% block stream %}
{{ output.text | indent }}
{% endblock stream %}
{% block data_svg %}
![svg]({{ output.svg_filename | path2support }})
{% endblock data_svg %}
{% block data_png %}
![png]({{ output.png_filename | path2support }})
{% endblock data_png %}
{% block data_jpg %}
![jpeg]({{ output.jpeg_filename | path2support }})
{% endblock data_jpg %}
{% block data_latex %}
{{ output.latex }}
{% endblock data_latex %}
{% block data_html scoped %}
{{ output.html }}
{% endblock data_html %}
{% block data_text scoped %}
{{ output.text | indent }}
{% endblock data_text %}
{% block markdowncell scoped %}
{{ cell.source | wrap_text(80) }}
{% endblock markdowncell %}
{% block headingcell scoped %}
{{ '#' * cell.level }} {{ cell.source | replace('\n', ' ') }}
{% endblock headingcell %}
{% block unknowncell scoped %}
unknown type {{ cell.type }}
{% endblock unknowncell %}
#!/usr/bin/env python
# This searches the converted .md file for GitHub style markdown backquotes (e.g. ```python)
# and converts them into Liquid tags {% highlight xxx %} depending on the language specified.
#
# put this file to your PATH and `chmod +x markdown_highlight.py`
import sys
for filename in sys.argv[1:]:
print("Markdown highlight script is processing " + filename + "...")
with open(filename) as f:
fl = f.readlines()
langs = ['python', 'bash', 'R']
i = 0
while i < len(fl):
stripped = fl[i].strip()
for lg in langs:
if stripped == '```' + lg:
print("Converted backquotes" + stripped)
fl[i] = '{% highlight '+ lg + ' linenos %}\n'
i += 1
while i < len(fl):
stripped = fl[i].strip()
if stripped == '```':
print("Converted corresponding backquotes" + stripped)
fl[i] = '{% endhighlight %}\n'
break
i += 1
i += 1
with open(filename, 'w') as f:
f.writelines(fl)
#!/usr/bin/env bash
# This shell wrapper is what you would use every day to convert a .ipynb to a .md file
# with supporting files (imgs) in a directory called `notebooks` in `$BLOG_DIR`, and move
# only the .md file in it to `$BLOG_DIR/_drafts/`. The supporting files will remain in
# `$BLOG_DIR/notebooks/` and be served by Jekyll.
#
# put this file to your PATH and `chmod +x nbconvert.sh`
#
# change this variable to your site directory here. Or `notebooks/`will be created where you
# execute the script.
export BLOG_DIR="."
ipython nbconvert --config jekyll.py "$@";
echo
markdown_highlight.py ${BLOG_DIR}/notebooks/*.md
echo
mv ${BLOG_DIR}/notebooks/*.md ${BLOG_DIR}/_drafts/
echo ".md files are moved from ${BLOG_DIR}/notebooks/ to ${BLOG_DIR}/_drafts/"
cp "$@" ${BLOG_DIR}/notebooks/
echo "$@" "is/are moved to ${BLOG_DIR}/notebooks/"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment