package mdx import "github.com/gomarkdown/markdown" import "github.com/gomarkdown/markdown/html" import "github.com/gomarkdown/markdown/parser" import "surdeus.su/core/xgo/v2" import "bytes" func GetModule() xgo.Importable { return &xgo.BuiltinModule{Attrs:map[string]xgo.Object{ "new": &xgo.BuiltinFunction{ Name: "new", Value: func( args ...xgo.Object, ) (xgo.Object, error){ return MakeDefaultMarkdown(), nil }, }, }} } type Markdown struct { xgo.ObjectImpl MakeParser func() *parser.Parser MakeRenderer func() *html.Renderer } func MakeDefaultMarkdown() *Markdown { return &Markdown{ MakeParser: MakeDefaultParser, MakeRenderer: MakeDefaultRenderer, } } func (md *Markdown) TypeName() string { return "*Markdown" } func (md *Markdown) String() string { if md == nil { return "" } return "&Markdown{...}" } func (md *Markdown) Render( data []byte, ) ([]byte, error) { doc := md.MakeParser().Parse(data) rendered := markdown.Render(doc, md.MakeRenderer()) return rendered, nil } func (md *Markdown) CanCall() bool { return md != nil } func (md *Markdown) Call( args ...xgo.Object, ) (xgo.Object, error) { var b bytes.Buffer for _, arg := range args { str, ok := xgo.ToString(arg) if !ok { return nil, xgo.ErrInvalidArgumentType{ Name: "v", Expected: "stringer", Found: arg.TypeName(), } } b.Write([]byte(str)) } rendered, err := md.Render(b.Bytes()) if err != nil { return nil, err } return xgo.FromInterface(rendered) } func MakeDefaultParser() *parser.Parser { return parser.NewWithExtensions( parser.CommonExtensions | parser.AutoHeadingIDs | parser.NoEmptyLineBeforeBlock | parser.Attributes | parser.Tables, ) } func MakeDefaultRenderer() *html.Renderer { return html.NewRenderer( html.RendererOptions{ Flags: html.CommonFlags | html.HrefTargetBlank, }, ) }