Source Code Formatter |
|
Disclaimer: You are not forced to use this script!! You may experience problems when pasting code snippets or scripts into the wiki editor because of tabs. This script is here to help you. Hopefully by having a similar source code format this wiki will look consistent and more organised. Please do not start a flame war about what is good and bad formatting. You are free to do as you please.
lua -f codeformat.lua ...options....
--file <lua file> - the Lua file to process
--ts <size> - the size of your tabs eg. --ts 4 (spaces)
--in <indent size> - number of spaces you use for indentation.
lua -f codeformat.lua --file myfile.lua --ts 4 --in 4 for files with a tab size of 4 spaces and an indent step of 4 spaces.
This program is for Lua 4.0. With Lua 5.0, look for compat.lua in your test/ directory and run the program with it loaded, e.g., lua -l /usr/share/doc/lua-5.0/test/compat.lua codeformat.lua --file myfile.lua.
-- Lua code formatter
-- Removes tabs and checks lines arent too long.
-- Nick Trout
-- $Header: /Tools/build/codefmt.lua 3 16/08/01 20:00 Nick $
mytabs = 4 -- spaces (default)
myindent = 4 -- spaces (default)
codetabsize = 8 -- spaces
codeindent = 2 -- spaces per indent
codelinelength = 80 -- characters
usage =
[[
Usage: lua -f codeformat.lua ...options...
Options are:
--file <lua file>
--ts <spaces>, tabsize: number of spaces in your tabs
--in <spaces>, indent size: number of spaces for each indentation
]]
function process_args()
-- get args set by user in command line
local t,i = {},1
while i<getn(arg) do
local a=arg[i]
if a=="--file" then
t.filename,i = arg[i+1],i+2
elseif a=="--ts" then
t.mytabsize,i = arg[i+1]+0,i+2
elseif a=="--in" then
t.myindent,i = arg[i+1]+0,i+2
else
print(usage.."Bad flag: "..a)
exit(-1)
end
end
return t
end
function readfile(f)
local fh=openfile(f,"rt")
local t={}
while 1 do
local ln=read(fh,"*l")
if ln then tinsert(t,ln) else break end
end
closefile(fh)
return t
end
-- convert any leading tabs in a given string to spaces.
-- the number of spaces to replace the tab by is given by args.mytabsize
function convertTabsToSpaces(ln)
local s,e = strfind(ln,"\t+",1)
if s and s==1 then
local spc = strrep(" ",args.mytabsize*(e-s+1))
ln = spc..strsub(ln,e+1)
end
return ln
end
-- convert any indentation to use the standard indent
function indent(ln)
local s,e = strfind(ln," +",1)
if s==1 then
local indent = (e-s+1)/args.myindent
ln = strrep(" ",codeindent*indent)..strsub(ln,e+1)
end
return ln
end
function process(lines)
for li=1,getn(lines) do
local line=lines[li]
line = convertTabsToSpaces(line)
line = indent(line)
-- warn if length too long
local len=strlen(line)
if len>codelinelength then
print("-- ######## Line too long ("..len.." chars) ######## :")
end
print(line)
end
end
args = process_args()
if not args.filename then error(usage.."no Lua file given") end
args.mytabsize = args.mytabsize or mytabs
args.myindent = args.myindent or myindent
process( readfile(args.filename) )