feat: 添加 Markdown 终端渲染支持(glamour)
This commit is contained in:
@@ -118,3 +118,38 @@ func (r *SimpleReader) ReadString() (string, error) {
|
||||
}
|
||||
return line, nil
|
||||
}
|
||||
|
||||
func FindParagraphEnd(text string, startPos int) int {
|
||||
if startPos >= len(text) {
|
||||
return 0
|
||||
}
|
||||
|
||||
inCodeBlock := false
|
||||
inMathBlock := false
|
||||
|
||||
for i := startPos; i < len(text); i++ {
|
||||
if i+3 < len(text) && text[i:i+3] == "```" {
|
||||
if !inCodeBlock {
|
||||
inCodeBlock = true
|
||||
} else {
|
||||
inCodeBlock = false
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
if i+2 < len(text) && (text[i:i+2] == "$$" || text[i:i+2] == "\\[") {
|
||||
inMathBlock = !inMathBlock
|
||||
continue
|
||||
}
|
||||
|
||||
if inCodeBlock || inMathBlock {
|
||||
continue
|
||||
}
|
||||
|
||||
if i+1 < len(text) && text[i] == '\n' && text[i+1] == '\n' {
|
||||
return i + 2
|
||||
}
|
||||
}
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
70
cmd/hxclaw/internal/markdown.go
Normal file
70
cmd/hxclaw/internal/markdown.go
Normal file
@@ -0,0 +1,70 @@
|
||||
package internal
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"charm.land/glamour/v2"
|
||||
)
|
||||
|
||||
func RenderMarkdown(md string) string {
|
||||
if md == "" {
|
||||
return ""
|
||||
}
|
||||
|
||||
style := getStyle()
|
||||
|
||||
r, err := glamour.NewTermRenderer(
|
||||
glamour.WithStandardStyle(style),
|
||||
glamour.WithWordWrap(80),
|
||||
)
|
||||
if err != nil {
|
||||
return md
|
||||
}
|
||||
defer r.Close()
|
||||
|
||||
out, err := r.Render(md)
|
||||
if err != nil {
|
||||
return md
|
||||
}
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
func RenderParagraph(text string) string {
|
||||
if text == "" {
|
||||
return ""
|
||||
}
|
||||
|
||||
text = strings.TrimRight(text, "\n")
|
||||
|
||||
if text == "" {
|
||||
return ""
|
||||
}
|
||||
|
||||
style := getStyle()
|
||||
|
||||
r, err := glamour.NewTermRenderer(
|
||||
glamour.WithStandardStyle(style),
|
||||
glamour.WithWordWrap(80),
|
||||
)
|
||||
if err != nil {
|
||||
return text
|
||||
}
|
||||
defer r.Close()
|
||||
|
||||
out, err := r.Render(text)
|
||||
if err != nil {
|
||||
return text
|
||||
}
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
func getStyle() string {
|
||||
style := "dark"
|
||||
if s := os.Getenv("GLAMOUR_STYLE"); s != "" {
|
||||
style = s
|
||||
}
|
||||
return style
|
||||
}
|
||||
Reference in New Issue
Block a user