csshtmlheader.py 3.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. """Module that pre-processes the notebook for export to HTML."""
  2. # Copyright (c) Jupyter Development Team.
  3. # Distributed under the terms of the Modified BSD License.
  4. import hashlib
  5. import os
  6. from jupyterlab_pygments import JupyterStyle # type:ignore[import-untyped]
  7. from pygments.style import Style
  8. from traitlets import Type, Unicode, Union
  9. from .base import Preprocessor
  10. try:
  11. from notebook import DEFAULT_STATIC_FILES_PATH # type:ignore[import-not-found]
  12. except ImportError:
  13. DEFAULT_STATIC_FILES_PATH = None
  14. class CSSHTMLHeaderPreprocessor(Preprocessor):
  15. """
  16. Preprocessor used to pre-process notebook for HTML output. Adds IPython notebook
  17. front-end CSS and Pygments CSS to HTML output.
  18. """
  19. highlight_class = Unicode(".highlight", help="CSS highlight class identifier").tag(config=True)
  20. style = Union(
  21. [Unicode("default"), Type(klass=Style)],
  22. help="Name of the pygments style to use",
  23. default_value=JupyterStyle,
  24. ).tag(config=True)
  25. def __init__(self, *pargs, **kwargs):
  26. """Initialize the preprocessor."""
  27. Preprocessor.__init__(self, *pargs, **kwargs)
  28. self._default_css_hash = None
  29. def preprocess(self, nb, resources):
  30. """Fetch and add CSS to the resource dictionary
  31. Fetch CSS from IPython and Pygments to add at the beginning
  32. of the html files. Add this css in resources in the
  33. "inlining.css" key
  34. Parameters
  35. ----------
  36. nb : NotebookNode
  37. Notebook being converted
  38. resources : dictionary
  39. Additional resources used in the conversion process. Allows
  40. preprocessors to pass variables into the Jinja engine.
  41. """
  42. resources["inlining"] = {}
  43. resources["inlining"]["css"] = self._generate_header(resources)
  44. return nb, resources
  45. def _generate_header(self, resources):
  46. """
  47. Fills self.header with lines of CSS extracted from IPython
  48. and Pygments.
  49. """
  50. from pygments.formatters import HtmlFormatter # noqa: PLC0415
  51. header = []
  52. formatter = HtmlFormatter(style=self.style)
  53. pygments_css = formatter.get_style_defs(self.highlight_class)
  54. header.append(pygments_css)
  55. # Load the user's custom CSS and IPython's default custom CSS. If they
  56. # differ, assume the user has made modifications to his/her custom CSS
  57. # and that we should inline it in the nbconvert output.
  58. config_dir = resources["config_dir"]
  59. custom_css_filename = os.path.join(config_dir, "custom", "custom.css")
  60. if os.path.isfile(custom_css_filename):
  61. if DEFAULT_STATIC_FILES_PATH and self._default_css_hash is None:
  62. self._default_css_hash = self._hash(
  63. os.path.join(DEFAULT_STATIC_FILES_PATH, "custom", "custom.css")
  64. )
  65. if self._hash(custom_css_filename) != self._default_css_hash:
  66. with open(custom_css_filename, encoding="utf-8") as f:
  67. header.append(f.read())
  68. return header
  69. def _hash(self, filename):
  70. """Compute the hash of a file."""
  71. md5 = hashlib.md5() # noqa: S324
  72. with open(filename, "rb") as f:
  73. md5.update(f.read())
  74. return md5.digest()