luaautoindent.lua
local decreaseIndentPattern = [[^\s*(elseif|else|end|\})\s*$]]
local increaseIndentPattern = [[^\s*(else|elseif|for|(local\s+)?function|if|repeat|until|while)\b((?!end).)*$|\{\s*$]]
local do_increase = false
local function getLinePositions(line_num)
local start_pos = editor:PositionFromLine(line_num)
local end_pos = start_pos + editor:LineLength(line_num)
return start_pos, end_pos
end
local function autoIndent_OnChar(ch)
if ch == "\n" then
local line_num = editor:LineFromPosition(editor.CurrentPos) - 1
local start_pos, end_pos = getLinePositions(line_num)
if editor:findtext(increaseIndentPattern, SCFIND_REGEXP, start_pos, end_pos) then
do_increase = true
end
else
local line_num = editor:LineFromPosition(editor.CurrentPos)
local start_pos, end_pos = getLinePositions(line_num)
if editor:findtext(decreaseIndentPattern, SCFIND_REGEXP, start_pos, end_pos) then
if line_num > 1 and editor.LineIndentation[line_num - 1] <= editor.LineIndentation[line_num] then
editor.LineIndentation[line_num] = editor.LineIndentation[line_num] - 4
end
end
end
return false
end
local function autoIndent_OnUpdateUI(flags)
if do_increase then
do_increase = false
editor:Tab()
end
return false
end
local function checkAutoIndent(bufferid)
while npp.RemoveEventHandler("OnChar", autoIndent_OnChar) do end
while npp.RemoveEventHandler("OnUpdateUI", autoIndent_OnUpdateUI) do end
if npp.BufferLangType[bufferid] == L_LUA then
do_increase = false
npp.AddEventHandler("OnChar", autoIndent_OnChar)
npp.AddEventHandler("OnUpdateUI", autoIndent_OnUpdateUI)
end
end
npp.AddEventHandler("OnSwitchFile", function(filename, bufferid)
checkAutoIndent(bufferid)
return false
end)
npp.AddEventHandler("OnLangChange", function()
checkAutoIndent(npp.CurrentBufferID)
return false
end)