1# Following work by @jiahao, we compute character widths using a combination of
2#   * character category
3#   * UAX 11: East Asian Width
4#   * a few exceptions as needed
5# Adapted from http://nbviewer.ipython.org/gist/jiahao/07e8b08bf6d8671e9734
6#
7# We used to also use data from GNU Unifont, but that has proven unreliable
8# and unlikely to match widths assumed by terminals.
9#
10# Requires Julia (obviously) and FontForge.
11
12#############################################################################
13CharWidths = Dict{Int,Int}()
14
15#############################################################################
16# Use ../libutf8proc for category codes, rather than the one in Julia,
17# to minimize bootstrapping complexity when a new version of Unicode comes out.
18catcode(c) = ccall((:utf8proc_category,"../libutf8proc"), Cint, (Int32,), c)
19
20# utf8proc category constants (must match h)
21const UTF8PROC_CATEGORY_CN = 0
22const UTF8PROC_CATEGORY_LU = 1
23const UTF8PROC_CATEGORY_LL = 2
24const UTF8PROC_CATEGORY_LT = 3
25const UTF8PROC_CATEGORY_LM = 4
26const UTF8PROC_CATEGORY_LO = 5
27const UTF8PROC_CATEGORY_MN = 6
28const UTF8PROC_CATEGORY_MC = 7
29const UTF8PROC_CATEGORY_ME = 8
30const UTF8PROC_CATEGORY_ND = 9
31const UTF8PROC_CATEGORY_NL = 10
32const UTF8PROC_CATEGORY_NO = 11
33const UTF8PROC_CATEGORY_PC = 12
34const UTF8PROC_CATEGORY_PD = 13
35const UTF8PROC_CATEGORY_PS = 14
36const UTF8PROC_CATEGORY_PE = 15
37const UTF8PROC_CATEGORY_PI = 16
38const UTF8PROC_CATEGORY_PF = 17
39const UTF8PROC_CATEGORY_PO = 18
40const UTF8PROC_CATEGORY_SM = 19
41const UTF8PROC_CATEGORY_SC = 20
42const UTF8PROC_CATEGORY_SK = 21
43const UTF8PROC_CATEGORY_SO = 22
44const UTF8PROC_CATEGORY_ZS = 23
45const UTF8PROC_CATEGORY_ZL = 24
46const UTF8PROC_CATEGORY_ZP = 25
47const UTF8PROC_CATEGORY_CC = 26
48const UTF8PROC_CATEGORY_CF = 27
49const UTF8PROC_CATEGORY_CS = 28
50const UTF8PROC_CATEGORY_CO = 29
51
52#############################################################################
53# Use a default width of 1 for all character categories that are
54# letter/symbol/number-like, as well as for unassigned/private-use chars.
55# This can be overridden by UAX 11
56# below, but provides a useful nonzero fallback for new codepoints when
57# a new Unicode version has been released but Unifont hasn't been updated yet.
58
59zerowidth = Set{Int}() # categories that may contain zero-width chars
60push!(zerowidth, UTF8PROC_CATEGORY_MN)
61push!(zerowidth, UTF8PROC_CATEGORY_MC)
62push!(zerowidth, UTF8PROC_CATEGORY_ME)
63# push!(zerowidth, UTF8PROC_CATEGORY_SK)  # see issue #167
64push!(zerowidth, UTF8PROC_CATEGORY_ZL)
65push!(zerowidth, UTF8PROC_CATEGORY_ZP)
66push!(zerowidth, UTF8PROC_CATEGORY_CC)
67push!(zerowidth, UTF8PROC_CATEGORY_CF)
68push!(zerowidth, UTF8PROC_CATEGORY_CS)
69for c in 0x0000:0x110000
70    if catcode(c) ∉ zerowidth
71        CharWidths[c] = 1
72    end
73end
74
75#############################################################################
76# Widths from UAX #11: East Asian Width
77#   .. these take precedence for all codepoints
78#      listed explicitly as wide/full/narrow/half-width
79
80for line in readlines(open("EastAsianWidth.txt"))
81    #Strip comments
82    (isempty(line) || line[1] == '#') && continue
83    precomment = split(line, '#')[1]
84    #Parse code point range and width code
85    tokens = split(precomment, ';')
86    length(tokens) >= 2 || continue
87    charrange = tokens[1]
88    width = strip(tokens[2])
89    #Parse code point range into Julia UnitRange
90    rangetokens = split(charrange, "..")
91    charstart = parse(UInt32, "0x"*rangetokens[1])
92    charend = parse(UInt32, "0x"*rangetokens[length(rangetokens)>1 ? 2 : 1])
93
94    #Assign widths
95    for c in charstart:charend
96        if width=="W" || width=="F" # wide or full
97            CharWidths[c]=2
98        elseif width=="Na"|| width=="H"
99            CharWidths[c]=1
100        end
101    end
102end
103
104#############################################################################
105# A few exceptions to the above cases, found by manual comparison
106# to other wcwidth functions and similar checks.
107
108for c in keys(CharWidths)
109    cat = catcode(c)
110
111    # make sure format control character (category Cf) have width 0
112    # (some of these, like U+0601, can have a width in some cases
113    #  but normally act like prepended combining marks.  U+fff9 etc
114    #  are also odd, but have zero width in typical terminal contexts)
115    if cat==UTF8PROC_CATEGORY_CF
116        CharWidths[c]=0
117    end
118
119    # Unifont has nonzero width for a number of non-spacing combining
120    # characters, e.g. (in 7.0.06): f84,17b4,17b5,180b,180d,2d7f, and
121    # the variation selectors
122    if cat==UTF8PROC_CATEGORY_MN
123        CharWidths[c]=0
124    end
125
126    # We also assign width of one to unassigned and private-use
127    # codepoints (Unifont includes ConScript Unicode Registry PUA fonts,
128    # but since these are nonstandard it seems questionable to use Unifont metrics;
129    # if they are printed as the replacement character U+FFFD they will have width 1).
130    if cat==UTF8PROC_CATEGORY_CO || cat==UTF8PROC_CATEGORY_CN
131        CharWidths[c]=1
132    end
133
134    # for some reason, Unifont has width-2 glyphs for ASCII control chars
135    if cat==UTF8PROC_CATEGORY_CC
136        CharWidths[c]=0
137    end
138end
139
140#Soft hyphen is typically printed as a hyphen (-) in terminals.
141CharWidths[0x00ad]=1
142
143#By definition, should have zero width (on the same line)
144#0x002028 '
' category: Zl name: LINE SEPARATOR/
145#0x002029 '
' category: Zp name: PARAGRAPH SEPARATOR/
146CharWidths[0x2028]=0
147CharWidths[0x2029]=0
148
149#############################################################################
150# Output (to a file or pipe) for processing by data_generator.rb,
151# encoded as a sequence of intervals.
152
153firstc = 0x000000
154lastv = 0
155uhex(c) = uppercase(string(c,base=16,pad=4))
156for c in 0x0000:0x110000
157    global firstc, lastv
158    v = get(CharWidths, c, 0)
159    if v != lastv || c == 0x110000
160        v < 4 || error("invalid charwidth $v for $c")
161        if firstc+1 < c
162            println(uhex(firstc), "..", uhex(c-1), "; ", lastv)
163        else
164            println(uhex(firstc), "; ", lastv)
165        end
166        firstc = c
167        lastv = v
168    end
169end
170