Page 1 of 1

Copy in Color

Posted: Tue Sep 25, 2018 1:18 pm
by Jor'Mox
I created two functions to capture text from a window in color, suited either for writing in labels or using with decho. They are copy2html and copy2decho. They both take a window name (defaults to "main"), the string you want to copy from that line (defaults to the entire line), and the instance of that string in the line that you want to copy (defaults to 1).
Code: [show] | [select all] lua
local function copy2color(name,win,str,inst)
    local line = getCurrentLine(win or "main")
    if (not str and line == "ERROR: mini console does not exist") or type(str) == "number" then
        win, str, inst = "main", win, str
        line = getCurrentLine(win)
    end
    win = win or "main"
    str = str or line
    inst = inst or 1
    local start, len = selectString(win, str, inst), #str
    if not start then
        error(name..": string not found",3)
    end
    local style, endspan, result, r, g, b, br, bg, bb, cr, cg, cb, crb, cgb, cbb
    if name == "copy2html" then
        style = "%s<span style=\'color: rgb(%d,%d,%d);background: rgb(%d,%d,%d);'>%s"
        endspan = "</span>"
    elseif name == "copy2decho" then
        style = "%s<%d,%d,%d:%d,%d,%d>%s"
        endspan = "<r>"
    end
    for index = start + 1, start + len do
        if win ~= "main" then
            selectSection(win, index - 1, 1)
        else
            selectSection(index - 1, 1)
        end
        r,g,b = getFgColor(win)
        rb,gb,bb = getBgColor(win)
        if not table.is_empty(table.complement({r,g,b,rb,gb,bb},{cr,cg,cb,crb,cgb,cbb})) then
            cr,cg,cb,crb,cgb,cbb = r,g,b,rb,gb,bb
            result = string.format(style, result and (result..endspan) or "", r, g, b, rb, gb, bb, line:sub(index, index))
        else
            result = result .. line:sub(index, index)
        end
    end
    result = result .. endspan
    if name == "copy2html" then
        local conversions = {["¦"] = "&brvbar;", ["×"] = "&times;", ["«"] = "&#171;", ["»"] = "&raquo;"}
        for from, to in pairs(conversions) do
            result = string.gsub(result, from, to)
        end
    end
    return result
end

function copy2html(...)
    return copy2color("copy2html",...)
end

function copy2decho(...)
    return copy2color("copy2decho",...)
end
As an example, if you had a trigger capturing something that you wanted to display on a label, you could use the following code to do so with these functions: echo("my_label", copy2html(matches[2]))

Re: Copy in Color

Posted: Mon Mar 23, 2020 1:27 am
by demonnic
This has gotten a bit buried and is super useful functionality that I kind of think Mudlet ought to include by default... would you mind if I put in a PR to include these functions as base Mudlet functionality?

Re: Copy in Color

Posted: Mon Mar 23, 2020 12:29 pm
by Jor'Mox
Sure, go right ahead.

Re: Copy in Color

Posted: Mon Mar 23, 2020 2:34 pm
by demonnic
thanks!