3131)
3232
3333
34- class BlackFormatter :
35- def __init__ (self , mode : Mode ) -> None :
36- self .mode : Mode = mode
34+ class BaseProcessor :
35+ """
36+ Base class for processing code blocks in documents.
37+ """
38+
39+ def __init__ (self ) -> None :
3740 self .errors : list [CodeBlockError ] = []
3841 self .off_ranges : list [tuple [int , int ]] = []
3942
43+ def process_code_block (self , code_block : str ) -> str :
44+ raise NotImplementedError
45+
4046 def _within_off_range (self , code_range : tuple [int , int ]) -> bool :
4147 index = bisect (self .off_ranges , code_range )
4248
@@ -63,7 +69,7 @@ def _md_match(self, match: Match[str]) -> str:
6369 code = textwrap .dedent (match ["code" ])
6470
6571 with self ._collect_error (match ):
66- code = black . format_str (code , mode = self . mode )
72+ code = self . process_code_block (code )
6773
6874 code = textwrap .indent (code , match ["indent" ])
6975
@@ -88,7 +94,7 @@ def _rst_match(self, match: Match[str]) -> str:
8894 code = textwrap .dedent (match ["code" ])
8995
9096 with self ._collect_error (match ):
91- code = black . format_str (code , mode = self . mode )
97+ code = self . process_code_block (code )
9298
9399 code = textwrap .indent (code , min_indent )
94100
@@ -109,7 +115,7 @@ def _rst_literal_blocks_match(self, match: Match[str]) -> str:
109115 code = textwrap .dedent (match ["code" ])
110116
111117 with self ._collect_error (match ):
112- code = black . format_str (code , mode = self . mode )
118+ code = self . process_code_block (code )
113119
114120 code = textwrap .indent (code , min_indent )
115121
@@ -125,7 +131,7 @@ def finish_fragment() -> None:
125131
126132 if fragment is not None :
127133 with self ._collect_error (match ):
128- fragment = black . format_str (fragment , mode = self . mode )
134+ fragment = self . process_code_block (fragment )
129135
130136 fragment_lines = fragment .splitlines ()
131137 code += f"{ PYCON_PREFIX } { fragment_lines [0 ]} \n "
@@ -201,7 +207,7 @@ def _latex_match(self, match: Match[str]) -> str:
201207 code = textwrap .dedent (match ["code" ])
202208
203209 with self ._collect_error (match ):
204- code = black . format_str (code , mode = self . mode )
210+ code = self . process_code_block (code )
205211
206212 code = textwrap .indent (code , match ["indent" ])
207213
@@ -287,3 +293,12 @@ def process_file(
287293 f .write (new_contents )
288294
289295 return 1
296+
297+
298+ class BlackFormatter (BaseProcessor ):
299+ def __init__ (self , mode : Mode ) -> None :
300+ super ().__init__ ()
301+ self .mode : Mode = mode
302+
303+ def process_code_block (self , code_block : str ) -> str :
304+ return black .format_str (code_block , mode = self .mode )
0 commit comments