Scite Strip Trailings

lua-users home
wiki

These Scripts remove trailing whitespace from line ends before file Saves, and contain functions to restore basic selection and view state after the process.

SciteCleanDocWhitespace has a similar script.

-----------------------------------------------------
-- Strip Trailing Spaces
-- Filename endings set here or in scite properties:
-- Luax.StripTrailSpaceEnds=.lua|.foo|readme
-- Luax.StripTLeaveEmpties=1   to leave empty lines
-- Luax.StripTReportStrips=1   to report lines stripped in output

local function isTrailingFile()
  
  if props["luax.StripsTrailSpaceEnds"]=="" then
    props["luax.StripsTrailSpaceEnds"]=".lua|.py"
  end

  if not fpatts then
    fpatts={}
    for v in string.gmatch(props["luax.StripsTrailSpaceEnds"] or"" , "[^|\"]+" ) do
      table.insert(fpatts,v)
    end
  end

  local flfnd=props["FilePath"].."\\\\"
  for _,fend in ipairs(fpatts) do
    if string.find(flfnd , fend.."\\\\",1,true) then return true end
  end
end

local function noteSelection()
 
  local c,a=editor.CurrentPos , editor.Anchor

  ntSel =
  { ['topl'] =editor.FirstVisibleLine,
    ['ccol'] =c -editor:PositionFromLine(
              editor:LineFromPosition(c)),
    ['cline']=editor:LineFromPosition(c),
    ['acol'] =a -editor:PositionFromLine(
              editor:LineFromPosition(a)),
    ['aline']=editor:LineFromPosition(a)
  }
end

local function restoreSelection()
  local c=ntSel.ccol+editor:PositionFromLine(ntSel.cline)
  local a=ntSel.acol+editor:PositionFromLine(ntSel.aline)

  if c >editor.LineEndPosition[ntSel.cline]  then
    c = editor.LineEndPosition[ntSel.cline]
  end

  if a >editor.LineEndPosition[ntSel.aline]  then
    a= editor.LineEndPosition[ntSel.aline]
  end
   
  editor.CurrentPos= c
  editor.Anchor= a
  editor.FirstVisibleLine=ntSel.topl
end
  
function stripTrailSpaces()
 
  if not isTrailingFile() then return end

  --(dunno syntax for testing props simply)
  local LeaveEmptyLines=true
  if tonumber(props['luax.StripsTLeaveEmpties'])==0 
  then LeaveEmptyLines=false end
  local ReportStrips=true
  if tonumber(props['luax.StripsTReportStrips'])==0 
  then ReportStrips=false end
  
  noteSelection()

  local e=editor
  local sfound,se,cnt = -1, 0,  0
 
  sfound,se=e:findtext("[\t ]+$", SCFIND_REGEXP, sfound+1 )
  while sfound do

    if LeaveEmptyLines and e:PositionFromLine(e:LineFromPosition(sfound))==sfound
    then
      sfound=se --skip
    else
      e:remove(sfound,se)
      cnt=cnt+1
    end

    sfound,se=e:findtext("[\t ]+$", SCFIND_REGEXP, sfound+1 )
  end

  restoreSelection()
  if ReportStrips and cnt>0 then
    print("- "..cnt.." runs of trailing spaces were stripped")
  end
end
scite_OnBeforeSave( stripTrailSpaces )

--from strainer


RecentChanges · preferences
edit · history
Last edited December 28, 2012 8:42 pm GMT (diff)