| 1 |
// Package unicode handles parsing of Unicode data files for string width calculation |
| 2 |
package main |
| 3 |
|
| 4 |
import ( |
| 5 |
"bufio" |
| 6 |
"fmt" |
| 7 |
"io" |
| 8 |
"net/http" |
| 9 |
"os" |
| 10 |
"path/filepath" |
| 11 |
"strconv" |
| 12 |
"strings" |
| 13 |
"unicode" |
| 14 |
) |
| 15 |
|
| 16 |
// UnicodeData contains all the parsed Unicode character properties |
| 17 |
type UnicodeData struct { |
| 18 |
EastAsianWidth map[rune]string // From EastAsianWidth.txt |
| 19 |
ExtendedPictographic map[rune]bool // From emoji-data.txt (Extended_Pictographic property) |
| 20 |
EmojiPresentation map[rune]bool // From emoji-data.txt (Emoji_Presentation property) |
| 21 |
RegionalIndicator map[rune]bool // From emoji-data.txt (Regional Indicator symbols, range 1F1E6..1F1FF) |
| 22 |
ControlChars map[rune]bool // From Go stdlib |
| 23 |
CombiningMarks map[rune]bool // From Go stdlib (Mn, Me only - Mc excluded for proper width) |
| 24 |
ZeroWidthChars map[rune]bool // Special zero-width characters |
| 25 |
} |
| 26 |
|
| 27 |
// property represents the properties of a character |
| 28 |
type property uint8 |
| 29 |
|
| 30 |
// PropertyDefinition describes a single character property flag |
| 31 |
type PropertyDefinition struct { |
| 32 |
Name string |
| 33 |
Comment string |
| 34 |
} |
| 35 |
|
| 36 |
// PropertyDefinitions is the single source of truth for all character properties. |
| 37 |
// The order matters - it defines the bit positions (via iota). |
| 38 |
var PropertyDefinitions = []PropertyDefinition{ |
| 39 |
{"Zero_Width", "Always 0 width, includes combining marks, control characters, non-printable, etc"}, |
| 40 |
{"Wide", "Always 2 wide (East Asian Wide F/W, Emoji, Regional Indicator)"}, |
| 41 |
{"East_Asian_Ambiguous", "Width depends on EastAsianWidth option"}, |
| 42 |
} |
| 43 |
|
| 44 |
// these constants are used to build the property bitmap, internally. |
| 45 |
// the external properties are above. Keep them in the same order! |
| 46 |
const ( |
| 47 |
// ZWSP, ZWJ, ZWNJ, etc. |
| 48 |
zero_Width property = iota + 1 |
| 49 |
// F, W (East Asian Wide), Emoji, Regional Indicator |
| 50 |
wide |
| 51 |
// A (East Asian Ambiguous) |
| 52 |
east_Asian_Ambiguous |
| 53 |
) |
| 54 |
|
| 55 |
// ParseUnicodeData downloads and parses all required Unicode data files |
| 56 |
func ParseUnicodeData() (*UnicodeData, error) { |
| 57 |
data := &UnicodeData{ |
| 58 |
EastAsianWidth: make(map[rune]string), |
| 59 |
ExtendedPictographic: make(map[rune]bool), |
| 60 |
EmojiPresentation: make(map[rune]bool), |
| 61 |
RegionalIndicator: make(map[rune]bool), |
| 62 |
ControlChars: make(map[rune]bool), |
| 63 |
CombiningMarks: make(map[rune]bool), |
| 64 |
ZeroWidthChars: make(map[rune]bool), |
| 65 |
} |
| 66 |
|
| 67 |
const unicodeVersion = "17.0.0" |
| 68 |
|
| 69 |
// Create data directory |
| 70 |
dataDir := filepath.Join("data", unicodeVersion) |
| 71 |
if err := os.MkdirAll(dataDir, 0755); err != nil { |
| 72 |
return nil, fmt.Errorf("failed to create data directory: %v", err) |
| 73 |
} |
| 74 |
|
| 75 |
eawFile := filepath.Join(dataDir, "EastAsianWidth.txt") |
| 76 |
if err := downloadFile(fmt.Sprintf("https://unicode.org/Public/%s/ucd/EastAsianWidth.txt", unicodeVersion), eawFile); err != nil { |
| 77 |
return nil, fmt.Errorf("failed to download EastAsianWidth.txt: %v", err) |
| 78 |
} |
| 79 |
if err := parseEastAsianWidth(eawFile, data); err != nil { |
| 80 |
return nil, fmt.Errorf("failed to parse EastAsianWidth.txt: %v", err) |
| 81 |
} |
| 82 |
|
| 83 |
emojiFile := filepath.Join(dataDir, "emoji-data.txt") |
| 84 |
if err := downloadFile(fmt.Sprintf("https://unicode.org/Public/%s/ucd/emoji/emoji-data.txt", unicodeVersion), emojiFile); err != nil { |
| 85 |
fmt.Printf("Warning: failed to download emoji-data.txt: %v\n", err) |
| 86 |
fmt.Println("Continuing with basic emoji detection from Go stdlib...") |
| 87 |
} else { |
| 88 |
if err := parseEmojiData(emojiFile, data); err != nil { |
| 89 |
fmt.Printf("Warning: failed to parse emoji-data.txt: %v\n", err) |
| 90 |
fmt.Println("Continuing with basic emoji detection from Go stdlib...") |
| 91 |
} |
| 92 |
} |
| 93 |
|
| 94 |
extractStdlibData(data) |
| 95 |
|
| 96 |
return data, nil |
| 97 |
} |
| 98 |
|
| 99 |
// downloadFile downloads a file from URL to local path |
| 100 |
func downloadFile(url, filepath string) error { |
| 101 |
// Check if file already exists |
| 102 |
if _, err := os.Stat(filepath); err == nil { |
| 103 |
fmt.Printf("File %s already exists, skipping download\n", filepath) |
| 104 |
return nil |
| 105 |
} |
| 106 |
|
| 107 |
fmt.Printf("Downloading %s...\n", url) |
| 108 |
resp, err := http.Get(url) |
| 109 |
if err != nil { |
| 110 |
return err |
| 111 |
} |
| 112 |
defer resp.Body.Close() |
| 113 |
|
| 114 |
if resp.StatusCode != http.StatusOK { |
| 115 |
return fmt.Errorf("bad status: %s", resp.Status) |
| 116 |
} |
| 117 |
|
| 118 |
out, err := os.Create(filepath) |
| 119 |
if err != nil { |
| 120 |
return err |
| 121 |
} |
| 122 |
defer out.Close() |
| 123 |
|
| 124 |
_, err = io.Copy(out, resp.Body) |
| 125 |
if err != nil { |
| 126 |
return err |
| 127 |
} |
| 128 |
|
| 129 |
fmt.Printf("Downloaded %s\n", filepath) |
| 130 |
return nil |
| 131 |
} |
| 132 |
|
| 133 |
// parseEastAsianWidth parses the EastAsianWidth.txt file |
| 134 |
func parseEastAsianWidth(filename string, data *UnicodeData) error { |
| 135 |
file, err := os.Open(filename) |
| 136 |
if err != nil { |
| 137 |
return err |
| 138 |
} |
| 139 |
defer file.Close() |
| 140 |
|
| 141 |
scanner := bufio.NewScanner(file) |
| 142 |
for scanner.Scan() { |
| 143 |
line := strings.TrimSpace(scanner.Text()) |
| 144 |
if line == "" || strings.HasPrefix(line, "#") { |
| 145 |
continue |
| 146 |
} |
| 147 |
|
| 148 |
parts := strings.Split(line, ";") |
| 149 |
if len(parts) < 2 { |
| 150 |
continue |
| 151 |
} |
| 152 |
|
| 153 |
rangeStr := strings.TrimSpace(parts[0]) |
| 154 |
widthStr := strings.TrimSpace(parts[1]) |
| 155 |
|
| 156 |
// Remove comments from width string |
| 157 |
if commentIndex := strings.Index(widthStr, "#"); commentIndex != -1 { |
| 158 |
widthStr = strings.TrimSpace(widthStr[:commentIndex]) |
| 159 |
} |
| 160 |
|
| 161 |
// Parse range |
| 162 |
if strings.Contains(rangeStr, "..") { |
| 163 |
// Range of codepoints |
| 164 |
rangeParts := strings.Split(rangeStr, "..") |
| 165 |
if len(rangeParts) != 2 { |
| 166 |
continue |
| 167 |
} |
| 168 |
start, err1 := strconv.ParseInt(rangeParts[0], 16, 32) |
| 169 |
end, err2 := strconv.ParseInt(rangeParts[1], 16, 32) |
| 170 |
if err1 != nil || err2 != nil { |
| 171 |
continue |
| 172 |
} |
| 173 |
for r := rune(start); r <= rune(end); r++ { |
| 174 |
data.EastAsianWidth[r] = widthStr |
| 175 |
} |
| 176 |
} else { |
| 177 |
// Single codepoint |
| 178 |
codepoint, err := strconv.ParseInt(rangeStr, 16, 32) |
| 179 |
if err != nil { |
| 180 |
continue |
| 181 |
} |
| 182 |
data.EastAsianWidth[rune(codepoint)] = widthStr |
| 183 |
} |
| 184 |
} |
| 185 |
|
| 186 |
return scanner.Err() |
| 187 |
} |
| 188 |
|
| 189 |
// parseEmojiData parses the emoji-data.txt file for Extended_Pictographic and Emoji_Presentation |
| 190 |
func parseEmojiData(filename string, data *UnicodeData) error { |
| 191 |
file, err := os.Open(filename) |
| 192 |
if err != nil { |
| 193 |
return err |
| 194 |
} |
| 195 |
defer file.Close() |
| 196 |
|
| 197 |
scanner := bufio.NewScanner(file) |
| 198 |
|
| 199 |
for scanner.Scan() { |
| 200 |
line := strings.TrimSpace(scanner.Text()) |
| 201 |
if line == "" || strings.HasPrefix(line, "#") { |
| 202 |
continue |
| 203 |
} |
| 204 |
|
| 205 |
// Parse line format: <codepoint(s)> ; <property> # <comments> |
| 206 |
parts := strings.Split(line, ";") |
| 207 |
if len(parts) < 2 { |
| 208 |
continue |
| 209 |
} |
| 210 |
|
| 211 |
rangeStr := strings.TrimSpace(parts[0]) |
| 212 |
propertyStr := strings.TrimSpace(parts[1]) |
| 213 |
|
| 214 |
// Remove comments from property string |
| 215 |
if commentIndex := strings.Index(propertyStr, "#"); commentIndex != -1 { |
| 216 |
propertyStr = strings.TrimSpace(propertyStr[:commentIndex]) |
| 217 |
} |
| 218 |
|
| 219 |
var r1, r2 rune |
| 220 |
|
| 221 |
// Parse range |
| 222 |
if strings.Contains(rangeStr, "..") { |
| 223 |
// Range of codepoints |
| 224 |
rangeParts := strings.Split(rangeStr, "..") |
| 225 |
if len(rangeParts) != 2 { |
| 226 |
continue |
| 227 |
} |
| 228 |
start, err1 := strconv.ParseInt(rangeParts[0], 16, 32) |
| 229 |
end, err2 := strconv.ParseInt(rangeParts[1], 16, 32) |
| 230 |
if err1 != nil || err2 != nil { |
| 231 |
continue |
| 232 |
} |
| 233 |
r1, r2 = rune(start), rune(end) |
| 234 |
} else { |
| 235 |
// Single codepoint |
| 236 |
codepoint, err := strconv.ParseInt(rangeStr, 16, 32) |
| 237 |
if err != nil { |
| 238 |
continue |
| 239 |
} |
| 240 |
r1, r2 = rune(codepoint), rune(codepoint) |
| 241 |
} |
| 242 |
|
| 243 |
// Skip characters below 0xFF (ASCII range is handled specially) |
| 244 |
if r2 < 0xFF { |
| 245 |
continue |
| 246 |
} |
| 247 |
|
| 248 |
// Check if this is a Regional Indicator character (range 1F1E6..1F1FF) |
| 249 |
// Regional Indicator characters can appear with any property, but we identify them by range |
| 250 |
const regionalIndicatorStart = 0x1F1E6 |
| 251 |
const regionalIndicatorEnd = 0x1F1FF |
| 252 |
if r1 >= regionalIndicatorStart && r2 <= regionalIndicatorEnd { |
| 253 |
// Add all Regional Indicator characters to the RegionalIndicator map |
| 254 |
for r := r1; r <= r2; r++ { |
| 255 |
data.RegionalIndicator[r] = true |
| 256 |
} |
| 257 |
// Don't add them to ExtendedPictographic or EmojiPresentation maps |
| 258 |
continue |
| 259 |
} |
| 260 |
|
| 261 |
// We're only interested in Extended_Pictographic and Emoji_Presentation for non-Regional Indicator characters |
| 262 |
if propertyStr != "Extended_Pictographic" && propertyStr != "Emoji_Presentation" { |
| 263 |
continue |
| 264 |
} |
| 265 |
|
| 266 |
// Add to the appropriate map |
| 267 |
for r := r1; r <= r2; r++ { |
| 268 |
switch propertyStr { |
| 269 |
case "Extended_Pictographic": |
| 270 |
data.ExtendedPictographic[r] = true |
| 271 |
case "Emoji_Presentation": |
| 272 |
data.EmojiPresentation[r] = true |
| 273 |
} |
| 274 |
} |
| 275 |
} |
| 276 |
|
| 277 |
return scanner.Err() |
| 278 |
} |
| 279 |
|
| 280 |
// extractStdlibData extracts character properties from Go's unicode package |
| 281 |
func extractStdlibData(data *UnicodeData) { |
| 282 |
// Extract control characters |
| 283 |
// Skip 0x00-0x1F and 0x7F as they're handled by the fast path in width.go |
| 284 |
// Only add C1 controls (0x80-0x9F) which are multi-byte in UTF-8 |
| 285 |
for r := rune(0x80); r <= 0x9F; r++ { |
| 286 |
data.ControlChars[r] = true // C1 controls |
| 287 |
} |
| 288 |
|
| 289 |
// Extract combining marks using range tables for efficiency |
| 290 |
// Mn: Nonspacing_Mark, Me: Enclosing_Mark |
| 291 |
// Note: Mc (Spacing Mark) characters are excluded so they get default width 1 |
| 292 |
extractRunesFromRangeTable(unicode.Mn, data.CombiningMarks) |
| 293 |
extractRunesFromRangeTable(unicode.Me, data.CombiningMarks) |
| 294 |
|
| 295 |
// Cf (Other, format) is the official Unicode category for format characters |
| 296 |
// which are generally invisible and have zero width. |
| 297 |
extractRunesFromRangeTable(unicode.Cf, data.ZeroWidthChars) |
| 298 |
|
| 299 |
// Zl (Other, line separator) is the official Unicode category for line separator characters |
| 300 |
// which are generally invisible and have zero width. |
| 301 |
extractRunesFromRangeTable(unicode.Zl, data.ZeroWidthChars) |
| 302 |
|
| 303 |
// Zp (Other, paragraph separator) is the official Unicode category for paragraph separator characters |
| 304 |
// which are generally invisible and have zero width. |
| 305 |
extractRunesFromRangeTable(unicode.Zp, data.ZeroWidthChars) |
| 306 |
|
| 307 |
// Noncharacters (U+nFFFE and U+nFFFF) |
| 308 |
data.ZeroWidthChars[0xFFFE] = true |
| 309 |
data.ZeroWidthChars[0xFFFF] = true |
| 310 |
} |
| 311 |
|
| 312 |
// extractRunesFromRangeTable efficiently extracts all runes from a Unicode range table |
| 313 |
func extractRunesFromRangeTable(table *unicode.RangeTable, target map[rune]bool) { |
| 314 |
// Iterate over 16-bit ranges |
| 315 |
for _, r16 := range table.R16 { |
| 316 |
for r := rune(r16.Lo); r <= rune(r16.Hi); r += rune(r16.Stride) { |
| 317 |
target[r] = true |
| 318 |
} |
| 319 |
} |
| 320 |
|
| 321 |
// Iterate over 32-bit ranges |
| 322 |
for _, r32 := range table.R32 { |
| 323 |
for r := rune(r32.Lo); r <= rune(r32.Hi); r += rune(r32.Stride) { |
| 324 |
target[r] = true |
| 325 |
} |
| 326 |
} |
| 327 |
} |
| 328 |
|
| 329 |
func buildPropertyBitmap(r rune, data *UnicodeData) property { |
| 330 |
if data.CombiningMarks[r] { |
| 331 |
return zero_Width |
| 332 |
} |
| 333 |
if data.ControlChars[r] { |
| 334 |
return zero_Width |
| 335 |
} |
| 336 |
if data.ZeroWidthChars[r] { |
| 337 |
return zero_Width |
| 338 |
} |
| 339 |
|
| 340 |
// As a practical matter, we probably don't need separate properties for |
| 341 |
// Emoji and East Asian Wide, as I believe they lead to the same |
| 342 |
// result. I made this distinction for VS15 handling. However, |
| 343 |
// eventually I came to the conclusion that VS15 is a no-op for width |
| 344 |
// calculation. Keeping the distinction for now. |
| 345 |
|
| 346 |
// Check for Regional Indicator before emoji |
| 347 |
if data.RegionalIndicator[r] { |
| 348 |
return wide |
| 349 |
} |
| 350 |
|
| 351 |
if data.ExtendedPictographic[r] && data.EmojiPresentation[r] { |
| 352 |
return wide |
| 353 |
} |
| 354 |
|
| 355 |
if eaw, exists := data.EastAsianWidth[r]; exists { |
| 356 |
switch eaw { |
| 357 |
case "F", "W": |
| 358 |
return wide |
| 359 |
case "A": |
| 360 |
return east_Asian_Ambiguous |
| 361 |
// H (Halfwidth), Na (Narrow), and N (Neutral) are not stored |
| 362 |
// as they all result in width 1 (default behavior) |
| 363 |
} |
| 364 |
} |
| 365 |
|
| 366 |
return 0 |
| 367 |
} |