Skip to content

Commit b985057

Browse files
refactor: Enhance describe function to preserve code blocks while formatting headers (#250)
Updated the `describe` function to include a new helper, `preserve_code_blocks`, which ensures that code blocks are not altered during header formatting.
1 parent 4903eb4 commit b985057

File tree

1 file changed

+30
-13
lines changed

1 file changed

+30
-13
lines changed

lib/spark/cheat_sheet.ex

Lines changed: 30 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -184,23 +184,40 @@ defmodule Spark.CheatSheet do
184184

185185
defp describe(entity) do
186186
entity
187-
|> String.split("\n")
188-
|> Enum.map(&String.trim_leading/1)
189-
|> Enum.map_join("\n", fn
190-
"####" <> rest ->
191-
"######" <> rest
187+
|> preserve_code_blocks(fn text ->
188+
text
189+
|> String.split("\n")
190+
|> Enum.map(&String.trim_leading/1)
191+
|> Enum.map_join("\n", fn
192+
"####" <> rest ->
193+
"######" <> rest
192194

193-
"###" <> rest ->
194-
"#####" <> rest
195+
"###" <> rest ->
196+
"#####" <> rest
195197

196-
"##" <> rest ->
197-
"####" <> rest
198+
"##" <> rest ->
199+
"####" <> rest
198200

199-
"#" <> rest ->
200-
"###" <> rest
201+
"#" <> rest ->
202+
"###" <> rest
201203

202-
other ->
203-
other
204+
other ->
205+
other
206+
end)
207+
end)
208+
end
209+
210+
defp preserve_code_blocks(entity, fun) do
211+
parts =
212+
Regex.split(~r/```[\s\S]*?```/, entity, include_captures: true)
213+
214+
Enum.map_join(parts, fn part ->
215+
if String.starts_with?(part, "```") do
216+
# Return code blocks EXACTLY as-is
217+
part
218+
else
219+
fun.(part)
220+
end
204221
end)
205222
end
206223

0 commit comments

Comments
 (0)