#!/usr/bin/env python # coding: utf-8 # # Putting things together. # # Put together the Markdown tangle, weave, and template actions. # In[150]: import ast, types, textwrap, IPython, jinja2, string import deathbeds.__String_Template_Ipython_formatter as strings, \ deathbeds.__Ipython_aware_jinja_templates as templates, \ deathbeds.__Markdown_to_vdom_with_mistletoe as weave, \ deathbeds.__Markdown_to_Python as tangle # In[151]: ip = IPython.get_ipython() # In[157]: class MarkdownShell(IPython.core.interactiveshell.InteractiveShell): """Markdown Shell""" def run_cell(self, raw, store_history=False, silent=False, shell_futures=True, **user_expressions): self._last_traceback = None source = tangle.markdown_to_python(raw) result = IPython.core.interactiveshell.InteractiveShell.run_cell( self, source, store_history=store_history, silent=silent, shell_futures=shell_futures) try: is_markdown = raw.strip() == ast.literal_eval(source).strip() except: is_markdown = False is_source = ''.join(map(str.rstrip, textwrap.dedent(raw).strip().splitlines(True)) ) == ''.join(map(str.rstrip, source.strip().splitlines(True))) if not (is_markdown or is_source): stripped = raw.rstrip() blank_line = stripped and not raw.splitlines()[0].strip() if not blank_line: IPython.display.display(raw) return result # In[158]: def show_type(type): if hasattr(type, '__doc__'): ns = vars(importlib.import_module(type.__module__)) type = type.__doc__ if isinstance(type, str): type = weave.FlexRenderer()(template(type, ns)) return ip.display_formatter.format(type) # In[159]: env = jinja2.Environment(finalize=templates.ipython_formatter) # In[160]: def template(str, dict): if ' $' in str: str = string.Template(str).safe_substitute(strings.IpythonChainMap(dict)) if ( (env.block_end_string in str ) and (env.block_start_string in str ) ) or ((env.variable_end_string in str) and (env.variable_start_string in str)): str = env.from_string(str).render(dict) return str # In[161]: def load_ipython_extension(ip): ip.run_cell = types.MethodType(MarkdownShell.run_cell, ip) ip.display_formatter.mimebundle_formatter.for_type( str, lambda str: ip.display_formatter.format(weave.FlexRenderer()(template(str, ip.user_ns)))) ip.display_formatter.mimebundle_formatter.for_type(type, show_type) __name__ == '__main__' and load_ipython_extension(IPython.get_ipython()) # In[ ]: