Search code examples
jinja2jupyter-notebookjupyternbconvert

nbconvert --to latex, remove all prompts


I'd like to remove the typical IPython prompts In [35]: from the LaTeX produced by jupyter-nbconvert --to latex.

Once there was a template, style_simple.tplx, that almost did what I want but now it has been removed, otoh its companion templates, style_bw_ipython.tplx et c. are still distributed but don't work any more with the new nbconvert.

I understand that I have to write an ad hoc template in the jinja2 template language, but both jinja2 template syntax and its use in nbconvert have eluded my understanding, despite the number of attempts I had made.

Given that I cannot write such a template, I'm seeking assistance with the task.


Solution

  • The two places prompts appear are the input and execute_result block.

    The default input block:

    ((* block input scoped *))
        ((( add_prompt(cell.source | highlight_code(strip_verbatim=True), cell, 'In ', 'incolor') )))
    ((* endblock input *))
    

    We can replace that with a block that puts highlighted source code on the page directly in a verbatim block, instead of adding prompts:

    ((* block input scoped *))
    \begin{Verbatim}[commandchars=\\\{\}]
    ((( cell.source | highlight_code(strip_verbatim=True) )))
    \end{Verbatim}
    ((* endblock input *))
    

    For outputs, we can use the fact that an execute_result output is actually the same as a display_data output, only adding prompts. So we can tell our template to display execute_result outputs the same as display_data:

    ((* block execute_result scoped *))
        ((* block display_data scoped *))
            ((( super() )))
        ((* endblock display_data *))
    ((* endblock execute_result *))
    

    Putting it all together in a custom template, extending the default article template:

    % extend the default article template:
    ((* extends 'article.tplx' *))
    
    % display input without prompts:
    ((* block input scoped *))
    \begin{Verbatim}[commandchars=\\\{\}]
    ((( cell.source | highlight_code(strip_verbatim=True) )))
    \end{Verbatim}
    ((* endblock input *))
    
    % treat execute_result (output with prompt) as display_data (output without prompt)
    ((* block execute_result scoped *))
        ((* block display_data scoped *))
            ((( super() )))
        ((* endblock display_data *))
    ((* endblock execute_result *))
    

    If we call this file noprompts.tplx, then we can use it with:

    jupyter nbconvert --to latex --template noprompts mynotebook.ipynb