summaryrefslogtreecommitdiff
path: root/tex/context/base/lang-hyp.lua
blob: 3b5eac9bad611fea5c2560982ad433faf4dc363f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
if not modules then modules = { } end modules ['lang-hyp'] = {
    version   = 1.001,
    comment   = "companion to lang-ini.mkiv",
    author    = "Hans Hagen, PRAGMA-ADE, Hasselt NL",
    copyright = "PRAGMA ADE / ConTeXt Development Team",
    license   = "see context related readme files"
}

-- In an automated workflow hypenation of long titles can be somewhat problematic
-- especially when demands conflict. For that reason I played a bit with a Lua based
-- variant of the traditional hyphenation machinery. This mechanism has been extended
-- several times in projects, of which a good description can be found in TUGboat,
-- Volume 27 (2006), No. 2 — Proceedings of EuroTEX2006: Automatic non-standard
-- hyphenation in OpenOffice.org by László Németh.
--
-- Being the result of two days experimenting the following implementation is probably
-- not completely okay yet. If there is demand I might add some more features and plugs.
-- The performance is quite okay but can probably improved a bit, although this is not
-- the most critital code.
--
-- . a l g o r i t h m .
--    4l1g4
--     l g o3
--      1g o
--            2i t h
--                4h1m
-- ---------------------
--    4 1 4 3 2 0 4 1
--   a l-g o-r i t h-m

-- . a s s z o n n y a l .
--     s1s z/sz=sz,1,3
--             n1n y/ny=ny,1,3
-- -----------------------
--    0 1 0 0 0 1 0 0 0/sz=sz,2,3,ny=ny,6,3
--   a s-s z o n-n y a l/sz=sz,2,3,ny=ny,6,3
--
-- ab1cd/ef=gh,2,2 : acd - efd (pattern/replacement,start,length

local type, rawset, tonumber = type, rawset, tonumber

local P, R, S, Cg, Cf, Ct, Cc, C, Carg, Cs = lpeg.P, lpeg.R, lpeg.S, lpeg.Cg, lpeg.Cf, lpeg.Ct, lpeg.Cc, lpeg.C, lpeg.Carg, lpeg.Cs
local lpegmatch = lpeg.match

local concat = table.concat

local utfchar = utf.char
local utfbyte = utf.byte

if not characters then
    require("char-ini")
end

local setmetatableindex = table.setmetatableindex

local languages         = languages or { }
local hyphenators       = languages.hyphenators or { }
languages.hyphenators   = hyphenators
local traditional       = hyphenators.traditional or { }
hyphenators.traditional = traditional

local dictionaries = setmetatableindex(function(t,k)
    local v = {
        patterns   = { },
        hyphenated = { },
        specials   = { },
    }
    t[k] = v
    return v
end)

local digit          = R("09")
local character      = lpeg.patterns.utf8character - P("/")
local splitpattern_k = Cs((digit/"" + character)^1)
local splitpattern_v = Ct(((digit/tonumber + Cc(0)) * character)^1 * (digit/tonumber)^0)
local splitpattern_v =
    Ct(((digit/tonumber + Cc(0)) * character)^1 * (digit/tonumber)^0) *
    (P("/") * Cf ( Ct("") *
        Cg ( Cc("before") * C((1-lpeg.P("="))^1)          * P("=") )
      * Cg ( Cc("after")  * C((1-lpeg.P(","))^1)          * P(",") )
      * Cg ( Cc("start")  * ((1-lpeg.P(","))^1/tonumber)  * P(",") )
      * Cg ( Cc("length") * ((1-lpeg.P(-1) )^1/tonumber)           )
    , rawset))^-1

local function register(patterns,specials,str,specification)
    local k = lpegmatch(splitpattern_k,str)
    local v1, v2 = lpegmatch(splitpattern_v,str)
    patterns[k] = v1
    if specification then
        specials[k] = specification
    elseif v2 then
        specials[k] = v2
    end
end

local word  = ((Carg(1) * Carg(2) * C((1 - P(" "))^1)) / register + 1)^1
local split = Ct(C(character)^1)

function traditional.loadpatterns(language,filename)
    local specification = require(filename)
    local dictionary    = dictionaries[language]
    if specification then
        local patterns = specification.patterns
        if patterns then
            lpegmatch(word,patterns.data,1,dictionary.patterns,dictionary.specials)
        end
    end
    return dictionary
end

local lcchars   = characters.lcchars
local uccodes   = characters.uccodes
local nofwords  = 0
local nofhashed = 0

local function hyphenate(dictionary,word)
    nofwords = nofwords + 1
    local hyphenated = dictionary.hyphenated
    local isstring   = type(word) == "string"
    local done
    if isstring then
        done = hyphenated[word]
    else
        done = hyphenated[concat(word)]
    end
    if done ~= nil then
        return done
    else
        done = false
    end
    local specials = dictionary.specials
    local patterns = dictionary.patterns
    local s = isstring and lpegmatch(split,word) or word
    local l = #s
    local w = { }
    for i=1,l do
        local si = s[i]
        w[i] = lcchars[si] or si
    end
    local spec
    for i=1,l do
        for j=i,l do
            local c = concat(w,"",i,j)
            local m = patterns[c]
            if m then
                local s = specials[c]
                if not done then
                    done = { }
                    spec = { }
                    for i=1,l do
                        done[i] = 0
                    end
                end
                for k=1,#m do
                    local new = m[k]
                    if not new then
                        break
                    elseif new > 0 then
                        local pos = i + k - 1
                        local old = done[pos]
                        if not old then
                            -- break ?
                        elseif new > old then
                            done[pos] = new
                            if s then
                                local b = i + s.start - 1
                                local e = b + s.length - 1
                                if pos >= b and pos <= e then
                                    spec[pos] = s
                                end
                            end
                        end
                    end
                end
            end
        end
    end
    if done then
        local okay = false
        for i=1,#done do
            if done[i] % 2 == 1 then
                done[i] = spec[i] or true
                okay = true
            else
                done[i] = false
            end
        end
        if not okay then
            done = false
        end
    end
    hyphenated[isstring and word or concat(word)] = done
    nofhashed = nofhashed + 1
    return done
end

local f_detail_1 = string.formatters["{%s}{%s}{}"]
local f_detail_2 = string.formatters["{%s%s}{%s%s}{%s}"]

function traditional.injecthyphens(dictionary,word,specification)
    local h = hyphenate(dictionary,word)
    if not h then
        return word
    end
    local w = lpegmatch(split,word)
    local r = { }
    local l = #h
    local n = 0
    local i = 1
    local leftmin   = specification.lefthyphenmin or 2
    local rightmin  = l - (specification.righthyphenmin or left) + 1
    local leftchar  = specification.lefthyphenchar
    local rightchar = specification.righthyphenchar
    while i <= l do
        if i > leftmin and i < rightmin then
            local hi = h[i]
            if not hi then
                n = n + 1
                r[n] = w[i]
                i = i + 1
            elseif hi == true then
                n = n + 1
                r[n] = f_detail_1(rightchar,leftchar)
                n = n + 1
                r[n] = w[i]
                i = i + 1
            else
                local b = i - hi.start
                local e = b + hi.length - 1
                n = b
                r[n] = f_detail_2(hi.before,rightchar,leftchar,hi.after,concat(w,"",b,e))
                if e + 1 == i then
                    i = i + 1
                else
                    i = e + 1
                end
            end
        else
            n = n + 1
            r[n] = w[i]
            i = i + 1
        end
    end
    return concat(r)
end

function traditional.registerpattern(language,str,specification)
    local dictionary = dictionaries[language]
    register(dictionary.patterns,dictionary.specials,str,specification)
end

-- todo: unicodes or utfhash ?

if context then

    local nodecodes     = nodes.nodecodes
    local glyph_code    = nodecodes.glyph
    local math_code     = nodecodes.math

    local nuts          = nodes.nuts
    local tonut         = nodes.tonut
    local nodepool      = nuts.pool

    local new_disc      = nodepool.disc

    local setfield      = nuts.setfield
    local getfield      = nuts.getfield
    local getchar       = nuts.getchar
    local getid         = nuts.getid
    local getnext       = nuts.getnext
    local getprev       = nuts.getprev
    local insert_before = nuts.insert_before
    local insert_after  = nuts.insert_after
    local copy_node     = nuts.copy
    local remove_node   = nuts.remove
    local end_of_math   = nuts.end_of_math
    local node_tail     = nuts.tail

    function traditional.loadpatterns(language)
        return dictionaries[language]
    end

    statistics.register("hyphenation",function()
        if nofwords > 0 then
            return string.format("%s words hyphenated, %s unique",nofwords,nofhashed)
        end
    end)

    setmetatableindex(dictionaries,function(t,k) -- we use an independent data structure
        local specification = languages.getdata(k)
        local dictionary    = {
            patterns   = { },
            hyphenated = { },
            specials   = { },
            instance   = 0,
            characters = { },
            unicodes   = { },
        }
        if specification then
            local resources = specification.resources
            if resources then
                local patterns = resources.patterns
                if patterns then
                    local data = patterns.data
                    if data then
                        -- regular patterns
                        lpegmatch(word,data,1,dictionary.patterns,dictionary.specials)
                    end
                    local extra = patterns.extra
                    if extra then
                        -- special patterns
                        lpegmatch(word,extra,1,dictionary.patterns,dictionary.specials)
                    end
                end
                local usedchars  = lpegmatch(split,patterns.characters)
                local characters = { }
                local unicodes   = { }
                for i=1,#usedchars do
                    local char  = usedchars[i]
                    local code  = utfbyte(char)
                    local upper = uccodes[code]
                    characters[char]  = code
                    unicodes  [code]  = char
                    unicodes  [upper] = utfchar(upper)
                end
                dictionary.characters = characters
                dictionary.unicodes   = unicodes
                setmetatableindex(characters,function(t,k) local v = utfbyte(k) t[k] = v return v end) -- can be non standard
             -- setmetatableindex(unicodes,  function(t,k) local v = utfchar(k) t[k] = v return v end)
            end
            t[specification.number] = dictionary
            dictionary.instance = specification.instance -- needed for hyphenchars
        end
        t[k] = dictionary
        return dictionary
    end)

    local function flush(head,start,stop,dictionary,w,h,lefthyphenchar,righthyphenchar,characters,lefthyphenmin,righthyphenmin)
        local r = { }
        local l = #h
        local n = 0
        local i = 1
        local left  = lefthyphenmin
        local right = l - righthyphenmin + 1
        while i <= l do
            if i > left and i < right then
                local hi = h[i]
                if not hi then
                    n = n + 1
                    r[n] = w[i]
                    i = i + 1
                elseif hi == true then
                    n = n + 1
                    r[n] = true
                    n = n + 1
                    r[n] = w[i]
                    i = i + 1
                else
                    local b = i - hi.start  -- + 1 - 1
                    local e = b + hi.length - 1
                    n = b
                    r[n] = { hi.before, hi.after, concat(w,"",b,e) }
                    i = e + 1
                end
            else
                n = n + 1
                r[n] = w[i]
                i = i + 1
            end
        end

        local function serialize(s,lefthyphenchar,righthyphenchar)
            if not s then
                return
            elseif s == true then
                local n = copy_node(stop)
                setfield(n,"char",lefthyphenchar or righthyphenchar)
                return n
            end
            local h = nil
            local c = nil
            if lefthyphenchar then
                h = copy_node(stop)
                setfield(h,"char",lefthyphenchar)
                c = h
            end
            if #s == 1 then
                local n = copy_node(stop)
                setfield(n,"char",characters[s])
                if not h then
                    h = n
                else
                    insert_after(c,c,n)
                end
                c = n
            else
                local t = lpegmatch(split,s)
                for i=1,#t do
                    local n = copy_node(stop)
                    setfield(n,"char",characters[t[i]])
                    if not h then
                        h = n
                    else
                        insert_after(c,c,n)
                    end
                    c = n
                end
            end
            if righthyphenchar then
                local n = copy_node(stop)
                insert_after(c,c,n)
                setfield(n,"char",righthyphenchar)
            end
            return h
        end

        -- no grow

        local current = start
        local size    = #r
        for i=1,size do
            local ri = r[i]
            if ri == true then
                local n = new_disc()
                if righthyphenchar then
                    setfield(n,"pre",serialize(true,righthyphenchar))
                end
                if lefthyphenchar then
                    setfield(n,"post",serialize(true,lefthyphenchar))
                end
                insert_before(head,current,n)
            elseif type(ri) == "table" then
                local n = new_disc()
                local pre, post, replace = ri[1], ri[2], ri[3]
                if pre then
                    setfield(n,"pre",serialize(pre,false,righthyphenchar))
                end
                if post then
                    setfield(n,"post",serialize(post,lefthyphenchar,false))
                end
                if replace then
                    setfield(n,"replace",serialize(replace))
                end
                insert_before(head,current,n)
            else
                setfield(current,"char",characters[ri])
                if i < size then
                    current = getnext(current)
                end
            end
        end
        if current ~= stop then
            local current = getnext(current)
            local last = getnext(stop)
            while current ~= last do
                head, current = remove_node(head,current,true)
            end
        end
    end

    -- simple cases: no special .. only inject

    local prehyphenchar  = lang.prehyphenchar
    local posthyphenchar = lang.posthyphenchar

    local lccodes        = characters.lccodes

    -- An experimental feature:
    --
    -- \setupalign[verytolerant,flushleft]
    -- \setuplayout[width=140pt] \showframe
    -- longword longword long word longword longwordword \par
    -- \enabledirectives[hyphenators.rightwordsmin=1]
    -- longword longword long word longword longwordword \par
    -- \disabledirectives[hyphenators.rightwordsmin]
    --
    -- An alternative is of course to pack the words in an hbox.

    local rightwordsmin = 0 -- todo: parproperties (each par has a number anyway)

    function traditional.hyphenate(head)
        local first      = tonut(head)
        local current    = first
        local dictionary = nil
        local instance   = nil
        local characters = nil
        local unicodes   = nil
        local language   = nil
        local start      = nil
        local stop       = nil
        local word       = nil -- maybe reuse and pass size
        local size       = 0
        local leftchar   = false
        local rightchar  = false -- utfbyte("-")
        local leftmin    = 0
        local rightmin   = 0
        local lastone    = nil

        if rightwordsmin > 0 then
            lastone = node_tail(first)
            local inword = false
            while lastone and rightwordsmin > 0 do
                local id = getid(lastone)
                if id == glyph_code then
                    inword = true
                elseif inword then
                    inword = false
                    rightwordsmin = rightwordsmin - 1
                end
                lastone = getprev(lastone)
            end
        end

        while current ~= lastone do
            local id = getid(current)
            if id == glyph_code then
                -- currently no lc/uc code support
                local code = getchar(current)
                local lang = getfield(current,"lang")
                if lang ~= language then
                    if dictionary then
                        if leftmin + rightmin < #word then
                            local done = hyphenate(dictionary,word)
                            if done then
                                flush(first,start,stop,dictionary,word,done,leftchar,rightchar,characters,leftmin,rightmin)
                            end
                        end
                    end
                    language   = lang
                    dictionary = dictionaries[language]
                    instance   = dictionary.instance
                    characters = dictionary.characters
                    unicodes   = dictionary.unicodes
                    leftchar   = instance and posthyphenchar(instance)
                    rightchar  = instance and prehyphenchar (instance)
                    leftmin    = getfield(current,"left")
                    rightmin   = getfield(current,"right")
                    if not leftchar or leftchar < 0 then
                        leftchar = false
                    end
                    if not rightchar or rightchar < 0 then
                        rightchar = false
                    end
                    local char = unicodes[code]
                    if char then
                        word  = { char }
                        size  = 1
                        start = current
                    end
                elseif word then
                    local char = unicodes[code]
                    if char then
                        size = size + 1
                        word[size] = char
                    elseif dictionary then
                        if leftmin + rightmin < #word then
                            local done = hyphenate(dictionary,word)
                            if done then
                                flush(first,start,stop,dictionary,word,done,leftchar,rightchar,characters,leftmin,rightmin)
                            end
                        end
                        word = nil
                    end
                else
                    local char = unicodes[code]
                    if char then
                        word     = { char }
                        size     = 1
                        start    = current
                     -- leftmin  = getfield(current,"left")  -- can be an option
                     -- rightmin = getfield(current,"right") -- can be an option
                    end
                end
                stop    = current
                current = getnext(current)
            elseif word then
                if dictionary then
                    if leftmin + rightmin < #word then
                        local done = hyphenate(dictionary,word)
                        current = getnext(current)
                        if done then
                            flush(first,start,stop,dictionary,word,done,leftchar,rightchar,characters,leftmin,rightmin)
                        end
                    else
                        current = getnext(current) -- hm
                    end
                else
                    current = getnext(current)
                end
                word = nil
            elseif id == math_code then
                current = getnext(end_of_math(current))
            else
                current = getnext(current)
            end
        end
        return head, true
    end

    local texmethod = "builders.kernel.hyphenation"
    local oldmethod = texmethod
    local newmethod = texmethod

 -- local newmethod = "languages.hyphenators.traditional.hyphenate"
 --
 -- nodes.tasks.prependaction("processors","words",newmethod)
 -- nodes.tasks.disableaction("processors",oldmethod)
 --
 -- nodes.tasks.replaceaction("processors","words",oldmethod,newmethod)

 -- \enabledirectives[hyphenators.method=traditional]
 -- \enabledirectives[hyphenators.method=builtin]

    directives.register("hyphenators.method",function(v)
        if type(v) == "string" then
            local valid = languages.hyphenators[v]
            if valid and valid.hyphenate then
                newmethod = "languages.hyphenators." .. v .. ".hyphenate"
            else
                newmethod = texmethod
            end
        else
            newmethod = texmethod
        end
        if oldmethod ~= newmethod then
            nodes.tasks.replaceaction("processors","words",oldmethod,newmethod)
        end
        oldmethod = newmethod
    end)

    -- experimental feature

    directives.register("hyphenators.rightwordsmin",function(v)
        rightwordsmin = tonumber(v) or 0
    end)

else

 -- traditional.loadpatterns("nl","lang-nl")
 -- traditional.loadpatterns("de","lang-de")

    traditional.registerpattern("nl","e1ë",      { start = 1, length = 2, before = "e",  after = "e"  } )
    traditional.registerpattern("nl","oo1ë",     { start = 2, length = 3, before = "o",  after = "e"  } )
    traditional.registerpattern("de","qqxc9xkqq",{ start = 3, length = 4, before = "ab", after = "cd" } )

    local specification = {
        lefthyphenmin   = 2,
        righthyphenmin  = 2,
        lefthyphenchar  = "<",
        righthyphenchar = ">",
    }

    print("reëel",       traditional.injecthyphens(dictionaries.nl,"reëel",       specification),"r{e>}{<e}{eë}el")
    print("reeëel",      traditional.injecthyphens(dictionaries.nl,"reeëel",      specification),"re{e>}{<e}{eë}el")
    print("rooëel",      traditional.injecthyphens(dictionaries.nl,"rooëel",      specification),"r{o>}{<e}{ooë}el")

    print(   "qxcxkq",   traditional.injecthyphens(dictionaries.de,   "qxcxkq",   specification),"")
    print(  "qqxcxkqq",  traditional.injecthyphens(dictionaries.de,  "qqxcxkqq",  specification),"")
    print( "qqqxcxkqqq", traditional.injecthyphens(dictionaries.de, "qqqxcxkqqq", specification),"")
    print("qqqqxcxkqqqq",traditional.injecthyphens(dictionaries.de,"qqqqxcxkqqqq",specification),"")

end