123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 |
- 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 "<nil>"
- }
- 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,
- },
- )
- }
|