package gmi2html import ( "html" "regexp" "strings" ) var heading1Regexp = regexp.MustCompile("^# (.*)$") var heading2Regexp = regexp.MustCompile("^## (.*)$") var heading3Regexp = regexp.MustCompile("^### (.*)$") var linkRegexp = regexp.MustCompile("^=> ([^\\s]+) ?(.+)?$") var blockquoteRegexp = regexp.MustCompile("^> (.*)$") var preRegexp = regexp.MustCompile("^```.*$") var bulletRegexp = regexp.MustCompile(`^\* ?(.*)$`) func clearLinkMode(linkMode *bool, rv *[]string) { if *linkMode { *rv = append(*rv, "
") *linkMode = false } } func clearUlMode(ulMode *bool, rv *[]string) { if *ulMode { *rv = append(*rv, "") *ulMode = false } } func sanitize(input string) string { return html.EscapeString(input) } func Convert(gmi string) string { var rv []string preMode := false ulMode := false linkMode := false for _, l := range strings.Split(gmi, "\n") { l = strings.TrimRight(l, "\r") if preMode { switch { case preRegexp.MatchString(l): rv = append(rv, "") preMode = false default: rv = append(rv, sanitize(l)) } } else { switch { case heading1Regexp.MatchString(l): clearUlMode(&ulMode, &rv) clearLinkMode(&linkMode, &rv) matches := heading1Regexp.FindStringSubmatch(l) rv = append(rv, ""+sanitize(matches[1])+"") case linkRegexp.MatchString(l): clearUlMode(&ulMode, &rv) matches := linkRegexp.FindStringSubmatch(l) if len(matches[2]) == 0 { matches[2] = matches[1] } if strings.HasSuffix(matches[1], ".png") || strings.HasSuffix(matches[1], ".PNG") || strings.HasSuffix(matches[1], ".jpg") || strings.HasSuffix(matches[1], ".JPG") || strings.HasSuffix(matches[1], ".jpeg") || strings.HasSuffix(matches[1], ".gif") || strings.HasSuffix(matches[1], ".GIF") { rv = append(rv, "") continue } if linkMode { rv = append(rv, ""+sanitize(matches[2])+"
"+sanitize(matches[2])+"
")
linkMode = true
case preRegexp.MatchString(l):
clearUlMode(&ulMode, &rv)
clearLinkMode(&linkMode, &rv)
rv = append(rv, "
") preMode = true case bulletRegexp.MatchString(l): clearLinkMode(&linkMode, &rv) matches := bulletRegexp.FindStringSubmatch(l) if ulMode { rv = append(rv, "
"+sanitize(l)+"
") } } } } clearUlMode(&ulMode, &rv) clearLinkMode(&linkMode, &rv) return strings.Join(rv, "\n") }