1
0
mirror of https://github.com/danog/blackfriday.git synced 2024-11-30 04:29:13 +01:00

add target blank attr

This commit is contained in:
gihnius 2014-03-21 10:52:46 +08:00
parent e078bb8ec3
commit ecf59d4a55
2 changed files with 49 additions and 2 deletions

35
html.go
View File

@ -31,6 +31,7 @@ const (
HTML_SKIP_SCRIPT // skip embedded <script> elements
HTML_SAFELINK // only link to trusted protocols
HTML_NOFOLLOW_LINKS // only link with rel="nofollow"
HTML_HREF_TARGET_BLANK // add a blank target
HTML_TOC // generate a table of contents
HTML_OMIT_CONTENTS // skip the main contents (for a standalone table of contents)
HTML_COMPLETE_PAGE // generate a complete HTML page
@ -413,6 +414,15 @@ func (options *Html) AutoLink(out *bytes.Buffer, link []byte, kind int) {
out.WriteString("mailto:")
}
attrEscape(out, link)
if options.flags&HTML_NOFOLLOW_LINKS != 0 {
out.WriteString("\" rel=\"nofollow")
}
// blank target only add to external link
if options.flags&HTML_HREF_TARGET_BLANK != 0 && !isRelativeLink(link) {
out.WriteString("\" target=\"_blank")
}
out.WriteString("\">")
// Pretty print: if we get an email address as
@ -503,6 +513,11 @@ func (options *Html) Link(out *bytes.Buffer, link []byte, title []byte, content
if options.flags&HTML_NOFOLLOW_LINKS != 0 {
out.WriteString("\" rel=\"nofollow")
}
// blank target only add to external link
if options.flags&HTML_HREF_TARGET_BLANK != 0 && !isRelativeLink(link) {
out.WriteString("\" target=\"_blank")
}
out.WriteString("\">")
out.Write(content)
out.WriteString("</a>")
@ -788,3 +803,23 @@ func doubleSpace(out *bytes.Buffer) {
out.WriteByte('\n')
}
}
func isRelativeLink(link []byte) (yes bool) {
yes = false
// a tag begin with '#'
if link[0] == '#' {
yes = true
}
// link begin with '/' but not '//', the second maybe a protocol relative link
if len(link) >= 2 && link[0] == '/' && link[1] != '/' {
yes = true
}
// only the root '/'
if len(link) == 1 && link[0] == '/' {
yes = true
}
return
}

View File

@ -429,6 +429,18 @@ func TestNofollowLink(t *testing.T) {
doTestsInlineParam(t, tests, 0, HTML_SAFELINK|HTML_NOFOLLOW_LINKS)
}
func TestHrefTargetBlank(t *testing.T) {
var tests = []string{
// internal link
"[foo](/bar/)\n",
"<p><a href=\"/bar/\">foo</a></p>\n",
"[foo](http://example.com)\n",
"<p><a href=\"http://example.com\" target=\"_blank\">foo</a></p>\n",
}
doTestsInlineParam(t, tests, 0, HTML_SAFELINK|HTML_HREF_TARGET_BLANK)
}
func TestSafeInlineLink(t *testing.T) {
var tests = []string{
"[foo](/bar/)\n",
@ -605,9 +617,9 @@ func TestFootnotes(t *testing.T) {
[^b]: Paragraph 1
Paragraph 2
` + "```\n\tsome code\n\t```" + `
Paragraph 3
No longer in the footnote