1313from pygments import highlight
1414from pygments .lexers .hdl import VhdlLexer
1515from pygments .lexers .python import PythonLexer
16+ from pygments .lexers import get_lexer_for_filename
1617from pygments .filters import NameHighlightFilter
1718from pygments .formatters .html import HtmlFormatter
19+ from pygments .formatters import get_formatter_for_filename
1820from pygments .token import Name , Keyword , Generic
21+ from pygments .util import ClassNotFound
1922
2023
2124def left_justify (code ):
@@ -72,6 +75,8 @@ def highlight_code(
7275 types = None ,
7376 highlights = None ,
7477 language = "vhdl" ,
78+ highlight_lines = None ,
79+ font_size = 14 ,
7580): # pylint: disable=too-many-arguments
7681 """Create HTML with syntax highlighted code."""
7782 if language .lower () not in ["vhdl" , "python" ]:
@@ -98,7 +103,10 @@ def highlight_code(
98103 code = left_justify (code )
99104 code = remove_nested_snippets (code )
100105
101- lexer = VhdlLexer () if language .lower () == "vhdl" else PythonLexer ()
106+ try :
107+ lexer = get_lexer_for_filename (str (code_path ))
108+ except ClassNotFound :
109+ lexer = VhdlLexer () if language .lower () == "vhdl" else PythonLexer ()
102110
103111 if functions :
104112 lexer .add_filter (NameHighlightFilter (names = functions , tokentype = Name .Function ))
@@ -112,17 +120,26 @@ def highlight_code(
112120 if not output_path .parent .exists ():
113121 output_path .parent .mkdir (parents = True , exist_ok = True )
114122
115- output_path .write_text (
116- highlight (
117- code ,
118- lexer ,
119- HtmlFormatter (
120- linenos = line_no_offset is not None ,
121- linenostart = 1 if line_no_offset is None else line_no_offset ,
122- ),
123- )
123+ formatter = get_formatter_for_filename (
124+ str (output_path ),
125+ line_numbers = line_no_offset is not None ,
126+ linenostart = 1 if line_no_offset is None else line_no_offset ,
127+ hl_lines = highlight_lines if highlight_lines else [],
128+ font_size = font_size ,
129+ )
130+
131+ output = highlight (
132+ code ,
133+ lexer ,
134+ formatter ,
124135 )
125136
137+ if isinstance (output , bytes ):
138+ output_path .write_bytes (output )
139+
140+ if isinstance (output , str ):
141+ output_path .write_text (output )
142+
126143
127144_CONEMU_COLORS = {
128145 30 : "#002b36" ,
0 commit comments