Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ---------------------
- --Created by Savior67
- --Version: 0.4
- ---------------------
- local indent = 2 --number of spaces to indent by
- local tArgs = { ... }
- if #tArgs ~= 1 then
- print("Usage: "..shell.getRunningProgram().." <file>")
- return
- end
- local file = tArgs[1]
- function main()
- local formatted = {}
- local currentIndent = 0 --how many indents are active
- local exception = false --true if else or elseif after if
- if not fs.exists(file) then
- print("File not found.")
- return
- else
- local h = fs.open(file,"r")
- local line = h.readLine()
- while line~=nil do
- formatted,currentIndent = keyFinder(line,currentIndent,formatted)
- line = h.readLine()
- end
- h.close()
- overwrite(formatted,file)
- end
- print(file.." was successfully formatted.")
- end
- function overwrite(lines,file)
- local h = fs.open(file,"w")
- for i,line in ipairs(lines) do
- h.writeLine(line)
- end
- h.close()
- end
- function formatLine(s,currIn)
- local whitespace = ""
- for i=1,currIn do
- whitespace = whitespace.." "
- end
- return(whitespace..trim(s))
- end
- function keyFinder(s,currentIndent,f)
- local inWrds = {"if","do","repeat","function"}
- local deWrds = {"end","until"}
- local specialCase = {"elseif","else"}
- local ded = findCases(s,deWrds)
- local ind = findCases(s,inWrds)
- local spe = findCases(s,specialCase)
- if ind and ded then
- table.insert(f,formatLine(s,currentIndent))
- elseif spe then
- table.insert(f,formatLine(s,currentIndent-indent))
- elseif ded then
- currentIndent = currentIndent-indent
- table.insert(f,formatLine(s,currentIndent))
- elseif ind then
- table.insert(f,formatLine(s,currentIndent))
- currentIndent = currentIndent+indent
- else
- table.insert(f,formatLine(s,currentIndent))
- end
- return f,currentIndent
- end
- function findCases(s,t)
- for k,v in ipairs(t) do
- if string.find(s,v) then
- if not inQuotes(s,v) and not isComment(s,v) then
- return true
- end
- end
- end
- return false
- end
- function inQuotes(s,word)
- local p1 = string.find(s,"\"")
- if p1 ~= nil then
- local p2 = string.find(s,"\"",p1+1)
- if not p2 then return false end
- local start,finish = string.find(s,word)
- if p1<start and p2>finish then return true end
- end
- return false
- end
- function isComment(s,word)
- local p1=0
- while true do
- p1 = string.find(s,"-",p1+1)
- if p1~= nil then
- local p2 = string.sub(s,p1+1,p1+1)
- if p2=="-" then
- local start,finish = string.find(s,word)
- if p1<start then return true end
- end
- else
- break
- end
- end
- return false
- end
- --removes leading and trailing whitespace
- function trim(s)
- -- from PiL2 20.4
- return (s:gsub("^%s*(.-)%s*$", "%1"))
- end
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement