Debian Codegraph @

CorsixTH/Lua/strings.lua

raw
1 --[[ Copyright (c) 2010 Peter "Corsix" Cawley
2
3 Permission is hereby granted, free of charge, to any person obtaining a copy of
4 this software and associated documentation files (the "Software"), to deal in
5 the Software without restriction, including without limitation the rights to
6 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
7 of the Software, and to permit persons to whom the Software is furnished to do
8 so, subject to the following conditions:
9
10 The above copyright notice and this permission notice shall be included in all
11 copies or substantial portions of the Software.
12
13 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19 SOFTWARE. --]]
20
21 local lfs = require("lfs")
22 local TH = require("TH")
23
24 --! Layer which handles the loading of localised text.
25 class "Strings"
26
27 ---@type Strings
28 local Strings = _G["Strings"]
29
30 function Strings:Strings(app)
31 self.app = app
32 end
33
34 local utf8conv
35 local cp437conv
36 local function id(...) return ... end
37
38 function Strings:init()
39 -- Load (but do not execute) everything from the language directory
40 -- Note that files are loaded with loadfile_envcall
41 self.language_chunks = {}
42 local pathsep = package.config:sub(1,1)
43 local path = self.app:getFullPath({"Lua", "languages"}, true)
44 for file in lfs.dir(path) do
45 if file:match("%.lua$") then
46 local result, err = loadfile_envcall(path .. file)
47 if not result then
48 print("Error loading languages" .. pathsep .. file .. ":\n" .. tostring(err))
49 else
50 self.language_chunks[result] = "languages" .. pathsep .. file
51 end
52 end
53 end
54
55 -- Build the language table from Language() calls
56 -- Every file in the languages folder should have a call to Language() near
57 -- the start of the file which gives the names for the language. These names
58 -- are used to link the user's choice of language to a file, and to link the
59 -- names given to Inherit() to a file. The first name is used as the official
60 -- name for this language, the others may be abbreviations or such.
61 self.languages = {}
62 self.languages_english = {}
63 self.language_to_chunk = {}
64 self.chunk_to_font = {}
65 self.chunk_to_names = {}
66 self.language_to_lang_code = {}
67 self.languages_with_arabic_numerals = {}
68 for chunk, filename in pairs(self.language_chunks) do
69 -- To allow the file to set global variables without causing an error, it
70 -- is given an infinite table as an environment. Reading a non-existent
71 -- key from an infinite table returns another infinite table, rather than
72 -- the default value of nil.
73 local infinite_table_mt
74 infinite_table_mt = {
75 __index = function(_, _)
76 return setmetatable({}, infinite_table_mt)
77 end
78 }
79 -- To abort evaluation of the chunk after Language() is called, a unique
80 -- marker is used as an error message. The other alternative would be to
81 -- do complex co-routine calls. A freshly made empty table is a suitable
82 -- unique marker.
83 local good_error_marker = {}
84 local env = setmetatable({
85 utf8 = id,
86 cp437 = cp437conv,
87 pairs = pairs,
88 Language = function(...)
89 local names = {...}
90 -- Use the first name for display purposes (case-dependent!).
91 if names[1] ~= "original_strings" then
92 self.languages[#self.languages + 1] = names[1]
93 -- Also save the second name for tooltips and internal purposes.
94 assert(names[2], filename .. " does not have an English name.")
95 self.languages_english[names[1]] = names[2]
96 end
97 -- Associate every passed name with this file, case-independently
98 for _, name in pairs(names) do
99 self.language_to_chunk[name:lower()] = chunk
100 self.language_to_lang_code[name:lower()] = names[3]
101 end
102 self.chunk_to_names[chunk] = names
103 error(good_error_marker)
104 end,
105 Font = function(...)
106 self.chunk_to_font[chunk] = ...
107 end,
108 -- Set Inherit and SetSpeechFile to do nothing
109 Inherit = function() end,
110 SetSpeechFile = function() end,
111 Encoding = function() end,
112 IsArabicNumerals = function() end,
113 -- Set LoadStrings to return an infinite table
114 LoadStrings = infinite_table_mt.__index,
115 }, infinite_table_mt)
116 -- Actually run the language file
117 local status, err = pcall(chunk, env)
118 if not status and err ~= good_error_marker and TheApp.good_install_folder then
119 print("Error evaluating " .. filename .. ":\n" .. tostring(err))
120 end
121 end
122 table.sort(self.languages)
123 end
124
125 -- String tables are shadowed so that all access to a string table goes
126 -- through a metamethod (which is desirable to catch invalid reads, provide
127 -- "__random", and prevent writes). This means that every string table is in
128 -- fact empty, and has it's keys and values stored in a separate table, called
129 -- the shadow table. The shadows table is used to associate a shadow table
130 -- with a string table.
131 local shadows = setmetatable({}, {__mode = "k"})
132
133 -- Metatable which is used for all tables returned by Strings:load()
134 -- The end effect is to raise errors on accesses to non-existent strings
135 -- (unless no_restriction is set to true), to add a special string called
136 -- "__random" to each table (which always resolves to a random string from
137 -- the table), and to prevent editing or adding to a string table.
138 local strings_metatable = function(no_restriction) return {
139 __index = function(t, key)
140 t = shadows[t]
141 local val = t[key]
142 if val ~= nil then
143 return val
144 end
145 if key ~= "__random" then
146 if no_restriction then return nil end
147 error("Non-existent string: " .. tostring(key), 2)
148 end
149 local candidates = {}
150 for _, v in pairs(t) do
151 candidates[#candidates + 1] = v
152 end
153 return candidates[math.random(1, #candidates)]
154 end,
155 __newindex = function(_, _, _)
156 error("String tables are read-only", 2)
157 end,
158 __pairs = function(t)
159 return pairs(shadows[t])
160 end,
161 __ipairs = function(t)
162 return ipairs(shadows[t])
163 end,
164 } end
165
166 -- no_restriction disables errors on access to non-existent strings (for debug purposes)
167 -- no_inheritance disables inheritance except original_strings (for debug purposes)
168 function Strings:load(language, no_restriction, no_inheritance)
169 assert(language ~= "original_strings", "Original strings can not be loaded directly. Please select a proper language.")
170 -- env is the table of globals to execute to the language file in, and hence
171 -- it also stores the resulting strings.
172 local env = {}
173 shadows[env] = {}
174 -- speech_file holds the result of any call to SetSpeechFile()
175 local speech_file
176 local default_encoding = id
177 local encoding = default_encoding
178 local language_called = false
179 local functions; functions = {
180 -- Convert UTF-8 to the file's default encoding
181 utf8 = function(s)
182 if encoding == cp437conv then
183 return utf8conv(s)
184 else
185 return s
186 end
187 end,
188 -- Convert CP437 to the file's default encoding
189 cp437 = function(s)
190 if encoding == cp437conv then
191 return s
192 else
193 return cp437conv(s)
194 end
195 end,
196 ipairs = ipairs,
197 pairs = pairs,
198 -- Calling the Language() function should have no effect any more
199 Language = function()
200 language_called = true
201 end,
202 Font = function()
203 if language_called then
204 error("Font declaration must occur before Language declaration")
205 end
206 end,
207 -- Inherit() should evaluate the named language in the current environment
208 -- NB: Inheritance of any but original_strings disabled when no_inheritance set
209 Inherit = function(lang, ...)
210 if no_inheritance and lang ~= "original_strings" then return end
211 local old_encoding = encoding
212 encoding = default_encoding
213 local old_language_called = language_called
214 language_called = false
215 self:_loadPrivate(lang, env, ...)
216 encoding = old_encoding
217 language_called = old_language_called
218 end,
219 -- Encoding() should set the default encoding for the remainder of the file
220 Encoding = function(new_encoding)
221 if new_encoding == functions.utf8 then
222 encoding = id
223 elseif new_encoding == functions.cp437 then
224 encoding = cp437conv
225 else
226 error("Invalid encoding; expected utf8 or cp437")
227 end
228 end,
229 -- LoadStrings() should return the original game string table
230 LoadStrings = function(filename)
231 return assert(TH.LoadStrings(self.app:readDataFile(filename)),
232 "Cannot load original string file '" .. filename .. "'")
233 end,
234 -- SetSpeechFile() should remember the named file to return to our caller
235 SetSpeechFile = function(...)
236 speech_file = ...
237 end,
238 IsArabicNumerals = function(is_enabled)
239 self.languages_with_arabic_numerals[language] = is_enabled
240 end,
241 _G = env,
242 type = type,
243 }
244 -- The metatable on the environment is set so that the above functions look
245 -- like top-level level globals, so that the environment behaves like an
246 -- infinite table, and so that assignments are merged into the string table.
247 local metatable
248 metatable = {
249 __index = function(t, k)
250 -- Make the functions look like top-level globals
251 local shadow = shadows[t]
252 local value = ((t == env) and functions[k]) or shadow[k]
253 if value == nil then
254 value = setmetatable({}, metatable)
255 shadow[k] = value
256 shadows[value] = {}
257 end
258 return value
259 end,
260 __newindex = function(t, k, v)
261 local ty = type(v)
262 if ty ~= "table" then
263 -- non-table values cannot be merged
264 if ty == "string" then
265 -- convert from file's default encoding to UTF-8
266 v = encoding(v)
267 end
268 shadows[t][k] = v
269 else
270 -- v should be merged into t[k]
271 -- Perform t[k][k2] = v2 for each (k2, v2) in v to recursively merge
272 t = t[k]
273 for k2, v2 in pairs(v) do
274 t[k2] = v2
275 end
276 end
277 end,
278 }
279 metatable.__pairs = strings_metatable(no_restriction).__pairs
280 -- Evaluate the language file
281 setmetatable(env, metatable)
282 self:_loadPrivate(language, env)
283 -- Change the metamethods on every string table to match strings_metatable
284 for k, v in pairs(strings_metatable(no_restriction)) do
285 metatable[k] = v
286 end
287 return env, speech_file
288 end
289
290 --! Get the Font() declaration of a language, if there was one.
291 function Strings:getFont(language)
292 local chunk = self.language_to_chunk[language:lower()]
293 return chunk and self.chunk_to_font[chunk]
294 end
295
296 function Strings:getLanguageNames(language)
297 local chunk = self.language_to_chunk[language:lower()]
298 return chunk and self.chunk_to_names[chunk]
299 end
300
301 function Strings:getLangCode(language)
302 local lang = language or self.app.config.language
303 return self.language_to_lang_code[lang:lower()]
304 end
305
306 function Strings:isArabicNumerals(language)
307 return self.languages_with_arabic_numerals[language:lower()]
308 end
309
310 --! Use local language text where possible.
311 --!param string (string) The default, likely English, text
312 --!param table (table) A table of translated text in language code fields
313 --!return (string) The text in the current language if available, or in English, or the default string.
314 function Strings:getLocalisedText(string, table)
315 if string and not table then return string
316 elseif table[self:getLangCode()] then return table[self:getLangCode()]
317 elseif table.en then return table.en
318 else return string
319 end
320 end
321
322 --! Checks the language we specify is known to the application.
323 --!param language (string) Language to check
324 --!return true if known
325 function Strings:checkLanguageExists(language)
326 return not not self.language_to_chunk[language:lower()]
327 end
328
329 function Strings:_loadPrivate(language, env, ...)
330 local chunk = self.language_to_chunk[language:lower()]
331 if not chunk then -- If selected language could not be found, try to revert to English
332 print(serialize(self.language_to_chunk, {detect_cycles=true, pretty=true}))
333 print("Language '" .. language .. "' could not be found. Reverting to English.")
334 chunk = self.language_to_chunk["english"]
335 if not chunk then -- If english could not be found, raise an error
336 error("Language 'English' could not be found. Please verify your installation.")
337 end
338 end
339 local status, err = pcall(chunk, env, ...)
340 if not status and self.app.good_install_folder then
341 print("Error evaluating " .. self.language_chunks[chunk] .. ":\n" .. tostring(err))
342 end
343 end
344
345 function Strings:setupAdviserMessage(messages)
346 local prioTable
347 prioTable = {
348 _priority = 5, -- Default priority
349 tutorial = { _priority = 11},
350 epidemic = { _priority = 6 },
351 --staff_advice
352 --earthquake
353 --multiplayer
354 --surgery_requirements
355 --vomit_wave
356 --level_progress
357 --staff_place_advice
358 --room_forbidden_non_reachable_parts
359 --research
360 --boiler_issue
361 --room_requirements
362 --goals
363 warnings = { _priority = 10 },
364 --placement_info
365 praise = { _priority = 1 },
366 --information
367 --build_advice
368 --cheats
369 }
370 -- Passes adviser message through string.format process
371 local formatFunc
372 formatFunc = function(format_self, ...)
373 -- After 'format', it is not useful to have indexing magic anymore.
374 return { text = format_self.text:format(...), priority = format_self.priority }
375 end
376 local indexFunc
377 indexFunc = function(index_self, field)
378 -- Since prioTable is a partial table, index_self.table may disappear, prevent infinite recursion.
379 if field == "table" then
380 return nil
381 end
382 local val = {}
383 val.text = index_self.text[field]
384 val.format = formatFunc
385 val.table = index_self.table
386 val.priority = index_self.priority
387 if val.table ~= nil then
388 val.table = val.table[field]
389 if val.table ~= nil and val.table._priority ~= nil then
390 val.priority = val.table._priority
391 end
392 end
393 setmetatable(val, {__index = indexFunc})
394 return val
395 end
396 -- Initial value
397 local adviserMessage = {
398 text = messages,
399 table = prioTable,
400 priority = prioTable._priority,
401 format = formatFunc
402 }
403 setmetatable(adviserMessage, {__index = indexFunc})
404 return adviserMessage
405 end
406
407
408 -- Primitive system to map UTF-8 characters onto Code Page 437.
409 -- Provided so that language scripts can encode text in a modern and well
410 -- supported manner, and have the text automatically transcoded into the
411 -- encoding which the Theme Hospital fonts use.
412
413 local codepoints_to_cp437 = {
414 -- Below 0x80 need no translation
415 [0xC7] = 0x80, -- majuscule c-cedilla
416 [0xFC] = 0x81, -- minuscule u-umlaut
417 [0xE9] = 0x82, -- minuscule e-acute
418 [0xE2] = 0x83, -- minuscule a-circumflex
419 [0xE4] = 0x84, -- minuscule a-umlaut
420 [0xE0] = 0x85, -- minuscule a-grave
421 [0xE5] = 0x86, -- minuscule a-ring
422 [0xE7] = 0x87, -- minuscule c-cedilla
423 [0xEA] = 0x88, -- minuscule e-circumflex
424 [0xEB] = 0x89, -- minuscule e-umlaut
425 [0xE8] = 0x8A, -- minuscule e-grave
426 [0xEF] = 0x8B, -- minuscule i-umlaut
427 [0xEE] = 0x8C, -- minuscule i-circumflex
428 [0xEC] = 0x8D, -- minuscule i-grave
429 [0xC4] = 0x8E, -- majuscule a-umlaut
430 [0xC5] = 0x8F, -- majuscule a-ring
431 [0xC9] = 0x90, -- majuscule e-acute
432 [0xE6] = 0x91, -- minuscule ae
433 [0xC6] = 0x91, -- majuscule ae (not in TH fonts - mapped to minuscule ae)
434 [0xF4] = 0x93, -- minuscule o-circumflex
435 [0xF6] = 0x94, -- minuscule o-umlaut
436 [0xF2] = 0x95, -- minuscule o-grave
437 [0xFB] = 0x96, -- minuscule u-circumflex
438 [0xF9] = 0x97, -- minuscule u-grave
439 [0xFF] = 0x98, -- minuscule y-umlaut
440 [0xD6] = 0x99, -- majuscule o-umlaut
441 [0xDC] = 0x9A, -- majuscule u-umlaut
442 -- 0x9B through 0x9F are currency symbols and not present in TH fonts
443 [0xE1] = 0xA0, -- minuscule a-acute
444 [0xED] = 0xA1, -- minuscule i-acute
445 [0xF3] = 0xA2, -- minuscule o-acute
446 [0xFA] = 0xA3, -- minuscule u-acute
447 [0xF1] = 0xA4, -- minuscule n-tilde
448 [0xD1] = 0xA5, -- majuscule n-tilde
449 -- 0xA6 and 0xA7 are ordinal indicators and not present in TH fonts
450 [0xBF] = 0xA8, -- inverted question mark
451 -- 0xA9 through 0xAC are not present in TH fonts
452 [0xA1] = 0xAD, -- inverted exclaimation mark
453 -- 0xAE through 0xE0 are not present in TH fonts
454 [0xDF] = 0xE1, -- eszett / sharp-S / lowercase-beta
455 -- 0xE2 through 0xFF are not present in TH fonts
456 }
457
458 local cp437_to_codepoints = {
459 [0x91] = 0xE6, -- minuscule ae
460 [0x9B] = 0xA2, -- cent sign
461 [0x9C] = 0xA3, -- pound sign
462 [0x9D] = 0xA5, -- yen sign
463 [0x9E] = 0x20A7, -- peseta sign
464 [0x9F] = 0x192, -- florin sign
465 [0xA6] = 0xAA, -- a ordinal indicator
466 [0xA7] = 0xBA, -- o ordinal indicator
467 [0xA9] = 0x2310, -- negation
468 [0xAA] = 0xAC, -- negation
469 [0xAB] = 0xBD, -- 1/2
470 [0xAC] = 0xBC, -- 1/4
471 [0xAE] = 0xAB, -- << guillemets
472 [0xAF] = 0xBB, -- >> guillemets
473 -- 0xB0 through 0xDF omitted
474 [0xE0] = 0x3B1, -- alpha
475 [0xE2] = 0x393, -- gamma
476 [0xE3] = 0x3C0, -- pi
477 [0xE4] = 0x3A3, -- majuscule sigma
478 [0xE5] = 0x3C3, -- minuscule sigma
479 [0xE6] = 0x3BC, -- minuscule mu
480 [0xE7] = 0x3C4, -- tau
481 [0xE8] = 0x3A6, -- majuscule phi
482 [0xE9] = 0x398, -- theta
483 [0xEA] = 0x3A9, -- omega
484 [0xEB] = 0x3B4, -- delta
485 [0xEC] = 0x221E, -- infinity
486 [0xED] = 0x3C6, -- minuscule phi
487 [0xEE] = 0x3B5, -- epsilon
488 [0xEF] = 0x2229, -- set intersection
489 [0xF0] = 0x2261, -- modular congruence / triple equals
490 [0xF1] = 0xB1, -- plus / minus
491 [0xF2] = 0x2265, -- >=
492 [0xF3] = 0x2264, -- <=
493 [0xF4] = 0x2320, -- upper integral sign
494 [0xF5] = 0x2321, -- lower integral sign
495 [0xF6] = 0xF7, -- obelus
496 [0xF7] = 0x2248, -- approximate equality
497 [0xF8] = 0xB0, -- degree symbol
498 [0xF9] = 0x2219, -- bullet
499 [0xFA] = 0xB7, -- interpunct
500 [0xFB] = 0x221A, -- square root
501 [0xFC] = 0x207F, -- exponentiation
502 [0xFD] = 0xB2, -- superscript 2
503 [0xFE] = 0x25A0, -- filled square
504 [0xFF] = 0xA0, -- non-breaking space
505 }
506
507 local function utf8encode(codepoint)
508 if codepoint <= 0x7F then
509 return string.char(codepoint)
510 elseif codepoint <= 0x7FF then
511 local sextet = codepoint % 64
512 codepoint = math.floor((codepoint - sextet) / 64)
513 return string.char(0xC0 + codepoint, 0x80 + sextet)
514 elseif codepoint <= 0xFFFF then
515 local sextet2 = codepoint % 64
516 codepoint = math.floor((codepoint - sextet2) / 64)
517 local sextet1 = codepoint % 64
518 codepoint = math.floor((codepoint - sextet2) / 64)
519 return string.char(0xE0 + codepoint, 0x80 + sextet1, 0x80 + sextet2)
520 else
521 local sextet3 = codepoint % 64
522 codepoint = math.floor((codepoint - sextet3) / 64)
523 local sextet2 = codepoint % 64
524 codepoint = math.floor((codepoint - sextet2) / 64)
525 local sextet1 = codepoint % 64
526 codepoint = math.floor((codepoint - sextet2) / 64)
527 return string.char(0xF0 + codepoint, 0x80 + sextet1, 0x80 + sextet2,
528 0x80 + sextet3)
529 end
530 end
531
532 local cp437_to_utf8_pattern = {"["}
533 local cp437_to_utf8_replacement = {}
534 for codepoint, cp437 in pairs(codepoints_to_cp437) do
535 if not cp437_to_codepoints[cp437] then
536 cp437_to_utf8_pattern[#cp437_to_utf8_pattern + 1] = string.char(cp437)
537 cp437_to_utf8_replacement[string.char(cp437)] = utf8encode(codepoint)
538 end
539 end
540 for cp437, codepoint in pairs(cp437_to_codepoints) do
541 cp437_to_utf8_pattern[#cp437_to_utf8_pattern + 1] = string.char(cp437)
542 cp437_to_utf8_replacement[string.char(cp437)] = utf8encode(codepoint)
543 end
544 cp437_to_utf8_pattern[#cp437_to_utf8_pattern + 1] = "]"
545 cp437_to_utf8_pattern = table.concat(cp437_to_utf8_pattern)
546 cp437conv = function(s)
547 return (s:gsub(cp437_to_utf8_pattern, cp437_to_utf8_replacement))
548 end
549
550 -- Table which maps a single character and a single unicode combining
551 -- diacritical mark to a single unicode codepoint
552 local circumflex = 0x302
553 local cedilla = 0x327
554 local umlaut = 0x308
555 local acute = 0x301
556 local grave = 0x300
557 local ring = 0x30A
558 local tilde = 0x303
559 local combine_diacritical_marks = {
560 a = {
561 [grave] = 0xE0,
562 [acute] = 0xE1,
563 [circumflex] = 0xE2,
564 [umlaut] = 0xE4,
565 [ring] = 0xE5,
566 },
567 e = {
568 [grave] = 0xE8,
569 [acute] = 0xE9,
570 [circumflex] = 0xEA,
571 [umlaut] = 0xEB,
572 },
573 i = {
574 [grave] = 0xEC,
575 [acute] = 0xED,
576 [circumflex] = 0xEE,
577 [umlaut] = 0xEF,
578 },
579 o = {
580 [grave] = 0xF2,
581 [acute] = 0xF3,
582 },
583 u = {
584 [grave] = 0xF9,
585 [acute] = 0xFA,
586 [circumflex] = 0xFB,
587 [umlaut] = 0xFC,
588 },
589 c = {
590 [cedilla] = 0xE7,
591 },
592 n = {
593 [tilde] = 0xF1,
594 },
595 y = {
596 [umlaut] = 0xFF,
597 },
598 A = {
599 [umlaut] = 0xC4,
600 [ring] = 0xC5,
601 },
602 E = {
603 [acute] = 0xC9,
604 },
605 O = {
606 [umlaut] = 0xD6,
607 },
608 U = {
609 [umlaut] = 0xDC,
610 },
611 C = {
612 [cedilla] = 0xC7,
613 },
614 N = {
615 [tilde] = 0xD1,
616 },
617 }
618
619 local function utf8char(c)
620 -- Test for presence of a normal character prior to the utf-8 character
621 local prechar
622 if c:byte() < 128 then
623 prechar = c:sub(1, 1)
624 c = c:sub(2, -1)
625 end
626 -- Extract the codepoint of the utf-8 character
627 local codepoint = 0
628 local multiplier = 1
629 for i = #c, 2, -1 do
630 codepoint = codepoint + (c:byte(i) - 128) * multiplier
631 multiplier = multiplier * 2^6
632 end
633 codepoint = codepoint + (c:byte(1) % 2^(7 - #c)) * multiplier
634 -- If the utf-8 character is a combining diacritical mark, merge it with the
635 -- preceding normal character
636 if prechar and (0x300 <= codepoint and codepoint < 0x370) then
637 if combine_diacritical_marks[prechar] then
638 if combine_diacritical_marks[prechar][codepoint] then
639 codepoint = combine_diacritical_marks[prechar][codepoint]
640 prechar = nil
641 else
642 return prechar
643 end
644 else
645 return prechar
646 end
647 end
648 -- Convert to Code Page 437
649 return (prechar or "") .. string.char(codepoints_to_cp437[codepoint] or 0x3F)
650 end
651
652 utf8conv = function(s)
653 -- Pull out each individual utf-8 character and pass it through utf8char
654 -- [\1-\127] picks up a preceding ASCII character to combine diacritics
655 -- [\192-\253] picks up the first byte of a utf-8 character (technically
656 -- only 194 through 244 should be used)
657 -- [\128-\191] picks up the remaining bytes of a utf-8 character
658 return (s:gsub("[\1-\127]?[\192-\253][\128-\191]*", utf8char))
659 end
660
661 -- Fix string.upper and string.lower to work with CP437 rather than current locale
662 local lower_to_upper, upper_to_lower = {}, {}
663 local function case(lower, upper)
664 lower = cp437conv(string.char(lower))
665 upper = cp437conv(string.char(upper))
666 lower_to_upper[lower] = upper
667 lower_to_upper[upper] = upper
668 upper_to_lower[lower] = lower
669 upper_to_lower[upper] = lower
670 end
671 case(0x87, 0x80) -- c-cedilla
672 case(0x81, 0x9A) -- u-umlaut
673 case(0x82, 0x90) -- e-acute
674 case(0x84, 0x8E) -- a-umlaut
675 case(0x86, 0x8F) -- a-ring
676 case(0x94, 0x99) -- o-umlaut
677 case(0xA4, 0xA5) -- n-tilde
678 local case_pattern = "\195[\128-\191]" -- Unicode range [0xC0, 0xFF] as UTF-8
679
680 local orig_upper = string.upper
681 function string.upper(s) -- luacheck: ignore 122
682 return orig_upper(s:gsub(case_pattern, lower_to_upper))
683 end
684
685 local orig_lower = string.lower
686 function string.lower(s) -- luacheck: ignore 122
687 return orig_lower(s:gsub(case_pattern, upper_to_lower))
688 end