1if not modules then modules = { } end modules ['typo-lan'] = {
2 version = 1.001,
3 comment = "companion to typo-lan.mkiv",
4 author = "Hans Hagen, PRAGMA-ADE, Hasselt NL",
5 copyright = "PRAGMA ADE / ConTeXt Development Team",
6 license = "see context related readme files"
7}
8
9local type, next = type, next
10
11local currentfont = font.current
12local setmetatableindex = table.setmetatableindex
13local utfbyte = utf.byte
14
15local hashes = fonts.hashes
16local fontdata = hashes.characters
17local emwidths = hashes.emwidths
18
19local frequencies = languages.frequencies or { }
20languages.frequencies = frequencies
21
22local frequencydata = { }
23local frequencyfile = string.formatters["lang-frq-%s.lua"]
24local frequencycache = { }
25
26setmetatableindex(frequencydata, function(t,language)
27 local fullname = resolvers.findfile(frequencyfile(language))
28 local v = fullname ~= "" and dofile(fullname)
29 if not v or not v.frequencies then
30 v = t.en
31 end
32 t[language] = v
33 return v
34end)
35
36setmetatableindex(frequencycache, function(t,language)
37 local dataset = frequencydata[language]
38 local frequencies = dataset.frequencies
39 if not frequencies then
40 return t.en
41 end
42 local v = { }
43 setmetatableindex(v, function(t,font)
44 local average = emwidths[font] / 2
45 if frequencies then
46 local characters = fontdata[font]
47 local sum, tot = 0, 0
48 for k, v in next, frequencies do
49 local character = characters[k]
50 tot = tot + v
51 sum = sum + v * (character and character.width or average)
52 end
53 average = sum / tot
54 end
55 t[font] = average
56 return average
57 end)
58 t[language] = v
59 return v
60end)
61
62function frequencies.getdata(language)
63 return frequencydata[language]
64end
65
66function frequencies.averagecharwidth(language,font)
67 return frequencycache[language or "en"][font or currentfont()]
68end
69
70interfaces.implement {
71 name = "averagecharwidth",
72 actions = { frequencies.averagecharwidth, context },
73 arguments = "string"
74}
75 |