// http://akelpad.sourceforge.net/forum/viewtopic.php?p=11960#11960
// Version: 2015-09-19
// Author: KDJ
//
// *** Replace replicate chars with one char ***
//
// Usage:
//   Call("Scripts::Main", 1, "ReplaceReplicateCharsWithOne.js")

var oSys = AkelPad.SystemFunction();

var pTxtCaption = "替换重复字符为单个字符";
var pTxtLabel   = "请输入要替换的字符 (若为空，将全部被替换):";

var hEditWnd = AkelPad.GetEditWnd();
var pChars;
var pSelTxt;
var rRE;
var i;

if (hEditWnd)
{
  if (AkelPad.GetSelStart() == AkelPad.GetSelEnd())
    AkelPad.SetSel(0, -1);

  pChars = AkelPad.InputBox(hEditWnd, pTxtCaption, pTxtLabel, pChars);

  if (pChars != undefined)
  {
    pSelTxt = AkelPad.GetSelText();

    if (! pChars) //replace all
      pSelTxt = pSelTxt.replace(/(.)\1+/g, "$1");

    else
    {
      for (i = 0; i < pChars.length ; ++i)
      {
        rRE = new RegExp("(" + escapeRegExp(pChars.charAt(i)) + ")\\1+", "g");
        pSelTxt = pSelTxt.replace(rRE, "$1");
      }
    }

    AkelPad.ReplaceSel(pSelTxt, -1);
  }
}

// function written by Infocatcher
function escapeRegExp(str)
{
  return str.replace(/[\\\/.^$+*?|()\[\]{}]/g, "\\$&");
}
