Skip to content

Commit

Permalink
Merge pull request #3 from LeKosfrancuz/tag-replace-fix
Browse files Browse the repository at this point in the history
Correctly convert .md links with tags to .html
  • Loading branch information
kpym authored Oct 31, 2024
2 parents 45b5411 + 756e718 commit 3569d4d
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 5 deletions.
18 changes: 13 additions & 5 deletions gm_compile.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,18 +76,26 @@ func compile(markdown []byte) (html []byte, err error) {
}

// regexMdLink is used to identify .md links like href="xxxx.md"
var regexMdLink = regexp.MustCompile(`href\s*=\s*"([^"]+)\.md"`)
// and .md links with tags like href="filename.md#tagname"
var regexMdLink = regexp.MustCompile(`href\s*=\s*"([^"]+)\.md#?[^"]*?"`)

// replaceLinks replace all links like href="path/xxxx.md" to href="path/xxxx.html"
// replaceLinks replaces all links like href="path/xxxx.md#tag" to href="path/xxxx.html#tag"
// if the file `path/xxxx.md` exists
func replaceLinks(html []byte, dir string) []byte {
// replace .md links with .html for local files
return regexMdLink.ReplaceAllFunc(html, func(s []byte) []byte {
filename := strings.Split(string(s), `"`)[1]
relname := filepath.Join(dir, filename)
fullhref := strings.Split(string(s), `"`)[1]
filename := strings.Split(string(fullhref), `#`)[0]
relname := filepath.Join(dir, filename)
if _, err := os.Stat(relname); err != nil {
return s
}
return []byte(fmt.Sprintf(`href="%s.html"`, filename[:len(filename)-3]))

if (fullhref == filename) {
return []byte(fmt.Sprintf(`href="%s.html"`, filename[:len(filename)-3]))
}

tagname := strings.Split(fullhref, `#`)[1]
return []byte(fmt.Sprintf(`href="%s.html#%s"`, filename[:len(filename)-3], tagname))
})
}
2 changes: 2 additions & 0 deletions test.md
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,8 @@ Right aligned columns

[Link to .md](test.md)

[Link to tag of .md](test.md#links)

[link with title](http://nodeca.github.io/pica/demo/ "title text!")

Autoconverted link https://github.com/nodeca/pica (enable linkify to see)
Expand Down

0 comments on commit 3569d4d

Please sign in to comment.