Lua Line Wrapping excluding certain characters

2019-08-10 13:57发布

I've located a code that I want to use when I'm writing notes on a MUD I play. Lines can only be 79 characters long for each note, so it's a hassle sometimes to write a note unless you're counting characters. The code is below:

function wrap(str, limit, indent, indent1)
  indent = indent or ""
  indent1 = indent1 or indent
  limit = limit or 79
  local here = 1-#indent1
  return indent1..str:gsub("(%s+)()(%S+)()",
                          function(sp, st, word, fi)
                            if fi-here > limit then
                              here = st - #indent
                              return "\n"..indent..word
                            end
                          end)
end

This would work great; I can type a 300 character line and it will format it to 79 characters, respecting full words.

The problem I'm having, and I cannot seem to figure out how to solve, is that sometimes, I want to add colour codes to the line, and colour codes are not counted against word count. For example:

@GThis is a colour-coded @Yline that should @Bbreak off at 79 @Mcharacters, but ignore @Rthe colour codes (@G, @Y, @B, @M, @R, etc) when doing so.

Essentially, it would strip the colour codes away and break the line appropriately, but without losing the colour codes.

Edited to include what it should check, and what the final output should be.

The function would only check the string below for line breaks:

This is a colour-coded line that should break off at 79 characters, but ignore the colour codes (, , , , , etc) when doing so.

but would actually return:

@GThis is a colour-coded @Yline that should @Bbreak off at 79 @Ncharacters, but ignore 
the colour codes (@G, @Y, @B, @M, @R, etc) when doing so.

To complicate things, we also have xterm colour codes, which are similar, but look like this:

@x123

It is always @x followed by a 3-digit number. And lastly, to further complicate things, I don't want it to strip out purpose colour codes (which would be @@R, @@x123, etc.).

Is there a clean way of doing this that I'm missing?

标签: lua word-wrap
1条回答
冷血范
2楼-- · 2019-08-10 14:30
function(sp, st, word, fi)
  local delta = 0
  word:gsub('@([@%a])', 
    function(c)
      if c == '@'     then delta = delta + 1 
      elseif c == 'x' then delta = delta + 5
      else                 delta = delta + 2 
      end
    end)
  here = here + delta
  if fi-here > limit then
    here = st - #indent + delta
    return "\n"..indent..word
  end
end
查看更多
登录 后发表回答