// Description(1033): Duplicate selected text at the end of the line
// Description(1049): Дублирует выделенный текст  в конец строки
//
// Usage:
//   Call("Scripts::Main", 1, "DuplicateSelAtEndLine.js")

var sSelText=AkelPad.GetSelText();
if (sSelText=="")
  WScript.Quit();
  // втихаря завершаем

var hEditWnd = AkelPad.GetEditWnd();
var sTitle = "Duplicate";
var nWordWrap;
var oSys = AkelPad.SystemFunction();
 
var nSelStart = AkelPad.GetSelStart();
var nSelEnd = AkelPad.GetSelEnd();

SetRedraw(hEditWnd, false);

  //Disable Word Wrap
nWordWrap = SendMessage(hEditWnd, 3241 /*AEM_GETWORDWRAP*/, 0, 0);
if (nWordWrap > 0)
  AkelPad.Command(4209 /*IDM_VIEW_WORDWRAP*/);

var nLine1 = SendMessage(hEditWnd, 1078 /*EM_EXLINEFROMCHAR*/, 0, nSelStart);
var nLine2 = SendMessage(hEditWnd, 1078 /*EM_EXLINEFROMCHAR*/, 0, nSelEnd);
if (nLine1 != nLine2)
{
SetRedraw(hEditWnd, true);
WScript.Quit();
}

var nLineEnd = GetEndLine(nLine2);

if (nWordWrap > 0)
{
AkelPad.Command(4209 /*IDM_VIEW_WORDWRAP*/);
SendMessage(hEditWnd, 3377 /*AEM_UPDATECARET*/, 0, 0);
}

AkelPad.SetSel(nLineEnd, nLineEnd);
AkelPad.ReplaceSel(sSelText);
AkelPad.SetSel(nSelStart, nSelEnd);

SetRedraw(hEditWnd, true);


function SetRedraw(hWnd, bRedraw)
{
  SendMessage(hWnd, 11 /*WM_SETREDRAW*/, bRedraw, 0);
  bRedraw && oSys.Call("User32::InvalidateRect", hWnd, 0, true);
}

function SendMessage(hWnd, uMsg, wParam, lParam)
{
  return oSys.Call("User32::SendMessage" + _TCHAR, hWnd, uMsg, wParam, lParam);
}

function GetEndLine(nLine)
{
  return SendMessage(hEditWnd, 187 /*EM_LINEINDEX*/, nLine, 0) + SendMessage(hEditWnd, 193 /*EM_LINELENGTH*/, SendMessage(hEditWnd, 187 /*EM_LINEINDEX*/, nLine, 0), 0);
}