Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow passing extra args to code highlighter #1683

Merged
merged 1 commit into from Dec 2, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
31 changes: 27 additions & 4 deletions nbconvert/filters/highlight.py
Expand Up @@ -14,6 +14,7 @@
from warnings import warn

from traitlets import observe
from traitlets.config import Dict

MULTILINE_OUTPUTS = ['text', 'html', 'svg', 'latex', 'javascript', 'json']

Expand All @@ -23,10 +24,21 @@
]

class Highlight2HTML(NbConvertBase):
extra_formatter_options = Dict(
{},
help="""
Extra set of options to control how code is highlighted.

Passed through to the pygments' HtmlFormatter class.
See available list in https://pygments.org/docs/formatters/#HtmlFormatter
""",
config=True
)

def __init__(self, pygments_lexer=None, **kwargs):
self.pygments_lexer = pygments_lexer or 'ipython3'
super().__init__(**kwargs)

@observe('default_language')
def _default_language_changed(self, change):
warn('Setting default_language in config is deprecated as of 5.0, '
Expand All @@ -53,15 +65,26 @@ def __call__(self, source, language=None, metadata=None):

return _pygments_highlight(source if len(source) > 0 else ' ',
# needed to help post processors:
HtmlFormatter(cssclass=" highlight hl-"+language),
HtmlFormatter(cssclass=" highlight hl-" + language, **self.extra_formatter_options),
language, metadata)


class Highlight2Latex(NbConvertBase):
extra_formatter_options = Dict(
{},
help="""
Extra set of options to control how code is highlighted.

Passed through to the pygments' LatexFormatter class.
See available list in https://pygments.org/docs/formatters/#LatexFormatter
""",
config=True
)

def __init__(self, pygments_lexer=None, **kwargs):
self.pygments_lexer = pygments_lexer or 'ipython3'
super().__init__(**kwargs)

@observe('default_language')
def _default_language_changed(self, change):
warn('Setting default_language in config is deprecated as of 5.0, '
Expand All @@ -87,7 +110,7 @@ def __call__(self, source, language=None, metadata=None, strip_verbatim=False):
if not language:
language=self.pygments_lexer

latex = _pygments_highlight(source, LatexFormatter(), language, metadata)
latex = _pygments_highlight(source, LatexFormatter(**self.extra_formatter_options), language, metadata)
if strip_verbatim:
latex = latex.replace(r'\begin{Verbatim}[commandchars=\\\{\}]' + '\n', '')
return latex.replace('\n\\end{Verbatim}\n', '')
Expand Down