Browse Source

fixed replacements to use regex so to not break strings

pull/34/head
David Haukeness 5 years ago
parent
commit
7408db2625
No known key found for this signature in database
GPG Key ID: A7F1091956853EF9
  1. 55
      emojiMap.go

55
emojiMap.go

@ -3,12 +3,9 @@ package main
import ( import (
"regexp" "regexp"
"strconv" "strconv"
"strings"
) )
// this is a global var set by flag that indicates whether emoji shortnames should be reprinted as unicode emojis var UNICODE_EMOJI_SUPPORT bool
// some systems may support this
var UNICODE_EMOJI_SUPPORT bool = false
type emojiData struct { type emojiData struct {
Name string Name string
@ -17,49 +14,35 @@ type emojiData struct {
Alias []string Alias []string
} }
// this converts shortname emojis to unicode emojis when they can be found in the data map
func emojiUnicodeConvert(s string) string { func emojiUnicodeConvert(s string) string {
// currently fails to find newlines and replace them needs fixed re := regexp.MustCompile(`:\w+:`)
pStr := strings.Fields(s) return re.ReplaceAllStringFunc(s, renderUnicodeEmoji)
reeMatch := regexp.MustCompile(`:\w+:`)
for i, word := range pStr {
if matched := reeMatch.MatchString(word); matched {
// renders a unicode emoji instead of the name
if temp, ok := emojiMap[word]; ok {
emj, err := renderUnicodeEmoji(temp)
if err == nil {
pStr[i] = emj
} // else don't do anything to the string
}
}
}
return strings.Join(pStr, " ")
} }
// this resolves emoji aliases back to the root emoji that actually renders to a picture
// for example `:cheeseburger:` => `:hamburger:`
func resolveRootEmojis(s string) string { func resolveRootEmojis(s string) string {
pStr := strings.Fields(s) re := regexp.MustCompile(`:\w+:`)
reMatch := regexp.MustCompile(`:\w+:`) return re.ReplaceAllStringFunc(s, emojiRootLookup)
for i, word := range pStr { }
if matched := reMatch.MatchString(word); matched {
// resolves the real emoji in case they typed an alias func emojiRootLookup(s string) string {
if temp, ok := emojiMap[word]; ok { if temp, ok := emojiMap[s]; ok {
pStr[i] = temp.Name return temp.Name
} } else {
} return s
} }
return strings.Join(pStr, " ")
} }
// this is the actual internal function that parses the unicode data to a unicode string representing the emoji func renderUnicodeEmoji(source string) string {
func renderUnicodeEmoji(data emojiData) (string, error) { if data, ok := emojiMap[source]; ok {
emj, err := strconv.ParseInt(data.Unicode, 16, 32) emj, err := strconv.ParseInt(data.Unicode, 16, 32)
if err != nil { if err != nil {
// because not all of them are parseable (like keycaps \u0031-FE0F-20E3) // because not all of them are parseable (like keycaps \u0031-FE0F-20E3)
return "", err return source
} else {
return string(emj)
}
} else { } else {
return string(emj), err return source
} }
} }

Loading…
Cancel
Save