| Posted by
| Nick Gammon
Australia (23,173 posts) Bio
Forum Administrator |
| Message
| Well, I changed my mind about the removing of styles, as I could see that removing from a table whilst stepping through it could be a problem. The example code below takes a line, looks for "o" in it, and recolours that.
test = {
[1] = {
textcolour = 12632256,
backcolour = 0,
length = 8,
style = 0,
text = "this is ",
},
[2] = {
textcolour = 65535,
backcolour = 0,
length = 14,
style = 1,
text = "test of style ",
},
[3] = {
textcolour = 16776960,
backcolour = 0,
length = 5,
style = 1,
text = "runs ",
},
[4] = {
textcolour = 65280,
backcolour = 0,
length = 6,
style = 1,
text = "today ",
},
}
-- display before amendment
for _, v in ipairs (test) do
ColourTell (RGBColourToName (v.textcolour),
RGBColourToName (v.backcolour),
v.text)
end -- for each style run
Note ("") -- wrap up line
local new_styles = {} -- copy style runs into here
target = "o"
for _, v in ipairs (test) do
-- find target string in this style
local s, e = v.text:find (target) -- s = start, e = end
if s then -- if found
-- copy part coming before the string
if s > 1 then
table.insert (new_styles,
{
textcolour = v.textcolour,
backcolour = v.backcolour,
length = s - 1,
text = v.text:sub (1, s - 1),
})
end -- if need to save first part
-- replace with amended string
table.insert (new_styles,
{
textcolour = ColourNameToRGB "green",
backcolour = ColourNameToRGB "white",
length = e - s + 1,
text = v.text:sub (s, e),
})
-- copy part coming after the string
if e < v.length then
table.insert (new_styles,
{
textcolour = v.textcolour,
backcolour = v.backcolour,
length = v.length - e,
text = v.text:sub (e + 1),
})
end -- if need to save last part
else
table.insert (new_styles, v) -- just copy entire style run over
end -- if
end -- for
-- display after amendment
for _, v in ipairs (new_styles) do
ColourTell (RGBColourToName (v.textcolour),
RGBColourToName (v.backcolour),
v.text)
end -- for each style run
Note ("") -- wrap up line
The "test" table is an example of how a style run might look. The test displays the line before and after (try running in the Immediate window).
The middle loop copies the entire style run to a new table, amending each style if necessary if the target word is detected.
|
- Nick Gammon
www.gammon.com.au, www.mushclient.com | | Top |
|