1 // Copyright 2012 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
15 Register("link", parseLink)
19 Cmd string // original command from present source
24 func (l Link) PresentCmd() string { return l.Cmd }
25 func (l Link) TemplateName() string { return "link" }
27 func parseLink(ctx *Context, fileName string, lineno int, text string) (Elem, error) {
28 args := strings.Fields(text)
30 return nil, fmt.Errorf("link element must have at least 2 arguments")
32 url, err := url.Parse(args[1])
38 label = strings.Join(args[2:], " ")
40 scheme := url.Scheme + "://"
41 if url.Scheme == "mailto" {
44 label = strings.Replace(url.String(), scheme, "", 1)
46 return Link{text, url, label}, nil
49 func renderLink(href, text string) string {
54 // Open links in new window only when their url is absolute.
56 if u, err := url.Parse(href); err != nil {
57 log.Println("renderLink parsing url:", err)
58 } else if !u.IsAbs() || u.Scheme == "javascript" {
62 return fmt.Sprintf(`<a href="%s" target="%s">%s</a>`, href, target, text)
65 // parseInlineLink parses an inline link at the start of s, and returns
66 // a rendered HTML link and the total length of the raw inline link.
67 // If no inline link is present, it returns all zeroes.
68 func parseInlineLink(s string) (link string, length int) {
69 if !strings.HasPrefix(s, "[[") {
72 end := strings.Index(s, "]]")
76 urlEnd := strings.Index(s, "]")
78 const badURLChars = `<>"{}|\^[] ` + "`" // per RFC2396 section 2.4.3
79 if strings.ContainsAny(rawURL, badURLChars) {
84 url, err := url.Parse(rawURL)
86 // If the URL is http://foo.com, drop the http://
87 // In other words, render [[http://golang.org]] as:
88 // <a href="http://golang.org">golang.org</a>
89 if strings.HasPrefix(rawURL, url.Scheme+"://") {
90 simpleURL = strings.TrimPrefix(rawURL, url.Scheme+"://")
91 } else if strings.HasPrefix(rawURL, url.Scheme+":") {
92 simpleURL = strings.TrimPrefix(rawURL, url.Scheme+":")
95 return renderLink(rawURL, simpleURL), end + 2
97 if s[urlEnd:urlEnd+2] != "][" {
100 text := s[urlEnd+2 : end]
101 return renderLink(rawURL, text), end + 2