-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode_block.go
More file actions
43 lines (36 loc) · 1.05 KB
/
code_block.go
File metadata and controls
43 lines (36 loc) · 1.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package llm
import "strings"
// ExtractFirstCodeBlock extracts the first code block from markdown content.
// If no code block is found, it returns the original input.
func ExtractFirstCodeBlock(markdown string) string {
// Split by lines to check each potential code block
lines := strings.Split(markdown, "\n")
var blockStart, blockEnd int = -1, -1
var fenceType string
for i, line := range lines {
trimmed := strings.TrimSpace(line)
// Check for start of code block
if blockStart == -1 {
if strings.HasPrefix(trimmed, "```") {
fenceType = "```"
blockStart = i
} else if strings.HasPrefix(trimmed, "~~~") {
fenceType = "~~~"
blockStart = i
}
} else {
// Look for matching end fence
if strings.HasPrefix(trimmed, fenceType) {
blockEnd = i
break
}
}
}
// If we found a complete code block, extract its content
if blockStart != -1 && blockEnd != -1 {
codeLines := lines[blockStart+1 : blockEnd]
return strings.Join(codeLines, "\n")
}
// No code block found, return original input
return markdown
}