| 1 | package format |
| 2 | |
| 3 | import ( |
| 4 | "strings" |
| 5 | "unicode" |
| 6 | "unicode/utf8" |
| 7 | ) |
| 8 | |
| 9 | // expandCurrency turns Google/Excel currency tokens into quoted literals |
| 10 | // before date detection: the D in [$CAD] is a currency code, not a day. |
| 11 | // Google ignores an optional hexadecimal locale suffix. Keep the stored |
| 12 | // format unchanged; this normalization only controls display. |
| 13 | // https://developers.google.com/workspace/sheets/api/guides/formats |
| 14 | func expandCurrency(section string) string { |
| 15 | var out strings.Builder |
| 16 | quoted := false |
| 17 | for i := 0; i < len(section); { |
| 18 | switch { |
| 19 | case section[i] == '\\' && i+1 < len(section): |
| 20 | _, size := utf8.DecodeRuneInString(section[i+1:]) |
| 21 | out.WriteString(section[i : i+1+size]) |
| 22 | i += 1 + size |
| 23 | case section[i] == '"': |
| 24 | quoted = !quoted |
| 25 | out.WriteByte(section[i]) |
| 26 | i++ |
| 27 | case !quoted && strings.HasPrefix(section[i:], "[$"): |
| 28 | end := strings.IndexByte(section[i+2:], ']') |
| 29 | if end >= 0 { |
| 30 | if symbol, ok := currencyLiteral(section[i+2 : i+2+end]); ok { |
| 31 | out.WriteByte('"') |
| 32 | out.WriteString(symbol) |
| 33 | out.WriteByte('"') |
| 34 | i += end + 3 |
| 35 | continue |
| 36 | } |
| 37 | } |
| 38 | out.WriteByte(section[i]) |
| 39 | i++ |
| 40 | default: |
| 41 | out.WriteByte(section[i]) |
| 42 | i++ |
| 43 | } |
| 44 | } |
| 45 | return out.String() |
| 46 | } |
| 47 | |
| 48 | func currencyLiteral(token string) (string, bool) { |
| 49 | symbol, locale, hasLocale := strings.Cut(token, "-") |
| 50 | if hasLocale { |
| 51 | if len(locale) == 0 || len(locale) > 8 { |
| 52 | return "", false |
| 53 | } |
| 54 | for _, r := range locale { |
| 55 | if !strings.ContainsRune("0123456789abcdefABCDEF", r) { |
| 56 | return "", false |
| 57 | } |
| 58 | } |
| 59 | } |
| 60 | r, size := utf8.DecodeRuneInString(symbol) |
| 61 | if size == len(symbol) && unicode.Is(unicode.Sc, r) { |
| 62 | return symbol, true |
| 63 | } |
| 64 | if len(symbol) != 3 { |
| 65 | return "", false |
| 66 | } |
| 67 | for _, r := range symbol { |
| 68 | if r < 'A' || r > 'Z' { |
| 69 | return "", false |
| 70 | } |
| 71 | } |
| 72 | return symbol, true |
| 73 | } |
| 74 | |