// Lines sort by length and string
// Call("Scripts::Main", 1, "LinesSortByLengthAndString.js")
// The script sorts all lines by two keys:
// key 1 - line length
// key 2 - string containing entire line

if (! AkelPad.GetEditWnd()) WScript.Quit();

AkelPad.SetSel(0, -1);

var bDesc1 = 0; // = 1 if key 1 descending
var bDesc2 = 0; // = 1 if key 2 descending
var pTxt   = AkelPad.GetSelText(1 /*\r*/);
var lpArr  = pTxt.split("\r");

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

lpArr.sort(function(a, b) {
  if      (a.getBytesLength() < b.getBytesLength()) return (bDesc1 ?  1 : -1);
  else if (a.getBytesLength() > b.getBytesLength()) return (bDesc1 ? -1 :  1);
  else if (a < b) return (bDesc2 ?  1 : -1);
  else if (a > b) return (bDesc2 ? -1 :  1);
  else return 0; });

pTxt = lpArr.join("\r");

AkelPad.ReplaceSel(pTxt);