Mirror characters with Bidi Mirrored property

From LuaTeXWiki

This example code for mirroring characters that has Bidi_Mirrored property (as defined by Unicode) in RTL contexts. It uses characters.data table defined in char-def.lua file from ConTeXt distribution to get character properties.

dofile("char-def.lua") -- character definition table

local function mirror(hlist)
  local rtl = false
  if tex.textdir == "TRT" then
    rtl = true
  elseif tex.textdir == "TLT" then
    rtl = false
  end
  for n in node.traverse(hlist) do
    if n.id == node.id('hlist') then
      mirror(n.list)
    end
    if n.id == node.id("whatsit") and n.subtype == 7 then
      if n.dir == "+TRT" or n.dir == "-TLT" then
        rtl = true
      elseif n.dir == "-TRT" or n.dir == "+TLT" then
        rtl = false
      end
    end
    if n.id == node.id('glyph') then
      if rtl then
      local char = n.char
      local mirror = characters.data[char].mirror
        if mirror then
          n.char = mirror
        end
      end
    end
  end
end

callback.register('pre_linebreak_filter',
  function(h)
     mirror(h)
     return true
  end
  )

Example usage:

\directlua{dofile("mirror.lua")}

(Left to right) {\textdir TRT (RIGHT TO LEFT)}

\textdir TRT

RIGHT [TO] LEFT (TEXT)

\textdir TLT

left [to] right (text)
\bye

--khaledhosny