// http://akelpad.sourceforge.net/forum/viewtopic.php?p=7081#7081
// Version: 1.5
// Author: Shengalts Aleksander aka Instructor
//
//
// Description(1033): Convert tabulation to spaces.
// Description(1049): Конвертировать табуляцию в пробелы.
//
// Arguments:
// -TabStop=4     -Tab stop size in characters. If -1, use program setting (default).
//
// Usage:
// Call("Scripts::Main", 1, "TabsToSpaces.js", `-TabStop=4`)

//Arguments
var nTabStop=AkelPad.GetArgValue("TabStop", -1);

//Variables
var hWndEdit=AkelPad.GetEditWnd();
var oSys=AkelPad.SystemFunction();
var bColumnSel;
var nTabStop;
var nInitColumn=0;
var nColumn;
var nSpaceCount;
var pSelText;
var pResult;
var pSpaces;
var lpSel;
var a;
var b;

if (hWndEdit)
{
  if (lpSel=AkelPad.MemAlloc(_X64?56:32 /*sizeof(AESELECTION)*/))
  {
    if (AkelPad.SendMessage(hWndEdit, 3125 /*AEM_GETSEL*/, 0, lpSel))
      nInitColumn=AkelPad.SendMessage(hWndEdit, 3147 /*AEM_INDEXTOCOLUMN*/, 0, lpSel /*AESELECTION.crSel.ciMin*/);
    else
      AkelPad.SetSel(0, -1);
    bColumnSel=AkelPad.SendMessage(hWndEdit, 3127 /*AEM_GETCOLUMNSEL*/, 0, 0);
    if (nTabStop == -1)
      nTabStop=AkelPad.SendMessage(hWndEdit, 3239 /*AEM_GETTABSTOP*/, 0, 0);
    AkelPad.MemFree(lpSel);
  }
  else WScript.Quit();

  //Scan selection
  pSelText=AkelPad.GetSelText();
  pResult="";

  // Support DoubleByteCharacter, Such as Chinese, Janpanese, Korean...
  String.prototype.getBytesLength = function()
  {
    return this.replace(/[^\u0000-\u00ff]/gi, "--").length;
  }

  for (a=0, b=0, nColumn=nInitColumn; b < pSelText.length; ++b)
  {
    if (pSelText.charAt(b) == '\t')
    {
      nSpaceCount=nTabStop - nColumn % nTabStop;
      nColumn+=nSpaceCount;
      for (pSpaces=""; nSpaceCount; --nSpaceCount)
        pSpaces=pSpaces + " ";
      pResult+=pSelText.substr(a, b - a) + pSpaces;
      a=b + 1;
    }
    else if (pSelText.charAt(b) == '\r')
      nColumn=bColumnSel?nInitColumn:0;
    else
    {
      if (pSelText.charAt(b).getBytesLength()==2)
      {
        ++nColumn;
      }
      ++nColumn;
    }
  }
  pResult+=pSelText.substr(a, b - a);
  AkelPad.ReplaceSel(pResult, -2);
}
