| 1 |
#!/usr/bin/env texlua |
| 2 |
----------------------------------------------------------------------- |
| 3 |
-- FILE: enigma.lua |
| 4 |
-- USAGE: Call via interface from within a TeX session. |
| 5 |
-- DESCRIPTION: Enigma logic. |
| 6 |
-- REQUIREMENTS: LuaTeX capable format (Luaplain, ConTeXt). |
| 7 |
-- AUTHOR: Philipp Gesang (Phg), <phg42 dot 2a at gmail dot com> |
| 8 |
-- VERSION: release |
| 9 |
-- CREATED: 2013-03-28 02:12:03+0100 |
| 10 |
----------------------------------------------------------------------- |
| 11 |
-- |
| 12 |
|
| 13 |
--[[ichd-- |
| 14 |
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
| 15 |
\startdocsection[title=Format Dependent Code] |
| 16 |
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
| 17 |
|
| 18 |
\startparagraph |
| 19 |
Exported functionality will be collected in the table |
| 20 |
\identifier{enigma}. |
| 21 |
\stopparagraph |
| 22 |
--ichd]]-- |
| 23 |
|
| 24 |
local enigma = { machines = { }, callbacks = { } } |
| 25 |
local format_is_context = false |
| 26 |
|
| 27 |
--[[ichd-- |
| 28 |
\startparagraph |
| 29 |
Afaict, \LATEX\ for \LUATEX\ still lacks a globally accepted |
| 30 |
namespacing convention. This is more than bad, but we’ll have to cope |
| 31 |
with that. For this reason we brazenly introduce |
| 32 |
\identifier{packagedata} (in analogy to \CONTEXT’s |
| 33 |
\identifier{thirddata}) table as a package namespace proposal. If this |
| 34 |
module is called from a \LATEX\ or plain session, the table |
| 35 |
\identifier{packagedata} will already have been created so we will |
| 36 |
identify the format according to its presence or absence, respectively. |
| 37 |
\stopparagraph |
| 38 |
--ichd]]-- |
| 39 |
|
| 40 |
if packagedata then -- latex or plain |
| 41 |
packagedata.enigma = enigma |
| 42 |
elseif thirddata then -- context |
| 43 |
format_is_context = true |
| 44 |
thirddata.enigma = enigma |
| 45 |
else -- external call, mtx-script or whatever |
| 46 |
_ENV.enigma = enigma |
| 47 |
end |
| 48 |
--[[ichd-- |
| 49 |
\stopdocsection |
| 50 |
--ichd]]-- |
| 51 |
|
| 52 |
--[[ichd-- |
| 53 |
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
| 54 |
\startdocsection[title=Prerequisites] |
| 55 |
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
| 56 |
\startparagraph |
| 57 |
First of all, we generate local copies of all those library functions |
| 58 |
that are expected to be referenced frequently. |
| 59 |
The format-independent stuff comes first; it consists of functions from |
| 60 |
the |
| 61 |
\identifier{io}, |
| 62 |
\identifier{lpeg}, |
| 63 |
\identifier{math}, |
| 64 |
\identifier{string}, |
| 65 |
\identifier{table}, and |
| 66 |
\identifier{unicode} |
| 67 |
libraries. |
| 68 |
\stopparagraph |
| 69 |
--ichd]]-- |
| 70 |
|
| 71 |
local get_debug_info = debug.getinfo |
| 72 |
local ioread = io.read |
| 73 |
local iowrite = io.write |
| 74 |
local mathfloor = math.floor |
| 75 |
local mathrandom = math.random |
| 76 |
local next = next |
| 77 |
local nodecopy = node and node.copy |
| 78 |
local nodeid = node and node.id |
| 79 |
local nodeinsert_before = node and node.insert_before |
| 80 |
local nodeinsert_after = node and node.insert_after |
| 81 |
local nodelength = node and node.length |
| 82 |
local nodenew = node and node.new |
| 83 |
local noderemove = node and node.remove |
| 84 |
local nodeslide = node and node.slide |
| 85 |
local nodetraverse = node and node.traverse |
| 86 |
local nodetraverse_id = node and node.traverse_id |
| 87 |
local nodesinstallattributehandler |
| 88 |
local nodestasksappendaction |
| 89 |
local nodestasksdisableaction |
| 90 |
if format_is_context then |
| 91 |
nodesinstallattributehandler = nodes.installattributehandler |
| 92 |
nodestasksappendaction = nodes.tasks.appendaction |
| 93 |
nodestasksdisableaction = nodes.tasks.disableaction |
| 94 |
end |
| 95 |
local stringfind = string.find |
| 96 |
local stringformat = string.format |
| 97 |
local stringlower = string.lower |
| 98 |
local stringsub = string.sub |
| 99 |
local stringupper = string.upper |
| 100 |
local tableconcat = table.concat |
| 101 |
local tonumber = tonumber |
| 102 |
local type = type |
| 103 |
local utf8byte = unicode.utf8.byte |
| 104 |
local utf8char = unicode.utf8.char |
| 105 |
local utf8len = unicode.utf8.len |
| 106 |
local utf8lower = unicode.utf8.lower |
| 107 |
local utf8sub = unicode.utf8.sub |
| 108 |
local utfcharacters = string.utfcharacters |
| 109 |
|
| 110 |
--- debugging tool (careful, this *will* break context!) |
| 111 |
--dofile(kpse.find_file("lualibs-table.lua")) -- archaic version :( |
| 112 |
--table.print = function (...) print(table.serialize(...)) end |
| 113 |
|
| 114 |
local tablecopy |
| 115 |
if format_is_context then |
| 116 |
tablecopy = table.copy |
| 117 |
else -- could use lualibs instead but not worth the overhead |
| 118 |
tablecopy = function (t) -- ignores tables as keys |
| 119 |
local result = { } |
| 120 |
for k, v in next, t do |
| 121 |
if type(v) == table then |
| 122 |
result[k] = tablecopy(v) |
| 123 |
else |
| 124 |
result[k] = v |
| 125 |
end |
| 126 |
end |
| 127 |
return result |
| 128 |
end |
| 129 |
end |
| 130 |
|
| 131 |
local GLYPH_NODE = node and nodeid"glyph" |
| 132 |
local GLUE_NODE = node and nodeid"glue" |
| 133 |
local GLUE_SPEC_NODE = node and nodeid"glue_spec" |
| 134 |
local KERN_NODE = node and nodeid"kern" |
| 135 |
local DISC_NODE = node and nodeid"disc" |
| 136 |
local HLIST_NODE = node and nodeid"hlist" |
| 137 |
local VLIST_NODE = node and nodeid"vlist" |
| 138 |
|
| 139 |
local IGNORE_NODES = node and { |
| 140 |
--[GLUE_NODE] = true, |
| 141 |
[KERN_NODE] = true, |
| 142 |
--[DISC_NODE] = true, |
| 143 |
} or { } |
| 144 |
|
| 145 |
--[[ichd-- |
| 146 |
\startparagraph |
| 147 |
The initialization of the module relies heavily on parsers generated by |
| 148 |
\type{LPEG}. |
| 149 |
\stopparagraph |
| 150 |
--ichd]]-- |
| 151 |
|
| 152 |
local lpeg = require "lpeg" |
| 153 |
|
| 154 |
local C, Cb, Cc, Cf, Cg, |
| 155 |
Cmt, Cp, Cs, Ct |
| 156 |
= lpeg.C, lpeg.Cb, lpeg.Cc, lpeg.Cf, lpeg.Cg, |
| 157 |
lpeg.Cmt, lpeg.Cp, lpeg.Cs, lpeg.Ct |
| 158 |
|
| 159 |
local P, R, S, V, lpegmatch |
| 160 |
= lpeg.P, lpeg.R, lpeg.S, lpeg.V, lpeg.match |
| 161 |
|
| 162 |
--local B = lpeg.version() == "0.10" and lpeg.B or nil |
| 163 |
|
| 164 |
--[[ichd-- |
| 165 |
\startparagraph |
| 166 |
By default the output to \type{stdout} will be zero. The verbosity |
| 167 |
level can be adjusted in order to alleviate debugging. |
| 168 |
\stopparagraph |
| 169 |
--ichd]]-- |
| 170 |
--local verbose_level = 42 |
| 171 |
local verbose_level = 0 |
| 172 |
|
| 173 |
--[[ichd-- |
| 174 |
\startparagraph |
| 175 |
Historically, Enigma-encoded messages were restricted to a size of 250 |
| 176 |
characters. With sufficient verbosity we will indicate whether this |
| 177 |
limit has been exceeded during the \TEX\ run. |
| 178 |
\stopparagraph |
| 179 |
--ichd]]-- |
| 180 |
local max_msg_length = 250 |
| 181 |
--[[ichd-- |
| 182 |
\stopdocsection |
| 183 |
--ichd]]-- |
| 184 |
|
| 185 |
|
| 186 |
--[[ichd-- |
| 187 |
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
| 188 |
\startdocsection[title=Globals] |
| 189 |
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
| 190 |
\startparagraph |
| 191 |
The following mappings are used all over the place as we convert back |
| 192 |
and forth between the characters (unicode) and their numerical |
| 193 |
representation. |
| 194 |
\stopparagraph |
| 195 |
--ichd]]-- |
| 196 |
|
| 197 |
local value_to_letter -- { [int] -> chr } |
| 198 |
local letter_to_value -- { [chr] -> int } |
| 199 |
local alpha_sorted -- string, length 26 |
| 200 |
local raw_rotor_wiring -- { string0, .. string5, } |
| 201 |
local notches -- { [int] -> int } // rotor num -> notch pos |
| 202 |
local reflector_wiring -- { { [int] -> int }, ... } // symmetrical |
| 203 |
do |
| 204 |
value_to_letter = { |
| 205 |
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", |
| 206 |
"n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", |
| 207 |
} |
| 208 |
|
| 209 |
letter_to_value = { |
| 210 |
a = 01, b = 02, c = 03, d = 04, e = 05, f = 06, g = 07, h = 08, |
| 211 |
i = 09, j = 10, k = 11, l = 12, m = 13, n = 14, o = 15, p = 16, |
| 212 |
q = 17, r = 18, s = 19, t = 20, u = 21, v = 22, w = 23, x = 24, |
| 213 |
y = 25, z = 26, |
| 214 |
} |
| 215 |
--[[ichd-- |
| 216 |
\startparagraph |
| 217 |
The five rotors to simulate.\reference[listing:rotor_wiring]{} |
| 218 |
Their wirings are created from strings at runtime, see below the |
| 219 |
function \luafunction{get_rotors}. |
| 220 |
\stopparagraph |
| 221 |
--ichd]]-- |
| 222 |
|
| 223 |
--[[ |
| 224 |
Nice: http://www.ellsbury.com/ultraenigmawirings.htm |
| 225 |
]]-- |
| 226 |
alpha_sorted = "abcdefghijklmnopqrstuvwxyz" |
| 227 |
raw_rotor_wiring = { |
| 228 |
[0] = alpha_sorted, |
| 229 |
"ekmflgdqvzntowyhxuspaibrcj", |
| 230 |
"ajdksiruxblhwtmcqgznpyfvoe", |
| 231 |
"bdfhjlcprtxvznyeiwgakmusqo", |
| 232 |
"esovpzjayquirhxlnftgkdcmwb", |
| 233 |
"vzbrgityupsdnhlxawmjqofeck", |
| 234 |
} |
| 235 |
|
| 236 |
--[[ichd-- |
| 237 |
\startparagraph |
| 238 |
Notches are assigned to rotors according to the Royal Army |
| 239 |
mnemonic. |
| 240 |
\stopparagraph |
| 241 |
--ichd]]-- |
| 242 |
notches = { } |
| 243 |
do |
| 244 |
local raw_notches = "rfwkannnn" |
| 245 |
--local raw_notches = "qevjz" |
| 246 |
local n = 1 |
| 247 |
for chr in utfcharacters(raw_notches) do |
| 248 |
local pos = stringfind(alpha_sorted, chr) |
| 249 |
notches[n] = pos - 1 |
| 250 |
n = n + 1 |
| 251 |
end |
| 252 |
end |
| 253 |
|
| 254 |
--[[ichd-- |
| 255 |
\placetable[here][listing:reflector]% |
| 256 |
{The three reflectors and their substitution rules.}{% |
| 257 |
\starttabulate[|r|l|] |
| 258 |
\NC UKW a \NC AE BJ CM DZ FL GY HX IV KW NR OQ PU ST \NC \NR |
| 259 |
\NC UKW b \NC AY BR CU DH EQ FS GL IP JX KN MO TZ VW \NC \NR |
| 260 |
\NC UKW c \NC AF BV CP DJ EI GO HY KR LZ MX NW QT SU \NC \NR |
| 261 |
\stoptabulate |
| 262 |
} |
| 263 |
--ichd]]-- |
| 264 |
|
| 265 |
reflector_wiring = { } |
| 266 |
local raw_ukw = { |
| 267 |
{ a = "e", b = "j", c = "m", d = "z", f = "l", g = "y", h = "x", |
| 268 |
i = "v", k = "w", n = "r", o = "q", p = "u", s = "t", }, |
| 269 |
{ a = "y", b = "r", c = "u", d = "h", e = "q", f = "s", g = "l", |
| 270 |
i = "p", j = "x", k = "n", m = "o", t = "z", v = "w", }, |
| 271 |
{ a = "f", b = "v", c = "p", d = "j", e = "i", g = "o", h = "y", |
| 272 |
k = "r", l = "z", m = "x", n = "w", q = "t", s = "u", }, |
| 273 |
} |
| 274 |
for i=1, #raw_ukw do |
| 275 |
local new_wiring = { } |
| 276 |
local current_ukw = raw_ukw[i] |
| 277 |
for from, to in next, current_ukw do |
| 278 |
from = letter_to_value[from] |
| 279 |
to = letter_to_value[to] |
| 280 |
new_wiring[from] = to |
| 281 |
new_wiring[to] = from |
| 282 |
end |
| 283 |
reflector_wiring[i] = new_wiring |
| 284 |
end |
| 285 |
end |
| 286 |
|
| 287 |
--[[ichd-- |
| 288 |
\stopdocsection |
| 289 |
--ichd]]-- |
| 290 |
|
| 291 |
--[[ichd-- |
| 292 |
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
| 293 |
\startdocsection[title=Pretty printing for debug purposes] |
| 294 |
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
| 295 |
\startparagraph |
| 296 |
The functions below allow for formatting of the terminal output; they |
| 297 |
have no effect on the workings of the enigma simulator. |
| 298 |
\stopparagraph |
| 299 |
--ichd]]-- |
| 300 |
|
| 301 |
local emit |
| 302 |
local pprint_ciphertext |
| 303 |
local pprint_encoding |
| 304 |
local pprint_encoding_scheme |
| 305 |
local pprint_init |
| 306 |
local pprint_machine_step |
| 307 |
local pprint_new_machine |
| 308 |
local pprint_rotor |
| 309 |
local pprint_rotor_scheme |
| 310 |
local pprint_step |
| 311 |
local polite_key_request |
| 312 |
local key_invalid |
| 313 |
do |
| 314 |
local eol = "\n" |
| 315 |
|
| 316 |
local colorstring_template = "\027[%d;1m%s\027[0m" |
| 317 |
local colorize = function (s, color) |
| 318 |
color = color and color < 38 and color > 29 and color or 31 |
| 319 |
return stringformat(colorstring_template, |
| 320 |
color, |
| 321 |
s) |
| 322 |
end |
| 323 |
|
| 324 |
local underline = function (s) |
| 325 |
return stringformat("\027[4;37m%s\027[0m", s) |
| 326 |
end |
| 327 |
|
| 328 |
local s_steps = [[Total characters encoded with machine “]] |
| 329 |
local f_warnsteps = [[ (%d over permitted maximum)]] |
| 330 |
pprint_machine_step = function (n, name) |
| 331 |
local sn |
| 332 |
name = colorize(name, 36) |
| 333 |
if n > max_msg_length then |
| 334 |
sn = colorize(n, 31) .. stringformat(f_warnsteps, |
| 335 |
n - max_msg_length) |
| 336 |
else |
| 337 |
sn = colorize(n, 37) |
| 338 |
end |
| 339 |
return s_steps .. name .. "”: " .. sn .. "." |
| 340 |
end |
| 341 |
local rotorstate = "[s \027[1;37m%s\027[0m n\027[1;37m%2d\027[0m]> " |
| 342 |
pprint_rotor = function (rotor) |
| 343 |
local visible = rotor.state % 26 + 1 |
| 344 |
local w, n = rotor.wiring, (rotor.notch - visible) % 26 + 1 |
| 345 |
local tmp = { } |
| 346 |
for i=1, 26 do |
| 347 |
local which = (i + rotor.state - 1) % 26 + 1 |
| 348 |
local chr = value_to_letter[rotor.wiring.from[which]] |
| 349 |
if i == n then -- highlight positions of notches |
| 350 |
tmp[i] = colorize(stringupper(chr), 32) |
| 351 |
--elseif chr == value_to_letter[visible] then |
| 352 |
---- highlight the character in window |
| 353 |
-- tmp[i] = colorize(chr, 33) |
| 354 |
else |
| 355 |
tmp[i] = chr |
| 356 |
end |
| 357 |
end |
| 358 |
return stringformat(rotorstate, |
| 359 |
stringupper(value_to_letter[visible]), |
| 360 |
n) |
| 361 |
.. tableconcat(tmp) |
| 362 |
end |
| 363 |
|
| 364 |
local rotor_scheme = underline"[rot not]" |
| 365 |
.. " " |
| 366 |
.. underline(alpha_sorted) |
| 367 |
pprint_rotor_scheme = function () |
| 368 |
return rotor_scheme |
| 369 |
end |
| 370 |
|
| 371 |
local s_encoding_scheme = eol |
| 372 |
.. [[in > 1 => 2 => 3 > UKW > 3 => 2 => 1]] |
| 373 |
pprint_encoding_scheme = function () |
| 374 |
return underline(s_encoding_scheme) |
| 375 |
end |
| 376 |
local s_step = " => " |
| 377 |
local stepcolor = 36 |
| 378 |
local finalcolor = 32 |
| 379 |
pprint_encoding = function (steps) |
| 380 |
local nsteps, result = #steps, { } |
| 381 |
for i=0, nsteps-1 do |
| 382 |
result[i+1] = colorize(value_to_letter[steps[i]], stepcolor) |
| 383 |
.. s_step |
| 384 |
end |
| 385 |
result[nsteps+1] = colorize(value_to_letter[steps[nsteps]], |
| 386 |
finalcolor) |
| 387 |
return tableconcat(result) |
| 388 |
end |
| 389 |
|
| 390 |
local init_announcement |
| 391 |
= colorize("\n" .. [[Initial position of rotors: ]], |
| 392 |
37) |
| 393 |
pprint_init = function (init) |
| 394 |
local result = "" |
| 395 |
result = value_to_letter[init[1]] .. " " |
| 396 |
.. value_to_letter[init[2]] .. " " |
| 397 |
.. value_to_letter[init[3]] |
| 398 |
return init_announcement .. colorize(stringupper(result), 34) |
| 399 |
end |
| 400 |
|
| 401 |
local machine_announcement = |
| 402 |
[[Enigma machine initialized with the following settings.]] .. eol |
| 403 |
local s_ukw = colorize(" Reflector:", 37) |
| 404 |
local s_pb = colorize("Plugboard setting:", 37) |
| 405 |
local s_ring = colorize(" Ring positions:", 37) |
| 406 |
local empty_plugboard = colorize(" ——", 34) |
| 407 |
pprint_new_machine = function (m) |
| 408 |
local result = { "" } |
| 409 |
result[#result+1] = underline(machine_announcement) |
| 410 |
result[#result+1] = s_ukw |
| 411 |
.. " " |
| 412 |
.. colorize( |
| 413 |
stringupper(value_to_letter[m.reflector]), |
| 414 |
34 |
| 415 |
) |
| 416 |
local rings = "" |
| 417 |
for i=1, 3 do |
| 418 |
local this = m.ring[i] |
| 419 |
rings = rings |
| 420 |
.. " " |
| 421 |
.. colorize(stringupper(value_to_letter[this + 1]), 34) |
| 422 |
end |
| 423 |
result[#result+1] = s_ring .. rings |
| 424 |
if m.__raw.plugboard then |
| 425 |
local tpb, pb = m.__raw.plugboard, "" |
| 426 |
for i=1, #tpb do |
| 427 |
pb = pb .. " " .. colorize(tpb[i], 34) |
| 428 |
end |
| 429 |
result[#result+1] = s_pb .. pb |
| 430 |
else |
| 431 |
result[#result+1] = s_pb .. empty_plugboard |
| 432 |
end |
| 433 |
result[#result+1] = "" |
| 434 |
result[#result+1] = pprint_rotor_scheme() |
| 435 |
for i=1, 3 do |
| 436 |
result[#result+1] = pprint_rotor(m.rotors[i]) |
| 437 |
end |
| 438 |
return tableconcat(result, eol) .. eol |
| 439 |
end |
| 440 |
|
| 441 |
local step_template = colorize([[Step № ]], 37) |
| 442 |
local chr_template = colorize([[ —— Input ]], 37) |
| 443 |
local pbchr_template = colorize([[ → ]], 37) |
| 444 |
pprint_step = function (n, chr, pb_chr) |
| 445 |
return eol |
| 446 |
.. step_template |
| 447 |
.. colorize(n, 34) |
| 448 |
.. chr_template |
| 449 |
.. colorize(stringupper(value_to_letter[chr]), 34) |
| 450 |
.. pbchr_template |
| 451 |
.. colorize(stringupper(value_to_letter[pb_chr]), 34) |
| 452 |
.. eol |
| 453 |
end |
| 454 |
|
| 455 |
-- Split the strings into lines, group them in bunches of five etc. |
| 456 |
local tw = 30 |
| 457 |
local pprint_textblock = function (s) |
| 458 |
local len = utf8len(s) |
| 459 |
local position = 1 -- position in string |
| 460 |
local nline = 5 -- width of current line |
| 461 |
local out = utf8sub(s, position, position+4) |
| 462 |
repeat |
| 463 |
position = position + 5 |
| 464 |
nline = nline + 6 |
| 465 |
if nline > tw then |
| 466 |
out = out .. eol .. utf8sub(s, position, position+4) |
| 467 |
nline = 1 |
| 468 |
else |
| 469 |
out = out .. " " .. utf8sub(s, position, position+4) |
| 470 |
end |
| 471 |
until position > len |
| 472 |
return out |
| 473 |
end |
| 474 |
|
| 475 |
local intext = colorize([[Input text:]], 37) |
| 476 |
local outtext = colorize([[Output text:]], 37) |
| 477 |
pprint_ciphertext = function (input, output, upper_p) |
| 478 |
if upper_p then |
| 479 |
input = stringupper(input) |
| 480 |
output = stringupper(output) |
| 481 |
end |
| 482 |
return eol |
| 483 |
.. intext |
| 484 |
.. eol |
| 485 |
.. pprint_textblock(input) |
| 486 |
.. eol .. eol |
| 487 |
.. outtext |
| 488 |
.. eol |
| 489 |
.. pprint_textblock(output) |
| 490 |
end |
| 491 |
|
| 492 |
--[[ichd-- |
| 493 |
\startparagraph |
| 494 |
\luafunction{emit} is the main wrapper function for |
| 495 |
\identifier{stdout}. Checks if the global verbosity setting exceeds |
| 496 |
the specified threshold, and only then pushes the output. |
| 497 |
\stopparagraph |
| 498 |
--ichd]]-- |
| 499 |
emit = function (v, f, ...) |
| 500 |
if f and v and verbose_level >= v then |
| 501 |
iowrite(f(...) .. eol) |
| 502 |
end |
| 503 |
return 0 |
| 504 |
end |
| 505 |
--[[ichd-- |
| 506 |
\startparagraph |
| 507 |
The \luafunction{polite_key_request} will be called in case the |
| 508 |
\identifier{day_key} field of the machine setup is empty at the time of |
| 509 |
initialization. |
| 510 |
\stopparagraph |
| 511 |
--ichd]]-- |
| 512 |
local s_request = "\n\n " |
| 513 |
.. underline"This is an encrypted document." .. [[ |
| 514 |
|
| 515 |
|
| 516 |
Please enter the document key for enigma machine |
| 517 |
“%s”. |
| 518 |
|
| 519 |
Key Format: |
| 520 |
|
| 521 |
Ref R1 R2 R3 I1 I2 I3 [P1 ..] Ref: reflector A/B/C |
| 522 |
Rn: rotor, I through V |
| 523 |
In: ring position, 01 through 26 |
| 524 |
Pn: optional plugboard wiring, upto 32 |
| 525 |
|
| 526 |
>]] |
| 527 |
polite_key_request = function (name) |
| 528 |
return stringformat(s_request, colorize(name, 33)) |
| 529 |
end |
| 530 |
|
| 531 |
local s_invalid_key = colorize"Warning!" |
| 532 |
.. " The specified key is invalid." |
| 533 |
key_invalid = function () |
| 534 |
return s_invalid_key |
| 535 |
end |
| 536 |
end |
| 537 |
|
| 538 |
--[[ichd-- |
| 539 |
\startparagraph |
| 540 |
The functions \luafunction{new} and \luafunction{ask_for_day_key} are |
| 541 |
used outside their scope, so we declare them beforehand. |
| 542 |
\stopparagraph |
| 543 |
--ichd]]-- |
| 544 |
local new |
| 545 |
local ask_for_day_key |
| 546 |
do |
| 547 |
--[[ichd-- |
| 548 |
\stopdocsection |
| 549 |
--ichd]]-- |
| 550 |
|
| 551 |
--[[ichd-- |
| 552 |
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
| 553 |
\startdocsection[title=Rotation] |
| 554 |
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
| 555 |
\startparagraph |
| 556 |
The following function \luafunction{do_rotate} increments the |
| 557 |
rotational state of a single rotor. There are two tests for notches: |
| 558 |
\startitemize[n] |
| 559 |
\item whether it’s at the current character, and |
| 560 |
\item whether it’s at the next character. |
| 561 |
\stopitemize |
| 562 |
The latter is an essential prerequisite for double-stepping. |
| 563 |
\stopparagraph |
| 564 |
--ichd]]-- |
| 565 |
local do_rotate = function (rotor) |
| 566 |
rotor.state = rotor.state % 26 + 1 |
| 567 |
return rotor, |
| 568 |
rotor.state == rotor.notch, |
| 569 |
rotor.state + 1 == rotor.notch |
| 570 |
end |
| 571 |
|
| 572 |
--[[ichd-- |
| 573 |
\startparagraph |
| 574 |
The \luafunction{rotate} function takes care of rotor (\emph{Walze}) |
| 575 |
movement. This entails incrementing the next rotor whenever the notch |
| 576 |
has been reached and covers the corner case \emph{double stepping}. |
| 577 |
\stopparagraph |
| 578 |
--ichd]]-- |
| 579 |
local rotate = function (machine) |
| 580 |
local rotors = machine.rotors |
| 581 |
local rc, rb, ra = rotors[1], rotors[2], rotors[3] |
| 582 |
|
| 583 |
ra, nxt = do_rotate(ra) |
| 584 |
if nxt or machine.double_step then |
| 585 |
rb, nxt, nxxt = do_rotate(rb) |
| 586 |
if nxt then |
| 587 |
rc = do_rotate(rc) |
| 588 |
end |
| 589 |
if nxxt then |
| 590 |
--- weird: home.comcast.net/~dhhamer/downloads/rotors1.pdf |
| 591 |
machine.double_step = true |
| 592 |
else |
| 593 |
machine.double_step = false |
| 594 |
end |
| 595 |
end |
| 596 |
machine.rotors = { rc, rb, ra } |
| 597 |
end |
| 598 |
--[[ichd-- |
| 599 |
\stopdocsection |
| 600 |
--ichd]]-- |
| 601 |
|
| 602 |
--[[ichd-- |
| 603 |
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
| 604 |
\startdocsection[title=Input Preprocessing] |
| 605 |
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
| 606 |
\startparagraph |
| 607 |
Internally, we will use lowercase strings as they are a lot more |
| 608 |
readable than uppercase. Lowercasing happens prior to any further |
| 609 |
dealings with input. After the encoding or decoding has been |
| 610 |
accomplished, there will be an optional (re-)uppercasing. |
| 611 |
\stopparagraph |
| 612 |
|
| 613 |
\startparagraph |
| 614 |
Substitutions \reference[listing:preproc]{}are applied onto the |
| 615 |
lowercased input. You might want to avoid some of these, above all the |
| 616 |
rules for numbers, because they translate single digits only. The |
| 617 |
solution is to write out numbers above ten. |
| 618 |
\stopparagraph |
| 619 |
--ichd]]-- |
| 620 |
|
| 621 |
local pp_substitutions = { |
| 622 |
-- Umlauts are resolved. |
| 623 |
["ö"] = "oe", |
| 624 |
["ä"] = "ae", |
| 625 |
["ü"] = "ue", |
| 626 |
["ß"] = "ss", |
| 627 |
-- WTF? |
| 628 |
["ch"] = "q", |
| 629 |
["ck"] = "q", |
| 630 |
-- Punctuation -> “x” |
| 631 |
[","] = "x", |
| 632 |
["."] = "x", |
| 633 |
[";"] = "x", |
| 634 |
[":"] = "x", |
| 635 |
["/"] = "x", |
| 636 |
["’"] = "x", |
| 637 |
["‘"] = "x", |
| 638 |
["„"] = "x", |
| 639 |
["“"] = "x", |
| 640 |
["“"] = "x", |
| 641 |
["-"] = "x", |
| 642 |
["–"] = "x", |
| 643 |
["—"] = "x", |
| 644 |
["!"] = "x", |
| 645 |
["?"] = "x", |
| 646 |
["‽"] = "x", |
| 647 |
["("] = "x", |
| 648 |
[")"] = "x", |
| 649 |
["["] = "x", |
| 650 |
["]"] = "x", |
| 651 |
["<"] = "x", |
| 652 |
[">"] = "x", |
| 653 |
-- Spaces are omitted. |
| 654 |
[" "] = "", |
| 655 |
["\n"] = "", |
| 656 |
["\t"] = "", |
| 657 |
["\v"] = "", |
| 658 |
["\\"] = "", |
| 659 |
-- Numbers are resolved. |
| 660 |
["0"] = "null", |
| 661 |
["1"] = "eins", |
| 662 |
["2"] = "zwei", |
| 663 |
["3"] = "drei", |
| 664 |
["4"] = "vier", |
| 665 |
["5"] = "fuenf", |
| 666 |
["6"] = "sechs", |
| 667 |
["7"] = "sieben", |
| 668 |
["8"] = "acht", |
| 669 |
["9"] = "neun", |
| 670 |
} |
| 671 |
|
| 672 |
--[[ichd-- |
| 673 |
\stopdocsection |
| 674 |
--ichd]]-- |
| 675 |
|
| 676 |
--[[ichd-- |
| 677 |
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
| 678 |
\startdocsection[ |
| 679 |
title={Main function chain to be applied to single characters}, |
| 680 |
] |
| 681 |
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
| 682 |
|
| 683 |
\startparagraph |
| 684 |
As far as the Enigma is concerned, there is no difference between |
| 685 |
encoding and decoding. Thus, we need only one function |
| 686 |
(\luafunction{encode_char}) to achieve the complete functionality. |
| 687 |
However, within every encoding step, characters will be wired |
| 688 |
differently in at least one of the rotors according to its rotational |
| 689 |
state. Rotation is simulated by adding the \identifier{state} field of |
| 690 |
each rotor to the letter value (its position on the ingoing end). |
| 691 |
\stopparagraph |
| 692 |
\placetable[here][table:dirs]{Directional terminology}{% |
| 693 |
\starttabulate[|l|r|l|] |
| 694 |
\NC boolean \NC direction \NC meaning \NC \AR |
| 695 |
\NC true \NC “from” \NC right to left \NC \AR |
| 696 |
\NC false \NC “to” \NC left to right \NC \AR |
| 697 |
\stoptabulate% |
| 698 |
} |
| 699 |
\startparagraph |
| 700 |
The function \luafunction{do_do_encode_char} returns the character |
| 701 |
substitution for one rotor. As a letter passes through each rotor |
| 702 |
twice, the argument \identifier{direction} determines which way the |
| 703 |
substitution is applied. |
| 704 |
\stopparagraph |
| 705 |
--ichd]]-- |
| 706 |
local do_do_encode_char = function (char, rotor, direction) |
| 707 |
local rw = rotor.wiring |
| 708 |
local rs = rotor.state |
| 709 |
local result = char |
| 710 |
if direction then -- from |
| 711 |
result = (result + rs - 1) % 26 + 1 |
| 712 |
result = rw.from[result] |
| 713 |
result = (result - rs - 1) % 26 + 1 |
| 714 |
else -- to |
| 715 |
result = (result + rs - 1) % 26 + 1 |
| 716 |
result = rw.to[result] |
| 717 |
result = (result - rs - 1) % 26 + 1 |
| 718 |
end |
| 719 |
return result |
| 720 |
end |
| 721 |
|
| 722 |
--[[ichd-- |
| 723 |
\startparagraph |
| 724 |
Behind the plugboard, every character undergoes seven substitutions: |
| 725 |
two for each rotor plus the central one through the reflector. The |
| 726 |
function \luafunction{do_encode_char}, although it returns the final |
| 727 |
result only, keeps every intermediary step inside a table for debugging |
| 728 |
purposes. This may look inefficient but is actually a great advantage |
| 729 |
whenever something goes wrong. |
| 730 |
\stopparagraph |
| 731 |
--ichd]]-- |
| 732 |
--- ra -> rb -> rc -> ukw -> rc -> rb -> ra |
| 733 |
local do_encode_char = function (rotors, reflector, char) |
| 734 |
local rc, rb, ra = rotors[1], rotors[2], rotors[3] |
| 735 |
local steps = { [0] = char } |
| 736 |
-- |
| 737 |
steps[1] = do_do_encode_char(steps[0], ra, true) |
| 738 |
steps[2] = do_do_encode_char(steps[1], rb, true) |
| 739 |
steps[3] = do_do_encode_char(steps[2], rc, true) |
| 740 |
steps[4] = reflector_wiring[reflector][steps[3]] |
| 741 |
steps[5] = do_do_encode_char(steps[4], rc, false) |
| 742 |
steps[6] = do_do_encode_char(steps[5], rb, false) |
| 743 |
steps[7] = do_do_encode_char(steps[6], ra, false) |
| 744 |
emit(2, pprint_encoding_scheme) |
| 745 |
emit(2, pprint_encoding, steps) |
| 746 |
return steps[7] |
| 747 |
end |
| 748 |
|
| 749 |
--[[ichd-- |
| 750 |
\startparagraph |
| 751 |
Before an input character is passed on to the actual encoding routing, |
| 752 |
the function \luafunction{encode_char} matches it agains the latin |
| 753 |
alphabet. |
| 754 |
Characters failing this test are either passed through or ignored, |
| 755 |
depending on the machine option \identifier{other_chars}. |
| 756 |
Also, the counter of encoded characters is incremented at this stage |
| 757 |
and some pretty printer hooks reside here. |
| 758 |
\stopparagraph |
| 759 |
|
| 760 |
\startparagraph |
| 761 |
\luafunction{encode_char} contributes only one element of the encoding |
| 762 |
procedure: the plugboard (\emph{Steckerbrett}). |
| 763 |
Like the rotors described above, a character passed through this |
| 764 |
device twice; the plugboard marks the beginning and end of every step. |
| 765 |
For debugging purposes, the first substitution is stored in a separate |
| 766 |
local variable, \identifier{pb_char}. |
| 767 |
\stopparagraph |
| 768 |
--ichd]]-- |
| 769 |
|
| 770 |
local encode_char = function (machine, char) |
| 771 |
machine.step = machine.step + 1 |
| 772 |
machine:rotate() |
| 773 |
local pb = machine.plugboard |
| 774 |
char = letter_to_value[char] |
| 775 |
local pb_char = pb[char] -- first plugboard substitution |
| 776 |
emit(2, pprint_step, machine.step, char, pb_char) |
| 777 |
emit(3, pprint_rotor_scheme) |
| 778 |
emit(3, pprint_rotor, machine.rotors[1]) |
| 779 |
emit(3, pprint_rotor, machine.rotors[2]) |
| 780 |
emit(3, pprint_rotor, machine.rotors[3]) |
| 781 |
char = do_encode_char(machine.rotors, |
| 782 |
machine.reflector, |
| 783 |
pb_char) |
| 784 |
return value_to_letter[pb[char]] -- second plugboard substitution |
| 785 |
end |
| 786 |
|
| 787 |
local get_random_pattern = function () |
| 788 |
local a, b, c |
| 789 |
= mathrandom(1,26), mathrandom(1,26), mathrandom(1,26) |
| 790 |
return value_to_letter[a] |
| 791 |
.. value_to_letter[b] |
| 792 |
.. value_to_letter[c] |
| 793 |
end |
| 794 |
|
| 795 |
local pattern_to_state = function (pat) |
| 796 |
return { |
| 797 |
letter_to_value[stringsub(pat, 1, 1)], |
| 798 |
letter_to_value[stringsub(pat, 2, 2)], |
| 799 |
letter_to_value[stringsub(pat, 3, 3)], |
| 800 |
} |
| 801 |
end |
| 802 |
|
| 803 |
local set_state = function (machine, state) |
| 804 |
local rotors = machine.rotors |
| 805 |
for i=1, 3 do |
| 806 |
rotors[i].state = state[i] - 1 |
| 807 |
end |
| 808 |
end |
| 809 |
|
| 810 |
--[[ichd-- |
| 811 |
\startparagraph |
| 812 |
When \modulename{Enigma} is called from \TEX, the encoding |
| 813 |
proceeds character by character as we iterate one node at a time. |
| 814 |
\luafunction{encode_string} is a wrapper for use with strings, e.~g. in |
| 815 |
the mtx-script (\at{page}[sec:fun]). |
| 816 |
It handles iteration and extraction of successive characters from the |
| 817 |
sequence. |
| 818 |
\stopparagraph |
| 819 |
--ichd]]-- |
| 820 |
local encode_string = function (machine, str) --, pattern) |
| 821 |
local result = { } |
| 822 |
for char in utfcharacters(str) do |
| 823 |
local tmp = machine:encode(char) |
| 824 |
if tmp ~= false then |
| 825 |
if type(tmp) == "table" then |
| 826 |
for i=1, #tmp do |
| 827 |
result[#result+1] = tmp[i] |
| 828 |
end |
| 829 |
else |
| 830 |
result[#result+1] = tmp |
| 831 |
end |
| 832 |
end |
| 833 |
end |
| 834 |
machine:processed_chars() |
| 835 |
return tableconcat(result) |
| 836 |
end |
| 837 |
--[[ichd-- |
| 838 |
\stopdocsection |
| 839 |
--ichd]]-- |
| 840 |
|
| 841 |
--[[ichd-- |
| 842 |
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
| 843 |
\startdocsection[title=Initialization string parser] |
| 844 |
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
| 845 |
|
| 846 |
\placetable[here][]{Initialization strings}{% |
| 847 |
\bTABLE |
| 848 |
\bTR |
| 849 |
\bTD Reflector \eTD |
| 850 |
\bTD[nc=3] Rotor \eTD |
| 851 |
\bTD[nc=3] Initial \eTD |
| 852 |
\bTD[nc=10] Plugboard wiring \eTD |
| 853 |
\eTR |
| 854 |
\eTR |
| 855 |
\bTR |
| 856 |
\bTD in slot \eTD |
| 857 |
\bTD[nc=3] setting \eTD |
| 858 |
\bTD[nc=3] rotor \eTD |
| 859 |
\eTR |
| 860 |
\bTR |
| 861 |
\bTD \eTD |
| 862 |
\bTD 1 \eTD\bTD 2 \eTD\bTD 3 \eTD |
| 863 |
\bTD 1 \eTD\bTD 2 \eTD\bTD 3 \eTD |
| 864 |
\bTD 1 \eTD\bTD 2 \eTD\bTD 3 \eTD\bTD 4 \eTD\bTD 5 \eTD |
| 865 |
\bTD 6 \eTD\bTD 7 \eTD\bTD 8 \eTD\bTD 9 \eTD\bTD 10 \eTD |
| 866 |
\eTR |
| 867 |
\bTR |
| 868 |
\bTD B \eTD |
| 869 |
\bTD I \eTD\bTD IV \eTD\bTD III \eTD |
| 870 |
\bTD 16 \eTD\bTD 26 \eTD\bTD 08 \eTD |
| 871 |
\bTD AD \eTD\bTD CN \eTD\bTD ET \eTD |
| 872 |
\bTD FL \eTD\bTD GI \eTD\bTD JV \eTD |
| 873 |
\bTD KZ \eTD\bTD PU \eTD\bTD QY \eTD |
| 874 |
\bTD WX \eTD |
| 875 |
\eTR |
| 876 |
\eTABLE |
| 877 |
} |
| 878 |
--ichd]]-- |
| 879 |
local roman_digits = { |
| 880 |
i = 1, I = 1, |
| 881 |
ii = 2, II = 2, |
| 882 |
iii = 3, III = 3, |
| 883 |
iv = 4, IV = 4, |
| 884 |
v = 5, V = 5, |
| 885 |
} |
| 886 |
|
| 887 |
local p_init = P{ |
| 888 |
"init", |
| 889 |
init = V"whitespace"^-1 * Ct(V"do_init"), |
| 890 |
do_init = (V"reflector" * V"whitespace")^-1 |
| 891 |
* V"rotors" * V"whitespace" |
| 892 |
* V"ring" |
| 893 |
* (V"whitespace" * V"plugboard")^-1 |
| 894 |
, |
| 895 |
reflector = Cg(C(R("ac","AC")) / stringlower, "reflector") |
| 896 |
, |
| 897 |
|
| 898 |
rotors = Cg(Ct(V"rotor" * V"whitespace" |
| 899 |
* V"rotor" * V"whitespace" |
| 900 |
* V"rotor"), |
| 901 |
"rotors") |
| 902 |
, |
| 903 |
rotor = Cs(V"roman_five" / roman_digits |
| 904 |
+ V"roman_four" / roman_digits |
| 905 |
+ V"roman_three" / roman_digits |
| 906 |
+ V"roman_two" / roman_digits |
| 907 |
+ V"roman_one" / roman_digits) |
| 908 |
, |
| 909 |
roman_one = P"I" + P"i", |
| 910 |
roman_two = P"II" + P"ii", |
| 911 |
roman_three = P"III" + P"iii", |
| 912 |
roman_four = P"IV" + P"iv", |
| 913 |
roman_five = P"V" + P"v", |
| 914 |
|
| 915 |
ring = Cg(Ct(V"double_digit" * V"whitespace" |
| 916 |
* V"double_digit" * V"whitespace" |
| 917 |
* V"double_digit"), |
| 918 |
"ring") |
| 919 |
, |
| 920 |
double_digit = C(R"02" * R"09"), |
| 921 |
|
| 922 |
plugboard = Cg(V"do_plugboard", "plugboard"), |
| 923 |
--- no need to enforce exactly ten substitutions |
| 924 |
--do_plugboard = Ct(V"letter_combination" * V"whitespace" |
| 925 |
-- * V"letter_combination" * V"whitespace" |
| 926 |
-- * V"letter_combination" * V"whitespace" |
| 927 |
-- * V"letter_combination" * V"whitespace" |
| 928 |
-- * V"letter_combination" * V"whitespace" |
| 929 |
-- * V"letter_combination" * V"whitespace" |
| 930 |
-- * V"letter_combination" * V"whitespace" |
| 931 |
-- * V"letter_combination" * V"whitespace" |
| 932 |
-- * V"letter_combination" * V"whitespace" |
| 933 |
-- * V"letter_combination") |
| 934 |
do_plugboard = Ct(V"letter_combination" |
| 935 |
* (V"whitespace" * V"letter_combination")^0) |
| 936 |
, |
| 937 |
letter_combination = C(R("az", "AZ") * R("az", "AZ")), |
| 938 |
|
| 939 |
whitespace = S" \n\t\v"^1, |
| 940 |
} |
| 941 |
|
| 942 |
|
| 943 |
--[[ichd-- |
| 944 |
\stopdocsection |
| 945 |
--ichd]]-- |
| 946 |
|
| 947 |
--[[ichd-- |
| 948 |
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
| 949 |
\startdocsection[title=Initialization routines] |
| 950 |
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
| 951 |
|
| 952 |
\startparagraph |
| 953 |
The plugboard is implemented as a pair of hash tables. |
| 954 |
\stopparagraph |
| 955 |
--ichd]]-- |
| 956 |
local get_plugboard_substitution = function (p) |
| 957 |
--- Plugboard wirings are symmetrical, thus we have one table for |
| 958 |
--- each direction. |
| 959 |
local tmp, result = { }, { } |
| 960 |
for _, str in next, p do |
| 961 |
local one, two = stringlower(stringsub(str, 1, 1)), |
| 962 |
stringlower(stringsub(str, 2)) |
| 963 |
tmp[one] = two |
| 964 |
tmp[two] = one |
| 965 |
end |
| 966 |
local n_letters = 26 |
| 967 |
|
| 968 |
local lv = letter_to_value |
| 969 |
for n=1, n_letters do |
| 970 |
local letter = value_to_letter[n] |
| 971 |
local sub = tmp[letter] or letter |
| 972 |
-- Map each char either to the plugboard substitution or itself. |
| 973 |
result[lv[letter]] = lv[sub or letter] |
| 974 |
end |
| 975 |
return result |
| 976 |
end |
| 977 |
|
| 978 |
--[[ichd-- |
| 979 |
\startparagraph |
| 980 |
Initialization of the rotors requires some precautions to be taken. |
| 981 |
The most obvious of which is adjusting the displacement of its wiring |
| 982 |
by the ring setting. |
| 983 |
\stopparagraph |
| 984 |
\startparagraph |
| 985 |
Another important task is to store the notch position in order for it |
| 986 |
to be retrievable by the rotation subroutine at a later point. |
| 987 |
\stopparagraph |
| 988 |
\startparagraph |
| 989 |
The actual bidirectional mapping is implemented as a pair of tables. |
| 990 |
The initial order of letters, before the ring shift is applied, is |
| 991 |
alphabetical on the input (right, “from”) side and, on the output |
| 992 |
(left, “to”) side taken by the hard wired correspondence as specified |
| 993 |
in the rotor wirings above. |
| 994 |
NB the descriptions in terms of “output” and “input” directions is |
| 995 |
misleading in so far as during any encoding step the electricity will |
| 996 |
pass through every rotor in both ways. |
| 997 |
Hence, the “input” (right, from) direction literally applies only to |
| 998 |
the first half of the encoding process between plugboard and reflector. |
| 999 |
\stopparagraph |
| 1000 |
\startparagraph |
| 1001 |
The function \luafunction{do_get_rotor} creates a single rotor instance |
| 1002 |
and populates it with character mappings. The \identifier{from} and |
| 1003 |
\identifier{to} subfields of its \identifier{wiring} field represent |
| 1004 |
the wiring in the respective directions. |
| 1005 |
This initital wiring was specified in the corresponding |
| 1006 |
\identifier{raw_rotor_wiring} table; the ringshift is added modulo the |
| 1007 |
alphabet size in order to get the correctly initialized rotor. |
| 1008 |
\stopparagraph |
| 1009 |
--ichd]]-- |
| 1010 |
local do_get_rotor = function (raw, notch, ringshift) |
| 1011 |
local rotor = { |
| 1012 |
wiring = { |
| 1013 |
from = { }, |
| 1014 |
to = { }, |
| 1015 |
}, |
| 1016 |
state = 0, |
| 1017 |
notch = notch, |
| 1018 |
} |
| 1019 |
local w = rotor.wiring |
| 1020 |
for from=1, 26 do |
| 1021 |
local to = letter_to_value[stringsub(raw, from, from)] |
| 1022 |
--- The shift needs to be added in both directions. |
| 1023 |
to = (to + ringshift - 1) % 26 + 1 |
| 1024 |
from = (from + ringshift - 1) % 26 + 1 |
| 1025 |
rotor.wiring.from[from] = to |
| 1026 |
rotor.wiring.to [to ] = from |
| 1027 |
end |
| 1028 |
--table.print(rotor, "rotor") |
| 1029 |
return rotor |
| 1030 |
end |
| 1031 |
|
| 1032 |
--[[ichd-- |
| 1033 |
\startparagraph |
| 1034 |
Rotors are initialized sequentially accordings to the initialization |
| 1035 |
request. |
| 1036 |
The function \luafunction{get_rotors} walks over the list of |
| 1037 |
initialization instructions and calls \luafunction{do_get_rotor} for |
| 1038 |
the actual generation of the rotor table. Each rotor generation request |
| 1039 |
consists of three elements: |
| 1040 |
\stopparagraph |
| 1041 |
\startitemize[n] |
| 1042 |
\item the choice of rotor (one of five), |
| 1043 |
\item the notch position of said rotor, and |
| 1044 |
\item the ring shift. |
| 1045 |
\stopitemize |
| 1046 |
--ichd]]-- |
| 1047 |
local get_rotors = function (rotors, ring) |
| 1048 |
local s, r = { }, { } |
| 1049 |
for n=1, 3 do |
| 1050 |
local nr = tonumber(rotors[n]) |
| 1051 |
local ni = tonumber(ring[n]) - 1 -- “1” means shift of zero |
| 1052 |
r[n] = do_get_rotor(raw_rotor_wiring[nr], notches[nr], ni) |
| 1053 |
s[n] = ni |
| 1054 |
end |
| 1055 |
return r, s |
| 1056 |
end |
| 1057 |
|
| 1058 |
local decode_char = encode_char -- hooray for involutory ciphers |
| 1059 |
|
| 1060 |
--[[ichd-- |
| 1061 |
\startparagraph |
| 1062 |
The function \luafunction{encode_general} is an intermediate step for |
| 1063 |
the actual single-character encoding / decoding routine |
| 1064 |
\luafunction{enchode_char}. |
| 1065 |
Its purpose is to ensure encodability of a given character before |
| 1066 |
passing it along. |
| 1067 |
Characters are first checked against the replacement table |
| 1068 |
\identifier{pp_substitutions} (see \at{page}[listing:preproc]). |
| 1069 |
For single-character replacements the function returns the encoded |
| 1070 |
character (string). |
| 1071 |
However, should the replacement turn out to consist of more than one |
| 1072 |
character, each one will be encoded successively, yielding a list. |
| 1073 |
\stopparagraph |
| 1074 |
--ichd]]-- |
| 1075 |
local encode_general = function (machine, chr) |
| 1076 |
local chr = utf8lower(chr) |
| 1077 |
local replacement |
| 1078 |
= pp_substitutions[chr] or letter_to_value[chr] and chr |
| 1079 |
if not replacement then |
| 1080 |
if machine.other_chars then |
| 1081 |
return chr |
| 1082 |
else |
| 1083 |
return false |
| 1084 |
end |
| 1085 |
end |
| 1086 |
|
| 1087 |
if utf8len(replacement) == 1 then |
| 1088 |
return encode_char(machine, replacement) |
| 1089 |
end |
| 1090 |
local result = { } |
| 1091 |
for new_chr in utfcharacters(replacement) do |
| 1092 |
result[#result+1] = encode_char(machine, new_chr) |
| 1093 |
end |
| 1094 |
return result |
| 1095 |
end |
| 1096 |
|
| 1097 |
local process_message_key |
| 1098 |
local alpha = R"az" |
| 1099 |
local alpha_dec = alpha / letter_to_value |
| 1100 |
local whitespace = S" \n\t\v" |
| 1101 |
local mkeypattern = Ct(alpha_dec * alpha_dec * alpha_dec) |
| 1102 |
* whitespace^0 |
| 1103 |
* C(alpha * alpha *alpha) |
| 1104 |
process_message_key = function (machine, message_key) |
| 1105 |
message_key = stringlower(message_key) |
| 1106 |
local init, three = lpegmatch(mkeypattern, message_key) |
| 1107 |
-- to be implemented |
| 1108 |
end |
| 1109 |
|
| 1110 |
local decode_string = function (machine, str, message_key) |
| 1111 |
machine.kenngruppe, str = stringsub(str, 3, 5), stringsub(str, 6) |
| 1112 |
machine:process_message_key(message_key) |
| 1113 |
local decoded = encode_string(machine, str) |
| 1114 |
return decoded |
| 1115 |
end |
| 1116 |
|
| 1117 |
local testoptions = { |
| 1118 |
size = 42, |
| 1119 |
|
| 1120 |
} |
| 1121 |
local generate_header = function (options) |
| 1122 |
end |
| 1123 |
|
| 1124 |
local processed_chars = function (machine) |
| 1125 |
emit(1, pprint_machine_step, machine.step, machine.name) |
| 1126 |
end |
| 1127 |
|
| 1128 |
--[[ichd-- |
| 1129 |
\startparagraph |
| 1130 |
The day key is entrusted to the function \luafunction{handle_day_key}. |
| 1131 |
If the day key is the empty string or \type{nil}, it will ask for a key |
| 1132 |
on the terminal. (Cf. below, \at{page}[listing:ask_for_day_key].) |
| 1133 |
Lesson: don’t forget providing day keys in your setups when running in |
| 1134 |
batch mode. |
| 1135 |
\stopparagraph |
| 1136 |
--ichd]]-- |
| 1137 |
local handle_day_key handle_day_key = function (dk, name, old) |
| 1138 |
local result |
| 1139 |
if not dk or dk == "" then |
| 1140 |
dk = ask_for_day_key(name, old) |
| 1141 |
end |
| 1142 |
result = lpegmatch(p_init, dk) |
| 1143 |
result.reflector = result.reflector or "b" |
| 1144 |
-- If we don’t like the key we’re going to ask again. And again.... |
| 1145 |
return result or handle_day_key(nil, name, dk) |
| 1146 |
end |
| 1147 |
|
| 1148 |
--[[ichd-- |
| 1149 |
\startparagraph |
| 1150 |
The enigma encoding is restricted to an input -- and, naturally, output |
| 1151 |
-- alphabet of exactly twenty-seven characters. Obviously, this would |
| 1152 |
severely limit the set of encryptable documents. For this reason the |
| 1153 |
plain text would be \emph{preprocessed} prior to encoding, removing |
| 1154 |
spaces and substituting a range of characters, e.\,g. punctuation, with |
| 1155 |
placeholders (“X”) from the encodable spectrum. See above |
| 1156 |
\at{page}[listing:preproc] for a comprehensive list of substitutions. |
| 1157 |
\stopparagraph |
| 1158 |
|
| 1159 |
\startparagraph |
| 1160 |
The above mentioned preprocessing, however, does not even nearly extend |
| 1161 |
to the whole unicode range that modern day typesetting is expected to |
| 1162 |
handle. Thus, sooner or later an Enigma machine will encounter |
| 1163 |
non-preprocessable characters and it will have to decide what to do |
| 1164 |
with them. The Enigma module offers two ways to handle this kind of |
| 1165 |
situation: \emph{drop} those characters, possibly distorting the |
| 1166 |
deciphered plain text, or to leave them in, leaving hints behind as to |
| 1167 |
the structure of the encrypted text. None of these is optional, so it |
| 1168 |
is nevertheless advisable to not include non-latin characters in the |
| 1169 |
plain text in the first place. The settings key |
| 1170 |
\identifier{other_chars} (type boolean) determines whether we will keep |
| 1171 |
or drop offending characters. |
| 1172 |
\stopparagraph |
| 1173 |
--ichd]]-- |
| 1174 |
|
| 1175 |
new = function (name, args) |
| 1176 |
local setup_string, pattern = args.day_key, args.rotor_setting |
| 1177 |
local raw_settings = handle_day_key(setup_string, name) |
| 1178 |
local rotors, ring = |
| 1179 |
get_rotors(raw_settings.rotors, raw_settings.ring) |
| 1180 |
local plugboard |
| 1181 |
= raw_settings.plugboard |
| 1182 |
and get_plugboard_substitution(raw_settings.plugboard) |
| 1183 |
or get_plugboard_substitution{ } |
| 1184 |
local machine = { |
| 1185 |
name = name, |
| 1186 |
step = 0, -- n characters encoded |
| 1187 |
init = { |
| 1188 |
rotors = raw_settings.rotors, |
| 1189 |
ring = raw_settings.ring |
| 1190 |
}, |
| 1191 |
rotors = rotors, |
| 1192 |
ring = ring, |
| 1193 |
state = init_state, |
| 1194 |
other_chars = args.other_chars, |
| 1195 |
spacing = args.spacing, |
| 1196 |
---> a>1, b>2, c>3 |
| 1197 |
reflector = letter_to_value[raw_settings.reflector], |
| 1198 |
plugboard = plugboard, |
| 1199 |
--- functionality |
| 1200 |
rotate = rotate, |
| 1201 |
--process_message_key = process_message_key, |
| 1202 |
encode_string = encode_string, |
| 1203 |
encode_char = encode_char, |
| 1204 |
encode = encode_general, |
| 1205 |
decode_string = decode_string, |
| 1206 |
decode_char = decode_char, |
| 1207 |
set_state = set_state, |
| 1208 |
processed_chars = processed_chars, |
| 1209 |
--- <badcodingstyle> -- hackish but occasionally useful |
| 1210 |
__raw = raw_settings |
| 1211 |
--- </badcodingstyle> |
| 1212 |
} --- machine |
| 1213 |
local init_state |
| 1214 |
= pattern_to_state(pattern or get_random_pattern()) |
| 1215 |
emit(1, pprint_init, init_state) |
| 1216 |
machine:set_state(init_state) |
| 1217 |
|
| 1218 |
--table.print(machine.rotors) |
| 1219 |
emit(1, pprint_new_machine, machine) |
| 1220 |
return machine |
| 1221 |
end |
| 1222 |
|
| 1223 |
end |
| 1224 |
--[[ichd-- |
| 1225 |
\stopdocsection |
| 1226 |
--ichd]]-- |
| 1227 |
|
| 1228 |
|
| 1229 |
--[[ichd-- |
| 1230 |
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
| 1231 |
\startdocsection[title=Setup Argument Handling] |
| 1232 |
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
| 1233 |
--ichd]]-- |
| 1234 |
do |
| 1235 |
--[[ichd-- |
| 1236 |
\startparagraph |
| 1237 |
As the module is intended to work both with the Plain and \LATEX\ |
| 1238 |
formats as well as \CONTEXT, we can’t rely on format dependent setups. |
| 1239 |
Hence the need for an argument parser. Should be more efficient anyways |
| 1240 |
as all the functionality resides in Lua. |
| 1241 |
\stopparagraph |
| 1242 |
--ichd]]-- |
| 1243 |
|
| 1244 |
local p_args = P{ |
| 1245 |
"args", |
| 1246 |
args = Cf(Ct"" * (V"kv_pair" + V"emptyline")^0, rawset), |
| 1247 |
kv_pair = Cg(V"key" |
| 1248 |
* V"separator" |
| 1249 |
* (V"value" * V"final" |
| 1250 |
+ V"empty")) |
| 1251 |
* V"rest_of_line"^-1 |
| 1252 |
, |
| 1253 |
key = V"whitespace"^0 * C(V"key_char"^1), |
| 1254 |
key_char = (1 - V"whitespace" - V"eol" - V"equals")^1, |
| 1255 |
separator = V"whitespace"^0 * V"equals" * V"whitespace"^0, |
| 1256 |
empty = V"whitespace"^0 * V"comma" * V"rest_of_line"^-1 |
| 1257 |
* Cc(false) |
| 1258 |
, |
| 1259 |
value = C((V"balanced" + (1 - V"final"))^1), |
| 1260 |
final = V"whitespace"^0 * V"comma" + V"rest_of_string", |
| 1261 |
rest_of_string = V"whitespace"^0 |
| 1262 |
* V"eol_comment"^-1 |
| 1263 |
* V"eol"^0 |
| 1264 |
* V"eof" |
| 1265 |
, |
| 1266 |
rest_of_line = V"whitespace"^0 * V"eol_comment"^-1 * V"eol", |
| 1267 |
eol_comment = V"comment_string" * (1 - (V"eol" + V"eof"))^0, |
| 1268 |
comment_string = V"lua_comment" + V"TeX_comment", |
| 1269 |
TeX_comment = V"percent", |
| 1270 |
lua_comment = V"double_dash", |
| 1271 |
emptyline = V"rest_of_line", |
| 1272 |
|
| 1273 |
balanced = V"balanced_brk" + V"balanced_brc", |
| 1274 |
balanced_brk = V"lbrk" |
| 1275 |
* (V"balanced" + (1 - V"rbrk"))^0 |
| 1276 |
* V"rbrk" |
| 1277 |
, |
| 1278 |
balanced_brc = V"lbrc" |
| 1279 |
* (V"balanced" + (1 - V"rbrc"))^0 |
| 1280 |
* V"rbrc" |
| 1281 |
, |
| 1282 |
-- Terminals |
| 1283 |
eol = P"\n\r" + P"\r\n" + P"\n" + P"\r", |
| 1284 |
eof = -P(1), |
| 1285 |
whitespace = S" \t\v", |
| 1286 |
equals = P"=", |
| 1287 |
dot = P".", |
| 1288 |
comma = P",", |
| 1289 |
dash = P"-", double_dash = V"dash" * V"dash", |
| 1290 |
percent = P"%", |
| 1291 |
lbrk = P"[", rbrk = P"]", |
| 1292 |
lbrc = P"{", rbrc = P"}", |
| 1293 |
} |
| 1294 |
|
| 1295 |
|
| 1296 |
--[[ichd-- |
| 1297 |
\startparagraph |
| 1298 |
In the next step we process the arguments, check the input for sanity |
| 1299 |
etc. The function \luafunction{parse_args} will test whether a value |
| 1300 |
has a sanitizer routine and, if so, apply it to its value. |
| 1301 |
\stopparagraph |
| 1302 |
--ichd]]-- |
| 1303 |
|
| 1304 |
local boolean_synonyms = { |
| 1305 |
["1"] = true, |
| 1306 |
doit = true, |
| 1307 |
indeed = true, |
| 1308 |
ok = true, |
| 1309 |
["⊤"] = true, |
| 1310 |
["true"] = true, |
| 1311 |
yes = true, |
| 1312 |
} |
| 1313 |
local toboolean |
| 1314 |
= function (value) return boolean_synonyms[value] or false end |
| 1315 |
local alpha = R("az", "AZ") |
| 1316 |
local digit = R"09" |
| 1317 |
local space = S" \t\v" |
| 1318 |
local ans = alpha + digit + space |
| 1319 |
local p_ans = Cs((ans + (1 - ans / ""))^1) |
| 1320 |
local alphanum_or_space = function (str) |
| 1321 |
if type(str) ~= "string" then return nil end |
| 1322 |
return lpegmatch(p_ans, str) |
| 1323 |
end |
| 1324 |
local ensure_int = function (n) |
| 1325 |
n = tonumber(n) |
| 1326 |
if not n then return 0 end |
| 1327 |
return mathfloor(n + 0.5) |
| 1328 |
end |
| 1329 |
p_alpha = Cs((alpha + (1 - alpha / ""))^1) |
| 1330 |
local ensure_alpha = function (s) |
| 1331 |
s = tostring(s) |
| 1332 |
return lpegmatch(p_alpha, s) |
| 1333 |
end |
| 1334 |
|
| 1335 |
local sanitizers = { |
| 1336 |
other_chars = toboolean, -- true = keep, false = drop |
| 1337 |
spacing = toboolean, |
| 1338 |
day_key = alphanum_or_space, |
| 1339 |
rotor_setting = ensure_alpha, |
| 1340 |
verbose = ensure_int, |
| 1341 |
} |
| 1342 |
enigma.parse_args = function (raw) |
| 1343 |
local args = lpegmatch(p_args, raw) |
| 1344 |
for k, v in next, args do |
| 1345 |
local f = sanitizers[k] |
| 1346 |
if f then |
| 1347 |
args[k] = f(v) |
| 1348 |
else |
| 1349 |
-- OPTIONAL be fascist and permit only predefined args |
| 1350 |
args[k] = v |
| 1351 |
end |
| 1352 |
end |
| 1353 |
return args |
| 1354 |
end |
| 1355 |
--[[ichd-- |
| 1356 |
\startparagraph |
| 1357 |
If the machine setting lacks key settings then we’ll go ahead and ask |
| 1358 |
\reference[listing:ask_for_day_key]{}% |
| 1359 |
the user directly, hence the function \luafunction{ask_for_day_key}. |
| 1360 |
We abort after three misses lest we annoy the user \dots |
| 1361 |
\stopparagraph |
| 1362 |
--ichd]]-- |
| 1363 |
local max_tries = 3 |
| 1364 |
ask_for_day_key = function (name, old, try) |
| 1365 |
if try == max_tries then |
| 1366 |
iowrite[[ |
| 1367 |
Aborting. Entered invalid key three times. |
| 1368 |
]] |
| 1369 |
os.exit() |
| 1370 |
end |
| 1371 |
if old then |
| 1372 |
emit(0, key_invalid) |
| 1373 |
end |
| 1374 |
emit(0, polite_key_request, name) |
| 1375 |
local result = ioread() |
| 1376 |
iowrite("\n") |
| 1377 |
return alphanum_or_space(result) or |
| 1378 |
ask_for_day_key(name, (try and try + 1 or 1)) |
| 1379 |
end |
| 1380 |
end |
| 1381 |
|
| 1382 |
--[[ichd-- |
| 1383 |
\stopdocsection |
| 1384 |
--ichd]]-- |
| 1385 |
|
| 1386 |
--[[ichd-- |
| 1387 |
\startdocsection[title=Callback] |
| 1388 |
\startparagraph |
| 1389 |
This is the interface to \TEX. We generate a new callback handler for |
| 1390 |
each defined Enigma machine. \CONTEXT\ delivers the head as third |
| 1391 |
argument of a callback only (...‽), so we’ll have to do some variable |
| 1392 |
shuffling on the function side. |
| 1393 |
\stopparagraph |
| 1394 |
|
| 1395 |
\startparagraph |
| 1396 |
When grouping output into the traditional blocks of five letters we |
| 1397 |
insert space nodes. As their properties depend on the font we need to |
| 1398 |
recreate the space item for every paragraph. Also, as \CONTEXT\ does |
| 1399 |
not preload a font we lack access to font metrics before |
| 1400 |
\type{\starttext}. Thus creating the space earlier will result in an |
| 1401 |
error. |
| 1402 |
The function \luafunction{generate_space} will be called inside the |
| 1403 |
callback in order to get an appropriate space glue. |
| 1404 |
\stopparagraph |
| 1405 |
--ichd]]-- |
| 1406 |
|
| 1407 |
local generate_space = function ( ) |
| 1408 |
local current_fontparms = font.getfont(font.current()).parameters |
| 1409 |
local space_node = nodenew(GLUE_NODE) |
| 1410 |
space_node.spec = nodenew(GLUE_SPEC_NODE) |
| 1411 |
space_node.spec.width = current_fontparms.space |
| 1412 |
space_node.spec.shrink = current_fontparms.space_shrink |
| 1413 |
space_node.spec.stretch = current_fontparms.space_stretch |
| 1414 |
return space_node |
| 1415 |
end |
| 1416 |
|
| 1417 |
--[[ichd-- |
| 1418 |
\startparagraph |
| 1419 |
\useURL[khaled_hosny_texsx] [http://tex.stackexchange.com/a/11970] |
| 1420 |
[] [tex.sx] |
| 1421 |
Registering a callback (“node attribute”?, “node task”?, “task |
| 1422 |
action”?) in \CONTEXT\ is not straightforward, let alone documented. |
| 1423 |
The trick is to create, install and register a handler first in order |
| 1424 |
to use it later on \dots\ many thanks to Khaled Hosny, who posted an |
| 1425 |
answer to \from[khaled_hosny_texsx]. |
| 1426 |
\stopparagraph |
| 1427 |
--ichd]]-- |
| 1428 |
|
| 1429 |
local new_callback = function (machine, name) |
| 1430 |
enigma.machines [name] = machine |
| 1431 |
local format_is_context = format_is_context |
| 1432 |
local current_space_node |
| 1433 |
local mod_5 = 0 |
| 1434 |
|
| 1435 |
--- First we need to choose an insertion method. If autospacing is |
| 1436 |
--- requested, a space will have to be inserted every five |
| 1437 |
--- characters. The rationale behind using differend functions to |
| 1438 |
--- implement each method is that it should be faster than branching |
| 1439 |
--- for each character. |
| 1440 |
local insert_encoded |
| 1441 |
|
| 1442 |
if machine.spacing then -- auto-group output |
| 1443 |
insert_encoded = function (head, n, replacement) |
| 1444 |
local insert_glyph = nodecopy(n) |
| 1445 |
if replacement then -- inefficient but bulletproof |
| 1446 |
insert_glyph.char = utf8byte(replacement) |
| 1447 |
--print(utf8char(n.char), "=>", utf8char(insertion.char)) |
| 1448 |
end |
| 1449 |
--- if we insert a space we need to return the |
| 1450 |
--- glyph node in order to track positions when |
| 1451 |
--- replacing multiple nodes at once (e.g. ligatures) |
| 1452 |
local insertion = insert_glyph |
| 1453 |
mod_5 = mod_5 + 1 |
| 1454 |
if mod_5 > 5 then |
| 1455 |
mod_5 = 1 |
| 1456 |
insertion = nodecopy(current_space_node) |
| 1457 |
insertion.next, insert_glyph.prev = insert_glyph, insertion |
| 1458 |
end |
| 1459 |
if head == n then --> replace head |
| 1460 |
local succ = head.next |
| 1461 |
if succ then |
| 1462 |
insert_glyph.next, succ.prev = succ, insert_glyph |
| 1463 |
end |
| 1464 |
head = insertion |
| 1465 |
else --> replace n |
| 1466 |
local pred, succ = n.prev, n.next |
| 1467 |
pred.next, insertion.prev = insertion, pred |
| 1468 |
if succ then |
| 1469 |
insert_glyph.next, succ.prev = succ, insert_glyph |
| 1470 |
end |
| 1471 |
end |
| 1472 |
|
| 1473 |
--- insertion becomes the new head |
| 1474 |
return head, insert_glyph -- so we know where to insert |
| 1475 |
end |
| 1476 |
else |
| 1477 |
|
| 1478 |
insert_encoded = function (head, n, replacement) |
| 1479 |
local insertion = nodecopy(n) |
| 1480 |
if replacement then |
| 1481 |
insertion.char = utf8byte(replacement) |
| 1482 |
end |
| 1483 |
if head == n then |
| 1484 |
local succ = head.next |
| 1485 |
if succ then |
| 1486 |
insertion.next, succ.prev = succ, insertion |
| 1487 |
end |
| 1488 |
head = insertion |
| 1489 |
else |
| 1490 |
nodeinsert_before(head, n, insertion) |
| 1491 |
noderemove(head, n) |
| 1492 |
end |
| 1493 |
return head, insertion |
| 1494 |
end |
| 1495 |
end |
| 1496 |
|
| 1497 |
--- The callback proper starts here. |
| 1498 |
local aux aux = function (head, recurse) |
| 1499 |
if recurse == nil then recurse = 0 end |
| 1500 |
for n in nodetraverse(head) do |
| 1501 |
local nid = n.id |
| 1502 |
--print(utf8char(n.char), n) |
| 1503 |
if nid == GLYPH_NODE then |
| 1504 |
local chr = utf8char(n.char) |
| 1505 |
--print(chr, n) |
| 1506 |
local replacement = machine:encode(chr) |
| 1507 |
--print(chr, replacement, n) |
| 1508 |
local treplacement = replacement and type(replacement) |
| 1509 |
--if replacement == false then |
| 1510 |
if not replacement then |
| 1511 |
noderemove(head, n) |
| 1512 |
elseif treplacement == "string" then |
| 1513 |
--print(head, n, replacement) |
| 1514 |
head, _ = insert_encoded(head, n, replacement) |
| 1515 |
elseif treplacement == "table" then |
| 1516 |
local current = n |
| 1517 |
for i=1, #replacement do |
| 1518 |
head, current = insert_encoded(head, current, replacement[i]) |
| 1519 |
end |
| 1520 |
end |
| 1521 |
elseif nid == GLUE_NODE then |
| 1522 |
if n.subtype ~= 15 then -- keeping the parfillskip |
| 1523 |
noderemove(head, n) |
| 1524 |
end |
| 1525 |
elseif IGNORE_NODES[nid] then |
| 1526 |
-- drop spaces and kerns |
| 1527 |
noderemove(head, n) |
| 1528 |
elseif nid == DISC_NODE then |
| 1529 |
--- ligatures need to be resolved if they are characters |
| 1530 |
local npre, npost = n.pre, n.post |
| 1531 |
if nodeid(npre) == GLYPH_NODE and |
| 1532 |
nodeid(npost) == GLYPH_NODE then |
| 1533 |
if npre.char and npost.char then -- ligature between glyphs |
| 1534 |
local replacement_pre = machine:encode(utf8char(npre.char)) |
| 1535 |
local replacement_post = machine:encode(utf8char(npost.char)) |
| 1536 |
insert_encoded(head, npre, replacement_pre) |
| 1537 |
insert_encoded(head, npost, replacement_post) |
| 1538 |
else -- hlists or whatever |
| 1539 |
-- pass |
| 1540 |
--noderemove(head, npre) |
| 1541 |
--noderemove(head, npost) |
| 1542 |
end |
| 1543 |
end |
| 1544 |
noderemove(head, n) |
| 1545 |
elseif nid == HLIST_NODE or nid == VLIST_NODE then |
| 1546 |
if nodelength(n.list) > 0 then |
| 1547 |
n.list = aux(n.list, recurse + 1) |
| 1548 |
end |
| 1549 |
-- else |
| 1550 |
-- -- TODO other node types |
| 1551 |
-- print(n) |
| 1552 |
end |
| 1553 |
end |
| 1554 |
nodeslide(head) |
| 1555 |
return head |
| 1556 |
end -- callback auxiliary |
| 1557 |
|
| 1558 |
--- Context requires |
| 1559 |
--- × argument shuffling; a properly registered “action” gets the |
| 1560 |
--- head passed as its third argument |
| 1561 |
--- × hacking our way around the coupling of pre_linebreak_filter |
| 1562 |
--- and hpack_filter; background: |
| 1563 |
--- http://www.ntg.nl/pipermail/ntg-context/2012/067779.html |
| 1564 |
local cbk = function (a, _, c) |
| 1565 |
local head |
| 1566 |
current_space_node = generate_space () |
| 1567 |
mod_5 = 0 |
| 1568 |
if format_is_context == true then |
| 1569 |
head = c |
| 1570 |
local cbk_env = get_debug_info(4) -- no getenv in lua 5.2 |
| 1571 |
--inspect(cbk_env) |
| 1572 |
if cbk_env.func == nodes.processors.pre_linebreak_filter then |
| 1573 |
-- how weird is that? |
| 1574 |
return aux(head) |
| 1575 |
end |
| 1576 |
return head |
| 1577 |
end |
| 1578 |
head = a |
| 1579 |
return aux(head) |
| 1580 |
end |
| 1581 |
|
| 1582 |
if format_is_context then |
| 1583 |
local cbk_id = "enigma_" .. name |
| 1584 |
enigma.callbacks[name] = nodesinstallattributehandler{ |
| 1585 |
name = cbk_id, |
| 1586 |
namespace = thirddata.enigma, |
| 1587 |
processor = cbk, |
| 1588 |
} |
| 1589 |
local cbk_location = "thirddata.enigma.callbacks." .. name |
| 1590 |
nodestasksappendaction("processors", |
| 1591 |
--"characters", |
| 1592 |
--"finalizers", |
| 1593 |
--- this one is tagged “for users” |
| 1594 |
--- (cf. node-tsk.lua) |
| 1595 |
"before", |
| 1596 |
cbk_location) |
| 1597 |
nodestasksdisableaction("processors", cbk_location) |
| 1598 |
else |
| 1599 |
enigma.callbacks[name] = cbk |
| 1600 |
end |
| 1601 |
end |
| 1602 |
|
| 1603 |
--[[ichd-- |
| 1604 |
\startparagraph |
| 1605 |
Enigma\reference[listing:retrieve]{} machines can be copied and derived |
| 1606 |
from one another at will, cf. the \texmacro{defineenigma} on |
| 1607 |
\at{page}[listing:define]. Two helper functions residing inside the |
| 1608 |
\identifier{thirddata.enigma} namespace take care of these actions: |
| 1609 |
\luafunction{save_raw_args} and \luafunction{retrieve_raw_args}. As |
| 1610 |
soon as a machine is defined, we store its parsed options inside the |
| 1611 |
table \identifier{configurations} for later reference. For further |
| 1612 |
details on the machine derivation mechanism see |
| 1613 |
\at{page}[listing:inherit]. |
| 1614 |
\stopparagraph |
| 1615 |
--ichd]]-- |
| 1616 |
local configurations = { } |
| 1617 |
|
| 1618 |
local save_raw_args = function (conf, name) |
| 1619 |
local current = configurations[name] or { } |
| 1620 |
for k, v in next, conf do |
| 1621 |
current[k] = v |
| 1622 |
end |
| 1623 |
configurations[name] = current |
| 1624 |
end |
| 1625 |
|
| 1626 |
local retrieve_raw_args = function (name) |
| 1627 |
local cn = configurations[name] |
| 1628 |
return cn and tablecopy(cn) or { } |
| 1629 |
end |
| 1630 |
|
| 1631 |
enigma.save_raw_args = save_raw_args |
| 1632 |
enigma.retrieve_raw_args = retrieve_raw_args |
| 1633 |
|
| 1634 |
|
| 1635 |
--[[ichd-- |
| 1636 |
\startparagraph |
| 1637 |
The function \luafunction{new_machine} instantiates a table containing |
| 1638 |
the complete specification of a workable \emph{Enigma} machine and |
| 1639 |
other metadata. The result is intended to be handed over to the |
| 1640 |
callback creation mechanism (\luafunction{new_callback}). However, the |
| 1641 |
arguments table is usally stored away in the |
| 1642 |
\identifier{thirddata.enigma} namespace anyway |
| 1643 |
(\luafunction{save_raw_args}), so that the specification of any machine |
| 1644 |
can be inherited by some new setup later on. |
| 1645 |
\stopparagraph |
| 1646 |
--ichd]]-- |
| 1647 |
local new_machine = function (name) |
| 1648 |
local args = configurations[name] |
| 1649 |
--table.print(configurations) |
| 1650 |
verbose_level = args and args.verbose or verbose_level |
| 1651 |
local machine = new(name, args) |
| 1652 |
return machine |
| 1653 |
end |
| 1654 |
|
| 1655 |
enigma.new_machine = new_machine |
| 1656 |
enigma.new_callback = new_callback |
| 1657 |
|
| 1658 |
--[[ichd-- |
| 1659 |
\stopdocsection |
| 1660 |
--ichd]]-- |
| 1661 |
|
| 1662 |
-- vim:ft=lua:sw=2:ts=2:tw=71:expandtab |