[script] Invert lines

Ask questions about how to create a script or swap scripts with other users.
Post Reply
User avatar
pjj
Posts: 1792
Joined: 13 Oct 2009 13:48
Location: Kraków, Poland

[script] Invert lines

Post by pjj »

Here's another simple script I wrote a couple days ago and I thought I'd share with you: it changes the order of lines, i.e.
line 1
line 2
line3
becomes
line 3
line 2
line1
It deletes blank lines in the selection, btw:

Code: Select all

// turn off screen updating
Document.BeginUpdate();
if (Document.SelLength == 0) {
  ShowMessage("Invert lines: nothing to do!");
} else {
  // make sure variables are integers
  var startX = 0, startY = 0, endX = 0, endY = 0;
  // find selection's coordinates
  Document.GetSelection(startX, startY, endX, endY);
  if (startY == endY) {
    ShowMessage("Invert lines: nothing to do!");
  } else {
    // actual inversion
    // if selection was made upwards, switch startY and endY
    var temp = 0;
    if (startY > endY) {
      temp = startY;
      startY = endY;
      endY = temp;
    }
    Document.SetSelection(0, startY, endX, endY);
    Document.CursorLineEnd(true);
    Document.DeleteBlankLines();
    var s = Document.SelText();
    var lines[1000]; // lines in selection
    var j = 0;
    for (var i = 1; i <= length(s); i++) {
      if ((s[i] != "\r") && (s[i] != "\n")) {
        lines[j] += s[i];
      }
      if (s[i] == "\n") {
        j++;
      }
    }
    var iLines[1000];
    for (i = 0; i <= j; i++) {
      iLines[i] = lines[j - i];
    }
  }
  // join lines
  s = "";
  for (i = 0; i <= j; i++) {
    s += iLines[i];
    if (i != j) {
      s += "\r\n";
    }
  }
  // invert lines in selection
  Document.SelText() = s;
}
// turn on screen updating
Document.EndUpdate();
This script is brought to you by the letter J (for July) and Document.GetSelection function.
Alium tibi quaere fratrem; hic, quem tuum putas, meus est. Titus Flāvius Caesar Vespasiānus Augustus

Post Reply