2222
2323IGNORED_DIRS = [".git" ]
2424
25+ def count_indent (string : str ) -> int :
26+ stripped = string .lstrip (" " )
27+ return len (string ) - len (stripped )
2528
2629def extract_inline_code (path , languages ):
2730 """extract inline code, language and filters from markdown"""
2831
2932 with open (path , "r" ) as f :
3033 content = f .read ()
3134
35+ lines = content .split ("\n " )
36+
3237 md = markdown_it .MarkdownIt ("commonmark" )
3338 ast = md .parse (content )
3439
@@ -44,15 +49,23 @@ def extract_inline_code(path, languages):
4449 language = info_string [0 ]
4550 flags = info_string [1 :]
4651 if flags and flags [0 ][0 ] == "{" and flags [- 1 ][- 1 ] == "}" :
47- flags [0 ] = flags [0 ][1 :]
48- flags [- 1 ] = flags [- 1 ][0 :- 1 ]
52+ flags [0 ] = flags [0 ][1 :]
53+ flags [- 1 ] = flags [- 1 ][0 :- 1 ]
4954 if language in languages :
5055 assert child .map is not None
56+ # Index of first line to include, the triple backtick fence:
57+ first_line = child .map [0 ]
58+ # The first line is triple backticks preceded by some spaces, count those:
59+ indent = count_indent (lines [first_line ])
60+ # Index of first line to NOT include, the line after closing triple backtick:
61+ last_line = child .map [1 ]
5162 yield {
5263 "language" : language ,
5364 "flags" : flags ,
5465 "first_line" : child .map [0 ],
5566 "last_line" : child .map [1 ],
67+ "indent" : indent ,
68+ "lines" : lines [first_line :last_line ] # Includes backtick fences on both sides
5669 }
5770
5871
@@ -137,7 +150,7 @@ def fn_check_output():
137150 pass
138151
139152
140- def fn_replace (origin_path , snippet_path , _language , first_line , last_line ):
153+ def fn_replace (origin_path , snippet_path , _language , first_line , last_line , indent ):
141154 try :
142155 with open (snippet_path , "r" ) as f :
143156 pretty_content = f .read ().strip ()
@@ -146,6 +159,8 @@ def fn_replace(origin_path, snippet_path, _language, first_line, last_line):
146159 origin_lines = f .read ().split ("\n " )
147160 pretty_lines = pretty_content .split ("\n " )
148161
162+ pretty_lines = [" " * indent + x for x in pretty_lines ]
163+
149164 offset = len (pretty_lines ) - len (
150165 origin_lines [first_line + 1 : last_line - 1 ]
151166 )
@@ -264,6 +279,7 @@ def _markdown_code_checker(
264279 language ,
265280 code_block ["first_line" ],
266281 code_block ["last_line" ],
282+ code_block ["indent" ],
267283 )
268284 if cleanup :
269285 os .remove (snippet_path )
0 commit comments