Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to extend inline markdown parsing? #291

Closed
kensanata opened this issue Sep 12, 2023 · 5 comments
Closed

How to extend inline markdown parsing? #291

kensanata opened this issue Sep 12, 2023 · 5 comments

Comments

@kensanata
Copy link
Contributor

kensanata commented Sep 12, 2023

I'd be interested in parsing [[links]] and #hashtags but don't know where to start.

My naïve approach would be something like the following for hashtags (untested, since it doesn't compile). I'm pretty new to Go so I'm guessing the reason this fails is because I have no access to Parser.inlineCallback. I think the best solution would be to add something to Options that would allow passing a additional values for inlineCallback?

func hashtag(p *parser.Parser, data []byte, offset int) (int, ast.Node) {
	data = data[offset:]
	i := 0
	n := len(data)
	for i < n && !parser.IsSpace(data[i]) {
		i++
	}
	if i == 0 {
		return 0, nil
	}
	link := &ast.Link{
		Destination: append([]byte("/search?q=%23"), data[1:i]...),
		Title: data[0:i],
	}
	return i + 1, link
}

// renderHtml renders the Page.Body to HTML and sets Page.Html.
func (p *Page) renderHtml() {
	parser := parser.New()
	parser.inlineCallback['#'] = hashtag
	maybeUnsafeHTML := markdown.ToHTML(p.Body, parser, nil)
	p.Html = sanitizeBytes(maybeUnsafeHTML)
	p.Language = language(p.plainText())
}
kensanata added a commit to kensanata/oddmu that referenced this issue Sep 12, 2023
@kensanata
Copy link
Contributor Author

kensanata commented Sep 12, 2023

I've forked a version of the markdown library and made the following change: 302893f

This seems to do what I want. In my wiki, I was able to add the extension to the parser, and test it successfully: 4c4156c44e7a0e43c4ca671e9361243dc8065822

@kjk
Copy link
Contributor

kjk commented Sep 12, 2023

I've added Parser.RegisterInline() which should give you a way to register hashtag without forking the library.

@kjk kjk closed this as completed Sep 12, 2023
kensanata added a commit to kensanata/oddmu that referenced this issue Sep 12, 2023
@kensanata
Copy link
Contributor Author

Thanks, works as intended!

@kensanata
Copy link
Contributor Author

If you're interested, I can try and write extract the two uses I have for this for your examples directory?

@kjk
Copy link
Contributor

kjk commented Sep 16, 2023

Yes, that would be great.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants