latex.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. """Module that allows latex output notebooks to be conditioned before
  2. they are converted.
  3. """
  4. # -----------------------------------------------------------------------------
  5. # Copyright (c) 2013, the IPython Development Team.
  6. #
  7. # Distributed under the terms of the Modified BSD License.
  8. #
  9. # The full license is in the file COPYING.txt, distributed with this software.
  10. # -----------------------------------------------------------------------------
  11. # -----------------------------------------------------------------------------
  12. # Imports
  13. # -----------------------------------------------------------------------------
  14. from traitlets import List, Unicode
  15. from .base import Preprocessor
  16. # -----------------------------------------------------------------------------
  17. # Classes
  18. # -----------------------------------------------------------------------------
  19. class LatexPreprocessor(Preprocessor):
  20. """Preprocessor for latex destined documents.
  21. Populates the ``latex`` key in the resources dict,
  22. adding definitions for pygments highlight styles.
  23. Sets the authors, date and title of the latex document,
  24. overriding the values given in the metadata.
  25. """
  26. date = Unicode(
  27. None,
  28. help=("Date of the LaTeX document"),
  29. allow_none=True,
  30. ).tag(config=True)
  31. title = Unicode(None, help=("Title of the LaTeX document"), allow_none=True).tag(config=True)
  32. author_names = List(
  33. Unicode(),
  34. default_value=None,
  35. help=("Author names to list in the LaTeX document"),
  36. allow_none=True,
  37. ).tag(config=True)
  38. style = Unicode("default", help="Name of the pygments style to use").tag(config=True)
  39. def preprocess(self, nb, resources):
  40. """Preprocessing to apply on each notebook.
  41. Parameters
  42. ----------
  43. nb : NotebookNode
  44. Notebook being converted
  45. resources : dictionary
  46. Additional resources used in the conversion process. Allows
  47. preprocessors to pass variables into the Jinja engine.
  48. """
  49. # Generate Pygments definitions for Latex
  50. from pygments.formatters import LatexFormatter # noqa: PLC0415
  51. resources.setdefault("latex", {})
  52. resources["latex"].setdefault(
  53. "pygments_definitions", LatexFormatter(style=self.style).get_style_defs()
  54. )
  55. resources["latex"].setdefault("pygments_style_name", self.style)
  56. if self.author_names is not None:
  57. nb.metadata["authors"] = [{"name": author} for author in self.author_names]
  58. if self.date is not None:
  59. nb.metadata["date"] = self.date
  60. if self.title is not None:
  61. nb.metadata["title"] = self.title
  62. return nb, resources