Created
February 19, 2017 21:18
-
-
Save exerro/a78c6a9925a26e0707a7351164b72eb9 to your computer and use it in GitHub Desktop.
This file contains 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 function splitspaced( str ) | |
local s, f = str:find "%S+" | |
local segments = {} | |
local i = 1 | |
while s do | |
local seg = str:sub( s, f ) | |
local pos = seg:find "'" or seg:find '"' | |
if pos then | |
if pos > 1 then | |
segments[i] = seg:sub( 1, pos - 1 ) | |
i = i + 1 | |
end | |
s = s + pos - 1 | |
local ch = seg:sub( pos, pos ) | |
local close_pos = find_non_escaped( str, ch, s + 1 ) | |
if close_pos then | |
segments[i] = str:sub( s, close_pos ) | |
s, f = str:find( "%S+", close_pos + 1 ) | |
i = i + 1 | |
else | |
segments[i] = str:sub( s ) | |
return segments, ch | |
end | |
elseif str:find( "^%[=*%[", s ) then -- multiline string | |
error "multiline strings are not yet supported" | |
else | |
segments[i] = seg | |
i = i + 1 | |
s, f = str:find( "%S+", f + 1 ) | |
end | |
end | |
return segments, false | |
end | |
local function microminify( line, state ) | |
local n = 1 | |
local res = {} | |
local is_word = false | |
local first_segment | |
if state.in_string then | |
local pos = find_non_escaped( line, state.string_closer, 1 ) | |
if pos then | |
first_segment = line:sub( 1, pos ) | |
line = line:sub( pos + 1 ) | |
state.in_string = false | |
else | |
first_segment = line | |
line = "" | |
end | |
end | |
local segments, strch = splitspaced( line ) | |
if first_segment then | |
table.insert( segments, 1, first_segment ) | |
end | |
if strch then | |
state.in_string = true | |
state.string_closer = strch | |
end | |
for i = 1, #segments do | |
if is_word and segments[i]:find "^[%w_]" then | |
res[n] = " " | |
n = n + 1 | |
end | |
res[n] = segments[i] | |
n = n + 1 | |
is_word = segments[i]:find "[%w_]$" | |
end | |
return table.concat( res ) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment