core

A merry FastHTML nbdev project that uses Pygments for Christmas joy

Get All Pygments Styles

print(pygstyles)
['abap', 'algol', 'algol_nu', 'arduino', 'autumn', 'bw', 'borland', 'coffee', 'colorful', 'default', 'dracula', 'emacs', 'friendly_grayscale', 'friendly', 'fruity', 'github-dark', 'gruvbox-dark', 'gruvbox-light', 'igor', 'inkpot', 'lightbulb', 'lilypond', 'lovelace', 'manni', 'material', 'monokai', 'murphy', 'native', 'nord-darker', 'nord', 'one-dark', 'paraiso-dark', 'paraiso-light', 'pastie', 'perldoc', 'rainbow_dash', 'rrt', 'sas', 'solarized-dark', 'solarized-light', 'staroffice', 'stata-dark', 'stata-light', 'tango', 'trac', 'vim', 'vs', 'xcode', 'zenburn']

From Python to Pygments-Highlighted FastTag

To display Python code in a FastHTML app with Pygments formatting, I made this FastTag:


source

PythonToPygmentsFT

 PythonToPygmentsFT (c, style='rrt')

Turns Python code into a Pygments syntax-highlighted FastTag

It includes the Pygments Python CSS for the style, scoped to a CSS class name that is the style name. That allows you to use it multiple times with different styles in the same page or notebook. See my Scoped Syntax Highlighting blog post for details.

Examples

Here are a couple FTs created with it. To show a FT in a Jupyter notebook, I use fasthtml.components.show:

pft = PythonToPygmentsFT('print("Hi Uma")')
show(pft)
print("Hi Uma")
pft = PythonToPygmentsFT(getsource(PythonToPygmentsFT), style="monokai")
show(pft)
def PythonToPygmentsFT(c, style='rrt'):
    "Turns Python code into a Pygments syntax-highlighted FastTag"
    fm = HtmlFormatter(style=style, cssclass=style)
    h = highlight(c, PythonLexer(), fm)
    sd = fm.get_style_defs(f".{style}")
    return Div(Style(sd), NotStr(h), id=style)

Highlight a Selected Notebook Cell

Let’s highlight a cell of this notebook.

nb = read_nb(Path("00_core.ipynb"))
c = nb.cells[5]
c
{ 'cell_type': 'code',
  'execution_count': None,
  'idx_': 5,
  'metadata': {},
  'outputs': [],
  'source': '#| export\npygstyles = L(pygments.styles.get_all_styles())'}
show(PythonToPygmentsFT(c.source, style='dracula'))
#| export
pygstyles = L(pygments.styles.get_all_styles())

Get Code Cells of a Notebook

This section is all about throwing away non-code cells.

Imagine those elves from Advent of Code doing whatever they want to a notebook


source

is_code_cell

 is_code_cell (c)
L(nb.cells).filter(is_code_cell).itemgot('source')[:2]
(#2) ['#| default_exp core','#| hide\nfrom nbdev.showdoc import *']

source

get_code_cells

 get_code_cells (nb)
get_code_cells(nb)
(#27) ['#| default_exp core','#| hide\nfrom nbdev.showdoc import *','#| export\nfrom execnb.nbio import *\nfrom fastcore.all import *\nfrom fasthtml.common import *\nfrom fasthtml.components import show\nfrom fasthtml.jupyter import *\nfrom inspect import getsource\nfrom IPython.display import display, HTML, IFrame\nfrom pathlib import Path\nimport pygments\nfrom pygments import highlight\nfrom pygments.lexers import PythonLexer\nfrom pygments.formatters import HtmlFormatter\nfrom random import choice','#| export\npygstyles = L(pygments.styles.get_all_styles())','print(pygstyles)','#| export\ndef PythonToPygmentsFT(c, style=\'rrt\'):\n    "Turns Python code into a Pygments syntax-highlighted FastTag"\n    fm = HtmlFormatter(style=style, cssclass=style)\n    h = highlight(c, PythonLexer(), fm)\n    sd = fm.get_style_defs(f".{style}")\n    return Div(Style(sd), NotStr(h), id=style)','pft = PythonToPygmentsFT(\'print("Hi Uma")\')\nshow(pft)','pft = PythonToPygmentsFT(getsource(PythonToPygmentsFT), style="monokai")\nshow(pft)','nb = read_nb(Path("00_core.ipynb"))\nc = nb.cells[5]\nc',"show(PythonToPygmentsFT(c.source, style='dracula'))","#| export\ndef is_code_cell(c): return c.cell_type == 'code'","L(nb.cells).filter(is_code_cell).itemgot('source')[:2]","#| export\ndef get_code_cells(nb): return L(nb.cells).filter(is_code_cell).itemgot('source')",'get_code_cells(nb)','#| export\ndef NotebookToPygmentsFT(nb, style=\'rrt\'):\n    "Warning: This gets only code cells, without their output or any other cells"\n    cells = get_code_cells(nb)\n    return cells.map(partial(PythonToPygmentsFT, style=style))','# show(Div(*NotebookToPygmentsFT(nb)))','#| export\ndef PythonToRandomPygmentsFT(c,print_style=True): \n    style = choice(pygstyles)\n    result = PythonToPygmentsFT(c, style=style)\n    if print_style:\n        result = Div(f"Pygments style: {style}", result)\n    return result','pft = PythonToRandomPygmentsFT(\'print("Hi Uma")\', print_style=False)\nshow(pft)','pft = PythonToRandomPygmentsFT(\'print("Hi Uma")\', print_style=True)\nshow(pft)','#| export\ndef NotebookToRandomPygmentsFT(nb):\n    "Warning: This gets only code cells, without their output or any other cells"\n    cells = get_code_cells(nb)\n    return cells.map(PythonToRandomPygmentsFT)'...]

Highlight Code Cells of a Notebook

This is sort of like a toy version of nb2fasthtml’s highly-customizable render_nb that throws away Markdown cells and code cell output:


source

NotebookToPygmentsFT

 NotebookToPygmentsFT (nb, style='rrt')

Warning: This gets only code cells, without their output or any other cells

To see what it does, uncomment this:

# show(Div(*NotebookToPygmentsFT(nb)))

Highlight Each Notebook Cell Randomly


source

PythonToRandomPygmentsFT

 PythonToRandomPygmentsFT (c, print_style=True)
pft = PythonToRandomPygmentsFT('print("Hi Uma")', print_style=False)
show(pft)
print("Hi Uma")
pft = PythonToRandomPygmentsFT('print("Hi Uma")', print_style=True)
show(pft)
Pygments style: autumn
print("Hi Uma")

source

NotebookToRandomPygmentsFT

 NotebookToRandomPygmentsFT (nb)

Warning: This gets only code cells, without their output or any other cells

FastHTML App

server = JupyUvi(app)

Routes and Handlers


source

index

 index ()

Random Pygments style for each cell


source

randstyle

 randstyle ()

Random Pygments style upon refresh

Stop Server

if 'server' in globals(): server.stop()

Export