Scripts discussion (3)

Discuss and announce AkelPad plugins
Locked
  • Author
  • Message
Offline
Site Admin
Posts: 6403
Joined: Thu Jul 06, 2006 7:20 am

Post by Instructor »

Kley wrote:About TabSwitch.js
Только сейчас обратил внимание, что на ноутбуке не работает жест заменяющий колесико мыши. Окно тут же пропадает и прокручивается сам документ.
Попробуйте добавить -SingleClick=false.

Offline
Posts: 202
Joined: Sat Mar 28, 2015 2:36 pm
Location: Russia

Post by Kley »

Instructor
Сожалею, но и так не заработало. А двойной клик по тачпаду, в списке, не перемещает на выбранную вкладку. Остаемся на прежней :(

Offline
Site Admin
Posts: 6403
Joined: Thu Jul 06, 2006 7:20 am

Post by Instructor »

Kley
Можете запостить версию TabSwitch.js 3.9?

Offline
Posts: 202
Joined: Sat Mar 28, 2015 2:36 pm
Location: Russia

Post by Kley »

Instructor
TabSwitch.js (v.3.9 Win-1251)

Code: Select all

// http://akelpad.sourceforge.net/forum/viewtopic.php?p=4368#p4368
// Version: 3.9
// Author: Shengalts Aleksander aka Instructor
//
//
// Description(1033): Switch between tabs.
// Description(1049): Переключение между вкладками
//
// Arguments:
// -Next=true         -Switch direction (one of the following):
//                       true   Forward switch.
//                       false  Backward switch (default).
//                       -1     Stay current.
// -CtrlTab=false     -No Ctrl+Tab hotkey is assigned to TabSwitch.js (default is true).
// -RightLeft=true    -Switch between tabs: Left-Right. Default is false - switch between tabs: Next-Previous.
// -MinTabs=2         -Minimum number of tabs before switch window appeared (default is 2).
// -TabIndex=0        -Activate tab by specified index. If used, all other arguments ignored.
// -FontName="Arial"  -Font name. Unchanged, if "".
// -FontStyle=3       -Font style (one of the following):
//                       0  ignored (default).
//                       1  normal.
//                       2  bold.
//                       3  italic.
//                       4  bold italic.
// -FontSize=10       -Font size. Unchanged, if 0 (default).
// -LineGap=10        -Space between items (default is 1).
// -SingleClick=false -Single mouse click chooses item (default is true).
// -ShowModify=2      -Show modification sign (one of the following):
//                       0  hidden.
//                       1  display asterisk * at the end (default).
//                       2  display asterisk * at the beginning.
// -OnlyNames=true    -Show only file name. Default is false - show full path.
// -WindowLeft=100    -Left window position. Special values:
//                      -1 centered (default).
//                      -2 cursor position.
// -WindowTop=100     -Top window position. Special values:
//                      -1 centered (default).
//                      -2 cursor position.
//
// Usage:
//   -"Previous (Ctrl+Tab)" Call("Scripts::Main", 1, "TabSwitch.js", `-Next=false`)
//   -"Next (Ctrl+Shift+Tab)" Call("Scripts::Main", 1, "TabSwitch.js", `-Next=true`)
//   -"Right (Ctrl+Tab)" Call("Scripts::Main", 1, "TabSwitch.js", `-RightLeft=true -Next=true`)
//   -"Left (Ctrl+Shift+Tab)" Call("Scripts::Main", 1, "TabSwitch.js", `-RightLeft=true -Next=false`)
//   -"Tab1 (Alt+1)" Call("Scripts::Main", 1, "TabSwitch.js", `-TabIndex=0`)
//   -"Tab2 (Alt+2)" Call("Scripts::Main", 1, "TabSwitch.js", `-TabIndex=1`)
// Toolbar button example:
//   -"Tab list" Call("Scripts::Main", 1, "TabSwitch.js", `-Next=-1 -CtrlTab=false -RightLeft=true -MinTabs=1 -WindowLeft=%bl -WindowTop=%bb`) Icon(0)
// ContextMenu item example:
//   -"Tab list" Call("Scripts::Main", 1, "TabSwitch.js", `-Next=-1 -CtrlTab=false -RightLeft=true -MinTabs=1 -WindowLeft=-2 -WindowTop=-2`)

//Arguments
var bNext=AkelPad.GetArgValue("Next", false);
var bCtrlTab=AkelPad.GetArgValue("CtrlTab", true);
var bRightLeft=AkelPad.GetArgValue("RightLeft", false);
var nMinTabs=AkelPad.GetArgValue("MinTabs", 2);
var nTabIndex=AkelPad.GetArgValue("TabIndex", -1);
var pFontName=AkelPad.GetArgValue("FontName", "");
var nFontStyle=AkelPad.GetArgValue("FontStyle", 0);
var nFontSize=AkelPad.GetArgValue("FontSize", 0);
var nLineGap=AkelPad.GetArgValue("LineGap", 1);
var bSingleClick=AkelPad.GetArgValue("SingleClick", true);
var nShowModify=AkelPad.GetArgValue("ShowModify", 1);
var bOnlyNames=AkelPad.GetArgValue("OnlyNames", false);
var nWindowLeft=AkelPad.GetArgValue("WindowLeft", -1);
var nWindowTop=AkelPad.GetArgValue("WindowTop", -1);

//Variables
var hMainWnd=AkelPad.GetMainWnd();
var hWndEdit=AkelPad.GetEditWnd();
var oSys=AkelPad.SystemFunction();
var hInstanceDLL=AkelPad.GetInstanceDll();
var pClassName="AkelPad::Scripts::" + WScript.ScriptName + "::" + oSys.Call("kernel32::GetCurrentProcessId");
var hWndContainer=0;
var hWndListBox=0;
var hSubClass;
var hDC;
var hBrushHollow;
var hFontEdit;
var lpFrameList=[];
var rcMain=[];
var ptPoint=[];
var nItemHeight;
var nControlWidth;
var nControlHeight;
var nCharWidth;
var nCharHeight;
var nMaxCharWidth=0;
var nMaxCharHeight=0;
var nIconSize=16;
var nIconGap=2;
var bNoSwitch=false;
var i;

if (nTabIndex >= 0)
{
  var hWndTab;
  var lpFrame;
  var nCurSel;

  hWndTab=oSys.Call("user32::GetDlgItem", hMainWnd, 10003 /*ID_TAB*/);
  if (lpFrame=AkelPad.SendMessage(hMainWnd, 1288 /*AKD_FRAMEFIND*/, 8 /*FWF_BYTABINDEX*/, nTabIndex))
    oSys.Call("user32::PostMessage" + _TCHAR, hMainWnd, 1285 /*AKD_FRAMEACTIVATE*/, 0, lpFrame);
  WScript.Quit();
}

//Get list of documents
nCurSel=GetFrameList(lpFrameList);

if (lpFrameList.length >= nMinTabs && lpFrameList.length > 0)
{
  if (bCtrlTab)
  {
    if (!(oSys.Call("user32::GetKeyState", 0x11 /*VK_CONTROL*/) & 0x8000))
    {
      //Ctrl already released
      if (lpFrameList.length >= 2)
        oSys.Call("user32::PostMessage" + _TCHAR, hMainWnd, 1285 /*AKD_FRAMEACTIVATE*/, 0, lpFrameList[nCurSel][1]);
      WScript.Quit();
    }
  }

  //Get font
  if (pFontName || nFontStyle || nFontSize)
    hFontEdit=CreateFont(pFontName, nFontStyle, nFontSize);
  else
    hFontEdit=AkelPad.SendMessage(hWndEdit, 0x31 /*WM_GETFONT*/, 0, 0);
  if (!hFontEdit) WScript.Quit();

  //Get maximum character size
  if (lpSize=AkelPad.MemAlloc(8 /*sizeof(SIZE)*/))
  {
    if (hDC=oSys.Call("user32::GetDC", hWndEdit))
    {
      oSys.Call("gdi32::SelectObject", hDC, hFontEdit);

      for (i=0; i < lpFrameList.length; ++i)
      {
        if (oSys.Call("gdi32::GetTextExtentPoint32" + _TCHAR, hDC, lpFrameList[i][0], lpFrameList[i][0].length, lpSize))
        {
          nCharWidth=AkelPad.MemRead(lpSize + 0 /*SIZE.cx*/, 3 /*DT_DWORD*/);
          nCharHeight=AkelPad.MemRead(lpSize + 4 /*SIZE.cy*/, 3 /*DT_DWORD*/);
          if (nCharWidth > nMaxCharWidth) nMaxCharWidth=nCharWidth;
          if (nCharHeight > nMaxCharHeight) nMaxCharHeight=nCharHeight;
        }
      }
      oSys.Call("user32::ReleaseDC", hWndEdit, hDC);
    }
    nMaxCharWidth+=nIconSize + nIconGap + 16;

    AkelPad.MemFree(lpSize);
  }

  //Create dialog
  if (AkelPad.WindowRegisterClass(pClassName))
  {
    if (hWndContainer=oSys.Call("user32::CreateWindowEx" + _TCHAR, 0, pClassName, 0, bCtrlTab?0x40000000 /*WS_CHILD*/:0x80000000 /*WS_POPUP*/, 0, 0, 0, 0, hMainWnd, 0, hInstanceDLL, DialogCallback))
    {
      if (hWndListBox=oSys.Call("user32::CreateWindowEx" + _TCHAR, 0, "LISTBOX", 0, 0x50600010 /*WS_VISIBLE|WS_CHILD|WS_VSCROLL|WS_DLGFRAME|LBS_OWNERDRAWFIXED*/, 0, 0, 0, 0, hWndContainer, 0, hInstanceDLL, 0))
      {
        //Make hWndContainer invisible
        hBrushHollow=oSys.Call("gdi32::GetStockObject", 5 /*HOLLOW_BRUSH*/);
        oSys.Call("user32::SetClassLong" + _TCHAR, hWndContainer, -10 /*GCL_HBRBACKGROUND*/, hBrushHollow);

        oSys.Call("user32::SetFocus", hWndListBox);
        AkelPad.SendMessage(hWndListBox, 48 /*WM_SETFONT*/, hFontEdit, 1);
        nItemHeight=nMaxCharHeight + nLineGap;
        i=AkelPad.SendMessage(hWndListBox, 0x1A1 /*LB_GETITEMHEIGHT*/, 0, 0);
        if (nItemHeight < i)
          nItemHeight=i;
        else
          AkelPad.SendMessage(hWndListBox, 0x1A0 /*LB_SETITEMHEIGHT*/, 0, nItemHeight);
        nControlHeight=lpFrameList.length * nItemHeight + oSys.Call("user32::GetSystemMetrics", 8 /*SM_CYDLGFRAME*/) * 2;
        nControlHeight=Math.min(oSys.Call("user32::GetSystemMetrics", 62 /*SM_CYMAXIMIZED*/), nControlHeight);
        nControlWidth=Math.min(oSys.Call("user32::GetSystemMetrics", 61 /*SM_CXMAXIMIZED*/) - 8, nMaxCharWidth);

        //Fill listbox
        for (i=0; i < lpFrameList.length; ++i)
          oSys.Call("user32::SendMessage" + _TCHAR, hWndListBox, 0x180 /*LB_ADDSTRING*/, 0, lpFrameList[i][0]);
        AkelPad.SendMessage(hWndListBox, 0x186 /*LB_SETCURSEL*/, nCurSel, 0);

        GetWindowPos(hMainWnd, 0, rcMain);
        if (nWindowLeft >= 0)
          rcMain.left=nWindowLeft;
        else if (nWindowLeft == -2)
        {
          GetCursorPos(ptPoint);
          rcMain.left=ptPoint.x;
        }
        else
          rcMain.left+=rcMain.right / 2 - nControlWidth / 2;
        rcMain.left=Math.min(rcMain.left, Math.max((oSys.Call("user32::GetSystemMetrics", 61 /*SM_CXMAXIMIZED*/) - 8) - nControlWidth, 0));
        if (rcMain.left < 0) rcMain.left=0;

        if (nWindowTop >= 0)
          rcMain.top=nWindowTop;
        else if (nWindowTop == -2)
        {
          GetCursorPos(ptPoint);
          rcMain.top=ptPoint.y;
        }
        else
          rcMain.top+=rcMain.bottom / 2 - nControlHeight / 2;
        rcMain.top=Math.min(rcMain.top, Math.max(oSys.Call("user32::GetSystemMetrics", 62 /*SM_CYMAXIMIZED*/) - nControlHeight, 0));
        if (rcMain.top < 0) rcMain.top=0;

        oSys.Call("user32::SetWindowPos", hWndContainer, 0, rcMain.left, rcMain.top, nControlWidth, nControlHeight, 0x14 /*SWP_NOZORDER|SWP_NOACTIVATE*/);
        oSys.Call("user32::SetWindowPos", hWndListBox, 0, 0, 0, nControlWidth, nControlHeight, 0x16 /*SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE*/);
        oSys.Call("user32::ShowWindow", hWndContainer, 5 /*SW_SHOW*/);
        oSys.Call("user32::UpdateWindow", hMainWnd);

        if (hSubClass=AkelPad.WindowSubClass(hWndListBox, ListBoxCallback, 0x87 /*WM_GETDLGCODE*/, 0x100 /*WM_KEYDOWN*/, 0x101 /*WM_KEYUP*/, 0x202 /*WM_LBUTTONUP*/, 0x203 /*WM_LBUTTONDBLCLK*/, 0x8 /*WM_KILLFOCUS*/))
        {
          //Message loop
          AkelPad.WindowGetMessage();

          AkelPad.WindowUnsubClass(hWndListBox);
        }

        if (!bNoSwitch)
        {
          i=AkelPad.SendMessage(hWndListBox, 0x188 /*LB_GETCURSEL*/, 0, 0);
          oSys.Call("user32::PostMessage" + _TCHAR, hMainWnd, 1285 /*AKD_FRAMEACTIVATE*/, 0, lpFrameList[i][1]);
        }
        //oSys.Call("user32::DestroyWindow", hWndListBox);
      }
      oSys.Call("user32::DestroyWindow", hWndContainer);
    }
    AkelPad.WindowUnregisterClass(pClassName);
  }

  //Release font
  if (pFontName || nFontStyle || nFontSize)
  {
    if (hFontEdit)
      oSys.Call("gdi32::DeleteObject", hFontEdit);
  }
}
else
{
  if (lpFrameList.length >= 2)
    oSys.Call("user32::PostMessage" + _TCHAR, hMainWnd, 1285 /*AKD_FRAMEACTIVATE*/, 0, lpFrameList[nCurSel][1]);
}

function DialogCallback(hWnd, uMsg, wParam, lParam)
{
  if (uMsg == 0x2B)  //WM_DRAWITEM
  {
    var hDC;
    var hIcon;
    var nItemID;
    var nItemState;
    var lpItem;
    var rcItem=[];
    var crText;
    var crBk;
    var hBrushBk;
    var nModeBkOld;

    hDC=AkelPad.MemRead(lParam + (_X64?32:24) /*offsetof(DRAWITEMSTRUCT, hDC)*/, 2 /*DT_QWORD*/);
    nItemID=AkelPad.MemRead(lParam + (_X64?8:8) /*offsetof(DRAWITEMSTRUCT, itemID)*/, 3 /*DT_DWORD*/);
    nItemState=AkelPad.MemRead(lParam + (_X64?16:16) /*offsetof(DRAWITEMSTRUCT, itemState)*/, 3 /*DT_DWORD*/);
    lpItem=lParam + (_X64?40:28) /*offsetof(DRAWITEMSTRUCT, rcItem)*/;
    RectToArray(lpItem, rcItem);

    //Set background
    if (nItemState & 0x1 /*ODS_SELECTED*/)
    {
      crText=oSys.Call("user32::GetSysColor", 14 /*COLOR_HIGHLIGHTTEXT*/);
      crBk=oSys.Call("user32::GetSysColor", 13 /*COLOR_HIGHLIGHT*/);
      hBrushBk=oSys.Call("user32::GetSysColorBrush", 13 /*COLOR_HIGHLIGHT*/);
    }
    else
    {
      crText=oSys.Call("user32::GetSysColor", 8 /*COLOR_WINDOWTEXT*/);
      crBk=oSys.Call("user32::GetSysColor", 5 /*COLOR_WINDOW*/);
      hBrushBk=oSys.Call("user32::GetSysColorBrush", 5 /*COLOR_WINDOW*/);
    }
    oSys.Call("user32::FillRect", hDC, lpItem, hBrushBk);
    nModeBkOld=oSys.Call("gdi32::SetBkMode", hDC, 1 /*TRANSPARENT*/);

    //Draw icon
    hIcon=AkelPad.SendMessage(hMainWnd, 1223 /*AKD_GETFRAMEINFO*/, 38 /*FI_ICONHANDLE*/, lpFrameList[nItemID][1]);
    oSys.Call("user32::DrawIconEx", hDC, rcItem.left, rcItem.top + (rcItem.bottom - rcItem.top) / 2 - nIconSize / 2, hIcon, nIconSize, nIconSize, 0, 0, 0x3 /*DI_NORMAL*/);

    //Draw text
    oSys.Call("gdi32::SetTextColor", hDC, crText);
    oSys.Call("gdi32::SetBkColor", hDC, crBk);
    oSys.Call("gdi32::TextOut" + _TCHAR, hDC, rcItem.left + nIconSize + nIconGap, rcItem.top + (rcItem.bottom - rcItem.top) / 2 - nMaxCharHeight / 2, lpFrameList[nItemID][0], lpFrameList[nItemID][0].length);

    oSys.Call("gdi32::SetBkMode", hDC, nModeBkOld);
  }
  return 0;
}

function ListBoxCallback(hWnd, uMsg, wParam, lParam)
{
  if (uMsg == 0x87 /*WM_GETDLGCODE*/)
  {
    AkelPad.WindowNoNextProc(hSubClass);
    return 0x4 /*DLGC_WANTALLKEYS*/;
  }
  else if (uMsg == 0x100 /*WM_KEYDOWN*/)
  {
    if (wParam == 0x43 /*c*/)
    {
      if (bCtrlTab || (oSys.Call("user32::GetKeyState", 0x11 /*VK_CONTROL*/) & 0x8000))
      {
        i=AkelPad.SendMessage(hWndListBox, 0x188 /*LB_GETCURSEL*/, 0, 0);
        AkelPad.SetClipboardText(lpFrameList[i][0]);
      }
    }
    else if (wParam == 0x9 /*VK_TAB*/)
    {
      var nCount;

      nCount=AkelPad.SendMessage(hWndListBox, 0x18B /*LB_GETCOUNT*/, 0, 0);
      i=AkelPad.SendMessage(hWndListBox, 0x188 /*LB_GETCURSEL*/, 0, 0);

      if (!(oSys.Call("user32::GetKeyState", 0x10 /*VK_SHIFT*/) & 0x8000))
      {
        if (++i >= nCount)
          i=0;
      }
      else
      {
        if (--i < 0)
          i=nCount - 1;
      }
      AkelPad.SendMessage(hWndListBox, 0x186 /*LB_SETCURSEL*/, i, 0);
    }
    else if (wParam == 0xD /*VK_RETURN*/)
    {
      //Exit message loop
      oSys.Call("user32::PostQuitMessage", 0);
    }
    else if (wParam == 0x1B /*VK_ESCAPE*/)
    {
      bNoSwitch=true;

      //Exit message loop
      oSys.Call("user32::PostQuitMessage", 0);
    }
  }
  else if (uMsg == 0x101 /*WM_KEYUP*/)
  {
    if (wParam == 0x11 /*VK_CONTROL*/)
    {
      if (bCtrlTab)
      {
        //Exit message loop
        oSys.Call("user32::PostQuitMessage", 0);
      }
    }
  }
  else if (uMsg == 0x202 /*WM_LBUTTONUP*/ ||
           uMsg == 0x203 /*WM_LBUTTONDBLCLK*/)
  {
    if (uMsg == 0x203 /*WM_LBUTTONDBLCLK*/ || bSingleClick)
    {
      var lResult=AkelPad.SendMessage(hWndListBox, 0x01A9 /*LB_ITEMFROMPOINT*/, 0, lParam);

      if (HIWORD(lResult) == 0)
        AkelPad.SendMessage(hWndListBox, 0x186 /*LB_SETCURSEL*/, LOWORD(lResult), 0);

      //Exit message loop
      oSys.Call("user32::PostQuitMessage", 0);
    }
  }
  else if (uMsg == 0x8)  //WM_KILLFOCUS
  {
    bNoSwitch=true;

    //Exit message loop
    oSys.Call("user32::PostQuitMessage", 0);
  }
}

function GetFrameList(lpFrameList)
{
  var lpCurFrame=AkelPad.SendMessage(hMainWnd, 1288 /*AKD_FRAMEFIND*/, 1 /*FWF_CURRENT*/, 0);
  var lpInitFrame;
  var lpFrame;
  var nCurFrame=0;
  var bModified;
  var i;

  if (bRightLeft)
    lpInitFrame=AkelPad.SendMessage(hMainWnd, 1288 /*AKD_FRAMEFIND*/, 8 /*FWF_BYTABINDEX*/, 0);
  else
    lpInitFrame=lpCurFrame;
  lpFrame=lpInitFrame;

  for (i=0; lpFrame; ++i)
  {
    lpFrameList[i]=[0, 0];
    lpFrameList[i][0]=AkelPad.MemRead(AkelPad.SendMessage(hMainWnd, 1223 /*AKD_GETFRAMEINFO*/, 32 /*FI_FILEW*/, lpFrame), 1 /*DT_UNICODE*/);
    lpFrameList[i][1]=lpFrame;
    if (bOnlyNames)
      lpFrameList[i][0]=GetFileName(lpFrameList[i][0]);
    if (nShowModify)
    {
      bModified=AkelPad.SendMessage(hMainWnd, 1223 /*AKD_GETFRAMEINFO*/, 15 /*FI_MODIFIED*/, lpFrame);
      lpFrameList[i][0]=((nShowModify == 2 && bModified)?"* ":"") + lpFrameList[i][0] + ((nShowModify == 1 && bModified)?" *":"");
    }
    if (lpFrame == lpCurFrame)
      nCurFrame=i;

    if (bRightLeft)
      lpFrame=AkelPad.SendMessage(hMainWnd, 1288 /*AKD_FRAMEFIND*/, 8 /*FWF_BYTABINDEX*/, i + 1);
    else
      lpFrame=AkelPad.SendMessage(hMainWnd, 1288 /*AKD_FRAMEFIND*/, 3 /*FWF_PREV*/, lpFrame);
    if (lpFrame == lpInitFrame) break;
  }

  //Next frame
  if (lpFrameList.length >= 2 && bNext != -1)
  {
    if ((bRightLeft && bNext) || (!bRightLeft && !bNext))
      ++nCurFrame;
    else
      --nCurFrame;
    if (nCurFrame < 0)
      nCurFrame=lpFrameList.length - 1;
    else if (nCurFrame >= lpFrameList.length)
      nCurFrame=0;
  }
  return nCurFrame;
}

function CreateFont(pFaceName, nFontStyle, nPointSize)
{
  //Release it with: oSys.Call("gdi32::DeleteObject", hFont);
  var lpLogFontSrc;
  var lpLogFontDst;
  var hDC;
  var hFont=0;
  var nHeight;
  var nWeight;
  var nItalic;

  if (lpLogFontDst=AkelPad.MemAlloc(92 /*sizeof(LOGFONTW)*/))
  {
    lpLogFontSrc=AkelPad.SendMessage(hMainWnd, 1223 /*AKD_GETFRAMEINFO*/, 48 /*FI_EDITFONTW*/, 0);
    oSys.Call("kernel32::RtlMoveMemory", lpLogFontDst, lpLogFontSrc, 92 /*sizeof(LOGFONTW)*/);

    if (nPointSize)
    {
      if (hDC=oSys.Call("user32::GetDC", hMainWnd))
      {
        nHeight=-oSys.Call("kernel32::MulDiv", nPointSize, oSys.Call("gdi32::GetDeviceCaps", hDC, 90 /*LOGPIXELSY*/), 72);
        AkelPad.MemCopy(lpLogFontDst + 0 /*offsetof(LOGFONTW, lfHeight)*/, nHeight, 3 /*DT_DWORD*/);
        oSys.Call("user32::ReleaseDC", hMainWnd, hDC);
      }
    }
    if (nFontStyle != 0 /*FS_NONE*/)
    {
      nWeight=(nFontStyle == 2 /*FS_FONTBOLD*/ || nFontStyle == 4 /*FS_FONTBOLDITALIC*/)?700 /*FW_BOLD*/:400 /*FW_NORMAL*/;
      AkelPad.MemCopy(lpLogFontDst + 16 /*offsetof(LOGFONTW, lfWeight)*/, nWeight, 3 /*DT_DWORD*/);
      nItalic=(nFontStyle == 3 /*FS_FONTITALIC*/ || nFontStyle == 4 /*FS_FONTBOLDITALIC*/)?1:0;
      AkelPad.MemCopy(lpLogFontDst + 20 /*offsetof(LOGFONTW, lfItalic)*/, nItalic, 5 /*DT_BYTE*/);
    }
    if (_TSTR == 0 /*DT_ANSI*/ && !pFaceName)
      pFaceName=AkelPad.MemRead(lpLogFontDst + 28 /*offsetof(LOGFONTW, lfFaceName)*/, 1 /*DT_UNICODE*/);
    if (pFaceName)
      AkelPad.MemCopy(lpLogFontDst + 28 /*offsetof(LOGFONTW, lfFaceName)*/, pFaceName.substr(0, 32 /*LF_FACESIZE*/), _TSTR);

    hFont=oSys.Call("gdi32::CreateFontIndirect" + _TCHAR, lpLogFontDst);
    AkelPad.MemFree(lpLogFontDst);
  }
  return hFont;
}

function GetFileName(pFile)
{
  var nOffset=pFile.lastIndexOf("\\");

  if (nOffset != -1)
    pFile=pFile.substr(nOffset + 1);
  return pFile;
}

function RectToArray(lpRect, rcRect)
{
  rcRect.left=AkelPad.MemRead(lpRect, 3 /*DT_DWORD*/);
  rcRect.top=AkelPad.MemRead(lpRect + 4, 3 /*DT_DWORD*/);
  rcRect.right=AkelPad.MemRead(lpRect + 8, 3 /*DT_DWORD*/);
  rcRect.bottom=AkelPad.MemRead(lpRect + 12, 3 /*DT_DWORD*/);
  return rcRect;
}

function GetCursorPos(ptPoint)
{
  var lpPoint;

  ptPoint.x=0;
  ptPoint.y=0;

  if (lpPoint=AkelPad.MemAlloc(8 /*sizeof(POINT)*/))
  {
    if (oSys.Call("user32::GetCursorPos", lpPoint))
    {
      ptPoint.x=AkelPad.MemRead(lpPoint + 0 /*offsetof(POINT, x)*/, 3 /*DT_DWORD*/);
      ptPoint.y=AkelPad.MemRead(lpPoint + 4 /*offsetof(POINT, y)*/, 3 /*DT_DWORD*/);
    }
    AkelPad.MemFree(lpPoint);
  }
}

function GetWindowPos(hWnd, hWndOwner, rcRect)
{
  var lpRect;
  var bResult=false;

  //Get rect
  if (lpRect=AkelPad.MemAlloc(16 /*sizeof(RECT)*/))
  {
    if (oSys.Call("user32::GetWindowRect", hWnd, lpRect))
    {
      RectToArray(lpRect, rcRect);
      rcRect.right-=rcRect.left;
      rcRect.bottom-=rcRect.top;

      if (hWndOwner)
        bResult=oSys.Call("user32::ScreenToClient", hWndOwner, lpRect);
      else
        bResult=true;
      rcRect.left=AkelPad.MemRead(lpRect, 3 /*DT_DWORD*/);
      rcRect.top=AkelPad.MemRead(lpRect + 4, 3 /*DT_DWORD*/);
    }
    AkelPad.MemFree(lpRect);
  }
  return bResult;
}

function LOWORD(dwNumber)
{
  return (dwNumber & 0xffff);
}

function HIWORD(dwNumber)
{
  return (dwNumber >> 16);
}

function MAKELONG(a, b)
{
  return (a & 0xffff) | ((b & 0xffff) << 16);
}

p.s. X64 Win7

Offline
Posts: 1873
Joined: Mon Aug 06, 2007 1:07 pm
Contact:

Post by Infocatcher »

Instructor
Кажется, пора и не идущие в комплекте скрипты подселить в репозиторий. :)

Offline
Posts: 276
Joined: Mon Jun 20, 2011 8:33 am
Location: Электросталь

Post by yozhic »

Instructor
Возникло недоумение, подскажите, пожалуйста. В Include\ShowMenu.js константа MF_HILITE. Пункт меню подсвечивается, но не работает, т.е. при нажатии Enter возвращает nItem == -1. Если при вызове меню нажать "стрелку вниз", то визуально ничего не меняется, подсветка как была на первом пункте, так и осталась, но уже становится работоспособной. Возможно я неправильно понял значение фразы "Item is highlighted"? Или это ошибка?

SFC
Offline
Posts: 24
Joined: Sun Jul 12, 2015 9:37 am

Вопрос по скрипту ShowMenuEx.js

Post by SFC »

При вызове скрипта SearchReplace_multi.js или даже при вызове скрипта test.js с рекомендованным содержанием, появляется окно:
'Option -pExt or pFile should be set'
Папка Params создана, там ничего нет понятно пока. Создание там пустых файлов с именем таких скриптов ни чего не меняет.
Скрипт старый multi_sr работает без проблем.

Что может быть.

Offline
Posts: 1162
Joined: Sun Oct 20, 2013 11:44 am

Post by Skif_off »

SFC
У вас сборка? Какая версия AkelPad?

SFC
Offline
Posts: 24
Joined: Sun Jul 12, 2015 9:37 am

Post by SFC »

Skif_off wrote: У вас сборка? Какая версия AkelPad?
AkelPad 4.9.4 x86 en установлен не в ProgramFiles а в другое место, открывается по вызову блокнота. система XPSP2
не сборка, - обычная версия, обновляемая через updater.
Обычный набор скриптов который идет с плагином и в папке Include два файла: ShowMenuEx и ShowMenu
Из доп. скриптов, которых нет в стандартном наборе: Multi_SR, NumberCount, OpenSaveMask, RenameFile

Offline
Posts: 382
Joined: Wed Sep 28, 2011 3:05 pm

Post by Cuprum »

VladSh
Хотелось бы, чтобы в скрипте NewFilebyRecent.js проверялось, включен ли плагин Templates, и если да, то не показывать окно выбора шаблона файла:

Code: Select all

AkelPad.Command(4101, 1);

Offline
Posts: 3234
Joined: Wed Nov 29, 2006 1:19 pm
Location: Киев, Русь
Contact:

Post by VladSh »

SFC
Надо SearchReplace_multi.js переделывать под новый ShowMenuEx.js. Попробую разобраться.

Cuprum
Спасибо за баг-репорт.
Пришлось выключать/включать Templates-плагин, иначе не получалось. Пробуйте.

KDJ
Offline
Posts: 1949
Joined: Sat Mar 06, 2010 7:40 pm
Location: Poland

Post by KDJ »

VladSh
How to avoid conflict with Templates plugin after AkelPad.Command(4101):
Cuprum wrote:

Code: Select all

AkelPad.Command(4101, 1);
Read here: http://akelpad.sourceforge.net/forum/vi ... 7695#17695

Offline
Posts: 3234
Joined: Wed Nov 29, 2006 1:19 pm
Location: Киев, Русь
Contact:

Post by VladSh »

KDJ
Thanks!)

Cuprum
NewFilebyRecent.js откорректировал.

SFC
Переделал

Code: Select all

// Description(1033): Multi search and replace using regular expressions
// http://akelpad.sourceforge.net/forum/viewtopic.php?p=8780#p8780
// Version: 1.1 (2015.07.14)
// Author: cnnnc
// Modified: VladSh
//
//  Come by official "SearchReplace.js", and others js. Thanks!
//
//  Use pattern file to handle file(s).
//
// Call Example:
// -"Chinese Simplify" Call("Scripts::Main", 1, "SearchReplace_Multi.js", `-pattern="ChineseSimplify.txt"`)
// -"SearchReplace_Multi" Call("Scripts::Main", 1, "SearchReplace_Multi.js")
//
// Arguments:
// 	-pattern - pattern filename, -pattern="?" or if there is no argument or the pattern is not a exist file then will show the list for a pattern file choise (from filesystem)
// 	The description of the -pExt or -pFile arguments look in ShowMenuEx.js;
// 		-pExt or -pFile can be set in arguments or in SearchReplace_Multi.ini file.
// 		If it set then popup a menu about all available pattern files that listed in the corresponding param-file.
// 
// Example of SearchReplace_Multi.ini:
// [Options]
// pExt=txt
// 
// The pattern files has to be placed in the folder of [AkelPad]\AkelFiles\Plugs\Scripts\Params\SearchReplace_Multi\.
//
// Below is example of pattern format of file :
// [Description]
// The content of description about this pattern file.
// [Options]
// RegExp=0
// Sensitive=1
// Multiline=0
// EscSequences=0
// ReplaceFunction=0
// Direction=8
// [SearchReplace]
// Notepad.exe   AkelPad.exe   Replace "notepad.exe" (ignore case) with "AkelPad.exe".
//
// The usage of four sections [Description], [Options], [SearchReplace] and [SearchReplaceAll]:
// [Description]   The content of its below is only descript what about the pattern file, won't be eval and handled.
// [Options]   Argument of option, the content of its below will be executed by method of eval.
//       Regular Expression:     RegExp            0 or 1, Default is 1
//       Case sensitive:     Sensitive         0 or 1, Default is 0
//       Multiline:           Multiline         0 or 1, Default is 0
//       Escape Sequences:     EscSequences      0 or 1, Default is 0
//       Replace function:   ReplaceFunction   0 or 1, Default is 0. If be set to 1, bEscSequences will be set to 0.
//       Direction:      Direction    1  /* DN_DOWN      =0x00000001 */ Search Forward.
//                                  2  /* DN_UP        =0x00000002 */ Search Backward.
//                                  4  /* DN_BEGINNING =0x00000004 */ Search from Beginning to Ending. (Default)
//                                  8  /* DN_SELECTION =0x00000008 */ Search in selection (When no selection, select all).
//                                  16 /* DN_ALLFILES  =0x00000010 */ Search in all files.
//
// [SearchReplace]   The content of its below must be separated by a TAB. The both side of every line's first TAB, left is the content of what to Search, right is Replace with.
//       More of ONE Tab’s right side always is treated as comment only.
//       \\ - Back slace char
//       \r - Return char
//       \n - new feed char
//       \t - TAB char
//       What:        pFindIt                Could not be Empty
//       With:        pReplaceWith           Could not same as pFindIt if bSensitive is true.
//
// [SearchReplaceAll] is similar to [SearchReplace], but its below are treated as the content of search and replace only, any section header won't be action.

try
{
  var hMainWnd=AkelPad.GetMainWnd();
}
catch (oError)
{
  WScript.Quit();
}

//Options
var bShowCountOfChanges=false;
var nFilterIndex=2;

//Buttons
var BT_REPLACEALL =4;

//Direction
var DN_DOWN      =0x00000001;
var DN_UP        =0x00000002;
var DN_BEGINNING =0x00000004;
var DN_SELECTION =0x00000008;
var DN_ALLFILES  =0x00000010;

var pScriptName = WScript.ScriptName;
var pInitialDir = AkelPad.GetAkelDir(5) + "\\Params\\" + pScriptName.substring(0, pScriptName.lastIndexOf(".")) + "\\";

var pFile;

var WshShell = new ActiveXObject("WScript.shell");
var fso = new ActiveXObject("Scripting.FileSystemObject");
var oSys=AkelPad.SystemFunction();
var nAkelEdit=AkelPad.IsAkelEdit();

var pFindIt;
var pReplaceWith;
var pReplaceWithEsc;
var pStringsArray;
var bRegExp           =1;
var bSensitive        =0;
var bMultiline        =0;
var bEscSequences     =0;
var bReplaceFunction  =0;
var nDirection        =0;
var nDirectionFirst   =0;
var bDescription=bOptions=bSearchReplace=bSearchReplaceAll=false;

var nButton           =BT_REPLACEALL;

var STRID_FILTER       =21;
var STRID_SYNTAXERROR  =22;
var STRID_SAME         =23;
var STRID_COUNTFILES   =24;
var STRID_COUNTCHANGES =25;
var STRID_ERROROPTIONS =26;

var nFilterIndex=2;

var oPattern;
var pSelText;
var nInitialSelStart;
var nInitialSelEnd;
var nSelStart;
var nSelEnd;
var lpInitialScroll;
var nMatches=0;
var nChangesCur=0;
var nChanges=0;
var nChangedFiles=0;
var nResult=-1;
var i;

var pattern = AkelPad.GetArgValue("pattern", "");
if (pattern) {
  if (pattern != "?") pFile = getEnvironmentPath(pInitialDir + pattern);
  if (!pFile) {
    pFile = FileDialog(true, hMainWnd, pInitialDir + "*", GetLangString(STRID_FILTER), nFilterIndex);
    if (!pFile) WScript.Quit();
  }
}
else {
  if (! AkelPad.Include("ShowMenuEx.js")) WScript.Quit();
  if (!opts.pExt) opts.pExt = "txt";
  pFile = pInitialDir + getSelectedMenuItem(POS_CURSOR, false);
  pFile = getEnvironmentPath(pFile);
  if (!pFile) WScript.Quit();
}

var pText;

if (!(pText=AkelPad.ReadFile(pFile))) WScript.Quit();

pText=pText.replace(/\r\n|\r|\n/g, "\r");
var pLinesArray   =pText.split("\r");

var lpFrameInit=AkelPad.SendMessage(hMainWnd, 1288 /*AKD_FRAMEFIND*/, 1 /*FWF_CURRENT*/, 0);
var hWndEdit=AkelPad.GetEditWnd();

var d=new Date();
var t=d.getTime();

for (;;)
{
  try
  {
    var nIndex=-1;

    while (++nIndex < pLinesArray.length-1)
    {
      pFindIt=null;
      pReplaceWith=null;
      pReplaceWithEsc=null;
      pStringsArray=null;
      CollectGarbage();

      if (!bSearchReplaceAll)
      {
        if (pLinesArray[nIndex]=="[SearchReplaceAll]")
        {
          bSearchReplaceAll=true;

          MakeSelection();

          continue;
        }
        else if (pLinesArray[nIndex]=="[Description]")
        {
          bDescription=true;
          bOptions=false;
          bSearchReplace=false;
          continue;
        }
        else if (pLinesArray[nIndex]=="[Options]")
        {
          bDescription=false;
          bOptions=true;
          bSearchReplace=false;
          continue;
        }
        else if (pLinesArray[nIndex]=="[SearchReplace]")
        {
          bDescription=false;
          bOptions=false;
          bSearchReplace=true;
          continue;
        }
        else
        {
          if (bDescription)
          {
            continue;
          }
          else if (bOptions)
          {
            if (pLinesArray[nIndex]=="RegExp=1")
              bRegExp=1;
            else if (pLinesArray[nIndex]=="RegExp=0")
              bRegExp=0;
            else if (pLinesArray[nIndex]=="Sensitive=1")
              bSensitive=1;
            else if (pLinesArray[nIndex]=="Sensitive=0")
              bSensitive=0;
            else if (pLinesArray[nIndex]=="Multiline=1")
              bMultiline=1;
            else if (pLinesArray[nIndex]=="Multiline=0")
              bMultiline=0;
            else if (pLinesArray[nIndex]=="EscSequences=1")
              bEscSequences=1;
            else if (pLinesArray[nIndex]=="EscSequences=0")
              bEscSequences=0;
            else if (pLinesArray[nIndex]=="ReplaceFunction=1")
              bReplaceFunction=1;
            else if (pLinesArray[nIndex]=="ReplaceFunction=0")
              bReplaceFunction=0;
            else if (pLinesArray[nIndex]=="Direction=1")
              nDirection=1;
            else if (pLinesArray[nIndex]=="Direction=2")
              nDirection=2;
            else if (pLinesArray[nIndex]=="Direction=4")
              nDirection=4;
            else if (pLinesArray[nIndex]=="Direction=8")
              nDirection=8;
            else if (pLinesArray[nIndex]=="Direction=16")
              nDirection=16;

            if (nDirectionFirst)
            {
              nDirection=nDirectionFirst;
            }
            else
            {
              if (nDirection)
              {
                if (nDirection==DN_DOWN || nDirection==DN_UP || nDirection==DN_BEGINNING || nDirection==DN_SELECTION || nDirection==DN_ALLFILES)
                {
                }
                else
                {
                  nDirection=DN_BEGINNING;
                }
                nDirectionFirst=nDirection;
              }
            }
            continue;
          }
          else if (bSearchReplace)
          {
            MakeSelection();
          }
          else
          {
            continue;
          }
        }
      }

      pStringsArray=pLinesArray[nIndex].split("\t");
      pFindIt=pStringsArray[0];
      if (pStringsArray[1]) pReplaceWith=pStringsArray[1];
      else pReplaceWith="";

      if (pFindIt=="")
      {
        continue;
      }

      if (bSensitive && pFindIt==pReplaceWith)
      {
        MessageBox(hMainWnd, GetLangString(STRID_SAME)+(nIndex+1).toString(), pScriptName, 64 /*MB_ICONINFORMATION*/);
        continue;
      }

      if (bRegExp && AkelPad.Include("cnRegExp.js")) pFindIt=cnRegExp(pFindIt);

      try
      {
        oPattern=new RegExp((bRegExp?pFindIt:PatternToString(pFindIt)), (bSensitive?"":"i") + ((nButton == BT_REPLACEALL || nDirection & DN_UP)?"g":"") + (bMultiline?"m":""));
      }
      catch (oError)
      {
        MessageBox(hMainWnd, oError.description, pScriptName, 16 /*MB_ICONERROR*/);
        continue;
      }

      if (nChangesCur)
      {
        if (bShowCountOfChanges)
        {
          nMatches=pSelText.match(oPattern);
          nMatches=nMatches?nMatches.length:0;
          nChangesCur+=nMatches;
        }
      }
      else
      {
        nMatches=pSelText.match(oPattern);
        nMatches=nMatches?nMatches.length:0;
        nChangesCur+=nMatches;
      }

      if (nMatches)
      {
        pReplaceWithEsc=pReplaceWith;
        if (bRegExp && bReplaceFunction)
        {
          //Replace with function: Infocatcher's code.
          if (!/(^|[^\w.])return(\s+\S|\s*\()/.test(pReplaceWithEsc))
            pReplaceWithEsc="return " + pReplaceWithEsc;
          pReplaceWithEsc='var args={}, l=arguments.length;'
                        + 'for (var i=0; i < l; ++i)\n'
                        + '  args["$" + i]=arguments[i];\n'
                        + 'args.offset=arguments[l - 2];\n'
                        + 'args.s=arguments[l - 1];\n'
                        + 'with (args)\n'
                        + '{\n'
                        +    pReplaceWithEsc
                        + '\n}';
          try
          {
            pReplaceWithEsc=new Function(pReplaceWithEsc);
          }
          catch (oError)
          {
            MessageBox(hMainWnd, oError.description, pScriptName, 16 /*MB_ICONERROR*/);
            WScript.Quit();
          }
        }
        else if (bEscSequences)
        {
          if (!bRegExp)
          {
            if (!(pFindIt=TranslateEscapeString(pFindIt)))
            {
              MessageBox(hMainWnd, GetLangString(STRID_SYNTAXERROR), pScriptName, 16 /*MB_ICONERROR*/);
              WScript.Quit();
            }
          }
        }

        if (!bReplaceFunction && pReplaceWithEsc)
        {
          if (bEscSequences)
          {
            pReplaceWithEsc=pReplaceWithEsc.replace(/\\\\/g, "\0");

            if (bRegExp && pFindIt.search(/\([^\(\)]*?\)/g) != -1)
            {
              if (pReplaceWithEsc.search(/\\[^rnt1-9]/g) != -1)
              {
                MessageBox(hWndDialog, GetLangString(STRID_SYNTAXERROR), pScriptName, 16 /*MB_ICONERROR*/);
                oSys.Call("user32::SetFocus", hWndWith);
                WScript.Quit();
              }
            }
            else
            {
              if (pReplaceWithEsc.search(/\\[^rnt]/g) != -1)
              {
                MessageBox(hWndDialog, GetLangString(STRID_SYNTAXERROR), pScriptName, 16 /*MB_ICONERROR*/);
                oSys.Call("user32::SetFocus", hWndWith);
                WScript.Quit();
              }
            }

            pReplaceWithEsc=pReplaceWithEsc.replace(/\\r\\n|\\r|\\n/g, "\n");
            pReplaceWithEsc=pReplaceWithEsc.replace(/\\t/g, "\t");
          }

          if (bRegExp && pFindIt.search(/\([^\(\)]*?\)/g) != -1)
          {
            pReplaceWithEsc=pReplaceWithEsc.replace(/\\(\d)/g,"$$$1");
          }

          if (bEscSequences)
          {
            pReplaceWithEsc=pReplaceWithEsc.replace(/\0/g, "\\");
          }
        }
        pSelText=pSelText.replace(oPattern, pReplaceWithEsc);
      }
    }

    if (nChangesCur)
    {
      if (bShowCountOfChanges)
      {
        ++nChangedFiles;
        nChanges+=nChangesCur;
        nChangesCur=0;
      }

      var nFirstLine;
      var nInitialLine;
      var nInitialCharInLine;

      //Save selection
      nFirstLine=SaveLineScroll(hWndEdit);
      nInitialLine=AkelPad.SendMessage(hWndEdit, 1078 /*EM_EXLINEFROMCHAR*/, 0, nInitialSelStart);
      nInitialCharInLine=nInitialSelStart - AkelPad.SendMessage(hWndEdit, 187 /*EM_LINEINDEX*/, nInitialLine, 0);

      //Replace selection
      if (nAkelEdit)
      {
        if (nDirection & DN_SELECTION)
        {
          if (AkelPad.SendMessage(hWndEdit, 3127 /*AEM_GETCOLUMNSEL*/, 0, 0))
          {
            dwOptions=AkelPad.SendMessage(hWndEdit, 3227 /*AEM_GETOPTIONS*/, 0, 0);
            if (!(dwOptions & 0x40 /*AECO_PASTESELECTCOLUMN*/))
              AkelPad.SendMessage(hWndEdit, 3228 /*AEM_SETOPTIONS*/, 2 /*AECOOP_OR*/, 0x40 /*AECO_PASTESELECTCOLUMN*/);
            AkelPad.ReplaceSel(pSelText);
            if (!(dwOptions & 0x40 /*AECO_PASTESELECTCOLUMN*/))
              AkelPad.SendMessage(hWndEdit, 3228 /*AEM_SETOPTIONS*/, 4 /*AECOOP_XOR*/, 0x40 /*AECO_PASTESELECTCOLUMN*/);
          }
          else
          {
            AkelPad.ReplaceSel(pSelText);
            AkelPad.SetSel(nSelStart, nSelStart + pSelText.length, 0x8 /*AESELT_LOCKSCROLL*/);
          }
        }
        else
        {
          AkelPad.SetSel(nSelStart, nSelEnd, 0x8 /*AESELT_LOCKSCROLL*/);

          //Replace selection
          AkelPad.ReplaceSel(pSelText);

          i=AkelPad.SendMessage(hWndEdit, 187 /*EM_LINEINDEX*/, nInitialLine, 0) + nInitialCharInLine;
          AkelPad.SetSel(i, i + (nInitialSelEnd - nInitialSelStart), 0x8 /*AESELT_LOCKSCROLL*/);
        }
        pSelText=null;
        CollectGarbage();
      }

      RestoreLineScroll(hWndEdit, nFirstLine);
    }

    if (nDirection & DN_ALLFILES)
    {
      nDirection&=~DN_DOWN;
      //Next MDI frame
      lpFrameCur=AkelPad.Command(4316 /*IDM_WINDOW_FRAMENEXT*/);
      hWndEdit=AkelPad.GetEditWnd();

      if (lpFrameCur != lpFrameInit)
      {
        continue;
      }
    }

    if (bShowCountOfChanges)
    {
      if (nDirection & DN_ALLFILES)
        MessageBox(hMainWnd, GetLangString(STRID_COUNTFILES) + nChangedFiles + "\n" + GetLangString(STRID_COUNTCHANGES) + nChanges, pScriptName, 64 /*MB_ICONINFORMATION*/);
      else
        MessageBox(hMainWnd, GetLangString(STRID_COUNTCHANGES) + nChanges, pScriptName, 64 /*MB_ICONINFORMATION*/);
    }
  }
  catch (oError)
  {
    MessageBox(hMainWnd, oError.description, pScriptName, 16 /*MB_ICONERROR*/);
  }
  break;
}
var d=new Date();
t=(d.getTime()-t)/1000;

if (Math.round(t)>1) MessageBox(hMainWnd, "    "+t.toFixed(3)+" s", pScriptName, 0 /*MB_OK*/);


//Functions
function FileDialog(bOpenTrueSaveFalse, hWnd, pInitialFile, pFilter, nFilterIndex)
{
  var nFlags=0x880804; //OFN_HIDEREADONLY|OFN_PATHMUSTEXIST|OFN_EXPLORER|OFN_ENABLESIZING
  var pDefaultExt="txt";
  var lpStructure;
  var lpFilterBuffer;
  var lpFileBuffer;
  var lpExtBuffer;
  var oSys;
  var pResultFile="";
  var nCallResult;

  if (lpFilterBuffer=AkelPad.MemAlloc(256 * _TSIZE))
  {
    AkelPad.MemCopy(lpFilterBuffer, pFilter.substr(0, 255), _TSTR);

    if (lpFileBuffer=AkelPad.MemAlloc(256 * _TSIZE))
    {
      AkelPad.MemCopy(lpFileBuffer, pInitialFile.substr(0, 255), _TSTR);

      if (lpExtBuffer=AkelPad.MemAlloc(256 * _TSIZE))
      {
        AkelPad.MemCopy(lpExtBuffer, pDefaultExt.substr(0, 255), _TSTR);

        if (lpStructure=AkelPad.MemAlloc(_X64?136:76))  //sizeof(OPENFILENAMEA) or sizeof(OPENFILENAMEW)
        {
          //Fill structure
          AkelPad.MemCopy(lpStructure, _X64?136:76, 3 /*DT_DWORD*/);                     //lStructSize
          AkelPad.MemCopy(lpStructure + (_X64?8:4), hWnd, 2 /*DT_QWORD*/);               //hwndOwner
          AkelPad.MemCopy(lpStructure + (_X64?24:12), lpFilterBuffer, 2 /*DT_QWORD*/);   //lpstrFilter
          AkelPad.MemCopy(lpStructure + (_X64?44:24), nFilterIndex, 3 /*DT_DWORD*/);     //nFilterIndex
          AkelPad.MemCopy(lpStructure + (_X64?48:28), lpFileBuffer, 2 /*DT_QWORD*/);     //lpstrFile
          AkelPad.MemCopy(lpStructure + (_X64?56:32), 256, 3 /*DT_DWORD*/);              //nMaxFile
          AkelPad.MemCopy(lpStructure + (_X64?96:52), nFlags, 3 /*DT_DWORD*/);           //Flags
          AkelPad.MemCopy(lpStructure + (_X64?104:60), lpExtBuffer, 2 /*DT_QWORD*/);     //lpstrDefExt

          if (oSys=AkelPad.SystemFunction())
          {
            //Call dialog
            if (bOpenTrueSaveFalse == true)
              nCallResult=oSys.Call("comdlg32::GetOpenFileName" + _TCHAR, lpStructure);
            else
              nCallResult=oSys.Call("comdlg32::GetSaveFileName" + _TCHAR, lpStructure);

            //Result file
            if (nCallResult) pResultFile=AkelPad.MemRead(lpFileBuffer, _TSTR);
          }
          AkelPad.MemFree(lpStructure);
        }
        AkelPad.MemFree(lpExtBuffer);
      }
      AkelPad.MemFree(lpFileBuffer);
    }
    AkelPad.MemFree(lpFilterBuffer);
  }
  return pResultFile;
}

function getEnvironmentPath(paths)
{
  var path = WshShell.ExpandEnvironmentStrings(paths);
  if (fso.FileExists(path)) return path;
  return "";
}

function SaveLineScroll(hWnd)
{
  AkelPad.SendMessage(hWnd, 11 /*WM_SETREDRAW*/, false, 0);
  return AkelPad.SendMessage(hWnd, 3129 /*AEM_GETLINENUMBER*/, 4 /*AEGL_FIRSTVISIBLELINE*/, 0);
}

function RestoreLineScroll(hWnd, nBeforeLine)
{
  if (AkelPad.SendMessage(hWnd, 3129 /*AEM_GETLINENUMBER*/, 4 /*AEGL_FIRSTVISIBLELINE*/, 0) != nBeforeLine)
  {
    var lpScrollPos;
    var nPosY=AkelPad.SendMessage(hWnd, 3198 /*AEM_VPOSFROMLINE*/, 0 /*AECT_GLOBAL*/, nBeforeLine);

    if (lpScrollPos=AkelPad.MemAlloc(_X64?16:8 /*sizeof(POINT64)*/))
    {
      AkelPad.MemCopy(lpScrollPos, -1, 2 /*DT_QWORD*/);
      AkelPad.MemCopy(lpScrollPos + (_X64?8:4), nPosY, 2 /*DT_QWORD*/);
      AkelPad.SendMessage(hWnd, 3180 /*AEM_SETSCROLLPOS*/, 0, lpScrollPos);
      AkelPad.MemFree(lpScrollPos);
    }
  }
  AkelPad.SendMessage(hWnd, 3377 /*AEM_UPDATECARET*/, 0, 0);
  AkelPad.SendMessage(hWnd, 11 /*WM_SETREDRAW*/, true, 0);
  oSys.Call("user32::InvalidateRect", hWnd, 0, true);
}

function MessageBox(hHandle, pText, pCaption, nType)
{
  var nResult;

  bMessageBox=true;
  nResult=AkelPad.MessageBox(hHandle, pText, pCaption, nType);
  bMessageBox=false;
  return nResult;
}

function TranslateEscapeString(pString)
{
  pString=pString.replace(/\\\\/g, "\0");
  if (pString.search(/\\[^rnt]/g) != -1)
    return "";
  pString=pString.replace(/\\r\\n|\\r|\\n/g, "\n");
  pString=pString.replace(/\\t/g, "\t");
  pString=pString.replace(/\0/g, "\\");
  return pString;
}

function PatternToString(pPattern)
{
  var pString="";
  var pCharCode;
  var i;

  for (i=0; i < pPattern.length; ++i)
  {
    pCharCode=pPattern.charCodeAt(i).toString(16);
    while (pCharCode.length < 4) pCharCode="0" + pCharCode;
    pString=pString + "\\u" + pCharCode;
  }
  return pString;
}


function MakeSelection()
{
  if (nDirectionFirst)
  {
    if (nDirection!=nDirectionFirst) nDirection=nDirectionFirst;
  }
  else
  {
    if (nDirection==DN_DOWN || nDirection==DN_UP || nDirection==DN_BEGINNING || nDirection==DN_SELECTION || nDirection==DN_ALLFILES)
    {
    }
    else
    {
      nDirection=DN_BEGINNING;
    }
    nDirectionFirst=nDirection;
  }

  if (pSelText==undefined || pSelText==null)
  {
    nInitialSelStart=AkelPad.GetSelStart();
    nInitialSelEnd=AkelPad.GetSelEnd();

    //Get ranges
    if (nDirection & DN_DOWN)
    {
      nSelStart=nInitialSelStart;
      nSelEnd=-1;
    }
    else if (nDirection & DN_UP)
    {
      nSelStart=0;
      nSelEnd=nInitialSelEnd;
    }
    else if (nDirection & DN_BEGINNING)
    {
      nSelStart=0;
      nSelEnd=-1;
    }
    else if (nDirection & DN_SELECTION)
    {
      if (AkelPad.SendMessage(hWndEdit, 3125 /*AEM_GETSEL*/, 0, 0))
      {
        nSelStart=nInitialSelStart;
        nSelEnd=nInitialSelEnd;
      }
      else
      {
        nSelStart=0;
        nSelEnd=-1;
        nDirection=DN_BEGINNING;
      }
    }
    else if (nDirection & DN_ALLFILES)
    {
      nSelStart=0;
      nSelEnd=-1;
    }

    if (nAkelEdit && AkelPad.SendMessage(hWndEdit, 3127 /*AEM_GETCOLUMNSEL*/, 0, 0) && (nDirection & DN_SELECTION))
      pSelText =AkelPad.GetSelText(2);
    else
      pSelText=AkelPad.GetTextRange(nSelStart, nSelEnd, 2 /*\n*/);
  }

  if (bRegExp != 0) bRegExp=1;
  if (bSensitive != 1) bSensitive=0;
  if (bMultiline != 1) bMultiline=0;
  if (bEscSequences != 1) bEscSequences=0;
  if (bReplaceFunction != 1)
  {
    bReplaceFunction=0;
  }
  else
  {
    bEscSequences=0;
  }

  if (nButton!=BT_REPLACEALL) nButton=BT_REPLACEALL;
}


function GetLangString(nStringID)
{
  var nLangID=AkelPad.GetLangId(1 /*LANGID_PRIMARY*/);

  if (nLangID == 0x4) //LANG_CHINESE
  {
    if (nStringID == STRID_FILTER)
      return "所有文件 (*.*)\x00*.*\x00文本文件 (*.txt)\x00*.txt\x00\x00";
    if (nStringID == STRID_SYNTAXERROR)
      return "语法错误:\n \\\\ - 反斜线\n \\r - 换行符\n \\t - 制表符";
    if (nStringID == STRID_SAME)
      return "查找内容与替换内容相同。行号为: ";
    if (nStringID == STRID_COUNTFILES)
      return "替换文件数: ";
    if (nStringID == STRID_COUNTCHANGES)
      return "替换次数: ";
    if (nStringID == STRID_ERROROPTIONS)
      return "选项错误。行号为: ";
  }
  else
  {
    if (nStringID == STRID_FILTER)
      return "All Files (*.*)\x00*.*\x00Text files (*.txt)\x00*.txt\x00\x00";
    if (nStringID == STRID_SYNTAXERROR)
      return "Syntax error:\n \\\\ - backslash\n \\r - line feed\n \\t - tabulation";
    if (nStringID == STRID_SAME)
      return "the content of Find equal to Replace's. Line #: ";
    if (nStringID == STRID_COUNTFILES)
      return "Changed files: ";
    if (nStringID == STRID_COUNTCHANGES)
      return "Count of changes: ";
    if (nStringID == STRID_ERROROPTIONS)
      return "Options error. Line #: ";
  }
  return "";
}
.
+ Изменил комменты в скрипте по поводу задания аргументов.
Файл со списком имён файлов паттернов должен находиться в ...\AkelPad\AkelFiles\Plugs\Scripts\Params\ и называться SearchReplace_Multi.txt. Если хотите, можете изменить имя (аргумент pFile).

Instructor
Когда люди подтвердят работоспособность, если можно, замените пожалуйста SearchReplace_Multi.js на странице скриптов моим, а то, чувствую, ещё много народа будет спрашивать.

KDJ
Offline
Posts: 1949
Joined: Sat Mar 06, 2010 7:40 pm
Location: Poland

Post by KDJ »

VladSh
Now you can make it simpler:
AkelPad.Command(4101, 1);
instead of:
AkelPad.SendMessage(AkelPad.GetMainWnd(), 273 /*WM_COMMAND*/, 4101 /*wParam=MAKEWAPARAM(0,IDM_FILE_NEW)*/, 1 /*lParam=TRUE*/);

Offline
Posts: 382
Joined: Wed Sep 28, 2011 3:05 pm

Post by Cuprum »

VladSh
Спасибо!
Locked