-- TIME_STAMP 2022-03-16 12:37:55 v 0.1 ---------------------------------------------------------------------------------------------------- --[[ in...: _line A line of text whose TAB are to be replaced by spaces. .....: _tabsize TAB size in number of characters. If it is omitted, 4 is used. out..: The line, with TAB replaced if necessary, and the number of replacements. ]] ---------------------------------------------------------------------------------------------------- TabReplace_Line = function(_line, _tabsize) if _line:find('^[\r\n]+$') then return _line, 0 end -- only a line break if _line == '' then return _line, 0 end -- only a empty string local posTab = _line:find('\t') if posTab == nil then return _line, 0 end -- no TAB included _tabsize = _tabsize or 4 -- default TAB width local tTab, s, sRep, iLen, sumLen = {}, ' ', '', 0, 0 while posTab ~= nil do -- calculation replacement string, taking into account characters to be inserted iLen = (_tabsize - ((posTab + sumLen -1) % _tabsize)) sumLen = sumLen + iLen -1 -- total length of the replacements sRep = s:rep(iLen) -- create replacement string table.insert(tTab, sRep) -- save to table posTab = _line:find('\t', posTab +1) -- find next TAB end local idx = 0 _line = _line:gsub('\t', function() idx = idx +1 return tTab[idx] end) return _line, idx end ---------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------- --[[ in...: _file Path of the file whose TAB are to be replaced by spaces. .....: _tabsize TAB size in number of characters. If it is omitted, 4 is used. out..: Success true, count-of-replacements .....: Failure false, 0 ]] ---------------------------------------------------------------------------------------------------- TabReplace_File = function(_file, _tabsize) local fh = io.open(_file, "rb") -- check if file exists if fh == nil then return false, 0 end local read = fh:read('*a') local lineBreak = read:find('\r') if lineBreak ~= nil then lineBreak = string.char(13,10) else lineBreak = string.char(10) end local nRepl, sumRepl, newLine, sWrite = 0, 0, '', '' fh:seek("set") for line in fh:lines() do newLine, nRepl = TabReplace_Line(line, _tabsize) sWrite = string.format('%s%s%s', sWrite, newLine, lineBreak) sumRepl = sumRepl + nRepl end fh:close() -- • file:lines() zerstört das Zeilenende? -- • Füge ich kein CRLF an, wird LF verwendet, was dazu führt, dass die berechneten Ersatzstrings für TAB falsch sind. -- • Füge ich CRLF an, ist das Ergebnis: "Zeileninhalt" & CR & CR & CRLF. -- • Deshalb wird das doppelte CR hier entfernt. sWrite = sWrite:gsub('\r\r', '') if sumRepl == 0 then return true, 0 end fh = io.open(_file, "w+") fh:write(sWrite) fh:close() return true, sumRepl end ----------------------------------------------------------------------------------------------------