summaryrefslogtreecommitdiff
path: root/tex/context/base/char-tex.lua
blob: 6e57a860a71909a37ca0946f47e81220da5c7d69 (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
if not modules then modules = { } end modules ['char-tex'] = {
    version   = 1.001,
    comment   = "companion to char-ini.mkiv",
    author    = "Hans Hagen, PRAGMA-ADE, Hasselt NL",
    copyright = "PRAGMA ADE / ConTeXt Development Team",
    license   = "see context related readme files"
}

local find = string.find

local lpeg = lpeg
local P, C, R, S, Cs, Cc = lpeg.P, lpeg.C, lpeg.R, lpeg.S, lpeg.Cs, lpeg.Cc
local U, lpegmatch = lpeg.patterns.utf8, lpeg.match

local allocate, mark = utilities.storage.allocate, utilities.storage.mark

characters       = characters or { }
local characters = characters
characters.tex   = characters.tex or { }

local accent_map = allocate {
   ['~'] = "̃" , --  ̃ Ẽ
   ['"'] = "̈" , --  ̈ Ë
   ["`"] = "̀" , --  ̀ È
   ["'"] = "́" , --  ́ É
   ["^"] = "̂" , --  ̂ Ê
    --  ̄ Ē
    --  ̆ Ĕ
    --  ̇ Ė
    --  ̉ Ẻ
    --  ̌ Ě
    --  ̏ Ȅ
    --  ̑ Ȇ
    --  ̣ Ẹ
    --  ̧ Ȩ
    --  ̨ Ę
    --  ̭ Ḙ
    --  ̰ Ḛ
}

local accents = table.concat(table.keys(accent_map))

local function remap_accents(a,c,braced)
    local m = accent_map[a]
    if m then
        return c .. m
    elseif braced then
        return "\\" .. a .. "{" .. c .. "}"
    else
        return "\\" .. a .. c
    end
end

local command_map = allocate {
    ["i"] = "ı"
}

local function remap_commands(c)
    local m = command_map[c]
    if m then
        return m
    else
        return "\\" .. c
    end
end

local accents  = (P('\\') * C(S(accents)) * (P("{") * C(U) * P("}" * Cc(true)) + C(U) * Cc(false))) / remap_accents
local commands = (P('\\') * C(R("az","AZ")^1)) / remap_commands

local convert_accents  = Cs((accents  + P(1))^0)
local convert_commands = Cs((commands + P(1))^0)

local no_l = P("{") / ""
local no_r = P("}") / ""

local convert_accents_strip  = Cs((no_l * accents  * no_r + accents  + P(1))^0)
local convert_commands_strip = Cs((no_l * commands * no_r + commands + P(1))^0)

function characters.tex.toutf(str,strip)
    if find(str,"\\") then -- we can start at teh found position
        if strip then
            str = lpegmatch(convert_commands_strip,str)
            str = lpegmatch(convert_accents_strip,str)
        else
            str = lpegmatch(convert_commands,str)
            str = lpegmatch(convert_accents,str)
        end
    end
    return str
end

--~ print(characters.tex.toutf([[\"{e}]]),true)
--~ print(characters.tex.toutf([[{\"{e}}]],true))