converting style runs to ansi

Posted by Fiendish on Sat 07 May 2011 05:45 PM — 1 posts, 6,834 views.

USA Global Moderator #0
I found myself needing a way to convert from style runs to a string with embedded ANSI escape codes, and a forum search came up with nothing. So I wrote this little thing:


-- also provide the reverse of the extended_colours global table
colours_extended = {}
for i,v in ipairs(extended_colours) do
   colours_extended[v] = i
end

ANSI_colours = {
  [GetNormalColour (1)] = {0,30},
  [GetNormalColour (2)] = {0,31},
  [GetNormalColour (3)] = {0,32},
  [GetNormalColour (4)] = {0,33},
  [GetNormalColour (5)] = {0,34},
  [GetNormalColour (6)] = {0,35},
  [GetNormalColour (7)] = {0,36},
  [GetNormalColour (8)] = {0,37},
  [GetBoldColour   (1)] = {1,30},
  [GetBoldColour   (2)] = {1,31},
  [GetBoldColour   (3)] = {1,32},
  [GetBoldColour   (4)] = {1,33},
  [GetBoldColour   (5)] = {1,34},
  [GetBoldColour   (6)] = {1,35},
  [GetBoldColour   (7)] = {1,36},
  [GetBoldColour   (8)] = {1,37}
  }  -- end conversion table

-- returns a string with embedded ansi codes
function stylesToANSI (styles)
   line = {}
   for _,v in ipairs (styles) do
      if colours_extended[v.textcolour] then -- use 256 color xterm ansi when available
         table.insert(line, ANSI(38,5,colours_extended[v.textcolour]))
      else -- the user may have customized their standard 16 colors
         local ansi_tab = ANSI_colours[v.textcolour]
         if ansi_tab then
            table.insert(line, ANSI(ansi_tab[1],ansi_tab[2]))
         end
      end
      table.insert(line, v.text)
   end
   table.insert(line, ANSI(0))
   return table.concat(line)
end