Last active
December 18, 2016 01:09
-
-
Save bmwalters/405b4d156a56ae7fb529d533e2d74677 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local _sep_chars, sep_chars = { | |
" ", "-", "\t" | |
}, {} | |
for _, c in pairs(_sep_chars) do | |
sep_chars[string.byte(c)] = true | |
end | |
local function wrap_text(text, width) | |
if surface.GetTextSize(text) <= width then | |
-- no wrapping required | |
return {text} | |
end | |
local lines = {} | |
local current_line = "" | |
local function commit_line() | |
if string.byte(current_line, #current_line) == 32 then | |
current_line = string.sub(current_line, 1, -2) | |
end | |
lines[#lines + 1] = current_line | |
current_line = "" | |
end | |
local current_word_start = 1 | |
for i = 1, #text do | |
if sep_chars[string.byte(text, i)] or i == #text then | |
local word = string.sub(text, current_word_start, i - 1) | |
local word_with_separator = string.sub(text, current_word_start, i) | |
if i == #text then | |
word = word_with_separator | |
end | |
-- special case: hyphen. todo: hyphen at start of next line | |
if string.byte(text, i) == string.byte("-") then | |
word_with_separator = word .. " " | |
end | |
current_word_start = i + 1 -- todo: go to next non-space | |
if surface.GetTextSize(current_line .. word) <= width then | |
-- it fits on this line, so add it | |
current_line = current_line .. word_with_separator | |
else | |
-- start a new line | |
if current_line ~= "" then | |
commit_line() | |
end | |
if surface.GetTextSize(word) <= width then | |
-- start the new line with the word | |
current_line = word | |
else | |
-- split the word onto multiple lines, joined by hyphens | |
local current_char_i = 0 | |
while current_char_i < #word do | |
-- append one character at a time until it is too large | |
while surface.GetTextSize(current_line) < width do | |
current_char_i = current_char_i + 1 | |
if current_char_i > #word then break end | |
current_line = current_line .. string.sub(word, current_char_i, current_char_i) | |
end | |
if current_char_i >= #word then | |
-- last line, don't hyphenate | |
commit_line() | |
else | |
-- replace last character with hyphen | |
current_line = string.sub(current_line, 1, -2) .. "-" | |
current_char_i = current_char_i - 1 | |
commit_line() | |
end | |
end | |
end | |
end | |
end | |
end | |
if current_line ~= "" then | |
commit_line() | |
end | |
return lines | |
end | |
return wrap_text |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment