Scripts collection

Discuss and announce AkelPad plugins
Post Reply
  • Author
  • Message
Offline
Posts: 2247
Joined: Tue Aug 07, 2007 2:03 pm
Location: Vinnitsa, Ukraine

Post by FeyFre »

Code: Select all

// Choose & insert/change color in RGB-format by standard color selection dialog
// supported short format of standard colors
// http://akelpad.sourceforge.net/forum/viewtopic.php?p=8611#p8611
// http://outstanding.hmarka.net/akelpad/scripts/ChooseColor.js
// https://gist.github.com/Infocatcher/4632145
// Version: 1.8.1 (2013.08.26)   Infocatcher (support for short color format like "#f80")
// Version: 1.8   (2013.01.25)   Infocatcher (support for color names like "silver")
// Version: 1.7.1 (2012.09.14)   VladSh (warning fixes by Lint)
// Version: 1.7   (2012.09.13)   VladSh (bug fixes, added/changed variation of formats of input/output data)
// Version: 1.6.1 (2011.02.16)   se7h (autoselect color under caret)
// Version: 1.5   (2011.02.01)   VladSh (change; short format)
// Version: 1.4   (2011.01.26)   VladSh (изменение выделенного цвета)
// Version: 1.3   (2011.01.18)   © FeyFre
//
// Arguments:
//    default - значения цветов, которые будут отображаться при открытии (при отсутствии выделенного текста); см. пример ниже
//    lcase ([0 | без параметра] / 1) - возможность вывода результата в нижнем регистре
//    place - куда помещать выводимый результат:
//       • [0 | без параметра] - в окно редактирования (замена выделенного текста)
//       • 1 - в буфер обмена
//       • 2 - в поле диалога (InputBox)
//
// Examples:
// -"Insert color..." Call("Scripts::Main", 1, "ChooseColor.js") Icon("%a\AkelFiles\Plugs\Toolbar.dll", 30)
// -"Вставка цвета..." Call("Scripts::Main", 1, "ChooseColor.js", `-default="127 127 127"`) Icon("%a\AkelFiles\Plugs\Toolbar.dll", 30)      //initial color values from se7h
 
//color values by default
var nRGB = [255 /*RED*/, 0 /*GREEN*/, 0 /*BLUE*/];
 
var nPlace = AkelPad.GetArgValue("place", 0);
var hWndEdit = AkelPad.GetEditWnd();
if (hWndEdit)
{
   var crSel = [];
   var pSelText = AkelPad.GetSelText();
   if (!pSelText) {
      crSel = getWordCaretInfo(hWndEdit);
      if (crSel) pSelText = AkelPad.GetTextRange(crSel.min, crSel.max);
   }
   else {
      crSel.min = AkelPad.GetSelStart();
      crSel.max = AkelPad.GetSelEnd();
   }
   if (pSelText) {
      // проверка возможного НЕзахвата решётки
      if (AkelPad.GetTextRange(crSel.min-1, crSel.min) == "#")
         crSel.min = crSel.min - 1;
      var hex = getHexFromName(pSelText);
      if (!hex) {
         // корректировка избыточной длины (при выделении вручную)
         var lRgbMax = 7;
         if ((crSel.max - crSel.min) > lRgbMax)
            crSel.max = crSel.min + lRgbMax;
      }
      AkelPad.SetSel(crSel.min, crSel.max);
      pSelText = hex || AkelPad.GetSelText();
   }
}
else {
   // если окна редактирования нет, то выводим результат в InputBox, игнорируя переданный параметр
   if (nPlace === 0) nPlace = 2;
}
 
if (!pSelText) {
   var dRGB = AkelPad.GetArgValue("default", "");
   if (dRGB) {
      dRGB = dRGB.split(" ");
      for (var i = 0; i < dRGB.length; i++)
         nRGB[i] = parseInt(dRGB[i]);
      dRGB = null;
   }
}
else
   nRGB = HexToRGB(pSelText);
 
var oFunc = AkelPad.SystemFunction();
var /*CHOOSECOLOR*/ ccs = AkelPad.MemAlloc((_X64?8:4) * 9);
var /*COLORREF[16]*/ lprgbcustcol = AkelPad.MemAlloc(4 * 16);
for (i = 0; i < 16; i++)
   AkelPad.MemCopy(lprgbcustcol + i * 4, 0x0FFFFFF, 3 /*DT_DWORD*/);
 
//!CHOOSECOLOR.lStructSize
AkelPad.MemCopy(ccs + (_X64?0:0), (_X64?8:4) * 9, 3 /*DT_DWORD*/);
//!CHOOSECOLOR.hWndOwner
AkelPad.MemCopy(ccs + (_X64?8:4), 0 + AkelPad.GetMainWnd(), 2 /*DT_QWORD*/);
//!CHOOSECOLOR.hInstance
AkelPad.MemCopy(ccs + (_X64?16:8), 0, 2 /*DT_QWORD*/);
//!CHOOSECOLOR.rgbResult
AkelPad.MemCopy(ccs + (_X64?24:12), (nRGB[2]<<16) + (nRGB[1]<<8) + (nRGB[0]), 3 /*DT_DWORD*/);
//!CHOOSECOLOR.lpCustColors
AkelPad.MemCopy(ccs + (_X64?32:16), lprgbcustcol, 2 /*DT_QWORD*/);
//!CHOOSECOLOR.FLAGS
AkelPad.MemCopy(ccs + (_X64?40:20), 0x00000103/*CC_ANYCOLOR|CC_FULLOPEN|CC_RGBINIT*/, 3 /*DT_DWORD*/);
//!CHOOSECOLOR.lCustData
AkelPad.MemCopy(ccs + (_X64?48:24), 0, 2 /*DT_QWORD*/);
//!CHOOSECOLOR.lpfnHook
AkelPad.MemCopy(ccs + (_X64?56:28), 0, 2 /*DT_QWORD*/);
//!CHOOSECOLOR.lpTemplateName
AkelPad.MemCopy(ccs + (_X64?64:32), 0, 2 /*DT_QWORD*/);
 
if (oFunc.Call("comdlg32::ChooseColor" + _TCHAR, ccs)) {
   // COLORREF in format 0x00BBGGRR
   var xColor = AkelPad.MemRead(ccs + (_X64?24:12), 3 /*DT_DWORD*/);
 
   var hColor = RGBToHex(xColor);
   if (AkelPad.GetArgValue("lcase", 0))
      hColor = hColor.toLowerCase();
 
   switch (nPlace) {
      case 1:
         AkelPad.SetClipboardText(hColor);
         break;
      case 2:
         AkelPad.InputBox(AkelPad.GetMainWnd(), WScript.ScriptName, "Color in RGB:", hColor);
         break;
      default:
         AkelPad.ReplaceSel(hColor, true);
         break;
   }
}
 
AkelPad.MemFree(ccs);
AkelPad.MemFree(lprgbcustcol);
 
 
function HexToRGB(hColor) {
   if (hColor.charAt(0) == '#')
      hColor = hColor.slice(1);
   if (hColor.length == 3) // #f80 -> #ff8800
      hColor = hColor.replace(/./g, "$&$&");
   var dec = parseInt(hColor, 16);
   return [dec >> 16, dec >> 8 & 255, dec & 255];
}
 
function RGBToHex(xColor) {
// переделать бы как-то на алгоритм от 2: http://jsperf.com/rgbtohex/5 ...
   var hex = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'];
   var hRGB = ['', '', ''];
   for (var n = 0; n <= 2; n++) {
      for (var i = 0; i < 2; i++) {
         hRGB[n] = hex[xColor%16] + hRGB[n];
         xColor = Math.floor(xColor / 16);
      }
   }
   return "#" + hRGB.join("");
}
 
//Select word under caret
function getWordCaretInfo(hWndEdit) {
   if (hWndEdit) {
      var nCaretPos = AkelPad.GetSelStart();
      var crInfo = [];
      crInfo.min = AkelPad.SendMessage(hWndEdit, 1100 /*EM_FINDWORDBREAK */, 0/*WB_LEFT*/, nCaretPos);
      crInfo.max = AkelPad.SendMessage(hWndEdit, 1100 /*EM_FINDWORDBREAK */, 7/*WB_RIGHTBREAK*/, crInfo.min);
      //! For case when caret located on word start position i.e. "prev-word |word-to-copy"
      if (crInfo.max < nCaretPos) {
         crInfo.min = AkelPad.SendMessage(hWndEdit, 1100/*EM_FINDWORDBREAK*/, 0/*WB_LEFT*/, nCaretPos + 1);
         crInfo.max = AkelPad.SendMessage(hWndEdit, 1100/*EM_FINDWORDBREAK*/, 7/*WB_RIGHTBREAK*/, crInfo.min);
      }
      if (crInfo.max >= nCaretPos)
         return crInfo;
   }
}
 
function getHexFromName(colorName) {
   var colors = {
      "aliceblue":            "#f0f8ff",
      "antiquewhite":         "#faebd7",
      "aqua":                 "#00ffff",
      "aquamarine":           "#7fffd4",
      "azure":                "#f0ffff",
      "beige":                "#f5f5dc",
      "bisque":               "#ffe4c4",
      "black":                "#000000",
      "blanchedalmond":       "#ffebcd",
      "blue":                 "#0000ff",
      "blueviolet":           "#8a2be2",
      "brown":                "#a52a2a",
      "burlywood":            "#deb887",
      "cadetblue":            "#5f9ea0",
      "chartreuse":           "#7fff00",
      "chocolate":            "#d2691e",
      "coral":                "#ff7f50",
      "cornflowerblue":       "#6495ed",
      "cornsilk":             "#fff8dc",
      "crimson":              "#dc143c",
      "cyan":                 "#00ffff",
      "darkblue":             "#00008b",
      "darkcyan":             "#008b8b",
      "darkgoldenrod":        "#b8860b",
      "darkgray":             "#a9a9a9",
      "darkgreen":            "#006400",
      "darkkhaki":            "#bdb76b",
      "darkmagenta":          "#8b008b",
      "darkolivegreen":       "#556b2f",
      "darkorange":           "#ff8c00",
      "darkorchid":           "#9932cc",
      "darkred":              "#8b0000",
      "darksalmon":           "#e9967a",
      "darkseagreen":         "#8fbc8f",
      "darkslateblue":        "#483d8b",
      "darkslategray":        "#2f4f4f",
      "darkturquoise":        "#00ced1",
      "darkviolet":           "#9400d3",
      "deeppink":             "#ff1493",
      "deepskyblue":          "#00bfff",
      "dimgray":              "#696969",
      "dodgerblue":           "#1e90ff",
      "firebrick":            "#b22222",
      "floralwhite":          "#fffaf0",
      "forestgreen":          "#228b22",
      "fuchsia":              "#ff00ff",
      "gainsboro":            "#dcdcdc",
      "ghostwhite":           "#f8f8ff",
      "gold":                 "#ffd700",
      "goldenrod":            "#daa520",
      "gray":                 "#808080",
      "green":                "#008000",
      "greenyellow":          "#adff2f",
      "honeydew":             "#f0fff0",
      "hotpink":              "#ff69b4",
      "indianred":            "#cd5c5c",
      "indigo":               "#4b0082",
      "ivory":                "#fffff0",
      "khaki":                "#f0e68c",
      "lavender":             "#e6e6fa",
      "lavenderblush":        "#fff0f5",
      "lawngreen":            "#7cfc00",
      "lemonchiffon":         "#fffacd",
      "lightblue":            "#add8e6",
      "lightcoral":           "#f08080",
      "lightcyan":            "#e0ffff",
      "lightgoldenrodyellow": "#fafad2",
      "lightgreen":           "#90ee90",
      "lightgrey":            "#d3d3d3",
      "lightpink":            "#ffb6c1",
      "lightsalmon":          "#ffa07a",
      "lightseagreen":        "#20b2aa",
      "lightskyblue":         "#87cefa",
      "lightslategray":       "#778899",
      "lightsteelblue":       "#b0c4de",
      "lightyellow":          "#ffffe0",
      "lime":                 "#00ff00",
      "limegreen":            "#32cd32",
      "linen":                "#faf0e6",
      "magenta":              "#ff00ff",
      "maroon":               "#800000",
      "mediumaquamarine":     "#66cdaa",
      "mediumblue":           "#0000cd",
      "mediumorchid":         "#ba55d3",
      "mediumpurple":         "#9370db",
      "mediumseagreen":       "#3cb371",
      "mediumslateblue":      "#7b68ee",
      "mediumspringgreen":    "#00fa9a",
      "mediumturquoise":      "#48d1cc",
      "mediumvioletred":      "#c71585",
      "midnightblue":         "#191970",
      "mintcream":            "#f5fffa",
      "mistyrose":            "#ffe4e1",
      "moccasin":             "#ffe4b5",
      "navajowhite":          "#ffdead",
      "navy":                 "#000080",
      "oldlace":              "#fdf5e6",
      "olive":                "#808000",
      "olivedrab":            "#6b8e23",
      "orange":               "#ffa500",
      "orangered":            "#ff4500",
      "orchid":               "#da70d6",
      "palegoldenrod":        "#eee8aa",
      "palegreen":            "#98fb98",
      "paleturquoise":        "#afeeee",
      "palevioletred":        "#db7093",
      "papayawhip":           "#ffefd5",
      "peachpuff":            "#ffdab9",
      "peru":                 "#cd853f",
      "pink":                 "#ffc0cb",
      "plum":                 "#dda0dd",
      "powderblue":           "#b0e0e6",
      "purple":               "#800080",
      "red":                  "#ff0000",
      "rosybrown":            "#bc8f8f",
      "royalblue":            "#4169e1",
      "saddlebrown":          "#8b4513",
      "salmon":               "#fa8072",
      "sandybrown":           "#f4a460",
      "seagreen":             "#2e8b57",
      "seashell":             "#fff5ee",
      "sienna":               "#a0522d",
      "silver":               "#c0c0c0",
      "skyblue":              "#87ceeb",
      "slateblue":            "#6a5acd",
      "slategray":            "#708090",
      "snow":                 "#fffafa",
      "springgreen":          "#00ff7f",
      "steelblue":            "#4682b4",
      "tan":                  "#d2b48c",
      "teal":                 "#008080",
      "thistle":              "#d8bfd8",
      "tomato":               "#ff6347",
      "turquoise":            "#40e0d0",
      "violet":               "#ee82ee",
      "wheat":                "#f5deb3",
      "white":                "#ffffff",
      "whitesmoke":           "#f5f5f5",
      "yellow":               "#ffff00",
      "yellowgreen":          "#9acd32"
   };
   return colors[colorName.toLowerCase()] || undefined;
}

UPD v1.3(2011.01.18-19):
* 64-bit compatibility(FeyFre)
* ANSI/Unicode system version portability(FeyFre)
* Ability to accept script parameters - preselected color(VladSh,seh7)
* Optionally display selected colour code in dialog box(VladSh)
UPD v1.4(2011.01.26)(VladSh)
UPD v1.5(2011.02.01)(VladSh)
UPD v1.6.1(2011.02.16)(se7h)
UPD v1.7(2012.09.13)(VladSh)
  • Bug fixes
  • Добавлена корректировка избыточной длины RGB-значения (при выделении вручную).
  • Изменён принцип передачи аргументов:
    • добавлена опция для возможности возвращения rgb-значения в нижнем регистре;
    • добавлена опция для возможности возвращения результата в буфер обмена и InputBox.
UPD v1.7.1 Fixes...
UPD v1.8 (2013.01.25)(Infocatcher) Support for color names like "silver"
UPD v1.8.1 (2013.08.26)(Infocatcher) Support for short color format like "#f80"
Last edited by FeyFre on Wed Aug 28, 2013 4:57 pm, edited 11 times in total.

DV
Online
Posts: 1250
Joined: Thu Nov 16, 2006 11:53 am
Location: Kyiv, Ukraine

Post by DV »

Вроде бы такого еще не было.
Скрипт-шаблон для обработки (изменения) выделенного текста.
A script template for modifying the text selected in AkelPad.

Code: Select all

var pSelText = AkelPad.GetSelText();       // whole selected text
if (pSelText.length > 0)
{
  var arrStr = pSelText.split("\r");       // array of strings
  var numStr = arrStr.length;              // number of strings
  var outText = "";                        // output text
  var i;
  for (i = 0; i < numStr; i++)
  {
    if (!excludeString(arrStr[i]))
    {
      outText += processString(arrStr[i]); // process each string
      if (i < numStr - 1)
        outText += "\r";
    }
  }
  AkelPad.ReplaceSel(outText);             // replace the selected text
}

// user-defined function
function excludeString(s)
{
  // return true to exclude the string s
  return false;
}

// user-defined function
function processString(s)
{
  // modify the string s
  if (s.length > 0)
  {
    return "\"" + s + "\"";
  }

  return "";
}

Изменение строк выделенного текста достигается модификацией пользовательских функций excludeString(s) и processString(s).
Посему дальнейшим развитием скрипта мог бы быть вынос этих двух функций в отдельное окно, появляющееся при запуске этого скрипта - чтобы пользователь мог менять их "на лету", не редактируя сам скрипт ProcessSelectedText.js.

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

Post by VladSh »

DV wrote:Скрипт-шаблон для обработки (изменения) выделенного текста.
ProcessSelectedText.js
Была такая идея при написании ShowMenuEx.js" но тогда я это забросил...
Супер, спасибо! 8)

Вынес "эту" функцию в отдельный скрипт, который подключаю, а сами функции processString и addToResult пишутся уже в вызывающем скрипте.
И проверку excludeString убрал, т.к. неудобно с этим работать (они могут быть не нужны), можно их делать внутри processString.

Свой вариант (по моему, это универсальнее):


Скрипт больше не поддерживается.
Несколько функций, из которых состоял скрипт, были перенесены в selCompleteLine.js.



Code: Select all

// http://akelpad.sourceforge.net/forum/viewtopic.php?p=8655#p8655
// Description(1033): Works with all files located in specified folder. Script implemented as the library for using in other scripts.
// Description(1049): Библиотека функций для организации обработки каждого файла определённой папки.
// Version: 1.1 (2011.07.21)
// Author: VladSh

function processFolderFiles(pFilePath, bErrMsg) {
	if (pFilePath) {
		var fso = new ActiveXObject("Scripting.FileSystemObject");
		
		var dir = fso.GetParentFolderName(pFilePath);
		if (fso.FolderExists(dir)) {
			var folder = fso.getFolder(dir);
			
			filescollection = new Enumerator(folder.files);
			
			for (; !filescollection.atEnd(); filescollection.moveNext())
				processFile(filescollection.item());
		}
		else {
			if (bErrMsg)
				AkelPad.MessageBox(AkelPad.GetEditWnd(), 'Папка "' + dir + '" не найдена на диске.', "AkelPad -> " + WScript.ScriptName, 0 /*MB_OK*/ + 64 /*MB_ICONINFORMATION*/);
		}
	}
}

/*
// user-defined function (copy it to the calling script)
function processFile(file) {
	//code
}
*/


Example of use: OpenAllFilesFromFileFolder.js.
Last edited by VladSh on Fri Jan 16, 2015 2:41 pm, edited 10 times in total.

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

Post by VladSh »

Code: Select all

// http://akelpad.sourceforge.net/forum/viewtopic.php?p=8663#p8663
// Description(1033): Run the script from his own menu of some scripts
// Description(1049): Запуск скрипта из собственного меню избранных скриптов
// Version: 1.7 (2015.04.10)
// Author: VladSh
// 
// Arguments:
// 	см. скрипт ShowMenuEx.js
// 	
// Usage:
// 	Call("Scripts::Main", 1, "ExecuteScriptMenu.js", `-configFile="LS.ini"`)           - menu is displayed from LS.ini
// 	Call("Scripts::Main", 1, "ExecuteScriptMenu.js", `-configFile="LS.ini" -place=-2`) - menu is displayed from LS.ini at the cursor position (see constants in ShowMenuEx.js)

if (WScript.Arguments.length == 0) WScript.Quit();

if (!AkelPad.Include("ShowMenuEx.js")) WScript.Quit();

var pPLACE = AkelPad.GetArgValue("place", "");
if (pPLACE == "") pPLACE = POS_CARET;		// если ничего не передано, то отталкиваемся от позиции каретки

var pScriptName = getSelectedMenuItem(pPLACE, false);
if (pScriptName) {
	checkFilePath("Скрипт", getScriptNameFull(pScriptName));
	AkelPad.Call("Scripts::Main", 1, pScriptName);
}

function getScriptNameFull(pScriptNameShort) {
	return AkelPad.GetAkelDir(5) + "\\" + pScriptNameShort;
}


: вынес эту кучу скриптов из общего контекстного меню окна редактирования в собственную менюшку, которая теперь вылетает по комбинации клавиш.

Вызов:

Code: Select all

Call("Scripts::Main", 1, "ExecuteScriptMenu.js", `-configFile="LS.ini" -place=-2`)
Содержимое LS.ini:

Code: Select all

GetItemValue = LSGetItemValue.js
ReplaceItemValue = LSReplaceItemValue.js
FunctionsItem -> Const = LSFunctionsItemToConst.js
Items -> Const = LSConst.js
Last edited by VladSh on Fri Jun 19, 2015 8:49 pm, edited 11 times in total.

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

Post by KDJ »

Moves left/right/up/down selected words or only selects whole words.

Code: Select all

// http://akelpad.sourceforge.net/forum/viewtopic.php?p=8668#p8668
// Version: 2015-01-08
// Author: KDJ
//
// *** Select or move left/right/up/down whole words ***
//
// Usage:
//   Call("Scripts::Main", 1, "WordsMoveSelect.js", "0")  - only select whole words, not move (default)
//   Call("Scripts::Main", 1, "WordsMoveSelect.js", "-1") - move left, to the previous word
//   Call("Scripts::Main", 1, "WordsMoveSelect.js", "1")  - move right, to the next word
//   Call("Scripts::Main", 1, "WordsMoveSelect.js", "-2") - move left, to the first word in the line
//   Call("Scripts::Main", 1, "WordsMoveSelect.js", "2")  - move right, to the last word in the line
//   Call("Scripts::Main", 1, "WordsMoveSelect.js", "-3") - move up
//   Call("Scripts::Main", 1, "WordsMoveSelect.js", "3")  - move down
//
// Remarks:
//   If there is no selection, it moves or selects the current word.
//   Does not work with columnar selection.
//   Can assign shortcut keys, eg: Ctrl+Shift+W, Ctrl+Shift+Alt+Left, Ctrl+Shift+Alt+Right, Ctrl+Shift+Alt+Home, Ctrl+Shift+Alt+End, Ctrl+Shift+Alt+Up, Ctrl+Shift+Alt+Down.

var DT_DWORD              = 3;
var AEM_GETINDEX          = 3130;
var AEM_INDEXCOMPARE      = 3133;
var AEM_INDEXTORICHOFFSET = 3136;
var AEM_GETNEXTBREAK      = 3144;
var AEM_GETPREVBREAK      = 3145;
var AEM_ISDELIMITER       = 3146;
var AEDLM_WORD            = 0x00000010;
var AEDLM_PREVCHAR        = 0x00000001;
var AEWB_LEFTWORDSTART    = 0x00000001;
var AEWB_LEFTWORDEND      = 0x00000002;
var AEWB_RIGHTWORDSTART   = 0x00000004;
var AEWB_RIGHTWORDEND     = 0x00000008;
var AEGI_FIRSTSELCHAR     = 3;
var AEGI_LASTSELCHAR      = 4;
var AEGI_WRAPLINEBEGIN    = 18;
var AEGI_WRAPLINEEND      = 19;

var hEditWnd = AkelPad.GetEditWnd();
if (! hEditWnd)
  WScript.Quit();

if (SendMessage(hEditWnd, 3127 /*AEM_GETCOLUMNSEL*/, 0, 0))
{
  WScript.Echo("Does not work with columnar selection.");
  WScript.Quit();
}

var nAction = 0;
if (WScript.Arguments.length)
  nAction = Number(WScript.Arguments(0));
if (!((nAction == 0) || (nAction == -1) || (nAction == 1) || (nAction == -2) || (nAction == 2) ||
      (nAction == -3) || (nAction == 3)))
  WScript.Quit();

var lpIndex1 = AkelPad.MemAlloc(_X64 ? 24 : 12 /*sizeof(AECHARINDEX)*/);
var lpIndex2 = AkelPad.MemAlloc(_X64 ? 24 : 12 /*sizeof(AECHARINDEX)*/);
var lpIndex3 = AkelPad.MemAlloc(_X64 ? 24 : 12 /*sizeof(AECHARINDEX)*/);
var nOffset1;
var nOffset2;
var nOffset3;
var lpBuffer;
var sSeps;
var rWords;
var rSeps;
var aWords;
var aSeps;
var bCanMove;
var sText;
var nRow;
var nCol;
var i;

if (WordsSelect() && nAction && (! AkelPad.GetEditReadOnly(hEditWnd)))
{
  if (nAction < 0)
  {
    SendMessage(hEditWnd, AEM_GETINDEX, AEGI_FIRSTSELCHAR, lpIndex3);
    if (nAction == -1) //left
    {
      if (SendMessage(hEditWnd, AEM_GETPREVBREAK, AEWB_LEFTWORDSTART, lpIndex3) &&
         (! SendMessage(hEditWnd, AEM_ISDELIMITER, AEDLM_WORD, lpIndex3)))
        bCanMove = true;
    }
    else if (nAction == -2) //begin of line
    {
      SendMessage(hEditWnd, AEM_GETINDEX, AEGI_WRAPLINEBEGIN, lpIndex3);
      if (SendMessage(hEditWnd, AEM_ISDELIMITER, AEDLM_WORD, lpIndex3))
        SendMessage(hEditWnd, AEM_GETNEXTBREAK, AEWB_RIGHTWORDSTART, lpIndex3);
      if (SendMessage(hEditWnd, AEM_INDEXCOMPARE, lpIndex3, lpIndex1) == -1)
        bCanMove = true;
    }
    else //up
    {
      SendMessage(hEditWnd, AEM_GETINDEX, AEGI_WRAPLINEBEGIN, lpIndex3);
      if (SendMessage(hEditWnd, AEM_GETPREVBREAK, AEWB_LEFTWORDSTART, lpIndex3) &&
         (! SendMessage(hEditWnd, AEM_ISDELIMITER, AEDLM_WORD, lpIndex3)))
      {
        bCanMove = true;

        nRow = AkelPad.MemRead(lpIndex3, DT_DWORD);
        nCol = AkelPad.MemRead(_PtrAdd(lpIndex1, _X64 ? 16 : 8), DT_DWORD);
        while (nCol < AkelPad.MemRead(_PtrAdd(lpIndex3, _X64 ? 16 : 8), DT_DWORD))
        {
          if (SendMessage(hEditWnd, AEM_GETPREVBREAK, AEWB_LEFTWORDSTART, lpIndex3))
          {
            if (SendMessage(hEditWnd, AEM_ISDELIMITER, AEDLM_WORD, lpIndex3) ||
               (nRow != AkelPad.MemRead(lpIndex3, DT_DWORD)))
            {
              SendMessage(hEditWnd, AEM_GETNEXTBREAK, AEWB_RIGHTWORDSTART, lpIndex3);
              break;
            }
          }
          else
            break;
        }
      }
    }
  }

  else
  {
    SendMessage(hEditWnd, AEM_GETINDEX, AEGI_LASTSELCHAR, lpIndex3);
    if (nAction == 1) //right
    {
      if (SendMessage(hEditWnd, AEM_GETNEXTBREAK, AEWB_RIGHTWORDEND, lpIndex3) &&
         (! SendMessage(hEditWnd, AEM_ISDELIMITER, AEDLM_WORD|AEDLM_PREVCHAR, lpIndex3)))
        bCanMove = true;
    }
    else if (nAction == 2) //end of line
    {
      SendMessage(hEditWnd, AEM_GETINDEX, AEGI_WRAPLINEEND, lpIndex3);
      if (SendMessage(hEditWnd, AEM_ISDELIMITER, AEDLM_WORD|AEDLM_PREVCHAR, lpIndex3))
        SendMessage(hEditWnd, AEM_GETPREVBREAK, AEWB_LEFTWORDEND, lpIndex3);
      if (SendMessage(hEditWnd, AEM_INDEXCOMPARE, lpIndex2, lpIndex3) == -1)
        bCanMove = true;
    }
    else //down
    {
      SendMessage(hEditWnd, AEM_GETINDEX, AEGI_WRAPLINEEND, lpIndex3);
      if (SendMessage(hEditWnd, AEM_GETNEXTBREAK, AEWB_RIGHTWORDEND, lpIndex3) &&
         (! SendMessage(hEditWnd, AEM_ISDELIMITER, AEDLM_WORD|AEDLM_PREVCHAR, lpIndex3)))
      {
        bCanMove = true;

        nRow = AkelPad.MemRead(lpIndex3, DT_DWORD);
        nCol = AkelPad.MemRead(_PtrAdd(lpIndex2, _X64 ? 16 : 8), DT_DWORD);
        while (nCol > AkelPad.MemRead(_PtrAdd(lpIndex3, _X64 ? 16 : 8), DT_DWORD))
        {
          if (SendMessage(hEditWnd, AEM_GETNEXTBREAK, AEWB_RIGHTWORDEND, lpIndex3))
          {
            if (SendMessage(hEditWnd, AEM_ISDELIMITER, AEDLM_WORD|AEDLM_PREVCHAR, lpIndex3) ||
               (nRow != AkelPad.MemRead(lpIndex3, DT_DWORD)))
            {
              SendMessage(hEditWnd, AEM_GETPREVBREAK, AEWB_LEFTWORDEND, lpIndex3);
              break;
            }
          }
          else
            break;
        }
      }
    }
  }

  if (bCanMove)
  {
    SetRedraw(hEditWnd, false);

    nOffset3 = SendMessage(hEditWnd, AEM_INDEXTORICHOFFSET, 0, lpIndex3);
    sText    = AkelPad.GetTextRange(nOffset3, (nAction < 0) ? nOffset1 : nOffset2);
    lpBuffer = SendMessage(AkelPad.GetMainWnd(), 1223 /*AKD_GETFRAMEINFO*/, 108 /*FI_WORDDELIMITERS*/, 0);
    sSeps    = AkelPad.MemRead(lpBuffer, _TSTR).replace(/[\\\/.^$+*?|()\[\]{}-]/g, "\\$&");
    sSeps    = sSeps.replace(/\n/g, "\r");
    rWords   = new RegExp("[^" + sSeps + "]+", "g");
    rSeps    = new RegExp("[" + sSeps + "]+", "g");
    aWords   = sText.match(rWords);
    aSeps    = sText.match(rSeps);
    sText    = AkelPad.GetSelText();
    nWordLen = sText.length;

    if (nAction < 0)
      aWords.unshift(sText);
    else
      aWords.push(sText);

    sText = aWords[0];
    for (i = 0; i < aSeps.length; ++i)
      sText += aSeps[i] + aWords[i + 1];

    AkelPad.SetSel(nOffset3, (nAction < 0) ? nOffset2 : nOffset1);
    AkelPad.ReplaceSel(sText);
    AkelPad.SetSel(nOffset3 + ((nAction < 0) ? nWordLen : -nWordLen), nOffset3);
    SetRedraw(hEditWnd, true);
  }
}

AkelPad.MemFree(lpIndex1);
AkelPad.MemFree(lpIndex2);
AkelPad.MemFree(lpIndex3);

function WordsSelect()
{
  var bSelWord = false;

  SendMessage(hEditWnd, AEM_GETINDEX, AEGI_FIRSTSELCHAR, lpIndex1);
  if (SendMessage(hEditWnd, AEM_ISDELIMITER, AEDLM_WORD, lpIndex1))
  {
    if (SendMessage(hEditWnd, AEM_ISDELIMITER, AEDLM_WORD|AEDLM_PREVCHAR, lpIndex1))
      SendMessage(hEditWnd, AEM_GETNEXTBREAK, AEWB_RIGHTWORDSTART, lpIndex1);
    else
      SendMessage(hEditWnd, AEM_GETPREVBREAK, AEWB_LEFTWORDSTART, lpIndex1);
  }
  else if (! SendMessage(hEditWnd, AEM_ISDELIMITER, AEDLM_WORD|AEDLM_PREVCHAR, lpIndex1))
    SendMessage(hEditWnd, AEM_GETPREVBREAK, AEWB_LEFTWORDSTART, lpIndex1);

  SendMessage(hEditWnd, AEM_GETINDEX, AEGI_LASTSELCHAR, lpIndex2);
  if (SendMessage(hEditWnd, AEM_ISDELIMITER, AEDLM_WORD, lpIndex2))
  {
    if (SendMessage(hEditWnd, AEM_ISDELIMITER, AEDLM_WORD|AEDLM_PREVCHAR, lpIndex2))
      SendMessage(hEditWnd, AEM_GETPREVBREAK, AEWB_LEFTWORDEND, lpIndex2);
  }
  else
    SendMessage(hEditWnd, AEM_GETNEXTBREAK, AEWB_RIGHTWORDEND, lpIndex2);

  nOffset1 = SendMessage(hEditWnd, AEM_INDEXTORICHOFFSET, 0, lpIndex1);
  nOffset2 = SendMessage(hEditWnd, AEM_INDEXTORICHOFFSET, 0, lpIndex2);

  if (nOffset1 < nOffset2)
  {
    AkelPad.SetSel(nOffset1, nOffset2);
    bSelWord = true;
  }

  return bSelWord;
}

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

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

Last edited by KDJ on Thu Jan 08, 2015 8:46 pm, edited 12 times in total.

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

Post by KDJ »

Inserts file name/path and copy to clipboard.

Code: Select all

// http://akelpad.sourceforge.net/forum/viewtopic.php?p=8690#p8690
// Version: 2015-09-19
// Author: KDJ
//
// *** Insert file name/path or copy to clipboard ***
//
// Usage:
//   Call("Scripts::Main", 1, "InsertFileNamePath.js"[, "Arg1 Arg2"])
//
// Arguments are optional. If not specified, a menu will appear.
//   Arg1 = 1 - file name
//   Arg1 = 2 - full file name with path
//   Arg1 = 3 - path without file name
//   Arg1 = 4 - file name without extension
//   Arg2 = 0 - insert into the text, not copy to the clipboard (default value, can be omitted),
//   Arg2 = 1 - insert into the text and copy to the clipboard,
//   Arg2 = 2 - copy to the clipboard, do not insert into the text.
//
// Can assign shortcut keys, eg: Ctrl+Shift+F, Ctrl+Shift+Alt+F, Shift+Alt+F.

var oSys = AkelPad.SystemFunction();

if (oSys.Call("kernel32::GetUserDefaultLangID") == 0x0415) //Polish
{
  var aTxtMenu1 = ["Nazwa pliku",
                   "Pełna nazwa pliku ze ścieżką",
                   "Ścieżka bez nazwy pliku",
                   "Nazwa pliku bez rozszerzenia"];
  var aTxtMenu2 = ["Wstaw do tekstu",
                   "Wstaw i kopiuj",
                   "Kopiuj do schowka"];
}
else
{
  var aTxtMenu1 = ["File name",
                   "Full file name with path",
                   "Path without file name",
                   "File name without extension"];
  var aTxtMenu2 = ["Insert into text",
                   "Insert and copy",
                   "Copy to clipboard"];
}

var hEditWnd = AkelPad.GetEditWnd();
var sFile;
var nArg1;
var nArg2;
var hWndHid;
var hMenu1;
var ahMenu2;
var nCmd;
var lpPoint;
var nX;
var nY;
var nSep;
var bColSel;
var nLines;
var aTxt;
var i, n;

if (! hEditWnd)
  WScript.Quit();

sFile = AkelPad.GetEditFile(hEditWnd);
if (! sFile.length)
  WScript.Quit();

if (WScript.Arguments.length)
  nArg1 = parseInt(WScript.Arguments(0));
if ((! isFinite(nArg1)) || (nArg1 < 1) || (nArg1 > 4))
  nArg1 = 0;

if (nArg1)
{
  if (WScript.Arguments.length > 1)
    nArg2 = parseInt(WScript.Arguments(1));
  if ((! isFinite(nArg2)) || (nArg2 < 1) || (nArg2 > 2))
    nArg2 = 0;
}

else
{
  lpPoint = AkelPad.MemAlloc(8); //sizeof(POINT)
  AkelPad.SendMessage(hEditWnd, 3190 /*AEM_GETCARETPOS*/, lpPoint, 0);
  oSys.Call("user32::ClientToScreen", hEditWnd, lpPoint);
  nX = AkelPad.MemRead(_PtrAdd(lpPoint, 0), 3 /*DT_DWORD*/);
  nY = AkelPad.MemRead(_PtrAdd(lpPoint, 4), 3 /*DT_DWORD*/) +
       AkelPad.SendMessage(hEditWnd, 3188 /*AEM_GETCHARSIZE*/, 0 /*AECS_HEIGHT*/, 0);

  hWndHid = oSys.Call("user32::CreateWindowEx" + _TCHAR, 0, "STATIC", 0, 0x50000000 /*WS_VISIBLE|WS_CHILD*/,
                       0, 0, 0, 0, hEditWnd, 0, AkelPad.GetInstanceDll(), 0);
  oSys.Call("user32::SetFocus", hWndHid);

  ahMenu2 = [];
  for (i = 0; i < 4; ++i)
  {
    ahMenu2[i] = oSys.Call("user32::CreatePopupMenu");
    for (n = 0; n < 3; ++n)
      oSys.Call("user32::AppendMenu" + _TCHAR, ahMenu2[i], 0x00 /*MF_STRING*/, ((i + 1) << 4) | n, aTxtMenu2[n]);
  }

  hMenu1  = oSys.Call("user32::CreatePopupMenu");
  for (i = 0; i < 4; ++i)
    oSys.Call("user32::AppendMenu" + _TCHAR, hMenu1, 0x10 /*MF_POPUP|MF_STRING*/, ahMenu2[i], aTxtMenu1[i]);


  nCmd = oSys.Call("user32::TrackPopupMenu", hMenu1, 0x0180 /*TPM_RETURNCMD|TPM_NONOTIFY*/,
                    nX, nY, 0, hWndHid, 0);

  for (i = 0; i < 4; ++i)
    oSys.Call("user32::DestroyMenu", ahMenu2[i]);
  oSys.Call("user32::DestroyMenu", hMenu1);
  oSys.Call("user32::DestroyWindow", hWndHid);
  AkelPad.MemFree(lpPoint);

  if (! nCmd)
    WScript.Quit();

  nArg1 = (nCmd >> 4) & 0xF;
  nArg2 = nCmd & 0xF;
}

nSep = sFile.lastIndexOf("\\");

if (nArg1 == 1)
  sFile = sFile.substr(nSep + 1);
else if (nArg1 == 3)
  sFile = sFile.substr(0, nSep + 1);
else if (nArg1 == 4)
  sFile = sFile.substr(nSep + 1).replace(/\.[^.]+$/, "");

if ((nArg2 < 2))
{
  bColSel = AkelPad.SendMessage(hEditWnd, 3127 /*AEM_GETCOLUMNSEL*/, 0, 0);

  if (bColSel)
  {
    nLines = AkelPad.SendMessage(hEditWnd, 3129 /*AEM_GETLINENUMBER*/, 2 /*AEGL_LASTSELLINE*/, 0) -
             AkelPad.SendMessage(hEditWnd, 3129 /*AEM_GETLINENUMBER*/, 1 /*AEGL_FIRSTSELLINE*/, 0) + 1;
    aTxt   = new Array(nLines);

    for (i = 0; i < nLines; ++i)
      aTxt[i] = sFile;

    sFile = aTxt.join("\r");
  }

  AkelPad.ReplaceSel(sFile, (AkelPad.GetSelStart() == AkelPad.GetSelEnd()) ? 0 : -1);
  AkelPad.SendMessage(hEditWnd, 3128 /*AEM_UPDATESEL*/, bColSel, 0);
}

if (nArg2 > 0)
  AkelPad.SetClipboardText(sFile);

Last edited by KDJ on Sat Sep 19, 2015 3:39 pm, edited 7 times in total.

Offline
Posts: 267
Joined: Mon Mar 12, 2007 3:45 pm

Post by [Yustas.NeO] »

Code: Select all

//	Сортировка текста по столбцам. Версия 2011-10-20
//	Sort text by columns. Version 2011-10-20

//	http://akelpad.sourceforge.net/forum/viewtopic.php?p=8738#p8738
//	ftp://akelscripts:akelscripts@95.172.154.20/NeO.Sort.js


//	2011-10-20
//	* Незначительные изменения.

//	2011-09-21
//	* Теперь правильно реагирует на пустой ввод и на отмену.

//	2010-12-07
//	* Теперь правильно сортирует по произвольному разделителю.



//	Вводится в формате
//		X1[-X2[-X3[...[=s]]]]
//		где
//			Xn	- номера столбцов в порядке выполнения будущей сортировки, разделенные знаком "-" (знак Минус без кавычек).
//			s	- любой набор символов, в качестве разделителя столбцов. Вводится последним значением в строке ввода, отделяя от списка столбцов знаком "=" (знак Равно без кавычек). Все что после знака Равно считается разделителем столбцов. Если этот параметр пропустить, то по умолчанию в качестве разделителя будет использован знак Табуляция.
//	Примеры:
//		1. Сортировать по второму столбцу
//			Введите: 2
//		2. Сортировать по третьему столбцу. В случае совпадения имен - сортировать по первому столбцу
//			Введите: 1-3
//		3. Сортировать по четвертому столбцу. В качестве разделителя использован знак ":"
//			Введите: 4=:
//		4. Сортировать по пятому столбцу. В случае совпадения имен - сортировать по шестому столбцу. Если и в этом столбце есть совпадения, то сортировать по седьмому. В качестве разделителя использован знак "="
//			Введите: 7-6-5==


//	Add in format
//		X1[-X2[-X3[...[=s]]]]
//		where
//			Xn	- numbers of cols according to future grading divided by "-" (Minus without quotation marks).
//			s	- any set of symbols that divides cols. Added as last point in entry line separated from cols list by "=" (Equals without quotation marks). Everything placed after "equals" mark is considered to be separator of cols. If this parameter is missed, Tab mark will be used as separator by default.
//	Examples:
//		1. Sorting according second col
//			Type in: 2
//		2. Sorting according third col. If titles coincide, then sort according the first col
//			Type in: 1-3
//		3. Sorting according fourth col. Mark ":" is used as separator
//			Type in: 4=:
//		4. Sorting according fifth col. If titles coincide, than sort according sixth col. If this col also has coincidences, than sort according seventh col. Mark "=" is used as separator.
//			Type in: 7-6-5==



//------------------------------------------------------------------------------
	function AutoRedrawOff(hEditWnd)
	{
	  AkelPad.SendMessage(hEditWnd, 11 /*WM_SETREDRAW*/, false, 0);
	}



	function AutoRedrawOn(hEditWnd)
	{
		AkelPad.SendMessage(hEditWnd, 11 /*WM_SETREDRAW*/, true, 0); 
		AkelPad.SystemFunction().Call("user32::InvalidateRect", hEditWnd, 0, true); 
	}



	function arrSort(tableToSort, colToSort)
	{
		var aTemp = new Array;
		colToSort--;
		for (jjj = 0;   jjj < aRowsLength;   jjj++);
		{
			for (iii = 0;   iii < aRowsLength-1;   iii++)
			{
				if (tableToSort[iii][colToSort] > tableToSort[iii+1][colToSort] || tableToSort[iii+1][colToSort] === undefined)
				{
					aTemp = tableToSort[iii];
					tableToSort[iii] = tableToSort[iii+1];
					tableToSort[iii+1] = aTemp;
				}
			}
		}
		return tableToSort;
	}
//------------------------------------------------------------------------------



	hEditWnd = AkelPad.GetEditWnd()
	hMainWnd = AkelPad.GetMainWnd()
	var aTable = new Array
	var aSortOrder = new Array

	if (AkelPad.SystemFunction().Call("kernel32::GetUserDefaultLangID") == 0x0419)
	{
		var InputBoxTitle = 'Сортировка по столбцам';
		var InputBoxHint  = 'Сначала по 2-му столбцу,  затем по 1-му;   разделитель - ";"';
	}
	else
	{
		var InputBoxTitle = 'Sort by columns';
		var InputBoxHint  = 'First sort by the 2nd column,  then by the 1st;   ";" is delimiter';
	}

	var sInput = AkelPad.InputBox(hMainWnd, InputBoxTitle, InputBoxHint, '2-1=;')
	if (sInput != undefined)
	{
		var iEqPos = sInput.indexOf('=', 0);

		if (iEqPos == -1)
		{
			aSortOrder = sInput.split('-');
			var sSeparator = '\t';
		}
		else
		{
			aSortOrder = sInput.substring(0, iEqPos).split('-');
			var sSeparator = sInput.substring(iEqPos+1, sInput.length);
		}

		AutoRedrawOff(hEditWnd);

		var nSelStart=AkelPad.GetSelStart();
		var nSelEnd=AkelPad.GetSelEnd();
		if (nSelStart == nSelEnd)
			AkelPad.SetSel(0, -1);
		else
		{
			var allText=AkelPad.GetTextRange(0, -1);
			var lineStart=allText.lastIndexOf('\r', nSelStart);
			var lineEnd=allText.indexOf('\r', nSelEnd);
			AkelPad.SetSel(lineStart+1, lineEnd);
		}

		var aRows = AkelPad.GetSelText().split('\r');

		var aRowsLength = aRows.length;
		for (iii = 0;   iii < aRowsLength;   iii++)
			aTable[iii] = aRows[iii].split(sSeparator);

		for (ccc = 0;   ccc < aSortOrder.length;   ccc++)
		{
			aTable = arrSort(aTable, aSortOrder[ccc]);
		}

		for (iii = 0;   iii < aRowsLength;   iii++)
			aRows[iii] = aTable[iii].join(sSeparator);

		var tText = aRows.join('\r');

		AkelPad.ReplaceSel(tText);

		AutoRedrawOn(hEditWnd);
	}






Сортировка текста по столбцам.
Sort text by columns.


2011-10-20
* Незначительные изменения.

2011-09-21
* Теперь правильно реагирует на пустой ввод и на отмену.



Или скачать можно тут:
ftp://akelscripts:akelscripts@95.172.154.20/NeO.Sort.js



Превращает:

Code: Select all

d	8	o	д
c	9	n	в
b	8	p

1	 	2

b	7	q	б



a	6	v	а
	

В:
(сортировка по второму столбцу)

Code: Select all







1	 	2
	
a	6	v	а
b	7	q	б
d	8	o	д
b	8	p
c	9	n	в
Last edited by [Yustas.NeO] on Thu Oct 20, 2011 8:28 pm, edited 2 times in total.

Offline
Posts: 119
Joined: Sat Jan 12, 2008 10:16 am
Location: Shantou, China

Post by cnnnc »

Divide Multi_SR.js into SearchReplace_cml.js and SearchReplace_multi.js.

Code: Select all

/// CommandLine of SearchReplace with Argument(s).
//
// Come by offical "SearchReplace.js", and others js. Thanks!
//
//   Example:
//     -"DelEmptyLines" Call("Scripts::Main", 1, "SearchReplace_cml.js", `-Find="^[  \t]*$\n*" -Replace="" -RegExp=1 -Sensitive=0 -Multiline=1 -EscSequences=0 -ReplaceFunction=0 -Direction=8`) Icon(0)
//
//   Note: \\ - backslash
//         \r - line feed
//         \n - new line
//         \t - tabulation
//
//    Find            Should not be Empty
//    Replace
//    RegExp          0 or 1, default is 1
//    Sensitive       0 or 1, default is 0
//    Multiline       0 or 1, default is 0
//    EscSequences    0 or 1, default is 0
//    ReplaceFunction 0 or 1, default is 0. if be set to 1, bEscSequences be set to 0
//    Direction       1  /* DN_DOWN      =0x00000001 */
//                    2  /* DN_UP        =0x00000002 */
//                    4  /* DN_BEGINNING =0x00000004 */ (default)
//                    8  /* DN_SELECTION =0x00000008 */ (if no selection then select all)
//                    16 /* DN_ALLFILES  =0x00000010 */
//    Button          3  /* BT_REPLACE    =3 */
//                    4  /* BT_REPLACEALL =4 */ (default)

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

//Options
var bShowCountOfChanges=false;

//Variables
if (!AkelPad.GetArgLine(0)) WScript.Quit();

var pFindIt=AkelPad.GetArgValue("Find", "");
if (pFindIt=="") WScript.Quit();

var oSys=AkelPad.SystemFunction();
var pScriptName=WScript.ScriptName;
var bAkelEdit=AkelPad.IsAkelEdit();

var pReplaceWithEsc;
var nSearchResult;
var i;

//Buttons
var BT_FIND       =1;
var BT_REPLACE    =3;
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;

//String ID
var STRID_SYNTAXERROR  =22;
var STRID_COUNTFILES   =24;
var STRID_COUNTCHANGES =25;

var pReplaceWith    =AkelPad.GetArgValue("Replace"        , "");
var bRegExp         =AkelPad.GetArgValue("RegExp"         , 1);
var bSensitive      =AkelPad.GetArgValue("Sensitive"      , 0);
var bMultiline      =AkelPad.GetArgValue("Multiline"      , 0);
var bEscSequences   =AkelPad.GetArgValue("EscSequences"   , 0);
var bReplaceFunction=AkelPad.GetArgValue("ReplaceFunction", 0);
var nDirection      =AkelPad.GetArgValue("Direction"      , DN_BEGINNING);
var nButton         =AkelPad.GetArgValue("Button"         , BT_REPLACEALL);

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 (nDirection==DN_DOWN || nDirection==DN_UP || nDirection==DN_BEGINNING || nDirection==DN_SELECTION || nDirection==DN_ALLFILES)
{
}
else
{
  nDirection=DN_BEGINNING;
}
if (nButton==BT_REPLACE || nButton==BT_REPLACEALL)
{
}
else
{
  nButton=BT_REPLACEALL;
}

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, "\\");
  }
}

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

nSearchResult=SearchReplace();

if (nSearchResult == -1)
{
  if (nDirection & DN_ALLFILES)
  {
    nDirection&=~DN_DOWN;
  }
  else if (nDirection & DN_BEGINNING)
  {
    nDirection&=~DN_DOWN;
  }
}
else
{
  if (nDirection == DN_ALLFILES)
  {
    nDirection|=DN_DOWN;
  }
  else if (nDirection == DN_BEGINNING)
  {
    nDirection|=DN_DOWN;
  }
}


//Functions
function SearchReplace()
{
  var lpFrameInit=AkelPad.SendMessage(hMainWnd, 1288 /*AKD_FRAMEFIND*/, 1 /*FWF_CURRENT*/, 0);
  var hWndEditCur=AkelPad.GetEditWnd();
  var oPattern;
  var lpArray;
  var pSelText;
  var pResult;
  var dwOptions;
  var nInitialSelStart;
  var nInitialSelEnd;
  var nSelStart;
  var nSelEnd;
  var nMatches=-1;
  var nChanges=0;
  var nChangedFiles=0;
  var nError;
  var nResult=-1;
  var i;

  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*/);
    return nResult;
  }

  for (;;)
  {
    nInitialSelStart=AkelPad.GetSelStart();
    nInitialSelEnd=AkelPad.GetSelEnd();

    //Check current selection for replace
    if (nButton == BT_REPLACE)
    {
      if (nInitialSelStart != nInitialSelEnd)
      {
        pSelText=AkelPad.GetSelText(2 /*\n*/);
        if (!bAkelEdit)
          pSelText=pSelText.replace(/\r/g, "\n");

        if (/\(\?[=!].*\)/.test(pFindIt)) // Lookahead assertions: x(?=y) or x(?!y)
        {
          var pEndText=AkelPad.GetTextRange(nInitialSelStart, -1, 2 /*\n*/);
          if (!bAkelEdit)
            pEndText=pEndText.replace(/\r/g, "\n");

          if (oPattern.test(pEndText) && RegExp.lastMatch == pSelText)
          {
            pResult=pEndText.replace(oPattern, pReplaceWithEsc);
            pResult=pResult.substr(0, pResult.length - (pEndText.length - pSelText.length));
            AkelPad.ReplaceSel(pResult);

            nInitialSelStart=AkelPad.GetSelStart();
            nInitialSelEnd=AkelPad.GetSelEnd();
          }
        }
        else
        {
          if (lpArray=pSelText.match(oPattern))
          {
            if (lpArray.index == 0 && lpArray[0].length == (nInitialSelEnd - nInitialSelStart))
            {
              pResult=pSelText.replace(oPattern, pReplaceWithEsc);
              AkelPad.ReplaceSel(pResult);

              nInitialSelStart=AkelPad.GetSelStart();
              nInitialSelEnd=AkelPad.GetSelEnd();
            }
          }
        }
      }
      nButton=BT_FIND;
    }

    //Get ranges
    if (nDirection & DN_DOWN)
    {
      if (nButton == BT_FIND)
      {
        nSelStart=nInitialSelEnd;
        nSelEnd=-1;
      }
      else
      {
        nSelStart=nInitialSelStart;
        nSelEnd=-1;
      }
    }
    else if (nDirection & DN_UP)
    {
      if (nButton == BT_FIND)
      {
        nSelStart=0;
        nSelEnd=nInitialSelStart;
      }
      else
      {
        nSelStart=0;
        nSelEnd=nInitialSelEnd;
      }
    }
    else if (nDirection & DN_BEGINNING)
    {
      nSelStart=0;
      nSelEnd=-1;
    }
    else if (nDirection & DN_SELECTION)
    {
      if (AkelPad.SendMessage(hWndEditCur, 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;
    }

    //Find or replace
    try
    {
      pSelText=AkelPad.GetTextRange(nSelStart, nSelEnd, 2 /*\n*/);

      if (nButton == BT_FIND)
      {
        if (lpArray=pSelText.match(oPattern))
        {
          if (nDirection & DN_UP)
          {
            for (i=0; lpArray[i]; ++i)
              AkelPad.SetSel(nSelStart + (lpArray.lastIndex - lpArray[i - 1].length), nSelStart + lpArray.lastIndex, 0x8 /*AESELT_LOCKSCROLL*/);
          }
          else
          {
            AkelPad.SetSel(nSelStart + lpArray.index, nSelStart + lpArray.index + lpArray[0].length, 0x8 /*AESELT_LOCKSCROLL*/);
          }

          ScrollCaret(hWndEditCur);
          nResult=AkelPad.GetSelStart();
        }
        else
        {
          if (nDirection & DN_ALLFILES)
          {
            nDirection&=~DN_DOWN;

            //Next MDI frame
            lpFrameCur=AkelPad.Command(4316 /*IDM_WINDOW_FRAMENEXT*/);
            hWndEditCur=AkelPad.GetEditWnd();
            if (lpFrameCur != lpFrameInit)
              continue;
          }
        }
      }
      else if (nButton == BT_REPLACEALL)
      {
        if (bShowCountOfChanges)
        {
          nMatches=pSelText.match(oPattern);
          nMatches=nMatches?nMatches.length:0;
          nChanges+=nMatches;
          if (nMatches) ++nChangedFiles;
        }

        if (nMatches)
        {
          var nFirstLine;
          var nInitialLine;
          var nInitialCharInLine;

          pResult=pSelText.replace(oPattern, pReplaceWithEsc);

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

          //Replace selection
          if (bAkelEdit)
          {
            if (nDirection & DN_SELECTION)
            {
              dwOptions=AkelPad.SendMessage(hWndEditCur, 3227 /*AEM_GETOPTIONS*/, 0, 0);
              if (!(dwOptions & 0x40 /*AECO_PASTESELECTCOLUMN*/))
                AkelPad.SendMessage(hWndEditCur, 3228 /*AEM_SETOPTIONS*/, 2 /*AECOOP_OR*/, 0x40 /*AECO_PASTESELECTCOLUMN*/);
            }
          }

          AkelPad.SetSel(nSelStart, nSelEnd, 0x8 /*AESELT_LOCKSCROLL*/);
          AkelPad.ReplaceSel(pResult);

          if (bAkelEdit)
          {
            if (nDirection & DN_SELECTION)
            {
              if (!(dwOptions & 0x40 /*AECO_PASTESELECTCOLUMN*/))
                AkelPad.SendMessage(hWndEditCur, 3228 /*AEM_SETOPTIONS*/, 4 /*AECOOP_XOR*/, 0x40 /*AECO_PASTESELECTCOLUMN*/);
            }
          }

          //Restore selection
          if (nDirection & DN_SELECTION)
          {
            if (!AkelPad.SendMessage(hWndEditCur, 3127 /*AEM_GETCOLUMNSEL*/, 0, 0))
              AkelPad.SetSel(nSelStart, nSelStart + pResult.length, 0x8 /*AESELT_LOCKSCROLL*/);
          }
          else
          {
            i=AkelPad.SendMessage(hWndEditCur, 187 /*EM_LINEINDEX*/, nInitialLine, 0) + nInitialCharInLine;
            AkelPad.SetSel(i, i + (nInitialSelEnd - nInitialSelStart), 0x8 /*AESELT_LOCKSCROLL*/);
          }

          RestoreLineScroll(hWndEditCur, nFirstLine);
        }

        if (nDirection & DN_ALLFILES)
        {
          nDirection&=~DN_DOWN;

          //Next MDI frame
          lpFrameCur=AkelPad.Command(4316 /*IDM_WINDOW_FRAMENEXT*/);
          hWndEditCur=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;
  }
  return nResult;
}

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 ScrollCaret(hWnd)
{
  if (nAkelEdit)
  {
    var lpStp;
    var dwScrollFlags=0;
    var dwScrollResult;

    if (lpStp=AkelPad.MemAlloc(_X64?32:20))  //sizeof(AESCROLLTOPOINT)
    {
      //Test scroll to caret
      dwScrollFlags=0x1|0x10|0x400|0x800 /*AESC_TEST|AESC_POINTCARET|AESC_OFFSETCHARX|AESC_OFFSETCHARY*/;
      AkelPad.MemCopy(lpStp, dwScrollFlags, 3 /*DT_DWORD*/);     //AESCROLLTOPOINT.dwFlags
      AkelPad.MemCopy(lpStp + (_X64?24:12), 1, 3 /*DT_DWORD*/);  //AESCROLLTOPOINT.nOffsetX
      AkelPad.MemCopy(lpStp + (_X64?28:16), 0, 3 /*DT_DWORD*/);  //AESCROLLTOPOINT.nOffsetY
      dwScrollResult=AkelPad.SendMessage(hWnd, 3183 /*AEM_SCROLLTOPOINT*/, 0, lpStp);

      dwScrollFlags=0x10 /*AESC_POINTCARET*/;
      if (dwScrollResult & 0x1 /*AECSE_SCROLLEDX*/)
        dwScrollFlags|=0x1000 /*AESC_OFFSETRECTDIVX*/;
      if (dwScrollResult & 0x2 /*AECSE_SCROLLEDY*/)
        dwScrollFlags|=0x2000 /*AESC_OFFSETRECTDIVY*/;

      //Scroll to caret
      AkelPad.MemCopy(lpStp, dwScrollFlags, 3 /*DT_DWORD*/);     //AESCROLLTOPOINT.dwFlags
      AkelPad.MemCopy(lpStp + (_X64?24:12), 3, 3 /*DT_DWORD*/);  //AESCROLLTOPOINT.nOffsetX
      AkelPad.MemCopy(lpStp + (_X64?28:16), 2, 3 /*DT_DWORD*/);  //AESCROLLTOPOINT.nOffsetY
      AkelPad.SendMessage(hWnd, 3183 /*AEM_SCROLLTOPOINT*/, 0, lpStp);

      AkelPad.MemFree(lpStp);
    }
  }
}

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 GetLangString(nStringID)
{
  var nLangID=AkelPad.GetLangId(1 /*LANGID_PRIMARY*/);

  if (nLangID == 0x4) //LANG_CHINESE
  {
    if (nStringID == STRID_SYNTAXERROR)
      return "语法错误:\n \\\\ - 反斜线\n \\r - 换行符\n \\t - 制表符";
    if (nStringID == STRID_COUNTFILES)
      return "替换文件数: ";
    if (nStringID == STRID_COUNTCHANGES)
      return "替换次数: ";
  }
  else
  {
    if (nStringID == STRID_SYNTAXERROR)
      return "Syntax error:\n \\\\ - backslash\n \\r - line feed\n \\t - tabulation";
    if (nStringID == STRID_COUNTFILES)
      return "Changed files: ";
    if (nStringID == STRID_COUNTCHANGES)
      return "Count of changes: ";
  }
  return "";
}
- CommandLine of SearchReplace with Argument(s).

Code: Select all

// Multi search and replace using regular expressions.
//
//  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", `"ChineseSimplify.txt"`)
// -"SearchReplace_Multi" Call("Scripts::Main", 1, "SearchReplace_Multi.js")
//
// If the argument is not a exist file, then open a FileDialog to choose a file.
//
// If there is no argument then popup a menu about all available pattern files.
// The pattern file of Argument 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 pInitialFile=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;

if (WScript.Arguments.length)
{
  pFile = getEnvironmentPath(pInitialFile+"\\" + WScript.Arguments(0));
  if (!pFile)
  {
    if (pFile=FileDialog(true, hMainWnd, pInitialFile+"\\*", GetLangString(STRID_FILTER), nFilterIndex))
    {
    }
    else
      WScript.Quit();
  }
}
else
{
  if (! AkelPad.Include("ShowMenuEx.js")) WScript.Quit();
  pFile = getEnvironmentPath(pInitialFile+"\\" + getSelectedMenuItem(POS_CURSOR, "", 0));
  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 "";
}
- Multi SearchReplace using regular expressions. Need ShowMenuEx.js
Last edited by cnnnc on Tue Dec 18, 2012 1:46 am, edited 3 times in total.

Offline
Posts: 876
Joined: Tue Jul 24, 2007 8:54 am

Post by Fr0sT »

Log message to text file snippet

Code: Select all

// Output message to log file snippet
// 2010 © Fr0sT
// Usage: insert the following text into your script and call: log("something");
// log file is created near the AkelPad.exe

function log(msg) 
{
	if (typeof(FSO) == "undefined")
		FSO = new ActiveXObject("Scripting.FileSystemObject");
	if (typeof(logFile) == "undefined")
		logFile = FSO.OpenTextFile(WScript.ScriptName+".log", 8, true); // open for append, create if not exist
	logFile.WriteLine(Date()+"\t" + msg);
}

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

Post by KDJ »

Inserts text at the beginning and at the end of selection or at the beginning and at the end each of selected lines.
I have used a few functions from scripts LinesFilter.js and SearchReplace.js written by Instructor.

Code: Select all

// Insert text at the beginning and at the end of selection - 2010-08-12
//
// Call("Scripts::Main", 1, "InsertText.js", "0") - insert in selection
// Call("Scripts::Main", 1, "InsertText.js", "1") - insert in each of selected lines
// Call("Scripts::Main", 1, "InsertText.js", "2") - insert in each part of columnar selection
//
// Argument "0" is default, can be omitted.


//Control IDs
var IDC_INPUT      = 1001;
var IDC_ESCNEWLINE = 1003;
var IDC_ESCTAB     = 1004;
var IDC_SELECTION  = 1005;
var IDC_LINES      = 1006;
var IDC_COLSEL     = 1007;
var IDC_OK         = 1008;
var IDC_CANCEL     = 1009;
var IDC_STATIC     = -1;

//Variables
var WshShell = new ActiveXObject("WScript.shell");
var hMainWnd = AkelPad.GetMainWnd();
var hEditWnd = AkelPad.GetEditWnd();
var bColSel  = AkelPad.SendMessage(hEditWnd, 3127 /*AEM_GETCOLUMNSEL*/, 0, 0);
var oSys = AkelPad.SystemFunction();
var pScriptName = WScript.ScriptName;
var hInstanceDLL = AkelPad.GetInstanceDll();
var hWndDialog;
var hWndStaticA;
var hWndStaticB;
var hWndStringA;
var hWndStringB;
var hWndEscNewLine;
var hWndEscTab;
var hWndRange;
var hWndSelection;
var hWndLines;
var hWndColSel;
var hWndOK;
var hWndCancel;
var hGuiFont;
var lpBuffer;

var pStringA    = "";
var pStringB    = "";
var bEscNewLine = false;
var bEscTab     = true;
var bCloseCombo = true;
var nStrings    = 10;
var lpStringsA  = new Array(nStrings);
var lpStringsB  = new Array(nStrings);
var nRange      = 0;
var i;

var pTxtJSver      = "JScript version is less than 5.5.";
var pTxtRO         = "Mode is read-only.";
var pTxtInvArg     = "Invalid argument: ";
var pTxtNoColSel   = "There is no columnar selection.";
var pTxtCaption    = "Insert text";
var pTxtStaticA    = ["at the beginning of selection:",
                      "at the beginning of lines:",
                      "at the beginning of columnar selection:"];
var pTxtStaticB    = ["at the end of selection:",
                      "at the end of lines:",
                      "at the end of columnar selection:"];
var pTxtEscNewLine = "\\n = new line";
var pTxtEscTab     = "\\t = tabulation";
var pTxtRange      = "Range";
var pTxtSelection  = "In selection";
var pTxtLines      = "In each of selected lines";
var pTxtColSel     = "In each part of columnar selection";
var pTxtOK         = "OK";
var pTxtCancel     = "Cancel";


if (hEditWnd)
{
  if (ScriptEngineMajorVersion() <= 5 && ScriptEngineMinorVersion() < 5)
  {
    AkelPad.MessageBox(hMainWnd, pTxtJSver, pScriptName, 48 /*MB_ICONEXCLAMATION*/);
    WScript.Quit();
  }

	if (AkelPad.GetEditReadOnly(hEditWnd))
  {
    AkelPad.MessageBox(hEditWnd, pTxtRO, pTxtCaption, 48 /*MB_ICONEXCLAMATION*/);
    WScript.Quit();
  }

  if (WScript.Arguments.length)
    nRange = WScript.Arguments(0);
  if (!((nRange == 0) || (nRange == 1) || (nRange == 2)))
  {
    AkelPad.MessageBox(hEditWnd, pTxtInvArg + nRange, pTxtCaption, 48 /*MB_ICONEXCLAMATION*/);
    WScript.Quit();
  }
  if ((nRange == 2) && (! bColSel))
  {
    AkelPad.MessageBox(hEditWnd, pTxtNoColSel, pTxtCaption, 48 /*MB_ICONEXCLAMATION*/);
    WScript.Quit();
  }


  if (AkelPad.WindowRegisterClass(pScriptName))
  {
    if (lpBuffer=AkelPad.MemAlloc(256 * _TSIZE))
    {
      //Create dialog
      AkelPad.MemCopy(lpBuffer, pScriptName, _TSTR);
      hWndDialog=oSys.Call("user32::CreateWindowEx" + _TCHAR,
                           0,               //dwExStyle
                           lpBuffer,        //lpClassName
                           0,               //lpWindowName
                           0x90CA0000,      //WS_VISIBLE|WS_POPUP|WS_CAPTION|WS_SYSMENU|WS_MINIMIZEBOX
                           0,               //x
                           0,               //y
                           354,             //nWidth
                           255,             //nHeight
                           hMainWnd,        //hWndParent
                           0,               //ID
                           hInstanceDLL,    //hInstance
                           DialogCallback); //Script function callback. To use it class must be registered by WindowRegisterClass.
      if (hWndDialog)
      {
        //Disable main window, to make dialog modal
        oSys.Call("user32::EnableWindow", hMainWnd, false);

        //Message loop
        AkelPad.WindowGetMessage();
      }
      AkelPad.MemFree(lpBuffer);
    }
    AkelPad.WindowUnregisterClass(pScriptName);
  }
}

//////////////

function DialogCallback(hWnd, uMsg, wParam, lParam)
{
  if (uMsg == 1)  //WM_CREATE
  {
    try
    {
      for (i=0; i < nStrings; ++i)
        lpStringsA[i]=WshShell.RegRead("HKCU\\Software\\Akelsoft\\AkelPad\\Plugs\\Scripts\\InsertText\\TextA" + i);
    }
    catch (nError)
    {
    }
    pSringA = lpStringsA[0];

    try
    {
      for (i=0; i < nStrings; ++i)
        lpStringsB[i]=WshShell.RegRead("HKCU\\Software\\Akelsoft\\AkelPad\\Plugs\\Scripts\\InsertText\\TextB" + i);
    }
    catch (nError)
    {
    }
    pSringB = lpStringsB[0];

    try
    {
      bEscNewLine=WshShell.RegRead("HKCU\\Software\\Akelsoft\\AkelPad\\Plugs\\Scripts\\InsertText\\EscNewLine");
      bEscTab    =WshShell.RegRead("HKCU\\Software\\Akelsoft\\AkelPad\\Plugs\\Scripts\\InsertText\\EscTab");
    }
    catch (nError)
    {
    }

    hGuiFont=oSys.Call("gdi32::GetStockObject", 17 /*DEFAULT_GUI_FONT*/);

    //Dialog caption
    AkelPad.MemCopy(lpBuffer, pTxtCaption, _TSTR);
    oSys.Call("user32::SetWindowText" + _TCHAR, hWnd, lpBuffer);

    //Create window static A
    AkelPad.MemCopy(lpBuffer, "STATIC", _TSTR);
    hWndStaticA=oSys.Call("user32::CreateWindowEx" + _TCHAR,
                          0,            //dwExStyle
                          lpBuffer,     //lpClassName
                          0,            //lpWindowName
                          0x50000000,   //WS_VISIBLE|WS_CHILD
                          11,           //x
                          13,           //y
                          305,          //nWidth
                          13,           //nHeight
                          hWnd,         //hWndParent
                          IDC_STATIC,   //ID
                          hInstanceDLL, //hInstance
                          0);           //lpParam
    //Set font and text
    SetWindowFontAndText(hWndStaticA, hGuiFont, pTxtStaticA[nRange]);

    //Create window static B
    AkelPad.MemCopy(lpBuffer, "STATIC", _TSTR);
    hWndStaticB=oSys.Call("user32::CreateWindowEx" + _TCHAR,
                          0,            //dwExStyle
                          lpBuffer,     //lpClassName
                          0,            //lpWindowName
                          0x50000000,   //WS_VISIBLE|WS_CHILD
                          11,           //x
                          61,           //y
                          305,          //nWidth
                          13,           //nHeight
                          hWnd,         //hWndParent
                          IDC_STATIC,   //ID
                          hInstanceDLL, //hInstance
                          0);           //lpParam
    //Set font and text
    SetWindowFontAndText(hWndStaticB, hGuiFont, pTxtStaticB[nRange]);

    //Create window edit A
    AkelPad.MemCopy(lpBuffer, "COMBOBOX", _TSTR);
    hWndStringA=oSys.Call("user32::CreateWindowEx" + _TCHAR,
                          0,            //dwExStyle
                          lpBuffer,     //lpClassName
                          0,            //lpWindowName
                          0x50210042,   //WS_VISIBLE|WS_CHILD|WS_TABSTOP|WS_VSCROLL|CBS_DROPDOWN|CBS_AUTOHSCROLL
                          11,           //x
                          31,           //y
                          323,          //nWidth
                          23,           //nHeight
                          hWnd,         //hWndParent
                          IDC_INPUT,    //ID
                          hInstanceDLL, //hInstance
                          0);           //lpParam
    //Fill combobox
    for (i=0; i < nStrings; ++i)
    {
      AkelPad.MemCopy(lpBuffer, lpStringsA[i], _TSTR);
      AkelPad.SendMessage(hWndStringA, 0x143 /*CB_ADDSTRING*/, 0, lpBuffer);
    }
    //Set font and text
    SetWindowFontAndText(hWndStringA, hGuiFont, "");
    AkelPad.SendMessage(hWndStringA, 0x14E /*CB_SETCURSEL*/, 0, 0);

    //Create window edit B
    AkelPad.MemCopy(lpBuffer, "COMBOBOX", _TSTR);
    hWndStringB=oSys.Call("user32::CreateWindowEx" + _TCHAR,
                          0,            //dwExStyle
                          lpBuffer,     //lpClassName
                          0,            //lpWindowName
                          0x50210042,   //WS_VISIBLE|WS_CHILD|WS_TABSTOP|WS_VSCROLL|CBS_DROPDOWN|CBS_AUTOHSCROLL
                          11,           //x
                          79,           //y
                          323,          //nWidth
                          23,           //nHeight
                          hWnd,         //hWndParent
                          IDC_INPUT,    //ID
                          hInstanceDLL, //hInstance
                          0);           //lpParam
    //Fill combobox
    for (i=0; i < nStrings; ++i)
    {
      AkelPad.MemCopy(lpBuffer, lpStringsB[i], _TSTR);
      AkelPad.SendMessage(hWndStringB, 0x143 /*CB_ADDSTRING*/, 0, lpBuffer);
    }
    //Set font and text
    SetWindowFontAndText(hWndStringB, hGuiFont, "");
    AkelPad.SendMessage(hWndStringB, 0x14E /*CB_SETCURSEL*/, 0, 0);

    //Create window GroupBox Range
    AkelPad.MemCopy(lpBuffer, "BUTTON", _TSTR);
    hWndRange=oSys.Call("user32::CreateWindowEx" + _TCHAR,
                         0,            //dwExStyle
                         lpBuffer,     //lpClassName
                         0,            //lpWindowName
                         0x50000007,   //WS_VISIBLE|WS_CHILD|BS_GROUPBOX
                         11,           //x
                         113,          //y
                         200,          //nWidth
                         82,           //nHeight
                         hWnd,         //hWndParent
                         IDC_STATIC,   //ID
                         hInstanceDLL, //hInstance
                         0);           //lpParam
    //Set font and text
    SetWindowFontAndText(hWndRange, hGuiFont, pTxtRange);

    //Create window Radiobutton Selection
    AkelPad.MemCopy(lpBuffer, "BUTTON", _TSTR);
    hWndSelection=oSys.Call("user32::CreateWindowEx" + _TCHAR,
                            0,             //dwExStyle
                            lpBuffer,      //lpClassName
                            0,             //lpWindowName
                            0x50000009,    //WS_VISIBLE|WS_CHILD|BS_AUTORADIOBUTTON
                            18,            //x
                            131,           //y
                            190,           //nWidth
                            16,            //nHeight
                            hWnd,          //hWndParent
                            IDC_SELECTION, //ID
                            hInstanceDLL,  //hInstance
                            0);            //lpParam
    //Set font and text
    SetWindowFontAndText(hWndSelection, hGuiFont, pTxtSelection);

    //Create window Radiobutton Lines
    AkelPad.MemCopy(lpBuffer, "BUTTON", _TSTR);
    hWndLines=oSys.Call("user32::CreateWindowEx" + _TCHAR,
                        0,            //dwExStyle
                        lpBuffer,     //lpClassName
                        0,            //lpWindowName
                        0x50000009,   //WS_VISIBLE|WS_CHILD|BS_AUTORADIOBUTTON
                        18,           //x
                        151,          //y
                        190,          //nWidth
                        16,           //nHeight
                        hWnd,         //hWndParent
                        IDC_LINES,    //ID
                        hInstanceDLL, //hInstance
                        0);           //lpParam
    //Set font and text
    SetWindowFontAndText(hWndLines, hGuiFont, pTxtLines);

    //Create window Radiobutton Columnar Selection
    AkelPad.MemCopy(lpBuffer, "BUTTON", _TSTR);
    hWndColSel=oSys.Call("user32::CreateWindowEx" + _TCHAR,
                         0,            //dwExStyle
                         lpBuffer,     //lpClassName
                         0,            //lpWindowName
                         0x50000009,   //WS_VISIBLE|WS_CHILD|BS_AUTORADIOBUTTON
                         18,           //x
                         171,          //y
                         190,          //nWidth
                         16,           //nHeight
                         hWnd,         //hWndParent
                         IDC_COLSEL,   //ID
                         hInstanceDLL, //hInstance
                         0);           //lpParam
    //Set font and text
    SetWindowFontAndText(hWndColSel, hGuiFont, pTxtColSel);
    //Check
    if (nRange == 0)
      AkelPad.SendMessage(hWndSelection, 241 /*BM_SETCHECK*/, 1 /*BST_CHECKED*/, 0);
    else if (nRange == 1)
      AkelPad.SendMessage(hWndLines, 241 /*BM_SETCHECK*/, 1 /*BST_CHECKED*/, 0);
    else
      AkelPad.SendMessage(hWndColSel, 241 /*BM_SETCHECK*/, 1 /*BST_CHECKED*/, 0);
    if (! bColSel)
      oSys.Call("user32::EnableWindow", hWndColSel, false);

    //Create window checkbox EscNewLine
    AkelPad.MemCopy(lpBuffer, "BUTTON", _TSTR);
    hWndEscNewLine=oSys.Call("user32::CreateWindowEx" + _TCHAR,
                             0,              //dwExStyle
                             lpBuffer,       //lpClassName
                             0,              //lpWindowName
                             0x50010003,     //WS_VISIBLE|WS_CHILD|WS_TABSTOP|BS_AUTOCHECKBOX
                             240,            //x
                             113,            //y
                             120,            //nWidth
                             16,             //nHeight
                             hWnd,           //hWndParent
                             IDC_ESCNEWLINE, //ID
                             hInstanceDLL,   //hInstance
                             0);             //lpParam
    //Set font and text
    SetWindowFontAndText(hWndEscNewLine, hGuiFont, pTxtEscNewLine);
    //Check
    if (bEscNewLine) AkelPad.SendMessage(hWndEscNewLine, 241 /*BM_SETCHECK*/, 1 /*BST_CHECKED*/, 0);
 
    //Create window checkbox EscTab
    AkelPad.MemCopy(lpBuffer, "BUTTON", _TSTR);
    hWndEscTab=oSys.Call("user32::CreateWindowEx" + _TCHAR,
                         0,            //dwExStyle
                         lpBuffer,     //lpClassName
                         0,            //lpWindowName
                         0x50010003,   //WS_VISIBLE|WS_CHILD|WS_TABSTOP|BS_AUTOCHECKBOX
                         240,          //x
                         134,          //y
                         120,          //nWidth
                         16,           //nHeight
                         hWnd,         //hWndParent
                         IDC_ESCTAB,   //ID
                         hInstanceDLL, //hInstance
                         0);           //lpParam
    //Set font and text
    SetWindowFontAndText(hWndEscTab, hGuiFont, pTxtEscTab);
    //Check
    if (bEscTab) AkelPad.SendMessage(hWndEscTab, 241 /*BM_SETCHECK*/, 1 /*BST_CHECKED*/, 0);

    //Create window OK button
    AkelPad.MemCopy(lpBuffer, "BUTTON", _TSTR);
    hWndOK=oSys.Call("user32::CreateWindowEx" + _TCHAR,
                     0,            //dwExStyle
                     lpBuffer,     //lpClassName
                     0,            //lpWindowName
                     0x50010001,   //WS_VISIBLE|WS_CHILD|WS_TABSTOP|BS_DEFPUSHBUTTON
                     260,          //x
                     160,          //y
                     75,           //nWidth
                     23,           //nHeight
                     hWnd,         //hWndParent
                     IDC_OK,       //ID
                     hInstanceDLL, //hInstance
                     0);           //lpParam
    //Set font and text
    SetWindowFontAndText(hWndOK, hGuiFont, pTxtOK);

    //Create window Cancel button
    AkelPad.MemCopy(lpBuffer, "BUTTON", _TSTR);
    hWndCancel=oSys.Call("user32::CreateWindowEx" + _TCHAR,
                         0,            //dwExStyle
                         lpBuffer,     //lpClassName
                         0,            //lpWindowName
                         0x50010000,   //WS_VISIBLE|WS_CHILD|WS_TABSTOP
                         260,          //x
                         190,          //y
                         75,           //nWidth
                         23,           //nHeight
                         hWnd,         //hWndParent
                         IDC_CANCEL,   //ID
                         hInstanceDLL, //hInstance
                         0);           //lpParam
    //Set font and text
    SetWindowFontAndText(hWndCancel, hGuiFont, pTxtCancel);

    //Center dialog
    CenterWindow(hEditWnd, hWnd);
  }

  else if (uMsg == 7)  //WM_SETFOCUS
    oSys.Call("user32::SetFocus", hWndStringA);
  else if (uMsg == 256)  //WM_KEYDOWN
  {
    if (bCloseCombo)
    {
      if (wParam == 27)  //VK_ESCAPE
        //Escape key pushes Cancel button
        oSys.Call("user32::PostMessage" + _TCHAR, hWndDialog, 273 /*WM_COMMAND*/, IDC_CANCEL, 0);
      else if (wParam == 13)  //VK_RETURN
        //Return key pushes OK button
        oSys.Call("user32::PostMessage" + _TCHAR, hWndDialog, 273 /*WM_COMMAND*/, IDC_OK, 0);
    }
  }
  else if (uMsg == 273)  //WM_COMMAND
  {
    if (LoWord(wParam) == IDC_INPUT)
    {
      if (HiWord(wParam) == 7 /*CBN_DROPDOWN*/)
        bCloseCombo = false;
      else if (HiWord(wParam) == 8 /*CBN_CLOSEUP*/)
        bCloseCombo = true;
    }

    if (LoWord(wParam) == IDC_ESCNEWLINE)
      bEscNewLine=AkelPad.SendMessage(hWndEscNewLine, 240 /*BM_GETCHECK*/, 0, 0);

    else if (LoWord(wParam) == IDC_ESCTAB)
      bEscTab=AkelPad.SendMessage(hWndEscTab, 240 /*BM_GETCHECK*/, 0, 0);

    else if (LoWord(wParam) == IDC_SELECTION)
    {
      nRange = 0;
      SetWindowFontAndText(hWndStaticA, hGuiFont, pTxtStaticA[nRange]);
      SetWindowFontAndText(hWndStaticB, hGuiFont, pTxtStaticB[nRange]);
    }

    else if (LoWord(wParam) == IDC_LINES)
    {
      nRange = 1;
      SetWindowFontAndText(hWndStaticA, hGuiFont, pTxtStaticA[nRange]);
      SetWindowFontAndText(hWndStaticB, hGuiFont, pTxtStaticB[nRange]);
    }

    else if (LoWord(wParam) == IDC_COLSEL)
    {
      nRange = 2;
      SetWindowFontAndText(hWndStaticA, hGuiFont, pTxtStaticA[nRange]);
      SetWindowFontAndText(hWndStaticB, hGuiFont, pTxtStaticB[nRange]);
    }

    else if (LoWord(wParam) == IDC_OK)
    {
      //pStringA
      oSys.Call("user32::GetWindowText" + _TCHAR, hWndStringA, lpBuffer, 256);
      pStringA = AkelPad.MemRead(lpBuffer, _TSTR);
      for (i=0; i < nStrings; ++i)
      {
        if (lpStringsA[i] == pStringA)
        {
          AkelPad.SendMessage(hWndStringA, 0x144 /*CB_DELETESTRING*/, i, 0);
          DeleteFromArray(lpStringsA, i, 1);
        }
      }
      InsertInArray(lpStringsA, pStringA, 0);
      if (lpStringsA.length > nStrings)
        DeleteFromArray(lpStringsA, -1, 1);
      AkelPad.MemCopy(lpBuffer, pStringA, _TSTR);
      AkelPad.SendMessage(hWndStringA, 0x14A /*CB_INSERTSTRING*/, 0, lpBuffer);
      AkelPad.SendMessage(hWndStringA, 0x14E /*CB_SETCURSEL*/, 0, 0);

      //pStringB
      oSys.Call("user32::GetWindowText" + _TCHAR, hWndStringB, lpBuffer, 256);
      pStringB = AkelPad.MemRead(lpBuffer, _TSTR);
      for (i=0; i < nStrings; ++i)
      {
        if (lpStringsB[i] == pStringB)
        {
          AkelPad.SendMessage(hWndStringB, 0x144 /*CB_DELETESTRING*/, i, 0);
          DeleteFromArray(lpStringsB, i, 1);
        }
      }
      InsertInArray(lpStringsB, pStringB, 0);
      if (lpStringsB.length > nStrings)
        DeleteFromArray(lpStringsB, -1, 1);
      AkelPad.MemCopy(lpBuffer, pStringB, _TSTR);
      AkelPad.SendMessage(hWndStringB, 0x14A /*CB_INSERTSTRING*/, 0, lpBuffer);
      AkelPad.SendMessage(hWndStringB, 0x14E /*CB_SETCURSEL*/, 0, 0);

      InsertText();

      oSys.Call("user32::PostMessage" + _TCHAR, hWndDialog, 16 /*WM_CLOSE*/, 0, 0);
    }

    else if (LoWord(wParam) == IDC_CANCEL)
    {
      oSys.Call("user32::PostMessage" + _TCHAR, hWndDialog, 16 /*WM_CLOSE*/, 0, 0);
    }
  }
  else if (uMsg == 16)  //WM_CLOSE
  {
    //Enable main window
    oSys.Call("user32::EnableWindow", hMainWnd, true);

    for (i=0; i < nStrings; ++i)
      WshShell.RegWrite("HKCU\\Software\\Akelsoft\\AkelPad\\Plugs\\Scripts\\InsertText\\TextA" + i, lpStringsA[i], "REG_SZ");
    for (i=0; i < nStrings; ++i)
      WshShell.RegWrite("HKCU\\Software\\Akelsoft\\AkelPad\\Plugs\\Scripts\\InsertText\\TextB" + i, lpStringsB[i], "REG_SZ");
    WshShell.RegWrite("HKCU\\Software\\Akelsoft\\AkelPad\\Plugs\\Scripts\\InsertText\\EscNewLine", bEscNewLine, "REG_DWORD");
    WshShell.RegWrite("HKCU\\Software\\Akelsoft\\AkelPad\\Plugs\\Scripts\\InsertText\\EscTab", bEscTab, "REG_DWORD");

    //Destroy dialog
    oSys.Call("user32::DestroyWindow", hWnd);
  }
  else if (uMsg == 2)  //WM_DESTROY
  {
    //Exit message loop
    oSys.Call("user32::PostQuitMessage", 0);
  }
  return 0;
}


function SetWindowFontAndText(hWnd, hFont, pText)
{
  var lpWindowText;

  AkelPad.SendMessage(hWnd, 48 /*WM_SETFONT*/, hFont, true);

  if (lpWindowText=AkelPad.MemAlloc(256 * _TSIZE))
  {
    AkelPad.MemCopy(lpWindowText, pText.substr(0, 255), _TSTR);
    oSys.Call("user32::SetWindowText" + _TCHAR, hWnd, lpWindowText);

    AkelPad.MemFree(lpWindowText);
  }
}


function CenterWindow(hWndParent, hWnd)
{
  var lpRect;
  var rcWndParent=[];
  var rcWnd=[];
  var X;
  var Y;

  if (lpRect=AkelPad.MemAlloc(16))  //sizeof(RECT)
  {
    if (!hWndParent)
      hWndParent=oSys.Call("user32::GetDesktopWindow");

    oSys.Call("user32::GetWindowRect", hWndParent, lpRect);
    RectToArray(lpRect, rcWndParent);

    oSys.Call("user32::GetWindowRect", hWnd, lpRect);
    RectToArray(lpRect, rcWnd);

    //Center window
    X=rcWndParent.left + ((rcWndParent.right - rcWndParent.left) / 2 - (rcWnd.right - rcWnd.left) / 2);
    Y=rcWndParent.top + ((rcWndParent.bottom - rcWndParent.top) / 2 - (rcWnd.bottom - rcWnd.top) / 2);

    oSys.Call("user32::SetWindowPos", hWnd, 0, X, Y, 0, 0, 0x15 /*SWP_NOZORDER|SWP_NOACTIVATE|SWP_NOSIZE*/);

    AkelPad.MemFree(lpRect);
  }
}


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 InsertInArray(lpArray, lpItem, nPos)
{
  var i;

  if (nPos < 0) nPos=lpArray.length + nPos + 1;
  if (nPos < 0) nPos=0;
  if (nPos > lpArray.length) nPos=lpArray.length;

  for (i=lpArray.length; i >= 0; --i)
  {
    if (i == nPos)
    {
      lpArray[i]=lpItem;
      break;
    }
    lpArray[i]=lpArray[i - 1];
  }
}


function DeleteFromArray(lpArray, nPos, nCount)
{
  var i;

  if (nPos < 0) nPos=lpArray.length + nPos;
  if (nPos < 0 || nPos >= lpArray.length) return;
  if (nPos + nCount >= lpArray.length) nCount=lpArray.length - nPos;

  for (i=nPos; i + nCount < lpArray.length; ++i)
  {
    lpArray[i]=lpArray[i + nCount];
  }
  lpArray.length-=nCount;
}


function LoWord(nParam)
{
  return (nParam & 0xffff);
}


function HiWord(nParam)
{
  return ((nParam >> 16) & 0xffff);
}


function GetOffset(hWnd, nFlag)
{
  var lpIndex;
  var nOffset=-1;

  if (lpIndex=AkelPad.MemAlloc(12 /*sizeof(AECHARINDEX)*/))
  {
    AkelPad.SendMessage(hWnd, 3130 /*AEM_GETINDEX*/, nFlag, lpIndex);
    nOffset=AkelPad.SendMessage(hWnd, 3136 /*AEM_INDEXTORICHOFFSET*/, 0, lpIndex);
    AkelPad.MemFree(lpIndex);
  }
  return nOffset;
} 


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


function InsertText()
{
  var nWordWrap;
  var nBegSel;
  var nEndSel;
	var nLine1;
	var nLine2;
  var pSelTxt;

  if (bEscNewLine)
  {
    pStringA = pStringA.replace(/\\n/g, "\r");
    pStringB = pStringB.replace(/\\n/g, "\r");
  }
  if (bEscTab)
  {
    pStringA = pStringA.replace(/\\t/g, "\t");
    pStringB = pStringB.replace(/\\t/g, "\t");
  }

  // insert in selection
  if (nRange == 0)
  {
    pSelTxt = AkelPad.GetSelText(1 /*\r*/);
    AkelPad.ReplaceSel(pStringA + pSelTxt + pStringB, true);

    if (bColSel)
      AkelPad.SendMessage(hEditWnd, 3128 /*AEM_UPDATESEL*/, 0x1 /*AESELT_COLUMNON*/, 0);
  }

  // insert in each of selected lines and columnar selection
  else
  {
    SetRedraw(hEditWnd, false);
    nWordWrap = AkelPad.SendMessage(hEditWnd, 3241 /*AEM_GETWORDWRAP*/, 0, 0);
    if (nWordWrap > 0)
      AkelPad.Command(4209 /*IDM_VIEW_WORDWRAP*/);

    if (nRange == 1)
    {
      nBegSel = AkelPad.GetSelStart();
      nEndSel = AkelPad.GetSelEnd();
      nLine1  = AkelPad.SendMessage(hEditWnd, 1078 /*EM_EXLINEFROMCHAR*/, 0, nBegSel);
      nLine2  = AkelPad.SendMessage(hEditWnd, 1078 /*EM_EXLINEFROMCHAR*/, 0, nEndSel);
      nBegSel = AkelPad.SendMessage(hEditWnd, 187 /*EM_LINEINDEX*/, nLine1, 0);
      nEndSel = AkelPad.SendMessage(hEditWnd, 187 /*EM_LINEINDEX*/, nLine2, 0) + AkelPad.SendMessage(hEditWnd, 193 /*EM_LINELENGTH*/, nEndSel, 0);

      AkelPad.SetSel(nBegSel, nEndSel);
    }

    pSelTxt = AkelPad.GetSelText(1 /*\r*/);
    pSelTxt = pSelTxt.replace(/\r/g, pStringB + "\r" + pStringA);
    pSelTxt = pStringA + pSelTxt + pStringB;

    AkelPad.ReplaceSel(pSelTxt, true);

    if (nRange == 2)
      AkelPad.SendMessage(hEditWnd, 3128 /*AEM_UPDATESEL*/, 0x1 /*AESELT_COLUMNON*/, 0);

    if (nWordWrap > 0)
      AkelPad.Command(4209 /*IDM_VIEW_WORDWRAP*/);
    SetRedraw(hEditWnd, true);
  }
}

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

Post by KDJ »

An expanded version of the script InsertText.js, inserts also line numbers.
I used the idea cnnnc for numbering lines (script NumberCount.js). Thank you cnnnc.

Code: Select all

// http://akelpad.sourceforge.net/forum/viewtopic.php?p=8939#p8939
// Version: 2015-09-19
// Author: KDJ
//
// *** Insert text/line number at beginning/end of selection ***
//
// Usage:
//   Call("Scripts::Main", 1, "InsertTextLN.js", "0") - insert in selection
//   Call("Scripts::Main", 1, "InsertTextLN.js", "1") - insert in each of selected lines
//   Call("Scripts::Main", 1, "InsertTextLN.js", "2") - insert in each part of columnar selection
//
// Remarks:
//   Argument "0" is default, can be omitted.
//   The script should be saved in Unicode format.

var oSys   = AkelPad.SystemFunction();
var pClass = "AkelPad::Scripts::" + WScript.ScriptName + "::" + AkelPad.GetInstanceDll();
var hDlg   = oSys.Call("User32::FindWindowExW", 0, 0, pClass, 0);

if (hDlg)
{
  if (! oSys.Call("User32::IsWindowVisible", hDlg))
    oSys.Call("User32::ShowWindow", hDlg, 8 /*SW_SHOWNA*/);
  if (oSys.Call("User32::IsIconic", hDlg))
    oSys.Call("User32::ShowWindow", hDlg, 9 /*SW_RESTORE*/);

  oSys.Call("User32::SetForegroundWindow", hDlg);
  WScript.Quit();
}

var hMainWnd  = AkelPad.GetMainWnd();
var hEditWnd  = AkelPad.GetEditWnd();
var bReadOnly = AkelPad.GetEditReadOnly(hEditWnd);
var bColSel   = AkelPad.SendMessage(hEditWnd, 3127 /*AEM_GETCOLUMNSEL*/, 0, 0);
var nStrMax   = 15;
var pStrA     = "";
var pStrB     = "";
var bEscNL    = 0;
var bEscTab   = 1;
var nRange    = 0;
var bIsLNL    = 0;
var pPadLNL   = "";
var pPreLNL   = "";
var pSufLNL   = "";
var bRelLNL   = 0;
var pIniLNL   = "1";
var pStepLNL  = "1";
var bIsLNR    = 0;
var pPadLNR   = "";
var pPreLNR   = "";
var pSufLNR   = "";
var bRelLNR   = 0;
var pIniLNR   = "1";
var pStepLNR  = "1";
var bReplace  = 0;
var nDlgX     = 200;
var nDlgY     = 100;
var lpStrsA;
var lpStrsB;

GetLangStrings();
ReadIni();

if (WScript.Arguments.length)
  nRange = parseInt(WScript.Arguments(0));

if ((nRange != 0) && (nRange != 1) && (nRange != 2))
  nRange = 0;

if ((nRange == 2) && (! bColSel))
{
  AkelPad.MessageBox(hEditWnd, pTxtNoColSel, pTxtCaption, 48 /*MB_ICONEXCLAMATION*/);
  nRange = 0;
}

var IDTXTA       = 1000;
var IDTXTB       = 1001;
var IDSTRA       = 1002;
var IDSTRB       = 1003;
var IDLNL        = 1004;
var IDISLNL      = 1005;
var IDTXTPADLNL  = 1006;
var IDPADLNL     = 1007;
var IDTXTPRELNL  = 1008;
var IDTXTSUFLNL  = 1009;
var IDPRELNL     = 1010;
var IDSUFLNL     = 1011;
var IDRELLNL     = 1012;
var IDTXTINILNL  = 1013;
var IDTXTSTEPLNL = 1014;
var IDINILNL     = 1015;
var IDSTEPLNL    = 1016;
var IDESC        = 1017;
var IDESCNL      = 1018;
var IDESCTAB     = 1019;
var IDRANGE      = 1020;
var IDSELECTION  = 1021;
var IDLINES      = 1022;
var IDCOLSEL     = 1023;
var IDREPLACE    = 1024;
var IDLNR        = 1025;
var IDISLNR      = 1026;
var IDTXTPADLNR  = 1027;
var IDPADLNR     = 1028;
var IDTXTPRELNR  = 1029;
var IDTXTSUFLNR  = 1030;
var IDPRELNR     = 1031;
var IDSUFLNR     = 1032;
var IDRELLNR     = 1033;
var IDTXTINILNR  = 1034;
var IDTXTSTEPLNR = 1035;
var IDINILNR     = 1036;
var IDSTEPLNR    = 1037;
var IDAPPLY      = 1038;
var IDOK         = 1039;
var IDCLOSE      = 1040;

AkelPad.WindowRegisterClass(pClass);

//0x50000000 = WS_VISIBLE|WS_CHILD
//0x50000007 = WS_VISIBLE|WS_CHILD|BS_GROUPBOX
//0x50000009 = WS_VISIBLE|WS_CHILD|BS_AUTORADIOBUTTON
//0x50010000 = WS_VISIBLE|WS_CHILD|WS_TABSTOP
//0x50010001 = WS_VISIBLE|WS_CHILD|WS_TABSTOP|BS_DEFPUSHBUTTON
//0x50010003 = WS_VISIBLE|WS_CHILD|WS_TABSTOP|BS_AUTOCHECKBOX
//0x50010080 = WS_VISIBLE|WS_CHILD|WS_TABSTOP|ES_AUTOHSCROLL
//0x50012080 = WS_VISIBLE|WS_CHILD|WS_TABSTOP|ES_AUTOHSCROLL|ES_NUMBER
//0x50210042 = WS_VISIBLE|WS_CHILD|WS_TABSTOP|WS_VSCROLL|CBS_DROPDOWN|CBS_AUTOHSCROLL
//0x90CA0040 = WS_VISIBLE|WS_POPUP|WS_CAPTION|WS_SYSMENU|WS_MINIMIZEBOX|DS_SETFONT
AkelPad.CreateDialog(0, pClass, pTxtCaption, 0x90CA0040, nDlgX, nDlgY, 485, 275, hMainWnd, DialogCallback, 0x2 /*CDF_PIXELS*/, 0, 0, "MS Shell Dlg", 1, 8, "|",
  //ExSt, Class,      Title,         Style,        X,   Y,   W,   H, ID,      lParam,
  0x0000, "STATIC",   "",            0x50000000,  10,  10, 225,  13, IDTXTA,       0, "|",
  0x0000, "STATIC",   "",            0x50000000, 250,  10, 225,  13, IDTXTB,       0, "|",
  0x0000, "COMBOBOX", "",            0x50210042,  10,  26, 225,  21, IDSTRA,       0, "|",
  0x0000, "COMBOBOX", "",            0x50210042, 250,  26, 225,  21, IDSTRB,       0, "|",
  0x0000, "BUTTON",   "",            0x50000007,  10,  55, 155, 177, IDLNL,        0, "|",
  0x0000, "BUTTON",   pTxtLNL,       0x50010003,  20,  70, 135,  16, IDISLNL,      0, "|",
  0x0000, "STATIC",   pTxtPadLN,     0x50000000,  20,  93,  70,  13, IDTXTPADLNL,  0, "|",
  0x0200, "EDIT",     pPadLNL,       0x50010080,  90,  91,  20,  20, IDPADLNL,     0, "|",
  0x0000, "STATIC",   pTxtPreLN,     0x50000000,  20, 117,  65,  13, IDTXTPRELNL,  0, "|",
  0x0000, "STATIC",   pTxtSufLN,     0x50000000,  90, 117,  65,  13, IDTXTSUFLNL,  0, "|",
  0x0200, "EDIT",     pPreLNL,       0x50010080,  20, 132,  65,  20, IDPRELNL,     0, "|",
  0x0200, "EDIT",     pSufLNL,       0x50010080,  90, 132,  65,  20, IDSUFLNL,     0, "|",
  0x0000, "BUTTON",   pTxtRelLN,     0x50010003,  20, 165, 135,  16, IDRELLNL,     0, "|",
  0x0000, "STATIC",   pTxtIniLN,     0x50000000,  20, 186,  65,  13, IDTXTINILNL,  0, "|",
  0x0000, "STATIC",   pTxtStepLN,    0x50000000,  90, 186,  65,  13, IDTXTSTEPLNL, 0, "|",
  0x0200, "EDIT",     pIniLNL,       0x50012080,  20, 201,  65,  20, IDINILNL,     0, "|",
  0x0200, "EDIT",     pStepLNL,      0x50012080,  90, 201,  65,  20, IDSTEPLNL,    0, "|",
  0x0000, "BUTTON",   "",            0x50000007, 175,  55, 135,  58, IDESC,        0, "|",
  0x0000, "BUTTON",   pTxtEscNL,     0x50010003, 185,  70, 120,  16, IDESCNL,      0, "|",
  0x0000, "BUTTON",   pTxtEscTab,    0x50010003, 185,  90, 120,  16, IDESCTAB,     0, "|",
  0x0000, "BUTTON",   pTxtRange,     0x50000007, 175, 122, 135,  81, IDRANGE,      0, "|",
  0x0000, "BUTTON",   pTxtSelection, 0x50000009, 185, 140, 120,  16, IDSELECTION,  0, "|",
  0x0000, "BUTTON",   pTxtLines,     0x50000009, 185, 160, 120,  16, IDLINES,      0, "|",
  0x0000, "BUTTON",   pTxtColSel,    0x50000009, 185, 180, 120,  16, IDCOLSEL,     0, "|",
  0x0000, "BUTTON",   pTxtReplace,   0x50010003, 185, 215, 120,  16, IDREPLACE,    0, "|",
  0x0000, "BUTTON",   "",            0x50000007, 320,  55, 155, 177, IDLNR,        0, "|",
  0x0000, "BUTTON",   pTxtLNR,       0x50010003, 330,  70, 135,  16, IDISLNR,      0, "|",
  0x0000, "STATIC",   pTxtPadLN,     0x50000000, 330,  93,  70,  13, IDTXTPADLNR,  0, "|",
  0x0200, "EDIT",     pPadLNR,       0x50010080, 400,  91,  20,  20, IDPADLNR,     0, "|",
  0x0000, "STATIC",   pTxtPreLN,     0x50000000, 330, 117,  65,  13, IDTXTPRELNR,  0, "|",
  0x0000, "STATIC",   pTxtSufLN,     0x50000000, 400, 117,  65,  13, IDTXTSUFLNR,  0, "|",
  0x0200, "EDIT",     pPreLNR,       0x50010080, 330, 132,  65,  20, IDPRELNR,     0, "|",
  0x0200, "EDIT",     pSufLNR,       0x50010080, 400, 132,  65,  20, IDSUFLNR,     0, "|",
  0x0000, "BUTTON",   pTxtRelLN,     0x50010003, 330, 165, 135,  16, IDRELLNR,     0, "|",
  0x0000, "STATIC",   pTxtIniLN,     0x50000000, 330, 186,  65,  13, IDTXTINILNR,  0, "|",
  0x0000, "STATIC",   pTxtStepLN,    0x50000000, 400, 186,  65,  13, IDTXTSTEPLNR, 0, "|",
  0x0200, "EDIT",     pIniLNR,       0x50012080, 330, 201,  65,  20, IDINILNR,     0, "|",
  0x0200, "EDIT",     pStepLNR,      0x50012080, 400, 201,  65,  20, IDSTEPLNR,    0, "|",
  0x0000, "BUTTON",   pTxtApply,     0x50010000, 120, 242,  75,  23, IDAPPLY,      0, "|",
  0x0000, "BUTTON",   pTxtOK,        0x50010001, 205, 242,  75,  23, IDOK,         0, "|",
  0x0000, "BUTTON",   pTxtClose,     0x50010000, 290, 242,  75,  23, IDCLOSE,      0, "|"
  );

if (hDlg)
{
  AkelPad.ScriptNoMutex();
  AkelPad.WindowGetMessage(0x2 /*WGM_NOKEYSEND*/);
}

AkelPad.WindowUnregisterClass(pClass);

function DialogCallback(hWnd, uMsg, wParam, lParam)
{
  var nID, i;

  if (uMsg == 272 /*WM_INITDIALOG*/)
  {
    hDlg = hWnd;

    //Fill comboboxes
    for (i = 0; i < lpStrsA.length; ++i)
      SendDlgItemMessage(IDSTRA, 323 /*CB_ADDSTRING*/, 0, lpStrsA[i]);
    for (i = 0; i < lpStrsB.length; ++i)
      SendDlgItemMessage(IDSTRB, 323 /*CB_ADDSTRING*/, 0, lpStrsB[i]);
    SetDlgItemText(IDSTRA, pStrA);
    SetDlgItemText(IDSTRB, pStrB);

    //Check
    CheckDlgButton(IDISLNL,   bIsLNL);
    CheckDlgButton(IDRELLNL,  bRelLNL);
    CheckDlgButton(IDESCNL,   bEscNL);
    CheckDlgButton(IDESCTAB,  bEscTab);
    CheckDlgButton(IDREPLACE, bReplace);
    CheckDlgButton(IDISLNR,   bIsLNR);
    CheckDlgButton(IDRELLNR,  bRelLNR);

    //Set limit edit text
    SendDlgItemMessage(IDPADLNL, 197 /*EM_LIMITTEXT*/, 1, 0);
    SendDlgItemMessage(IDPADLNR, 197 /*EM_LIMITTEXT*/, 1, 0);
  }

  else if (uMsg == 6 /*WM_ACTIVATE*/)
  {
    if (LoWord(wParam))
    {
      hEditWnd  = AkelPad.GetEditWnd();
      bReadOnly = AkelPad.GetEditReadOnly(hEditWnd);
      bColSel   = AkelPad.SendMessage(hEditWnd, 3127 /*AEM_GETCOLUMNSEL*/, 0, 0);

      if (hEditWnd && (! bReadOnly))
      {
        for (i = IDTXTA; i <= IDOK; ++i)
          oSys.Call("User32::EnableWindow", GetDlgItem(i), 1);
        for (i = IDTXTPADLNL; i <= IDRELLNL; ++i)
          oSys.Call("User32::EnableWindow", GetDlgItem(i), bIsLNL);
        for (i = IDTXTINILNL; i <= IDSTEPLNL; ++i)
          oSys.Call("User32::EnableWindow", GetDlgItem(i), (bIsLNL && bRelLNL));
        for (i = IDTXTPADLNR; i <= IDRELLNR; ++i)
          oSys.Call("User32::EnableWindow", GetDlgItem(i), bIsLNR);
        for (i = IDTXTINILNR; i <= IDSTEPLNR; ++i)
          oSys.Call("User32::EnableWindow", GetDlgItem(i), (bIsLNR && bRelLNR));

        if ((nRange == 2) && (! bColSel))
          nRange = 0;

        oSys.Call("User32::CheckRadioButton", hDlg, IDSELECTION, IDCOLSEL, IDSELECTION + nRange);
        oSys.Call("User32::EnableWindow", GetDlgItem(IDCOLSEL), bColSel);

        SetDlgItemText(IDTXTA, pTxtA[nRange]);
        SetDlgItemText(IDTXTB, pTxtB[nRange]);
      }
      else
      {
        for (i = IDTXTA; i <= IDOK; ++i)
          oSys.Call("User32::EnableWindow", GetDlgItem(i), 0);

        oSys.Call("User32::DefDlgProcW", hDlg, 1025 /*DM_SETDEFID*/, IDCLOSE, 0);
      }
    }
  }

  else if (uMsg == 273 /*WM_COMMAND*/)
  {
    nID = LoWord(wParam);

    if ((nID == IDISLNL) || (nID == IDRELLNL))
    {
      bIsLNL  = IsDlgButtonChecked(IDISLNL);
      bRelLNL = IsDlgButtonChecked(IDRELLNL);
      for (i = IDTXTPADLNL; i <= IDRELLNL; ++i)
        oSys.Call("User32::EnableWindow", GetDlgItem(i), bIsLNL);
      for (i = IDTXTINILNL; i <= IDSTEPLNL; ++i)
        oSys.Call("User32::EnableWindow", GetDlgItem(i), (bIsLNL && bRelLNL));
    }

    else if (nID == IDESCNL)
      bEscNL = IsDlgButtonChecked(nID);

    else if (nID == IDESCTAB)
      bEscTab = IsDlgButtonChecked(nID);

    else if ((nID >= IDSELECTION) && (nID <= IDCOLSEL))
    {
      nRange = nID - IDSELECTION;
      SetDlgItemText(IDTXTA, pTxtA[nRange]);
      SetDlgItemText(IDTXTB, pTxtB[nRange]);
    }

    else if (nID == IDREPLACE)
      bReplace = IsDlgButtonChecked(IDREPLACE);

    else if ((nID == IDISLNR) || (nID == IDRELLNR))
    {
      bIsLNR  = IsDlgButtonChecked(IDISLNR);
      bRelLNR = IsDlgButtonChecked(IDRELLNR);
      for (i = IDTXTPADLNR; i <= IDRELLNR; ++i)
        oSys.Call("User32::EnableWindow", GetDlgItem(i), bIsLNR);
      for (i = IDTXTINILNR; i <= IDSTEPLNR; ++i)
        oSys.Call("User32::EnableWindow", GetDlgItem(i), (bIsLNR && bRelLNR));
    }

    else if ((nID == IDAPPLY) || (nID == IDOK))
    {
      InsertText();

      if (nID == IDOK)
        oSys.Call("User32::PostMessageW", hDlg, 16 /*WM_CLOSE*/, 0, 0);
    }

    else if ((nID == IDCLOSE) || (nID == 2 /*IDCANCEL*/))
      oSys.Call("User32::PostMessageW", hDlg, 16 /*WM_CLOSE*/, 0, 0);
  }

  else if (uMsg == 16 /*WM_CLOSE*/)
  {
    WriteIni();
    oSys.Call("User32::PostQuitMessage", 0);
    oSys.Call("User32::DestroyWindow", hDlg);
  }

  return 0;
}

function LoWord(nParam)
{
  return (nParam & 0xFFFF);
}

//function HiWord(nParam)
//{
//  return ((nParam >> 16) & 0xFFFF);
//}

function GetDlgItem(nID)
{
  return oSys.Call("User32::GetDlgItem", hDlg, nID);
}

function SendDlgItemMessage(nID, uMsg, wParam, lParam)
{
  return oSys.Call("User32::SendDlgItemMessageW", hDlg, nID, uMsg, wParam, lParam);
}

function GetDlgItemText(nID)
{
  var nTextLen = SendDlgItemMessage(nID, 14 /*WM_GETTEXTLENGTH*/, 0, 0);
  var pText    = "";
  var lpBuffer;

  if (nTextLen)
  {
    lpBuffer = AkelPad.MemAlloc(nTextLen * 2 + 2);
    oSys.Call("User32::GetDlgItemTextW", hDlg, nID, lpBuffer, nTextLen + 1);
    pText = AkelPad.MemRead(lpBuffer, 1 /*DT_UNICODE*/);
    AkelPad.MemFree(lpBuffer);
  }

  return pText;
}

function SetDlgItemText(nID, pText)
{
  oSys.Call("User32::SetDlgItemTextW", hDlg, nID, pText);
}

function IsDlgButtonChecked(nID)
{
  return oSys.Call("User32::IsDlgButtonChecked", hDlg, nID);
}

function CheckDlgButton(nID, bCheck)
{
  oSys.Call("User32::CheckDlgButton", hDlg, nID, bCheck);
}

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

function Pad(pString, nLen, pType, pChar)
{
  var i = 0;

  if (! pType) pType = "R";
  if (! pChar) pChar = " ";

  if (pType == "R")
  {
    while (pString.length < nLen)
      pString += pChar;
  }
  else if (pType == "L")
  {
    while (pString.length < nLen)
      pString = pChar + pString;
  }
  else if (pType == "C")
  {
    while (pString.length < nLen)
    {
      if ((i % 2) == 0)
        pString += pChar;
      else
        pString = pChar + pString;
      ++ i;
    }
  }
  return pString;
}

function InsertText()
{
  var nWordWrap = AkelPad.SendMessage(hEditWnd, 3241 /*AEM_GETWORDWRAP*/, 0, 0);

  SetRedraw(hEditWnd, false);
  if (nWordWrap > 0)
    AkelPad.Command(4209 /*IDM_VIEW_WORDWRAP*/);

  var nBegSel  = AkelPad.GetSelStart();
  var nEndSel  = AkelPad.GetSelEnd();
  var nLine1   = AkelPad.SendMessage(hEditWnd, 1078 /*EM_EXLINEFROMCHAR*/, 0, nBegSel);
  var nLine2   = AkelPad.SendMessage(hEditWnd, 1078 /*EM_EXLINEFROMCHAR*/, 0, nEndSel);
  var nLines   = nLine2 - nLine1 + 1;
  var aLinNumL = new Array(nLines);
  var aLinNumR = new Array(nLines);
  var nStep;
  var nIniNum;
  var nLenNum;
  var aLines;
  var pText;
  var i;

  if (pStrA = GetDlgItemText(IDSTRA))
  {
    if (! FindInArray(lpStrsA, pStrA))
    {
      lpStrsA.unshift(pStrA);
      SendDlgItemMessage(IDSTRA, 330 /*CB_INSERTSTRING*/, 0, pStrA);

      if (lpStrsA.length > nStrMax)
      {
        lpStrsA.length = nStrMax;
        SendDlgItemMessage(IDSTRA, 324 /*CB_DELETESTRING*/, nStrMax, 0);
      }
    }
  }

  if (pStrB = GetDlgItemText(IDSTRB))
  {
    if (! FindInArray(lpStrsB, pStrB))
    {
      lpStrsB.unshift(pStrB);
      SendDlgItemMessage(IDSTRB, 330 /*CB_INSERTSTRING*/, 0, pStrB);

      if (lpStrsB.length > nStrMax)
      {
        lpStrsB.length = nStrMax;
        SendDlgItemMessage(IDSTRB, 324 /*CB_DELETESTRING*/, nStrMax, 0);
      }
    }
  }

  pPadLNL  = GetDlgItemText(IDPADLNL);
  pPreLNL  = GetDlgItemText(IDPRELNL);
  pSufLNL  = GetDlgItemText(IDSUFLNL);
  pIniLNL  = GetDlgItemText(IDINILNL);
  pStepLNL = GetDlgItemText(IDSTEPLNL);
  pPadLNR  = GetDlgItemText(IDPADLNR);
  pPreLNR  = GetDlgItemText(IDPRELNR);
  pSufLNR  = GetDlgItemText(IDSUFLNR);
  pIniLNR  = GetDlgItemText(IDINILNR);
  pStepLNR = GetDlgItemText(IDSTEPLNR);

  for (i = 0; i < nLines; ++i)
  {
    aLinNumL[i] = "";
    aLinNumR[i] = "";
  }

  if (bEscNL)
  {
    pStrA = pStrA.replace(/\\n/g, "\r");
    pStrB = pStrB.replace(/\\n/g, "\r");
  }

  if (bEscTab)
  {
    pStrA = pStrA.replace(/\\t/g, "\t");
    pStrB = pStrB.replace(/\\t/g, "\t");
  }

  if (bIsLNL)
  {
    if (pPadLNL == "")
      pPadLNL = " ";

    if (bRelLNL)
    {
      nStep   = parseInt(pStepLNL);
      nIniNum = parseInt(pIniLNL);
      nLenNum = String((nIniNum + nStep * (nLines - 1))).length;
    }
    else
    {
      nStep   = 1;
      nIniNum = nLine1 + 1;
      nLenNum = String(nLine2 + 1).length;
    }

    for (i = 0; i < nLines; ++i)
      aLinNumL[i] = pPreLNL + Pad(String(nIniNum + nStep * i), nLenNum, "L", pPadLNL) + pSufLNL;
  }

  if (bIsLNR)
  {
    if (pPadLNR == "")
      pPadLNR = " ";

    if (bRelLNR)
    {
      nStep   = parseInt(pStepLNR);
      nIniNum = parseInt(pIniLNR);
      nLenNum = String((nIniNum + nStep * (nLines - 1))).length;
    }
    else
    {
      nStep   = 1;
      nIniNum = nLine1 + 1;
      nLenNum = String(nLine2 + 1).length;
    }

    for (i = 0; i < nLines; ++i)
      aLinNumR[i] = pPreLNR + Pad(String(nIniNum + nStep * i), nLenNum, "L", pPadLNR) + pSufLNR;
  }

  // insert in selection
  if (nRange == 0)
    pText = pStrA + aLinNumL[0] +
            (bReplace ? "" : AkelPad.GetSelText(1 /*\r*/)) +
            aLinNumR[nLines - 1] + pStrB;

  // insert in each of selected lines and columnar selection
  else
  {
    if (nRange == 1)
    {
      nEndSel = AkelPad.SendMessage(hEditWnd, 187 /*EM_LINEINDEX*/, nLine2, 0) + AkelPad.SendMessage(hEditWnd, 193 /*EM_LINELENGTH*/, nEndSel, 0);
      AkelPad.SetSel(nBegSel, nEndSel);
    }

    pText  = AkelPad.GetSelText(1 /*\r*/);
    aLines = pText.split("\r");

    for (i = 0; i < nLines; ++i)
      aLines[i] = pStrA + aLinNumL[i] +
                  (bReplace ? "" : aLines[i]) +
                  aLinNumR[i] + pStrB;

    pText = aLines.join("\r");
  }

  AkelPad.ReplaceSel(pText, -1);

  if (((nRange == 0) && bColSel) || (nRange == 2))
    AkelPad.SendMessage(hEditWnd, 3128 /*AEM_UPDATESEL*/, 0x1 /*AESELT_COLUMNON*/, 0);

  if (nWordWrap > 0)
    AkelPad.Command(4209 /*IDM_VIEW_WORDWRAP*/);
  SetRedraw(hEditWnd, true);
}

function FindInArray(lpArray, pText)
{
  for (var i = 0; i < lpArray.length; ++i)
  {
    if (lpArray[i] == pText)
      return true;
  }
  return false;
}

function ReadIni()
{
  var i;

  try
  {
    eval(ReadIni.Text = AkelPad.ReadFile(WScript.ScriptFullName.replace(/\.js$/i, ".ini"), 0x1D /*OD_ADT_BINARY_ERROR|OD_ADT_DETECT_CODEPAGE|OD_ADT_DETECT_BOM|OD_ADT_NOMESSAGES*/));
  }
  catch (oError)
  {}

  if (! lpStrsA)
    lpStrsA = [];
  if (! lpStrsB)
    lpStrsB = [];

  if (lpStrsA.length > nStrMax)
    lpStrsA.length = nStrMax;
  if (lpStrsB.length > nStrMax)
    lpStrsB.length = nStrMax;

  //for compatibility with ver. 2015-01-07
  for (i = lpStrsA.length - 1; i >= 0; --i)
  {
    if (! lpStrsA[i])
      lpStrsA.splice(i, 1);
  }
  for (i = lpStrsB.length - 1; i >= 0; --i)
  {
    if (! lpStrsB[i])
      lpStrsB.splice(i, 1);
  }
}

function WriteIni()
{
  var lpRect = AkelPad.MemAlloc(16); //sizeof(RECT)
  var pText  = 'lpStrsA=[';
  var i;

  oSys.Call("User32::GetWindowRect", hDlg, lpRect);
  oSys.Call("User32::ScreenToClient", hMainWnd, lpRect);
  nDlgX = AkelPad.MemRead(_PtrAdd(lpRect,  0), 3 /*DT_DWORD*/);
  nDlgY = AkelPad.MemRead(_PtrAdd(lpRect,  4), 3 /*DT_DWORD*/);
  AkelPad.MemFree(lpRect);

  for (i = 0; i < lpStrsA.length; ++i)
  {
    pText += '"' + EscapeStr(lpStrsA[i]) + '"';
    if (i < lpStrsA.length - 1)
      pText += ',';
  }
  pText += '];\r\nlpStrsB=[';

  for (i = 0; i < lpStrsB.length; ++i)
  {
    pText += '"' + EscapeStr(lpStrsB[i]) + '"';
    if (i < lpStrsB.length - 1)
      pText += ',';
  }
  pText += '];\r\n';

  pText += 'pStrA="'    + EscapeStr(pStrA)   + '";\r\n' + 
           'pStrB="'    + EscapeStr(pStrB)   + '";\r\n' + 
           'bEscNL='    + bEscNL   + ';\r\n' + 
           'bEscTab='   + bEscTab  + ';\r\n' +
           'bIsLNL='    + bIsLNL   + ';\r\n' +
           'pPadLNL="'  + EscapeStr(pPadLNL) + '";\r\n' + 
           'pPreLNL="'  + EscapeStr(pPreLNL) + '";\r\n' +
           'pSufLNL="'  + EscapeStr(pSufLNL) + '";\r\n' +
           'bRelLNL='   + bRelLNL  + ';\r\n' +
           'pIniLNL="'  + pIniLNL  + '";\r\n' +
           'pStepLNL="' + pStepLNL + '";\r\n' +
           'bIsLNR='    + bIsLNR   + ';\r\n' +
           'pPadLNR="'  + EscapeStr(pPadLNR) + '";\r\n' + 
           'pPreLNR="'  + EscapeStr(pPreLNR) + '";\r\n' +
           'pSufLNR="'  + EscapeStr(pSufLNR) + '";\r\n' +
           'bRelLNR='   + bRelLNR  + ';\r\n' +
           'pIniLNR="'  + pIniLNR  + '";\r\n' +
           'pStepLNR="' + pStepLNR + '";\r\n' +
           'bReplace='  + bReplace + ';\r\n' +
           'nDlgX='     + nDlgX + ';\r\n' +
           'nDlgY='     + nDlgY + ';'

  if (pText != ReadIni.Text) 
    AkelPad.WriteFile(WScript.ScriptFullName.replace(/\.js$/i, ".ini"), pText, pText.length, 1200 /*UTF-16LE*/, true);
}

function EscapeStr(pStr)
{
  return pStr.replace(/[\\"]/g, '\\$&').replace(/\n/g, '\\n').replace(/\r/g, '\\r');
}

function GetLangStrings()
{
  switch (AkelPad.GetLangId())
  {
    case 1045: //Polish
      pTxtCaption   = "Wstaw tekst i numer wiersza";
      pTxtNoColSel  = "Brak zaznaczenia pionowego.";
      pTxtA         =["Na początku zaznaczenia:",
                      "Na początku wierszy:",
                      "Z lewej każdej części zaznaczenia:"];
      pTxtB         =["Na końcu zaznaczenia:",
                      "Na końcu wierszy:",
                      "Z prawej każdej części zaznaczenia:"];
      pTxtEscNL     = "\\n = &Nowy wiersz";
      pTxtEscTab    = "\\t = &Tabulacja";
      pTxtRange     = "Zakres";
      pTxtSelection = "Z&aznaczenie";
      pTxtLines     = "Zaznaczone &wiersze";
      pTxtColSel    = "Pionow&e zaznaczenie";
      pTxtLNL       = "Numer wiersza z &Lewej";
      pTxtLNR       = "Numer wiersza z &Prawej";
      pTxtPadLN     = "Wypełnienie:";
      pTxtPreLN     = "Prefiks:";
      pTxtSufLN     = "Sufiks:";
      pTxtRelLN     = "Numeracja względna";
      pTxtIniLN     = "Pierwszy nr:";
      pTxtStepLN    = "Skok:";
      pTxtReplace   = "Usuń &zaznaczenie";
      pTxtApply     = "Wykonaj";
      pTxtOK        = "OK";
      pTxtClose     = "Zamknij";
      break;
    case 1049: //Russian translation by F. Phoenix
      pTxtCaption   = "Вставка текста и номеров строк";
      pTxtNoColSel  = "Нет активного блочного выделения.";
      pTxtA         =["В начале выделения:",
                      "В начале строк:",
                      "В начале строк блока:"];
      pTxtB         =["В конце выделения:",
                      "В конце строк:",
                      "В конце строк блока:"];
      pTxtEscNL     = "\\n = &Новая строка";
      pTxtEscTab    = "\\t = &Табуляция";
      pTxtRange     = "Область";
      pTxtSelection = "В&ыделение";
      pTxtLines     = "Выделенные &строки";
      pTxtColSel    = "&Блочное выделение";
      pTxtLNL       = "Номера строк с&лева";
      pTxtLNR       = "Номера строк с&права";
      pTxtPadLN     = "Заполнение:";
      pTxtPreLN     = "Префикс:";
      pTxtSufLN     = "Постфикс:";
      pTxtRelLN     = "&Относит. нумерация";
      pTxtIniLN     = "Начало:";
      pTxtStepLN    = "Шаг:";
      pTxtReplace   = "Замена &выделения";
      pTxtApply     = "Применить";
      pTxtOK        = "OK";
      pTxtClose     = "Закрыть";
      break; 
    default: //English
      pTxtCaption   = "Insert text and line number";
      pTxtNoColSel  = "There is no columnar selection.";
      pTxtA         =["At beginning of selection:",
                      "At left of lines:",
                      "At left any part of columnar selection:"];
      pTxtB         =["At end of selection:",
                      "At right of lines:",
                      "At right any part of columnar selection:"];
      pTxtEscNL     = "\\n = &New line";
      pTxtEscTab    = "\\t = &Tabulation";
      pTxtRange     = "Range";
      pTxtSelection = "S&election";
      pTxtLines     = "Selecte&d lines";
      pTxtColSel    = "&Columnar selection";
      pTxtLNL       = "Line number at &Left";
      pTxtLNR       = "Line number at &Right";
      pTxtPadLN     = "Padding char:";
      pTxtPreLN     = "Prefix:";
      pTxtSufLN     = "Suffix:";
      pTxtRelLN     = "Relative numbers";
      pTxtIniLN     = "First number:";
      pTxtStepLN    = "Step:";
      pTxtReplace   = "Replace &selection";
      pTxtApply     = "Apply";
      pTxtOK        = "OK";
      pTxtClose     = "Close";
  }
}

Last edited by KDJ on Sat Sep 19, 2015 3:42 pm, edited 15 times in total.

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

Post by KDJ »

JScript expressions calculator.

Code: Select all

// http://akelpad.sourceforge.net/forum/viewtopic.php?p=8988#p8988
// Version: 2016-08-05
// Author: KDJ
//
// *** JScript expressions calculator ***
//
// Run in AkelPad window:
//   Call("Scripts::Main", 1, "CalculatorJS.js")
// Run from command line (require registration: regsvr32.exe Scripts.dll):
//   wscript.exe CalculatorJS.js
//
// Warning:
//   After running the script, immediately will be executed the code from calculator input (selected text in AkelPad window).
//   Try this:
//   AkelPad.Command(4109 /*IDM_FILE_EXIT*/);

//temporarily
var WM_USER = 1024;

//globals
var E, PI, abs, acos, asin, atan, ceil, cos, exp, floor, log, max, min, pow, random, round, sin, sqrt, tan;
var LoWord;
var HiWord;
var MkLong;
var cot;
var acot;
var average;
var integer;
var round2;
var bin2dec;
var root;
var lg;
var factorial;
var x, X, y, Y, z, Z;
var Calculate = function(){
  if (arguments[0])
  {
    try
    {
      return eval(arguments[0]);
    }
    catch (oError)
    {
      return oError;
    }
  }
  return undefined;
};

//main function
(function(){
if (typeof AkelPad == "undefined")
{
  try
  {
    AkelPad = new ActiveXObject("AkelPad.Document");
    _PtrAdd = function(n1, n2) {return AkelPad.Global._PtrAdd(n1, n2);};
    _X64    = AkelPad.Constants._X64;
  }
  catch (oError)
  {
    WScript.Echo("You need register Scripts.dll");
    WScript.Quit();
  }
}

var oSys         = AkelPad.SystemFunction();
var hInstanceDLL = AkelPad.GetInstanceDll();
var sClassName   = "AkelPad::Scripts::" + WScript.ScriptName + "::" + hInstanceDLL;
var hWndDlg;

if (hWndDlg = oSys.Call("User32::FindWindowExW", 0, 0, sClassName, 0))
{
  if (! oSys.Call("User32::IsWindowVisible", hWndDlg))
    oSys.Call("User32::ShowWindow", hWndDlg, 8 /*SW_SHOWNA*/);
  if (oSys.Call("User32::IsIconic", hWndDlg))
    oSys.Call("User32::ShowWindow", hWndDlg, 9 /*SW_RESTORE*/);

  oSys.Call("User32::SetForegroundWindow", hWndDlg);
}
else
{
  var sScriptName = "CalculatorJS";
  var hMainWnd    = AkelPad.GetMainWnd();
  var hGuiFont    = oSys.Call("Gdi32::GetStockObject", 17 /*DEFAULT_GUI_FONT*/);
  var nMaxLen     = 30000;
  var lpBuffer    = AkelPad.MemAlloc(nMaxLen * 2);
  var oFSO        = new ActiveXObject("Scripting.FileSystemObject");
  var aWndMem     = new Array(3);
  var aNumType    = [["hex", 16], ["dec", 10], ["oct", 8], ["bin", 2]];
  var nNumType    = 1;
  var sStrIn      = "";
  var aStrIn      = [];
  var nMaxStrIn   = 20;
  var bCloseCB1   = 0;
  var bCloseCB2   = 1;
  var nBegSelIn   = 0;
  var nEndSelIn   = 0;
  var nWndX       = 200;
  var nWndY       = 170;
  var nView       = 1;
  var hWndStrOut;
  var hWndOutType;
  var hWndNumType;
  var hWndStrIn;
  var hWndView;
  var hFocus;
  var vResult;
  var _X_, _Y_, _Z_, _Calculate_;

  var IDMEMX    = 100;
  var IDMEMY    = 101;
  var IDMEMZ    = 102;
  var IDOUTPUT  = 103;
  var IDOUTTYPE = 104;
  var IDNUMTYPE = 105;
  var IDINPUT   = 106;
  var IDVIEW    = 107;

  var IDWND = 0;
  var HWND  = 1;
  var TXT   = 2;
  var FUN   = 3;
  var ARG   = 4;
  //Actions   IDWND, HWND,                TXT,       FUN, ARG
  var aActs = [[200,    0,     "Result to &X",  OutToMem,   0],
               [201,    0,     "Result to &Y",  OutToMem,   1],
               [202,    0,     "Result to &Z",  OutToMem,   2],
               [203,    0,     "Copy &result",   CopyOut     ],
               [204,    0,      "Copy &expr.",    CopyIn     ],
               [205,    0,"Expr. to &history",  InToHist     ],
               [206,    0,  "X to expr. (&1)",   MemToIn,   0],
               [207,    0,  "Y to expr. (&2)",   MemToIn,   1],
               [208,    0,  "Z to expr. (&3)",   MemToIn,   2],
               [209,    0, "Result &to expr.",   OutToIn     ],
               [210,    0,     "&Clear expr.",   ClearIn     ],
               [211,    0,    "Clear history", ClearHist     ]];
  //Functions  IDWND, HWND,        TXT,          FUN
  var aFuncs = [[300,    0,      "min",    "min(.,)"],
                [301,    0,      "max",    "max(., )"],
                [302,    0,     "ceil",     "ceil(.)"],
                [303,    0,     "sqrt",     "sqrt(.)"],
                [304,    0,   "random",   "random(.)"],
                [305,    0,  "average", "average(.,)"],
                [306,    0,      "abs",      "abs(.)"],
                [307,    0,    "floor",    "floor(.)"],
                [308,    0,     "root",    "root(.,)"],
                [309,    0,"factorial","factorial(.)"],
                [310,    0,      "sin",      "sin(.)"],
                [311,    0,     "asin",     "asin(.)"],
                [312,    0,  "integer",  "integer(.)"],
                [313,    0,      "exp",      "exp(.)"],
                [314,    0,   "LoWord",   "LoWord(.)"],
                [315,    0,      "cos",      "cos(.)"],
                [316,    0,     "acos",     "acos(.)"],
                [317,    0,    "round",    "round(.)"],
                [318,    0,      "pow",     "pow(.,)"],
                [319,    0,   "HiWord",   "HiWord(.)"],
                [320,    0,      "tan",      "tan(.)"],
                [321,    0,     "atan",     "atan(.)"],
                [322,    0,   "round2",  "round2(.,)"],
                [323,    0,      "log",      "log(.)"],
                [324,    0,   "MkLong",  "MkLong(.,)"],
                [325,    0,      "cot",      "cot(.)"],
                [326,    0,     "acot",     "acot(.)"],
                [327,    0,  "bin2dec",  "bin2dec(.)"],
                [328,    0,       "lg",      "lg(.,)"],
                [329,    0,  "1/(...)",      "1/(.)"]];
  //Operators  IDWND, HWND,    TXT,    FUN
  var aOpers = [[400,    0,    "/",    "/"],
                [401,    0,    "*",    "*"],
                [402,    0,    "-",    "-"],
                [403,    0,    "+",    "+"],
                [404,    0,   "!=",   "!="],
                [405,    0,  "!==",  "!=="],
                [406,    0,   "==",   "=="],
                [407,    0,  "===",  "==="],
                [408,    0,    "<",    "<"],
                [409,    0,   "<=",   "<="],
                [410,    0,   ">=",   ">="],
                [411,    0,    ">",    ">"],
                [412,    0,    "!",    "!"],
                [413,    0, "&&&&",   "&&"],
                [414,    0,   "||",   "||"],
                [415,    0,   "?:", "(?:)"],
                [416,    0,    "~",    "~"],
                [417,    0,   "&&",    "&"],
                [418,    0,    "|",    "|"],
                [419,    0,    "^",    "^"],
                [420,    0,   "<<",   "<<"],
                [421,    0,   ">>",   ">>"],
                [422,    0,  ">>>",  ">>>"],
                [423,    0,    "%",    "%"]];
  //Constants IDWND, HWND,     TXT
  var aCons = [[500,    0,     "D"],
               [501,    0,     "E"],
               [502,    0,     "F"],
               [503,    0,    "0x"],
               [504,    0,     "A"],
               [505,    0,     "B"],
               [506,    0,     "C"],
               [507,    0,    "PI"],
               [508,    0,     "7"],
               [509,    0,     "8"],
               [510,    0,     "9"],
               [511,    0, "/.../"],
               [512,    0,     "4"],
               [513,    0,     "5"],
               [514,    0,     "6"],
               [515,    0, "{...}"],
               [516,    0,     "1"],
               [517,    0,     "2"],
               [518,    0,     "3"],
               [519,    0, "[...]"],
               [520,    0,     "0"],
               [521,    0,     "."],
               [522,    0,     ","],
               [523,    0, "(...)"]];
  var hIcon =
    oSys.Call("User32::LoadImageW",
              hInstanceDLL, //hinst
              101,          //lpszName
              1,            //uType=IMAGE_ICON
              0,            //cxDesired
              0,            //cyDesired
              0x00000040);  //fuLoad=LR_DEFAULTSIZE

  ReadIni();
  AkelPad.ScriptNoMutex(0x11 /*ULT_LOCKSENDMESSAGE|ULT_UNLOCKSCRIPTSQUEUE*/);
  AkelPad.WindowRegisterClass(sClassName);

  hWndDlg =
    oSys.Call("User32::CreateWindowExW",
              0,               //dwExStyle
              sClassName,      //lpClassName
              sScriptName,     //lpWindowName
              0x90CA0000,      //WS_VISIBLE|WS_POPUP|WS_CAPTION|WS_SYSMENU|WS_MINIMIZEBOX
              nWndX,           //x
              nWndY,           //y
              0,               //nWidth
              0,               //nHeight
              hMainWnd,        //hWndParent
              0,               //ID
              hInstanceDLL,    //hInstance
              DialogCallback); //Script function callback. To use it class must be registered by WindowRegisterClass.


  AkelPad.WindowGetMessage();
  AkelPad.WindowUnregisterClass(sClassName);

  AkelPad.MemFree(lpBuffer);
  oSys.Call("User32::DestroyIcon", hIcon);
}

function DialogCallback(hWnd, uMsg, wParam, lParam)
{
  if (uMsg == 1) //WM_CREATE
  {
    var i;

    //Create EDIT Memory (x,y,z)
    for (i = 0; i < 3; ++i)
    {
      aWndMem[i] =
        oSys.Call("User32::CreateWindowExW",
                  0,             //dwExStyle
                  "EDIT",        //lpClassName
                  0,             //lpWindowName
                  0x50810880,    //WS_VISIBLE|WS_CHILD|WS_BORDER|WS_TABSTOP|ES_AUTOHSCROLL|ES_READONLY
                  3+(172)*(i%3), //x
                  5,             //y
                  171,           //nWidth
                  21,            //nHeight
                  hWnd,          //hWndParent
                  IDMEMX + i,    //ID
                  hInstanceDLL,  //hInstance
                  0);            //lpParam
      SetMem(i);
    }

    //Create EDIT Output
    hWndStrOut =
      oSys.Call("User32::CreateWindowExW",
                0,            //dwExStyle
                "EDIT",       //lpClassName
                0,            //lpWindowName
                0x50810880,   //WS_VISIBLE|WS_CHILD|WS_BORDER|WS_TABSTOP|ES_AUTOHSCROLL|ES_READONLY
                3,            //x
                30,           //y
                376,          //nWidth
                21,           //nHeight
                hWnd,         //hWndParent
                IDOUTPUT,     //ID
                hInstanceDLL, //hInstance
                0);           //lpParam
    SetWindowFontAndText(hWndStrOut, "");

    //Create STATIC Out type
    hWndOutType =
      oSys.Call("User32::CreateWindowExW",
                0,            //dwExStyle
                "STATIC",     //lpClassName
                0,            //lpWindowName
                0x50800001,   //WS_VISIBLE|WS_CHILD|WS_BORDER|SS_CENTER
                380,          //x
                30,           //y
                94,           //nWidth
                21,           //nHeight
                hWnd,         //hWndParent
                IDOUTTYPE,    //ID
                hInstanceDLL, //hInstance
                0);           //lpParam

    //Create COMBOBOX Num types
    hWndNumType =
      oSys.Call("User32::CreateWindowExW",
                0,            //dwExStyle
                "COMBOBOX",   //lpClassName
                0,            //lpWindowName
                0x50010003,   //WS_VISIBLE|WS_CHILD|WS_TABSTOP|CBS_DROPDOWNLIST
                475,          //x
                30,           //y
                43,           //nWidth
                100,          //nHeight
                hWnd,         //hWndParent
                IDNUMTYPE,    //ID
                hInstanceDLL, //hInstance
                0);           //lpParam
    for (i = 0; i < 4; ++i)
      oSys.Call("User32::SendMessageW", hWndNumType, 0x143 /*CB_ADDSTRING*/, 0, aNumType[i][0]);

    SetWindowFontAndText(hWndNumType, "");
    AkelPad.SendMessage(hWndNumType, 0x14E /*CB_SETCURSEL*/, nNumType, 0);

    //Create COMBOBOX Input
    hWndStrIn =
      oSys.Call("User32::CreateWindowExW",
                0,            //dwExStyle
                "COMBOBOX",   //lpClassName
                0,            //lpWindowName
                0x50210042,   //WS_VISIBLE|WS_CHILD|WS_VSCROLL|WS_TABSTOP|CBS_DROPDOWN|CBS_AUTOHSCROLL
                3,            //x
                55,           //y
                515,          //nWidth
                300,          //nHeight
                hWnd,         //hWndParent
                IDINPUT,      //ID
                hInstanceDLL, //hInstance
                0);           //lpParam
    AkelPad.SendMessage(hWndStrIn, 0x0155 /*CB_SETEXTENDEDUI*/, 1, 0);
    SetWindowFontAndText(hWndStrIn, sStrIn);
    for (i = 0; i < aStrIn.length; ++i)
      oSys.Call("User32::SendMessageW", hWndStrIn, 0x143 /*CB_ADDSTRING*/, 0, aStrIn[i]);

    //Create BUTTONs Action
    for (i = 0; i < aActs.length; ++i)
    {
      aActs[i][HWND] =
        oSys.Call("User32::CreateWindowExW",
                  0,                       //dwExStyle
                  "BUTTON",                //lpClassName
                  0,                       //lpWindowName
                  0x50010000,              //WS_VISIBLE|WS_CHILD|WS_TABSTOP
                  3+(75)*(i%6),            //x
                  83+(23)*Math.floor(i/6), //y
                  75,                      //nWidth
                  23,                      //nHeight
                  hWnd,                    //hWndParent
                  aActs[i][IDWND],         //ID
                  hInstanceDLL,            //hInstance
                  0);                      //lpParam
      SetWindowFontAndText(aActs[i][HWND], aActs[i][TXT]);
    }

    //Create BUTTON View
    hWndView =
      oSys.Call("User32::CreateWindowExW",
                0,            //dwExStyle
                "BUTTON",     //lpClassName
                0,            //lpWindowName
                0x50010000,   //WS_VISIBLE|WS_CHILD|WS_TABSTOP
                463,          //x
                83,           //y
                55,           //nWidth
                46,           //nHeight
                hWnd,         //hWndParent
                IDVIEW,       //ID
                hInstanceDLL, //hInstance
                0);           //lpParam
    SetWindowFontAndText(hWndView, "&View");

    //Create BUTTONs Functions
    for (i = 0; i < aFuncs.length; ++i)
    {
      aFuncs[i][HWND] =
        oSys.Call("User32::CreateWindowExW",
                  0,                        //dwExStyle
                  "BUTTON",                 //lpClassName
                  0,                        //lpWindowName
                  0x50010000,               //WS_VISIBLE|WS_CHILD|WS_TABSTOP
                  3+(55)*(i%5),             //x
                  136+(23)*Math.floor(i/5), //y
                  55,                       //nWidth
                  23,                       //nHeight
                  hWnd,                     //hWndParent
                  aFuncs[i][IDWND],         //ID
                  hInstanceDLL,             //hInstance
                  0);                       //lpParam
      SetWindowFontAndText(aFuncs[i][HWND], aFuncs[i][TXT]);
    }

    //Create BUTTONs Operators
    for (i = 0; i < aOpers.length; ++i)
    {
      aOpers[i][HWND] =
        oSys.Call("User32::CreateWindowExW",
                  0,                        //dwExStyle
                  "BUTTON",                 //lpClassName
                  0,                        //lpWindowName
                  0x50010000,               //WS_VISIBLE|WS_CHILD|WS_TABSTOP
                  288+(30)*(i%4),           //x
                  136+(23)*Math.floor(i/4), //y
                  30,                       //nWidth
                  23,                       //nHeight
                  hWnd,                     //hWndParent
                  aOpers[i][IDWND],         //ID
                  hInstanceDLL,             //hInstance
                  0);                       //lpParam
      SetWindowFontAndText(aOpers[i][HWND], aOpers[i][TXT]);
    }

    //Create BUTTONs Constants
    for (i = 0; i < aCons.length; ++i)
    {
      aCons[i][HWND] =
        oSys.Call("User32::CreateWindowExW",
                  0,                        //dwExStyle
                  "BUTTON",                 //lpClassName
                  0,                        //lpWindowName
                  0x50010000,               //WS_VISIBLE|WS_CHILD|WS_TABSTOP
                  418+(25)*(i%4),           //x
                  136+(23)*Math.floor(i/4), //y
                  25,                       //nWidth
                  23,                       //nHeight
                  hWnd,                     //hWndParent
                  aCons[i][IDWND],          //ID
                  hInstanceDLL,             //hInstance
                  0);                       //lpParam
      SetWindowFontAndText(aCons[i][HWND], aCons[i][TXT]);
    }

    SetView(hWnd);
    AkelPad.SendMessage(hWnd, 0x0080 /*WM_SETICON*/, 0 /*ICON_SMALL*/, hIcon);
    oSys.Call("User32::PostMessageW", hWnd, 273 /*WM_COMMAND*/, MkLong(IDINPUT, 5 /*CBN_EDITCHANGE*/), hWndStrIn);

    hFocus = hWndStrIn;
  }

  else if ((uMsg == 6 /*WM_ACTIVATE*/) && (! wParam))
    hFocus = oSys.Call("User32::GetFocus");

  else if (uMsg == 7) //WM_SETFOCUS
    oSys.Call("User32::SetFocus", hFocus);

  else if (uMsg == 256) //WM_KEYDOWN
  {
    if ((wParam == 27 /*VK_ESCAPE*/) && (bCloseCB1) && (bCloseCB2))
      oSys.Call("User32::PostMessageW", hWndDlg, 16 /*WM_CLOSE*/, 0, 0);
  }

  else if (uMsg == 273) //WM_COMMAND
  {
    var nLowParam = LoWord(wParam);
    var nHiwParam = HiWord(wParam);
    bCloseCB1 = 1;

    if (nLowParam == IDINPUT)
    {
      if (nHiwParam == 3 /*CBN_SETFOCUS*/)
        AkelPad.SendMessage(hWndStrIn, 0x0142 /*CB_SETEDITSEL*/, 0, MkLong(nBegSelIn, nEndSelIn));
      else if (nHiwParam == 10 /*CBN_SELENDCANCEL*/)
      {
        nBegSelIn = LoWord(AkelPad.SendMessage(hWndStrIn, 0x0140 /*CB_GETEDITSEL*/, 0, 0));
        nEndSelIn = HiWord(AkelPad.SendMessage(hWndStrIn, 0x0140 /*CB_GETEDITSEL*/, 0, 0));
      }
      else if (nHiwParam == 5 /*CBN_EDITCHANGE*/)
      {
        sStrIn  = GetWindowText(hWndStrIn);
        vResult = Calculate(sStrIn);
        x = X = _X_;
        y = Y = _Y_;
        z = Z = _Z_;
        Calculate = _Calculate_;
        GetGlobals();
        SetOut();
      }
      else if (nHiwParam == 1 /*CBN_SELCHANGE*/)
        oSys.Call("User32::PostMessageW", hWnd, 273 /*WM_COMMAND*/, MkLong(IDINPUT, 5 /*CBN_EDITCHANGE*/), hWndStrIn);
      else if (nHiwParam == 7 /*CBN_DROPDOWN*/)
        bCloseCB2 = 0;
      else if (nHiwParam == 8 /*CBN_CLOSEUP*/)
        bCloseCB2 = 1;
    }

    else if ((nLowParam >= IDMEMX) && (nLowParam <= IDMEMZ))
      AkelPad.SendMessage(lParam, 0x00B1 /*EM_SETSEL*/, 2, -1);

    else if (nLowParam == IDNUMTYPE)
    {
      if (nHiwParam == 1 /*CBN_SELCHANGE*/)
      {
        nNumType = AkelPad.SendMessage(hWndNumType, 0x147 /*CB_GETCURSEL*/, 0, 0);
        SetOut();
      }
      else if (nHiwParam == 8 /*CBN_CLOSEUP*/)
        bCloseCB1 = 0;
    }

    else if ((nLowParam >= aActs[0][IDWND]) && (nLowParam <= aActs[aActs.length - 1][IDWND]))
    {
      oSys.Call("User32::SetFocus", hWndStrIn);
      aActs[nLowParam - aActs[0][0]][FUN](aActs[nLowParam - aActs[0][0]][ARG]);
    }

    else if ((nLowParam >= aFuncs[0][IDWND]) && (nLowParam <= aFuncs[aFuncs.length - 1][IDWND]))
      FunToIn(aFuncs[nLowParam - aFuncs[0][0]][FUN]);

    else if ((nLowParam >= aOpers[0][IDWND]) && (nLowParam <= aOpers[aOpers.length - 1][IDWND]))
      FunToIn(aOpers[nLowParam - aOpers[0][0]][FUN]);

    else if ((nLowParam >= aCons[0][IDWND]) && (nLowParam <= aCons[aCons.length - 1][IDWND]))
      FunToIn(aCons[nLowParam - aCons[0][0]][TXT]);

    else if (nLowParam == IDVIEW)
    {
      nView = Number(! nView);
      SetView(hWnd);
    }

    oSys.Call("User32::DefDlgProcW", hWnd, 1025 /*DM_SETDEFID*/, nLowParam, 0);
    oSys.Call("User32::DefDlgProcW", hWnd, 1025 /*DM_SETDEFID*/, IDOUTPUT, 0);
  }

  else if (uMsg == 16) //WM_CLOSE
  {
    WriteIni();
    //Destroy dialog
    oSys.Call("User32::DestroyWindow", hWnd);
  }

  else if (uMsg == 2) //WM_DESTROY
  {
    //Exit message loop
    oSys.Call("User32::PostQuitMessage", 0);
  }

  return 0;
}

function ReadIni()
{
  var sIniFile = WScript.ScriptFullName.substring(0, WScript.ScriptFullName.lastIndexOf(".")) + ".ini";
  var oFile;
  var i;

  if (oFSO.FileExists(sIniFile))
  {
    oFile = oFSO.OpenTextFile(sIniFile, 1, false, -1);

    try
    {
      eval(oFile.ReadAll());
    }
    catch (oError)
    {}

    oFile.Close();
  }

  _X_ = X = x;
  _Y_ = Y = y;
  _Z_ = Z = z;
  _Calculate_ = Calculate;
  GetGlobals();

  if (AkelPad.GetSelStart() != AkelPad.GetSelEnd())
  {
    sStrIn = AkelPad.GetSelText(1 /*\r*/).substring(0, nMaxLen).replace(/\r/g, " ");
    nBegSelIn = nEndSelIn = 0;
  }
}

function WriteIni()
{
  var oFile  = oFSO.OpenTextFile(WScript.ScriptFullName.substring(0, WScript.ScriptFullName.lastIndexOf(".")) + ".ini", 2, true, -1);
  var lpRect = AkelPad.MemAlloc(16) //sizeof(RECT);
  var sIniTxt;
  var vMem;
  var sStrMem;
  var i;

  oSys.Call("User32::GetWindowRect", hWndDlg, lpRect);
  nWndX = AkelPad.MemRead(_PtrAdd(lpRect, 0), 3 /*DT_DWORD*/);
  nWndY = AkelPad.MemRead(_PtrAdd(lpRect, 4), 3 /*DT_DWORD*/);
  AkelPad.MemFree(lpRect);

  oSys.Call("User32::SetFocus", hWndStrIn);

  sIniTxt =
    'nWndX='     + nWndX     + ';\r\n' +
    'nWndY='     + nWndY     + ';\r\n' +
    'nView='     + nView     + ';\r\n' +
    'nNumType='  + nNumType  + ';\r\n' +
    'nBegSelIn=' + nBegSelIn + ';\r\n' +
    'nEndSelIn=' + nEndSelIn + ';\r\n' +
    'sStrIn="'   + EscapeStr(sStrIn) + '";\r\n' +
    'aStrIn=[';

  for (i = 0; i < aStrIn.length; ++i)
    sIniTxt += '"' + EscapeStr(aStrIn[i]) + '"' + ((i < aStrIn.length - 1) ? ',' : '');
  sIniTxt += '];\r\n';

  for (i = 0; i < 3; ++i)
  {
    vMem    = [x, y, z][i];
    sStrMem = ["x=", "y=", "z="][i];

    if ((typeof vMem == "boolean") || (typeof vMem == "number") || (vMem === null))
      sIniTxt += sStrMem + vMem + ';\r\n';
    else if (typeof vMem == "string")
      sIniTxt += sStrMem + '"' + EscapeStr(vMem) + '";\r\n';
  }
	
  oFile.Write(sIniTxt);
  oFile.Close();
}

function EscapeStr(sText)
{
  return sText.replace(/[\\"]/g, '\\$&').replace(/\n/g, '\\n').replace(/\r/g, '\\r');
}

function SetView(hWnd)
{
  var i;

  for (i = 0; i < aFuncs.length; ++i)
    oSys.Call("User32::EnableWindow", aFuncs[i][HWND], nView);
  for (i = 0; i < aOpers.length; ++i)
    oSys.Call("User32::EnableWindow", aOpers[i][HWND], nView);
  for (i = 0; i < aCons.length; ++i)
    oSys.Call("User32::EnableWindow", aCons[i][HWND], nView);

  oSys.Call("User32::SetWindowPos", hWnd, 0, 0, 0, 527, (nView ? 308 : 163), 0x16 /*SWP_NOZORDER|SWP_NOACTIVATE/SWP_NOMOVE*/);
  oSys.Call("User32::SetFocus", hWndStrIn);
}

function GetWindowText(hWnd)
{
  oSys.Call("User32::GetWindowTextW", hWnd, lpBuffer, nMaxLen);
  return AkelPad.MemRead(lpBuffer, 1 /*DT_UNICODE*/);
}

function SetWindowFontAndText(hWnd, sText)
{
  AkelPad.SendMessage(hWnd, 48 /*WM_SETFONT*/, hGuiFont, true);
  oSys.Call("User32::SetWindowTextW", hWnd, sText);
}

function OutToMem(nMem)
{
  var vMem;

  if ((typeof vResult == "boolean") || (vResult instanceof Boolean) || (typeof vResult == "number") || (vResult instanceof Number) || (typeof vResult == "string") || (vResult instanceof String))
    vMem = vResult.valueOf();
  else if ((typeof vResult == "undefined") || (vResult === null))
    vMem = vResult;
  else
  {
    AkelPad.MessageBox(hWndDlg, "To memory cache (x, y, z), you can assign only values of type:\n- boolean\n- null\n- number\n- string\n- undefined", sScriptName, 0x30 /*MB_ICONWARNING*/);
    return;
  }

  if (nMem == 0)
    x = X = _X_ = vMem;
  else if (nMem == 1)
    y = Y = _Y_ = vMem;
  else
    z = Z = _Z_ = vMem;

  SetMem(nMem);
}

function MemToIn(nMem)
{
  var vMem = [x, y, z][nMem];

  if (typeof vMem != "undefined")
  {
    if (typeof vMem == "string")
      vMem = '"' + EscapeStr(vMem) + '"';
    else
      vMem = "" + vMem;

    sStrIn    = sStrIn.substr(0, nBegSelIn) + vMem + sStrIn.substr(nEndSelIn);
    nBegSelIn = nBegSelIn + vMem.length;
    nEndSelIn = nBegSelIn;

    EditChange();
  }
}

function CopyOut()
{
  var sStrOut = GetWindowText(hWndStrOut);
  if (sStrOut) AkelPad.SetClipboardText(sStrOut);
}

function OutToIn()
{
  var sStrOut = GetWindowText(hWndStrOut);

  if (((typeof vResult == "number") || (vResult instanceof Number)) && (nNumType == 3) && (! /[^01-]/.test(sStrOut)))
    sStrOut = "bin2dec(" + sStrOut + ")";
  else if ((typeof vResult == "string") || (vResult instanceof String))
    sStrOut = '"' + EscapeStr(sStrOut.slice(1, -1)) + '"';

  sStrIn    = sStrIn.substr(0, nBegSelIn) + sStrOut + sStrIn.substr(nEndSelIn);
  nBegSelIn = nBegSelIn + sStrOut.length;
  nEndSelIn = nBegSelIn;

  EditChange();
}

function CopyIn()
{
  if (sStrIn) AkelPad.SetClipboardText(sStrIn);
}

function ClearIn()
{
  sStrIn = "";
  nBegSelIn = nEndSelIn = 0;

  EditChange();
}

function InToHist()
{
  if (sStrIn)
  {
    for (var i = 0; i < aStrIn.length; ++i)
    {
      if (aStrIn[i] == sStrIn)
      {
        aStrIn.splice(i, 1);
        AkelPad.SendMessage(hWndStrIn, 0x144 /*CB_DELETESTRING*/, i, 0);
      }
    }

    if (aStrIn.length == nMaxStrIn)
    {
      aStrIn.pop();
      AkelPad.SendMessage(hWndStrIn, 0x144 /*CB_DELETESTRING*/, nMaxStrIn - 1, 0);
    }

    aStrIn.unshift(sStrIn);
    oSys.Call("User32::SendMessageW", hWndStrIn, 0x14A /*CB_INSERTSTRING*/, 0, sStrIn);
  }
}

function ClearHist()
{
  aStrIn = [];
  AkelPad.SendMessage(hWndStrIn, 0x14B /*CB_RESETCONTENT*/, 0, 0);
}

function FunToIn(sText)
{
  var oRE = /\.+(?=[^\(]*\)|\]|\}|\/)/;

  oSys.Call("User32::SetFocus", hWndStrIn);

  if (oRE.test(sText))
  {
    sText  = sText.replace(oRE, sStrIn.substring(nBegSelIn, nEndSelIn));
    sStrIn = sStrIn.substr(0, nBegSelIn) + sText + sStrIn.substr(nEndSelIn);

    nBegSelIn += RegExp.index;
    nEndSelIn += RegExp.index;
  }
  else
  {
    sStrIn = sStrIn.substr(0, nBegSelIn) + sText + sStrIn.substr(nEndSelIn);
    nBegSelIn = nBegSelIn + ((sText.indexOf("(") >= 0) ? sText.indexOf("(") + 1 : sText.length);
    nEndSelIn = nBegSelIn;
  }

  EditChange();
}

function EditChange()
{
  SetWindowFontAndText(hWndStrIn, sStrIn);
  AkelPad.SendMessage(hWndStrIn, 0x0142 /*CB_SETEDITSEL*/, 0, MkLong(nBegSelIn, nEndSelIn));
  oSys.Call("User32::PostMessageW", hWndDlg, 273 /*WM_COMMAND*/, MkLong(IDINPUT, 5 /*CBN_EDITCHANGE*/), hWndStrIn);
}

function SetMem(nMem)
{
  var sStrMem;
  var vMem;

  if (nMem == 0)
  {
    sStrMem = "x=";
    vMem    = x;
  }
  else if (nMem == 1)
  {
    sStrMem = "y=";
    vMem    = y;
  }
  else
  {
    sStrMem = "z=";
    vMem    = z;
  }

  if ((typeof vMem == "boolean") || (typeof vMem == "number") || (vMem === null))
    sStrMem += vMem;
  else if (typeof vMem == "string")
    sStrMem += '"' + vMem + '"';

  SetWindowFontAndText(aWndMem[nMem], sStrMem);
}

function SetOut()
{
  var sOutType = typeof vResult;
  var sStrOut  = "";

  if (! sStrIn)
    sOutType = "";
  else if ((sOutType == "boolean") || (sOutType == "function") || (sOutType == "number"))
    sStrOut = vResult.toString();
  else if (sOutType == "string")
    sStrOut = '"' + vResult + '"';
  else if (sOutType == "date")
    sStrOut = Date(vResult);
  else if (sOutType == "undefined")
    sStrOut = "";
  else if (sOutType == "object")
  {
    sOutType = "obj ";
    if (vResult === null)
    {
      sStrOut   = "null";
      sOutType += "Null";
    }
    else if (vResult instanceof ActiveXObject)
      sOutType += " ActiveXObject";
    else if (vResult instanceof Array)
    {
      sStrOut   = vResult.toString();
      sOutType += "Array";
    }
    else if (vResult instanceof Boolean)
    {
      sStrOut   = vResult.toString();
      sOutType += "Boolean";
    }
    else if (vResult instanceof Date)
    {
      sStrOut   = vResult.toString();
      sOutType += "Date";
    }
    else if (vResult instanceof Enumerator)
      sOutType += "Enumerator";
    else if (vResult instanceof Error)
    {
      sStrOut  = vResult.name + ": " + vResult.description;
      sOutType = "Error";
    }
    else if (vResult instanceof Number)
    {
      sStrOut   = vResult.toString();
      sOutType += "Number";
    }
    else if (vResult instanceof RegExp)
    {
      sStrOut   = vResult.toString();
      sOutType += "RegExp";
    }
    else if (vResult instanceof String)
    {
      sStrOut   = '"' + vResult + '"';
      sOutType += "String";
    }
    else if (vResult instanceof VBArray)
    {
      sStrOut   = vResult.toArray().toString();
      sOutType += "VBArray";
    }
    else if (vResult instanceof Object)
    {
      sStrOut   = vResult.toString();
      sOutType += "Object";
    }
    else
      sOutType += "unknown";
  }

  if (((sOutType == "number") || (vResult instanceof Number)) && (nNumType != 1) && (vResult % 1 == 0))
  {
    //for a higher value, toString() returns number in an exponential notation
    if (Math.abs(vResult) < 0x1FFFFFFFFFFFFF80)
    {
      sStrOut = Math.abs(vResult).toString(aNumType[nNumType][1]).toUpperCase();

      if (nNumType == 0)
        sStrOut = "0x" + sStrOut;
      else if (nNumType == 2)
        sStrOut = "0" + sStrOut;

      if (vResult < 0)
        sStrOut = "-" + sStrOut;
    }
    else
    {
      nNumType = 1;
      AkelPad.SendMessage(hWndNumType, 0x14E /*CB_SETCURSEL*/, nNumType, 0);
    }
  }

  SetWindowFontAndText(hWndStrOut, sStrOut);
  SetWindowFontAndText(hWndOutType, sOutType);
}

function GetGlobals()
{
  E      = Math.E;
  PI     = Math.PI;
  abs    = Math.abs;
  acos   = Math.acos;
  asin   = Math.asin;
  atan   = Math.atan;
  ceil   = Math.ceil;
  cos    = Math.cos;
  exp    = Math.exp;
  floor  = Math.floor;
  log    = Math.log;
  max    = Math.max;
  min    = Math.min;
  pow    = Math.pow;
  random = Math.random;
  round  = Math.round;
  sin    = Math.sin;
  sqrt   = Math.sqrt;
  tan    = Math.tan;

  LoWord = function(nDwNum){
    return (nDwNum & 0xFFFF);
  };

  HiWord = function(nDwNum){
    return ((nDwNum >> 16) & 0xFFFF);
  };

  MkLong = function(nLoWord, nHiWord){
    return (nLoWord & 0xFFFF) | (nHiWord << 16);
  };

  cot = function(nNum){
    return 1 / Math.tan(nNum);
  };

  acot = function(nNum){
    return Math.PI / 2 - Math.atan(nNum);
  };

  average = function(){
    var nSum = 0;
    for (var i = 0; i < arguments.length; ++i)
      nSum += arguments[i];
    return nSum / arguments.length;
  };

  integer = function(nNum){
    return parseInt(nNum);
  };

  round2 = function(nNum, nDec){
    return Math.round(nNum * Math.pow(10, nDec))/Math.pow(10, nDec);
  };

  bin2dec = function(nNum){
    var nBeg = 0;
    var i;
    if (nNum < 0)
      nBeg = 1;
    for (i = nBeg; i < nNum.toString().length; ++i)
    {
      if ((nNum.toString().charAt(i) != "0") && (nNum.toString().charAt(i) != "1"))
        return NaN;
    }
    return parseInt(nNum, 2);
  };

  root = function(nNum, nDeg){
    return Math.pow(nNum, 1 / nDeg);
  };

  lg = function(nNum, nBase){
    if (nBase == 2)
      return Math.LOG2E * Math.log(nNum);
    if (nBase == 10)
      return Math.LOG10E * Math.log(nNum);
    return Math.log(nNum) / Math.log(nBase);
  };

  factorial = function(nNum){
    var nResult = 1;
    var i;
    if (nNum < 0)
      return NaN;
    for (i = 1; i <= nNum; ++i)
      nResult *= i;
    return nResult;
  };
}
})();

Last edited by KDJ on Fri Aug 05, 2016 9:24 pm, edited 10 times in total.

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

Post by KDJ »

Converts text in csv format to text in columns.

Code: Select all

// http://akelpad.sourceforge.net/forum/viewtopic.php?p=9055#p9055
// Version: 2015-09-19
// Author: KDJ
//
// *** Converts text in csv format to text in columns ***
//
// Usage:
//   Call("Scripts::Main", 1, "CSVToColumnText.js")

var oSys = AkelPad.SystemFunction();

if (oSys.Call("kernel32::GetUserDefaultLangID") == 0x0415) //Polish
{
  var pTxtCaption   = "Konwersja tekstu csv";
  var pTxtMDIRO     = "Musi być włączony tryb MDI/PMDI lub wyłączony tryb tylko do odczytu.";
  var pTxtNoSep     = "Musisz wpisać separator.";
  var pTxtBadSep    = "Niewłaściwy separator";
  var pTxtWait      = "Czekaj lub Esc";
  var pTxtCountIn   = "Wiersz w tekście wejściowym:";
  var pTxtCountOut  = "Wiersz w tekście wyjściowym:";
  var pTxtCountMes1 = "Przetworzonych wierszy: ";
  var pTxtCountMes2 = ". Tekst jest dłuższy. Czy kontynuować?";
  var pTxtInput     = "Tekst wejściowy";
  var pTxtInSep     = "Separator";
  var pTxtInSep0    = ", Przecinek";
  var pTxtInSep1    = "; Średnik";
  var pTxtInSep2    = ": Dwukropek";
  var pTxtInSep3    = ". Kropka";
  var pTxtInSep4    = "| Pipe";
  var pTxtInSep5    = "Tab";
  var pTxtInSep6    = "Spacja";
  var pTxtInSep7    = "Inny:";
  var pTxtOutput    = "Tekst wyjściowy";
  var pTxtRCSep     = "Separatory";
  var pTxtCSep      = "Separator kolumn:";
  var pTxtRSep      = "Separator wierszy:";
  var pTxtAdCol     = "Dodaj kolumnę z numerem wiersza";
  var pTxtAdColL    = "z lewej";
  var pTxtAdColR    = "z prawej";
  var pTxtAdColTxt  = "Pierwszy numer:";
  var pTxtAlign     = "Wyrównanie w kolumnach";
  var pTxtAlignL    = "Lewa";
  var pTxtAlignR    = "Prawa";
  var pTxtAlignC    = "Środek";
  var pTxtAction    = "Wykonaj";
  var pTxtAction0   = "Otwórz na nowej karcie (MDI)";
  var pTxtAction1   = "Zamień zaznaczenie";
  var pTxtAction2   = "Wstaw przed zaznaczeniem";
  var pTxtAction3   = "Wstaw po zaznaczeniu";
  var pTxtOK        = "OK";
  var pTxtCancel    = "Anuluj";
}
else
{
  var pTxtCaption   = "CSV to column text";
  var pTxtMDIRO     = "Must be switched on MDI/PMDI mode or switched off read-only mode.";
  var pTxtNoSep     = "You must specify a separator.";
  var pTxtBadSep    = "Unacceptable separator";
  var pTxtWait      = "Wait or Esc";
  var pTxtCountIn   = "Line number at input text:";
  var pTxtCountOut  = "Line number at output text:";
  var pTxtCountMes1 = "Processed lines: ";
  var pTxtCountMes2 = ". The text is longer. Continue?";
  var pTxtInput     = "Input text";
  var pTxtInSep     = "Separator";
  var pTxtInSep0    = ", Comma";
  var pTxtInSep1    = "; Semicolon";
  var pTxtInSep2    = ": Colon";
  var pTxtInSep3    = ". Dot";
  var pTxtInSep4    = "| Pipe";
  var pTxtInSep5    = "Tab";
  var pTxtInSep6    = "Space";
  var pTxtInSep7    = "Other:";
  var pTxtOutput    = "Output text";
  var pTxtRCSep     = "Separators";
  var pTxtCSep      = "Columns separator:";
  var pTxtRSep      = "Rows separator:";
  var pTxtAdCol     = "Add column with row number";
  var pTxtAdColL    = "at left";
  var pTxtAdColR    = "at right";
  var pTxtAdColTxt  = "Initial number:";
  var pTxtAlign     = "Align in columns";
  var pTxtAlignL    = "Left";
  var pTxtAlignR    = "Right";
  var pTxtAlignC    = "Center";
  var pTxtAction    = "Action";
  var pTxtAction0   = "Open in new tab (MDI mode)";
  var pTxtAction1   = "Replace selection";
  var pTxtAction2   = "Insert before selection";
  var pTxtAction3   = "Insert after selection";
  var pTxtOK        = "OK";
  var pTxtCancel    = "Cancel";
}

var hMainWnd     = AkelPad.GetMainWnd();
var hEditWnd     = AkelPad.GetEditWnd();
var hGuiFont     = oSys.Call("gdi32::GetStockObject", 17 /*DEFAULT_GUI_FONT*/);
var pScriptName  = WScript.ScriptName;
var hInstanceDLL = AkelPad.GetInstanceDll();
var bIsRO        = AkelPad.GetEditReadOnly(hEditWnd);

var DT_DWORD  = 3;
var nInSep    = 0;
var pOtSepStr = "";
var bCSep     = 1;
var pCSepStr  = "|";
var bRSep     = 0;
var pRSepStr  = "-";
var bAdColL   = 0;
var bAdColR   = 0;
var pAdColNum = "1";
var pAlign    = "L";
var nAction   = 0;
var pSepars   = ",;:.|\t ";
var pInSep;
var pCSep;
var pRSep;
var hWndDlg;
var lpBuffer;
var nLowParam;
var nHiwParam;
var nWndPosX;
var nWndPosY;
var i;

ReadWriteIni(0);

var aWnd       = [];
var IDINPUT    = 1000;
var IDINSEP    = 1001;
var IDINSEP0   = 1002;
var IDINSEP1   = 1003;
var IDINSEP2   = 1004;
var IDINSEP3   = 1005;
var IDINSEP4   = 1006;
var IDINSEP5   = 1007;
var IDINSEP6   = 1008;
var IDINSEP7   = 1009;
var IDOTSEPSTR = 1010;
var IDOUTPUT   = 1011;
var IDRCSEP    = 1012;
var IDCSEP     = 1013;
var IDCSEPSTR  = 1014;
var IDRSEP     = 1015;
var IDRSEPSTR  = 1016;
var IDADCOL    = 1017;
var IDADCOLL   = 1018;
var IDADCOLR   = 1019;
var IDADCOLTXT = 1020;
var IDADCOLNUM = 1021;
var IDALIGN    = 1022;
var IDALIGNL   = 1023;
var IDALIGNR   = 1024;
var IDALIGNC   = 1025;
var IDACTION   = 1026;
var IDACTION0  = 1027;
var IDACTION1  = 1028;
var IDACTION2  = 1029;
var IDACTION3  = 1030;
var IDCOUNTER  = 1031;
var IDOK       = 1032;
var IDCANCEL   = 1033;

var WNDTYPE  = 0;
var WND      = 1;
var WNDEXSTY = 2;
var WNDSTY   = 3;
var WNDX     = 4;
var WNDY     = 5;
var WNDW     = 6;
var WNDH     = 7;
var WNDTXT   = 8;

//0x50000000 - WS_VISIBLE|WS_CHILD
//0x50000007 - WS_VISIBLE|WS_CHILD|BS_GROUPBOX
//0x50000009 - WS_VISIBLE|WS_CHILD|BS_AUTORADIOBUTTON
//0x50010000 - WS_VISIBLE|WS_CHILD|WS_TABSTOP
//0x50010001 - WS_VISIBLE|WS_CHILD|WS_TABSTOP|BS_DEFPUSHBUTTON
//0x50010003 - WS_VISIBLE|WS_CHILD|WS_TABSTOP|BS_AUTOCHECKBOX
//0x50010080 - WS_VISIBLE|WS_CHILD|WS_TABSTOP|ES_AUTOHSCROLL
//0x50012080 - WS_VISIBLE|WS_CHILD|WS_TABSTOP|ES_AUTOHSCROLL|ES_NUMBER
//Windows             WNDTYPE,WND,WNDEXSTY,     WNDSTY,WNDX,WNDY,WNDW,WNDH, WNDTXT
aWnd[IDINPUT   ] = ["BUTTON",  0,       0, 0x50000007,  10,  10, 116, 216, pTxtInput];
aWnd[IDINSEP   ] = ["BUTTON",  0,       0, 0x50000007,  18,  30, 100, 189, pTxtInSep];
aWnd[IDINSEP0  ] = ["BUTTON",  0,       0, 0x50000009,  28,  50,  85,  16, pTxtInSep0];
aWnd[IDINSEP1  ] = ["BUTTON",  0,       0, 0x50000009,  28,  70,  85,  16, pTxtInSep1];
aWnd[IDINSEP2  ] = ["BUTTON",  0,       0, 0x50000009,  28,  90,  85,  16, pTxtInSep2];
aWnd[IDINSEP3  ] = ["BUTTON",  0,       0, 0x50000009,  28, 110,  85,  16, pTxtInSep3];
aWnd[IDINSEP4  ] = ["BUTTON",  0,       0, 0x50000009,  28, 130,  85,  16, pTxtInSep4];
aWnd[IDINSEP5  ] = ["BUTTON",  0,       0, 0x50000009,  28, 150,  85,  16, pTxtInSep5];
aWnd[IDINSEP6  ] = ["BUTTON",  0,       0, 0x50000009,  28, 170,  85,  16, pTxtInSep6];
aWnd[IDINSEP7  ] = ["BUTTON",  0,       0, 0x50000009,  28, 190,  50,  16, pTxtInSep7];
aWnd[IDOTSEPSTR] = ["EDIT",    0,   0x200, 0x50010080,  80, 190,  20,  20, pOtSepStr];
aWnd[IDOUTPUT  ] = ["BUTTON",  0,       0, 0x50000007, 142,  10, 397, 186, pTxtOutput];
aWnd[IDRCSEP   ] = ["BUTTON",  0,       0, 0x50000007, 150,  30, 185,  74, pTxtRCSep];
aWnd[IDCSEP    ] = ["BUTTON",  0,       0, 0x50010003, 160,  50, 110,  16, pTxtCSep];
aWnd[IDCSEPSTR ] = ["EDIT",    0,   0x200, 0x50010080, 275,  50,  50,  20, pCSepStr];
aWnd[IDRSEP    ] = ["BUTTON",  0,       0, 0x50010003, 160,  74, 110,  16, pTxtRSep];
aWnd[IDRSEPSTR ] = ["EDIT",    0,   0x200, 0x50010080, 275,  74,  20,  20, pRSepStr];
aWnd[IDADCOL   ] = ["BUTTON",  0,       0, 0x50000007, 150, 114, 185,  74, pTxtAdCol];
aWnd[IDADCOLL  ] = ["BUTTON",  0,       0, 0x50010003, 160, 134,  60,  16, pTxtAdColL];
aWnd[IDADCOLR  ] = ["BUTTON",  0,       0, 0x50010003, 270, 134,  60,  16, pTxtAdColR];
aWnd[IDADCOLTXT] = ["STATIC",  0,       0, 0x50000000, 177, 158, 100,  13, pTxtAdColTxt];
aWnd[IDADCOLNUM] = ["EDIT",    0,   0x200, 0x50012080, 255, 158,  50,  20, pAdColNum];
aWnd[IDALIGN   ] = ["BUTTON",  0,       0, 0x50000007, 345,  30, 185,  43, pTxtAlign];
aWnd[IDALIGNL  ] = ["BUTTON",  0,       0, 0x50000009, 355,  50,  50,  16, pTxtAlignL];
aWnd[IDALIGNR  ] = ["BUTTON",  0,       0, 0x50000009, 412,  50,  50,  16, pTxtAlignR];
aWnd[IDALIGNC  ] = ["BUTTON",  0,       0, 0x50000009, 469,  50,  50,  16, pTxtAlignC];
aWnd[IDACTION  ] = ["BUTTON",  0,       0, 0x50000007, 345,  83, 185, 105, pTxtAction];
aWnd[IDACTION0 ] = ["BUTTON",  0,       0, 0x50000009, 355, 103, 160,  16, pTxtAction0];
aWnd[IDACTION1 ] = ["BUTTON",  0,       0, 0x50000009, 355, 123, 160,  16, pTxtAction1];
aWnd[IDACTION2 ] = ["BUTTON",  0,       0, 0x50000009, 355, 143, 160,  16, pTxtAction2];
aWnd[IDACTION3 ] = ["BUTTON",  0,       0, 0x50000009, 355, 163, 160,  16, pTxtAction3];
aWnd[IDCOUNTER ] = ["STATIC",  0,       0, 0x50000000, 220, 209, 150,  13, ""];
aWnd[IDOK      ] = ["BUTTON",  0,       0, 0x50010001, 365, 206,  80,  23, pTxtOK];
aWnd[IDCANCEL  ] = ["BUTTON",  0,       0, 0x50010000, 460, 206,  80,  23, pTxtCancel];


if (hEditWnd)
{
  if ((AkelPad.IsMDI() == 0) && bIsRO)
  {
    AkelPad.MessageBox(hMainWnd, pTxtMDIRO, pTxtCaption, 48 /*MB_ICONEXCLAMATION*/);
    WScript.Quit();
  }
  else if ((AkelPad.IsMDI() == 0) && (nAction == 0))
    nAction = 3;
  else if (bIsRO && (nAction > 0))
    nAction = 0;

  if (AkelPad.WindowRegisterClass(pScriptName))
  {
    if (lpBuffer = AkelPad.MemAlloc(256 * _TSIZE))
    {
      //Create dialog
      AkelPad.MemCopy(lpBuffer, pScriptName, _TSTR);
      hWndDlg=oSys.Call("user32::CreateWindowEx" + _TCHAR,
                        0,               //dwExStyle
                        lpBuffer,        //lpClassName
                        0,               //lpWindowName
                        0x90CA0000,      //WS_VISIBLE|WS_POPUP|WS_CAPTION|WS_SYSMENU|WS_MINIMIZEBOX
                        0,               //x
                        0,               //y
                        554,             //nWidth
                        267,             //nHeight
                        hMainWnd,        //hWndParent
                        0,               //ID
                        hInstanceDLL,    //hInstance
                        DialogCallback); //Script function callback. To use it class must be registered by WindowRegisterClass.
      if (hWndDlg)
      {
        //Disable main window, to make dialog modal
        oSys.Call("user32::EnableWindow", hMainWnd, false);

        //Message loop
        AkelPad.WindowGetMessage();
      }
      AkelPad.MemFree(lpBuffer);
    }
    AkelPad.WindowUnregisterClass(pScriptName);
  }
}

function DialogCallback(hWnd, uMsg, wParam, lParam)
{
  if (uMsg == 1)  //WM_CREATE
  {
    //Dialog caption
    AkelPad.MemCopy(lpBuffer, pTxtCaption, _TSTR);
    oSys.Call("user32::SetWindowText" + _TCHAR, hWnd, lpBuffer);

    //Create windows
    for (i = 1000; i < aWnd.length; ++i)
    {
      AkelPad.MemCopy(lpBuffer, aWnd[i][WNDTYPE], _TSTR);
      aWnd[i][WND] = oSys.Call("user32::CreateWindowEx" + _TCHAR,
                               aWnd[i][WNDEXSTY], //dwExStyle
                               lpBuffer,          //lpClassName
                               0,                 //lpWindowName
                               aWnd[i][WNDSTY],   //dwStyle
                               aWnd[i][WNDX],     //x
                               aWnd[i][WNDY],     //y
                               aWnd[i][WNDW],     //nWidth
                               aWnd[i][WNDH],     //nHeight
                               hWnd,              //hWndParent
                               i,                 //ID
                               hInstanceDLL,      //hInstance
                               0);                //lpParam
      //Set font and text
      SetWindowFontAndText(aWnd[i][WND], hGuiFont, aWnd[i][WNDTXT]);
    }

    //Set limit edit text
    AkelPad.SendMessage(aWnd[IDOTSEPSTR][WND], 197 /*EM_LIMITTEXT*/, 1, 0);
    AkelPad.SendMessage(aWnd[IDRSEPSTR][WND], 197 /*EM_LIMITTEXT*/, 1, 0);

    //Check
    AkelPad.SendMessage(aWnd[eval("IDINSEP" + nInSep)][WND], 241 /*BM_SETCHECK*/, 1 /*BST_CHECKED*/, 0);
    oSys.Call("user32::EnableWindow", aWnd[IDOTSEPSTR][WND], (nInSep == 7));

    if (bCSep) AkelPad.SendMessage(aWnd[IDCSEP][WND], 241 /*BM_SETCHECK*/, 1 /*BST_CHECKED*/, 0);
    if (bRSep) AkelPad.SendMessage(aWnd[IDRSEP][WND], 241 /*BM_SETCHECK*/, 1 /*BST_CHECKED*/, 0);
    oSys.Call("user32::EnableWindow", aWnd[IDCSEPSTR][WND], bCSep);
    oSys.Call("user32::EnableWindow", aWnd[IDRSEPSTR][WND], bRSep);

    if (bAdColL) AkelPad.SendMessage(aWnd[IDADCOLL][WND], 241 /*BM_SETCHECK*/, 1 /*BST_CHECKED*/, 0);
    if (bAdColR) AkelPad.SendMessage(aWnd[IDADCOLR][WND], 241 /*BM_SETCHECK*/, 1 /*BST_CHECKED*/, 0);
    oSys.Call("user32::EnableWindow", aWnd[IDADCOLNUM][WND], ((bAdColL) || (bAdColR)));

    AkelPad.SendMessage(aWnd[eval("IDALIGN" + pAlign)][WND], 241 /*BM_SETCHECK*/, 1 /*BST_CHECKED*/, 0);

    AkelPad.SendMessage(aWnd[eval("IDACTION" + nAction)][WND], 241 /*BM_SETCHECK*/, 1 /*BST_CHECKED*/, 0);
    oSys.Call("user32::EnableWindow", aWnd[IDACTION1][WND], (! bIsRO));
    oSys.Call("user32::EnableWindow", aWnd[IDACTION2][WND], (! bIsRO));
    oSys.Call("user32::EnableWindow", aWnd[IDACTION3][WND], (! bIsRO));
    if (AkelPad.IsMDI() == 0)
      oSys.Call("user32::EnableWindow", aWnd[IDACTION0][WND], false);

    //Set window position
    if ((nWndPosX == undefined) || (nWndPosY == undefined))
      MoveWindow(hMainWnd, hWnd, "RT");
    else
      MoveWindow(hMainWnd, hWnd, [nWndPosX, nWndPosY]);
  }

  else if (uMsg == 7)  //WM_SETFOCUS
    oSys.Call("user32::SetFocus", aWnd[eval("IDINSEP" + nInSep)][WND]);

  else if (uMsg == 256)  //WM_KEYDOWN
  {
    if (wParam == 27)  //VK_ESCAPE
      oSys.Call("user32::PostMessage" + _TCHAR, hWndDlg, 273 /*WM_COMMAND*/, IDCANCEL, 0);
    else if (wParam == 13)  //VK_RETURN
      oSys.Call("user32::PostMessage" + _TCHAR, hWndDlg, 273 /*WM_COMMAND*/, IDOK, 0);
  }

  else if ((uMsg == 260) /*WM_SYSKEYDOWN*/ &&
           (oSys.Call("user32::GetAsyncKeyState", 0xA0 /*VK_LSHIFT*/)))
  {
    if (wParam == 0x27) //VK_RIGHT
      MoveWindow(hMainWnd, hWnd, "R");
    else if (wParam == 0x25) //VK_LEFT
      MoveWindow(hMainWnd, hWnd, "L");
    else if (wParam == 0x28) //VK_DOWN
      MoveWindow(hMainWnd, hWnd, "D");
    else if (wParam == 0x26) //VK_UP
      MoveWindow(hMainWnd, hWnd, "U");
    else if (wParam == 0x23) //VK_END
      MoveWindow(hMainWnd, hWnd, "E");
    else if (wParam == 0x24) //VK_HOME
      MoveWindow(hMainWnd, hWnd, "H");
    else if (wParam == 0x22) //VK_NEXT
      MoveWindow(hMainWnd, hWnd, "B");
    else if (wParam == 0x21) //VK_PRIOR
      MoveWindow(hMainWnd, hWnd, "T");
  }

  else if (uMsg == 273)  //WM_COMMAND
  {
    nLowParam = LoWord(wParam);
    nHiwParam = HiWord(wParam);

    if ((nLowParam >= IDINSEP0) && (nLowParam <= IDINSEP7))
    {
      nInSep = nLowParam - IDINSEP0;
      oSys.Call("user32::EnableWindow", aWnd[IDOTSEPSTR][WND], (nInSep == 7));
      AkelPad.SendMessage(aWnd[eval("IDALIGN" + pAlign)][WND], 241 /*BM_SETCHECK*/, 1 /*BST_CHECKED*/, 0);
      AkelPad.SendMessage(aWnd[eval("IDACTION" + nAction)][WND], 241 /*BM_SETCHECK*/, 1 /*BST_CHECKED*/, 0);
    }

    else if (nLowParam == IDCSEP)
    {
      bCSep = AkelPad.SendMessage(aWnd[IDCSEP][WND], 240 /*BM_GETCHECK*/, 0, 0);
      oSys.Call("user32::EnableWindow", aWnd[IDCSEPSTR][WND], bCSep);
    }
    else if (nLowParam == IDRSEP)
    {
      bRSep = AkelPad.SendMessage(aWnd[IDRSEP][WND], 240 /*BM_GETCHECK*/, 0, 0);
      oSys.Call("user32::EnableWindow", aWnd[IDRSEPSTR][WND], bRSep);
    }

    else if ((nLowParam == IDADCOLL) || (nLowParam == IDADCOLR))
    {
      if (nLowParam == IDADCOLL)
        bAdColL = AkelPad.SendMessage(aWnd[IDADCOLL][WND], 240 /*BM_GETCHECK*/, 0, 0);
      else
        bAdColR = AkelPad.SendMessage(aWnd[IDADCOLR][WND], 240 /*BM_GETCHECK*/, 0, 0);
      oSys.Call("user32::EnableWindow", aWnd[IDADCOLNUM][WND], ((bAdColL) || (bAdColR)));
    }

    else if ((nLowParam >= IDALIGNL) && (nLowParam <= IDALIGNC))
    {
      pAlign = "LRC".charAt(nLowParam - IDALIGNL);
      AkelPad.SendMessage(aWnd[eval("IDACTION" + nAction)][WND], 241 /*BM_SETCHECK*/, 1 /*BST_CHECKED*/, 0);
      AkelPad.SendMessage(aWnd[eval("IDINSEP" + nInSep)][WND], 241 /*BM_SETCHECK*/, 1 /*BST_CHECKED*/, 0);
    }

    else if ((nLowParam >= IDACTION0) && (nLowParam <= IDACTION3))
    {
      nAction = nLowParam - IDACTION0;
      AkelPad.SendMessage(aWnd[eval("IDALIGN" + pAlign)][WND], 241 /*BM_SETCHECK*/, 1 /*BST_CHECKED*/, 0);
      AkelPad.SendMessage(aWnd[eval("IDINSEP" + nInSep)][WND], 241 /*BM_SETCHECK*/, 1 /*BST_CHECKED*/, 0);
    }

    else if (LoWord(wParam) == IDOK)
    {
      if (nInSep == 7)
      {
        oSys.Call("user32::GetWindowText" + _TCHAR, aWnd[IDOTSEPSTR][WND], lpBuffer, 256);
        pOtSepStr = AkelPad.MemRead(lpBuffer, _TSTR);
        if (! pOtSepStr)
        {
          AkelPad.MessageBox(hWnd, pTxtNoSep, pTxtCaption, 48 /*MB_ICONEXCLAMATION*/);
          oSys.Call("user32::SetFocus", aWnd[IDOTSEPSTR][WND]);
          return;
        }
        else if (pOtSepStr == '"')
        {
          AkelPad.MessageBox(hWnd, pTxtBadSep, pTxtCaption, 48 /*MB_ICONEXCLAMATION*/);
          oSys.Call("user32::SetFocus", aWnd[IDOTSEPSTR][WND]);
          return;
        }
      }
      pInSep = (pSepars + pOtSepStr).charAt(nInSep);

      if (bCSep)
      {
        oSys.Call("user32::GetWindowText" + _TCHAR, aWnd[IDCSEPSTR][WND], lpBuffer, 256);
        pCSepStr = AkelPad.MemRead(lpBuffer, _TSTR);
        pCSep    = pCSepStr;
      }
      else
        pCSep = "";

      if (bRSep)
      {
        oSys.Call("user32::GetWindowText" + _TCHAR, aWnd[IDRSEPSTR][WND], lpBuffer, 256);
        pRSepStr = AkelPad.MemRead(lpBuffer, _TSTR);
        pRSep    = pRSepStr;
      }
      else
        pRSep = "";

      oSys.Call("user32::GetWindowText" + _TCHAR, aWnd[IDADCOLNUM][WND], lpBuffer, 256);
      pAdColNum = AkelPad.MemRead(lpBuffer, _TSTR);
      if (! pAdColNum)
        pAdColNum = "0";

      CSVToColTxt();
      oSys.Call("user32::PostMessage" + _TCHAR, hWndDlg, 16 /*WM_CLOSE*/, 0, 0);
    }

    else if (LoWord(wParam) == IDCANCEL)
      oSys.Call("user32::PostMessage" + _TCHAR, hWndDlg, 16 /*WM_CLOSE*/, 0, 0);
  }

  else if (uMsg == 16)  //WM_CLOSE
  {
    ReadWriteIni(1);

    //Enable main window
    oSys.Call("user32::EnableWindow", hMainWnd, true);
    //Destroy dialog
    oSys.Call("user32::DestroyWindow", hWnd);
  }

  else if (uMsg == 2)  //WM_DESTROY
  {
    //Exit message loop
    oSys.Call("user32::PostQuitMessage", 0);
  }

  else
  {
    if (oSys.Call("user32::GetFocus") != aWnd[IDCANCEL][WND])
      oSys.Call("user32::DefDlgProc" + _TCHAR, hWnd, 1025 /*DM_SETDEFID*/, IDOK, 0);
  }

  return 0;
}

function SetWindowFontAndText(hWnd, hFont, pText)
{
  AkelPad.SendMessage(hWnd, 48 /*WM_SETFONT*/, hFont, true);
  oSys.Call("user32::SetWindowText" + _TCHAR, hWnd, pText);
}

function MoveWindow(hWndParent, hWnd, Action)
{
  var rcWndParent;
  var rcWnd;
  var nX;
  var nY;

  if (! hWndParent)
    hWndParent=oSys.Call("user32::GetDesktopWindow");

  rcWndParent = GetWindowPos(hWndParent);
  rcWnd       = GetWindowPos(hWnd);

  nX = rcWnd.left;
  nY = rcWnd.top;

  if (Action == "R") //Move right
    nX = rcWnd.left + ((rcWnd.left < rcWndParent.right - 50) ? 20: 0);
  else if (Action == "L") //Move left
    nX = rcWnd.left - ((rcWnd.right > rcWndParent.left + 50) ? 20: 0);
  else if (Action == "D") //Move down
    nY = rcWnd.top + ((rcWnd.top < rcWndParent.bottom - 50) ? 20: 0);
  else if (Action == "U") //Move up
    nY = rcWnd.top - ((rcWnd.bottom > rcWndParent.top + 50) ? 20: 0);
  else if (Action == "E") //Move end (right)
    nX = rcWnd.left + (rcWndParent.right - rcWnd.right);
  else if (Action == "H") //Move home (left)
    nX = rcWnd.left + (rcWndParent.left - rcWnd.left);
  else if (Action == "B") //Move bottom
    nY = rcWnd.top + (rcWndParent.bottom - rcWnd.bottom);
  else if (Action == "T") //Move top
    nY = rcWnd.top + (rcWndParent.top - rcWnd.top);
  else if (Action == "C") //Center window
  {
    nX = rcWndParent.left + ((rcWndParent.right  - rcWndParent.left) / 2 - (rcWnd.right  - rcWnd.left) / 2);
    nY = rcWndParent.top  + ((rcWndParent.bottom - rcWndParent.top)  / 2 - (rcWnd.bottom - rcWnd.top)  / 2);
  }
  else if (Action == "LT") //Move left top
  {
    nX = rcWndParent.left;
    nY = rcWndParent.top;
  }
  else if (Action == "RT") //Move right top
  {
    nX = rcWnd.left + (rcWndParent.right - rcWnd.right);
    nY = rcWndParent.top;
  }
  else if (Action == "LB") //Move left bottom
  {
    nX = rcWndParent.left;
    nY = rcWnd.top + (rcWndParent.bottom - rcWnd.bottom);
  }
  else if (Action == "RB") //Move right bottom
  {
    nX = rcWnd.left + (rcWndParent.right - rcWnd.right);
    nY = rcWnd.top + (rcWndParent.bottom - rcWnd.bottom);
  }
  else
  {
    nX = Action[0];
    nY = Action[1];
  }

  oSys.Call("user32::SetWindowPos", hWnd, 0, nX, nY, 0, 0, 0x15 /*SWP_NOZORDER|SWP_NOACTIVATE|SWP_NOSIZE*/);
}

function GetWindowPos(hWnd)
{
  var lpRect = AkelPad.MemAlloc(16) //sizeof(RECT);
  var rcRect = [];

  oSys.Call("user32::GetWindowRect", hWnd, lpRect);

  rcRect.left   = AkelPad.MemRead(_PtrAdd(lpRect,  0), DT_DWORD);
  rcRect.top    = AkelPad.MemRead(_PtrAdd(lpRect,  4), DT_DWORD);
  rcRect.right  = AkelPad.MemRead(_PtrAdd(lpRect,  8), DT_DWORD);
  rcRect.bottom = AkelPad.MemRead(_PtrAdd(lpRect, 12), DT_DWORD);
  AkelPad.MemFree(lpRect);

  return rcRect;
}

function LoWord(nParam)
{
  return (nParam & 0xffff);
}

function HiWord(nParam)
{
  return ((nParam >> 16) & 0xffff);
}

function ReadWriteIni(bWrite)
{
  var oFSO     = new ActiveXObject("Scripting.FileSystemObject");
  var pIniName = WScript.ScriptFullName.substring(0, WScript.ScriptFullName.lastIndexOf(".")) + ".ini";
  var rcWnd;
  var nError;
  var oFile;
  var pTxt;

  if (bWrite)
  {
    rcWnd = GetWindowPos(hWndDlg);

    oSys.Call("user32::GetWindowText" + _TCHAR, aWnd[IDOTSEPSTR][WND], lpBuffer, 256);
    pOtSepStr = AkelPad.MemRead(lpBuffer, _TSTR);
    oSys.Call("user32::GetWindowText" + _TCHAR, aWnd[IDCSEPSTR][WND], lpBuffer, 256);
    pCSepStr = AkelPad.MemRead(lpBuffer, _TSTR);
    oSys.Call("user32::GetWindowText" + _TCHAR, aWnd[IDCSEPSTR][WND], lpBuffer, 256);
    pCSepStr = AkelPad.MemRead(lpBuffer, _TSTR);
    oSys.Call("user32::GetWindowText" + _TCHAR, aWnd[IDADCOLNUM][WND], lpBuffer, 256);
    pAdColNum = AkelPad.MemRead(lpBuffer, _TSTR);

    pTxt = 'nWndPosX='   + rcWnd.left + ';\r\n' +
           'nWndPosY='   + rcWnd.top  + ';\r\n' +
           'nInSep='     + nInSep + ';\r\n' +
           'pOtSepStr="' + pOtSepStr.replace(/[\\"]/g, "\\$&") + '";\r\n' +
           'bCSep='      + bCSep + ';\r\n' +
           'pCSepStr="'  + pCSepStr.replace(/[\\"]/g, "\\$&") + '";\r\n' +
           'bRSep='      + bRSep + ';\r\n' +
           'pRSepStr="'  + pRSepStr.replace(/[\\"]/g, "\\$&") + '";\r\n' +
           'bAdColL='    + bAdColL + ';\r\n' +
           'bAdColR='    + bAdColR + ';\r\n' +
           'pAdColNum="' + pAdColNum + '";\r\n' +
           'pAlign="'    + pAlign + '";\r\n' +
           'nAction='    + nAction + ';';

    oFile = oFSO.OpenTextFile(pIniName, 2, true, 0);
    oFile.Write(pTxt);
    oFile.Close();
  }

  else if (oFSO.FileExists(pIniName))
  {
    try
    {
      eval(AkelPad.ReadFile(pIniName));
    }
    catch (nError)
    {
    }
  }
}

function Pad(pString, nLen, pType, pChar)
{
  var i = 0;

  if (! pType) pType = "R";
  if (! pChar) pChar = " ";

  if (pType == "R")
  {
    while (pString.length < nLen)
      pString += pChar;
  }
  else if (pType == "L")
  {
    while (pString.length < nLen)
      pString = pChar + pString;
  }
  else if (pType == "C")
  {
    while (pString.length < nLen)
    {
      if ((i % 2) == 0)
        pString += pChar;
      else
        pString = pChar + pString;
      ++ i;
    }
  }
  return pString;
}

function Replicate(pStrIn, nNum)
{
  var pStrOut = "";
  var i;

  for (i=0; i < nNum; ++i)
    pStrOut += pStrIn;

  return pStrOut;
}

function CSVToColTxt()
{
  var pPad      = pAlign;
  var nAdColNum = parseInt(pAdColNum);
  var nBegSel   = AkelPad.GetSelStart();
  var nEndSel   = AkelPad.GetSelEnd();
  var aColLen   = [];
  var aRowNum   = [];
  var aTxt1     = [];
  var aTxt2     = [];
  var pRSepLine;
  var pTxt;
  var nNumLen;
  var i, n, v;

  if (pAlign == "L") pPad = "R";
  else if (pAlign == "R") pPad = "L";

  if (nBegSel == nEndSel)
  {
    nBegSel = 0;
    nEndSel = -1;
  }

  SetWindowFontAndText(aWnd[IDCOUNTER][WND], hGuiFont, pTxtCountIn);
  SetWindowFontAndText(aWnd[IDCANCEL][WND], hGuiFont, pTxtWait);

  aTxt1 = CSVToArray(AkelPad.GetTextRange(nBegSel, nEndSel), pInSep);

  if (aTxt1 == null)
    return;

  for (i=0; i < aTxt1.length; ++i)
  {
    aRowNum.push(1);

    while (aColLen.length < aTxt1[i].length)
      aColLen.push(0);

    for (n=0; n < aTxt1[i].length; ++n)
    {
      aTxt1[i][n] = aTxt1[i][n].split("\r");

      if (aRowNum[i] < aTxt1[i][n].length)
        aRowNum[i] = aTxt1[i][n].length;

      for (v=0; v < aTxt1[i][n].length; ++v)
      {
        if (aColLen[n] < aTxt1[i][n][v].length)
          aColLen[n] = aTxt1[i][n][v].length;
      }
    }
  }

  nNumLen = (aTxt1.length + nAdColNum - 1).toString().length;

  if (bRSep)
  {
    pRSepLine = pCSep;
    for (n=0; n < aColLen.length; ++n)
      pRSepLine = pRSepLine + Replicate(pRSep, aColLen[n]) + pCSep;
    if (bAdColL)
      pRSepLine = pCSep + Replicate(pRSep, nNumLen) + pRSepLine;
    if (bAdColR)
      pRSepLine = pRSepLine + Replicate(pRSep, nNumLen) + pCSep;
    aTxt2.push(pRSepLine);
  }

  SetWindowFontAndText(aWnd[IDCOUNTER][WND], hGuiFont, pTxtCountOut);

  for (i=0; i < aTxt1.length; ++i)
  {
    while (aTxt1[i].length < aColLen.length)
      aTxt1[i].push([""]);

    for (n=0; n < aColLen.length; ++n)
    {
      while (aTxt1[i][n].length < aRowNum[i])
        aTxt1[i][n].push("");
    }

    for (v=0; v < aRowNum[i]; ++v)
    {
      pTxt = pCSep;
      for (n=0; n < aColLen.length; ++n)
        pTxt = pTxt + Pad(aTxt1[i][n][v], aColLen[n], pPad) + pCSep;
      if (bAdColL)
      {
        if (v == 0)
          pTxt = pCSep + Pad(String(i + nAdColNum), nNumLen, "L") + pTxt;
        else
          pTxt = pCSep + Replicate(" ", nNumLen) + pTxt;
      }
      if (bAdColR)
      {
        if (v == 0)
          pTxt = pTxt + Pad(String(i + nAdColNum), nNumLen, "L") + pCSep;
        else
          pTxt = pTxt + Replicate(" ", nNumLen) + pCSep;
      }

      aTxt2.push(pTxt);
    }

    if (bRSep)
      aTxt2.push(pRSepLine);

    SetWindowFontAndText(aWnd[IDOK][WND], hGuiFont, i.toString());
    if (oSys.Call("User32::GetAsyncKeyState", 0x1B /*VK_ESCAPE*/) < 0)
    {
      if (AkelPad.MessageBox(hWndDlg, pTxtCountMes1 + i + pTxtCountMes2, pTxtCaption,
                             0x00000024 /*MB_ICONQUESTION|MB_YESNO*/) == 7 /*IDNO*/)
        return;
    }
  }

  if (nAction == 0)
    AkelPad.SendMessage(hMainWnd, 273 /*WM_COMMAND*/, 4101 /*wParam=MAKEWPARAM(0,IDM_FILE_NEW)*/, 1 /*lParam=TRUE*/);
  else if (nAction == 1)
    AkelPad.SetSel(nBegSel, nEndSel);
  else if (nAction == 2)
  {
    AkelPad.SetSel(nBegSel, nBegSel);
    aTxt2.push("");
  }
  else if (nAction == 3)
  {
    AkelPad.SetSel(nEndSel, nEndSel);
    aTxt2.unshift("");
  }

  AkelPad.ReplaceSel(aTxt2.join("\r"), (nAction > 0) ? -1 : 0);
  return;
}

// Function CSVToArray() by Ben Nadel:
// http://www.bennadel.com/blog/1504-Ask-Ben-Parsing-CSV-Strings-With-Javascript-Exec-Regular-Expression-Command.htm
//
// This will parse a delimited string into an array of
// arrays. The default delimiter is the comma, but this
// can be overriden in the second argument.
function CSVToArray(strData, strDelimiter)
{
  // Check to see if the delimiter is defined. If not, then default to comma.
  strDelimiter = (strDelimiter || ",");

  // Create a regular expression to parse the CSV values.
  var objPattern = new RegExp(
  (
  // Delimiters.
  "(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +
  // Quoted fields.
  "(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +
  // Standard fields.
  "([^\"\\" + strDelimiter + "\\r\\n]*))"
  ),"gi");

  // Create an array to hold our data. Give the array a default empty first row.
  var arrData = [[]];

  // Create an array to hold our individual pattern matching groups.
  var arrMatches = null;

  // Keep looping over the regular expression matches until we can no longer find a match.
  while (arrMatches = objPattern.exec(strData))
  {
    // Get the delimiter that was found.
    var strMatchedDelimiter = arrMatches[1];

    // Check to see if the given delimiter has a length (is not the start of string) and if it matches
    // field delimiter. If id does not, then we know that this delimiter is a row delimiter.
    if (strMatchedDelimiter.length && (strMatchedDelimiter != strDelimiter))
    {
      // Since we have reached a new row of data, add an empty row to our data array.
      arrData.push([]);
    }

    // Now that we have our delimiter out of the way, let's check to see which kind of value we
    // captured (quoted or unquoted).
    if (arrMatches[2])
    {
      // We found a quoted value. When we capture this value, unescape any double quotes.
      var strMatchedValue = arrMatches[2].replace(new RegExp("\"\"", "g" ), "\"");
    }
    else
    {
      // We found a non-quoted value.
      var strMatchedValue = arrMatches[3];
    }

    // Now that we have our value string, let's add it to the data array.
    arrData[arrData.length - 1].push(strMatchedValue);

    // Is no in oryginal function CSVToArray()
    SetWindowFontAndText(aWnd[IDOK][WND], hGuiFont, arrData.length.toString());
    if (oSys.Call("User32::GetAsyncKeyState", 0x1B /*VK_ESCAPE*/) < 0)
    {
      if (AkelPad.MessageBox(hWndDlg, pTxtCountMes1 + arrData.length + pTxtCountMes2, pTxtCaption,
                             0x00000024 /*MB_ICONQUESTION|MB_YESNO*/) == 7 /*IDNO*/)
        return;
    }
  }

  // Return the parsed data.
  return(arrData);
}

Last edited by KDJ on Sat Sep 19, 2015 3:37 pm, edited 12 times in total.

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

Post by KDJ »

Select all text before or after the caret.

Code: Select all

// http://akelpad.sourceforge.net/forum/viewtopic.php?p=9079#p9079
// Version: 2013-08-31
// Author: KDJ
//
// *** Select all text before/after the caret ***
//
// Usage:
//   Call("Scripts::Main", 1, "SelectBeforeAfterCaret.js")
//
// Can assign shortcut key eg: Ctrl+Shift+A

var hEditWnd = AkelPad.GetEditWnd();
if (! hEditWnd)
	WScript.Quit();

var nBegSel   = AkelPad.GetSelStart();
var nEndSel   = AkelPad.GetSelEnd();
var nCarPos   = GetOffset(hEditWnd, 5 /*AEGI_CARETCHAR*/);
var nLastChar = GetOffset(hEditWnd, 2 /*AEGI_LASTCHAR*/);

if (nBegSel == nEndSel)
  if (nBegSel == 0)
    nBegSel = nLastChar;
  else
    nBegSel = 0;
else if (nBegSel == nCarPos)
{
  nBegSel = 0;
  nEndSel = nCarPos;
}
else
{
  nBegSel = nLastChar;
  nEndSel = nCarPos;
}

AkelPad.SetSel(nBegSel, nEndSel);

function GetOffset(hWnd, nFlag)
{
  var nOffset = -1;
  var lpIndex;

  if (lpIndex = AkelPad.MemAlloc(_X64 ? 24 : 12 /*sizeof(AECHARINDEX)*/))
  {
    SendMessage(hWnd, 3130 /*AEM_GETINDEX*/, nFlag, lpIndex);
    nOffset = SendMessage(hWnd, 3136 /*AEM_INDEXTORICHOFFSET*/, 0, lpIndex);
    AkelPad.MemFree(lpIndex);
  }
  return nOffset;
}

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

Last edited by KDJ on Sat Dec 20, 2014 7:20 pm, edited 2 times in total.

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

Post by KDJ »

Align selected lines to the left, right, center or justify.

Code: Select all

// http://akelpad.sourceforge.net/forum/viewtopic.php?p=9169#p9169
// Version: 2015-09-19
// Author: KDJ
//
// *** Align selected lines to the left, right, center or justify ***
//
// Usage:
//   Call("Scripts::Main", 1, "AlignJustify.js", "Action LineLength")
//
// Arguments:
//   Action:
//     L - left
//     R - right
//     C - center
//     J - justify (default)
//   LineLength:
//     - line length in characters
//     - default is length of the longest line in selection (max line length)
//     - value less than max line length - displays input box
//
// Examples:
//   Call("Scripts::Main", 1, "AlignJustify.js")         - justify to max line length
//   Call("Scripts::Main", 1, "AlignJustify.js", "C")    - center in max line length
//   Call("Scripts::Main", 1, "AlignJustify.js", "R 80") - right align, line length 80
//   Call("Scripts::Main", 1, "AlignJustify.js", "L -1") - left align, input box with line length
//
// Remarks:
//   In the case of columnar selection, only selected text will be aligned.
//   To effect was clearly visible, you should use a fixed-width font and turn off word wrap.

var hEditWnd = AkelPad.GetEditWnd();

if (! hEditWnd)
  WScript.Quit();

var bColSel = AkelPad.SendMessage(hEditWnd, 3127 /*AEM_GETCOLUMNSEL*/, 0, 0);
var nMaxLineLen = 0;
var aLines;
var nOffset1;
var nOffset2;
var sAction;
var nLineLen;
var sLineLen;
var nWordsLen;
var aWords;
var aSpaces;
var sPadType;
var i, n;

if (bColSel)
  aLines = AkelPad.GetSelText(1 /*\r*/).replace(/\t/gm, " ").split("\r"); //replace tabs with spaces
else
{
  GetOffsets();
  aLines = AkelPad.GetTextRange(nOffset1, nOffset2, 1 /*\r*/).replace(/\t/gm, " ").split("\r"); //replace tabs with spaces
}

for (i = 0; i < aLines.length; ++i)
{
  if (nMaxLineLen < aLines[i].length)
    nMaxLineLen = aLines[i].length;

  aLines[i] = aLines[i].replace(/(^ +)|( +$)/g, ""); //delete leading and trailing spaces
}

if (nMaxLineLen < 2)
  WScript.Quit();

if (WScript.Arguments.length)
{
  sAction = WScript.Arguments(0).charAt(0).toUpperCase();

  if (WScript.Arguments.length > 1)
    nLineLen = parseInt(WScript.Arguments(1), 10);
}

if ((! sAction) || ("LRCJ".indexOf(sAction) < 0))
  sAction = "J";

if (typeof nLineLen == "undefined")
  nLineLen = nMaxLineLen;
else if (! isFinite(nLineLen))
  nLineLen = -1;

if (nLineLen < nMaxLineLen)
{
  sLineLen = nMaxLineLen.toString();

  for (;;)
  {
    sLineLen = AkelPad.InputBox(hEditWnd, WScript.ScriptName, "Line length (in characters):", sLineLen);

    if (typeof sLineLen == "undefined")
      WScript.Quit();

    nLineLen = parseInt(sLineLen, 10);

    if (nLineLen >= nMaxLineLen)
      break;

    AkelPad.MessageBox(hEditWnd, "Line length must be >= " + nMaxLineLen, WScript.ScriptName, 0x30 /*MB_ICONWARNING*/);
  }
}

if (sAction == "J")
{
  for (i = 0; i < aLines.length; ++i)
  {
    aWords = aLines[i].split(/ +/);

    if (aWords.length > 1)
    {
      nWordsLen = aLines[i].replace(/ +/g, "").length;
      aSpaces   = [];

      for (n = 0; n < aWords.length - 1; ++n)
        aSpaces.push(Pad("", Math.floor((nLineLen - nWordsLen) / (aWords.length - 1)), "R"));

      for (n = 0; n < (nLineLen - nWordsLen) % (aWords.length - 1); ++n)
        aSpaces[n] += " ";

      aLines[i] = aWords[0];
      for (n = 0; n < aSpaces.length; ++n)
        aLines[i] = aLines[i] + aSpaces[n] + aWords[n + 1];
    }
    else
      aLines[i] = Pad(aWords[0], nLineLen, "R");
  }
}
else
{
  if (sAction == "L")
    sPadType = "R";
  else if (sAction == "R")
    sPadType = "L";
  else
    sPadType = sAction;

  for (i = 0; i < aLines.length; ++i)
    aLines[i] = Pad(aLines[i], nLineLen, sPadType);
}

if (! bColSel)
  AkelPad.SetSel(nOffset1, nOffset2);

AkelPad.ReplaceSel(aLines.join("\r"), -1);

function Pad(sString, nLen, sType)
{
  var i = 0;

  if (sType == "R")
  {
    while (sString.length < nLen)
      sString += " ";
  }
  else if (sType == "L")
  {
    while (sString.length < nLen)
      sString = " " + sString;
  }
  else if (sType == "C")
  {
    while (sString.length < nLen)
    {
      if ((i % 2) == 0)
        sString += " ";
      else
        sString = " " + sString;
      ++ i;
    }
  }

  return sString;
}

function GetOffsets()
{
  var lpIndex = AkelPad.MemAlloc(_X64 ? 24 : 12 /*sizeof(AECHARINDEX)*/);

  AkelPad.SendMessage(hEditWnd, 3130 /*AEM_GETINDEX*/,  3 /*AEGI_FIRSTSELCHAR*/, lpIndex);
  AkelPad.SendMessage(hEditWnd, 3130 /*AEM_GETINDEX*/, 18 /*AEGI_WRAPLINEBEGIN*/, lpIndex);
  nOffset1 = AkelPad.SendMessage(hEditWnd, 3136 /*AEM_INDEXTORICHOFFSET*/, 0, lpIndex);

  AkelPad.SendMessage(hEditWnd, 3130 /*AEM_GETINDEX*/,  4 /*AEGI_LASTSELCHAR*/, lpIndex);
  AkelPad.SendMessage(hEditWnd, 3130 /*AEM_GETINDEX*/, 19 /*AEGI_WRAPLINEEND*/, lpIndex);
  nOffset2 = AkelPad.SendMessage(hEditWnd, 3136 /*AEM_INDEXTORICHOFFSET*/, 0, lpIndex);

  AkelPad.MemFree(lpIndex);
}

Last edited by KDJ on Sat Sep 19, 2015 3:36 pm, edited 3 times in total.
Post Reply