/* * Reverse_Lines.bsh - a BeanShell macro script for reversing the order * of lines in a buffer. If there are selections, the lines in the selections * will be reversed, otherwise the whole buffer will be reversed. * NOTE: Lines are not sorted or reverse sorted, simply reversed. * * Copyright (C) 2002 Ollie Rutherfurd, oliver@rutherfurd.net * * :mode=beanshell:tabSize=4:indentSize=4:maxLineLen=0:noTabs=false: * :indentOnTab=true:indentOnEnter=true:folding=explicit:collapseFolds=1: * {{{ License * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with the jEdit program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * }}} * * $Id: Reverse_Lines.bsh 28 2003-03-25 22:40:28Z oliver $ */ void ReverseLines(textArea) { Buffer buffer = textArea.getBuffer(); Selection[] selections = textArea.getSelection(); // doesn't work with rectangular selections, check for them up-front for(int i = 0; i < selections.length; i++) { if(selections[i] instanceof Selection.Rect) { //Toolkit.getDefaultToolkit().beep(); Macros.error(view, "Sorry, this macro doesn't work with Rectangular Selections."); return; } } buffer.beginCompoundEdit(); // do whole buffer if no selections if(selections.length == 0){ StringBuffer sb = new StringBuffer(buffer.getLength()); for(int i = buffer.getLineCount() - 1; i >= 0; i--){ String line = buffer.getLineText(i); sb.append(line); if(i > 0) // don't append a newline for the last line sb.append('\n'); } buffer.remove(0, buffer.getLength()); buffer.insert(0, sb.toString()); } // reverse all lines that are selected *NOT* just selected portions of lines else{ for(int i = 0; i < selections.length; i++){ int startLine = selections[i].getStartLine(); int endLine = selections[i].getEndLine(); int startOffset = buffer.getLineStartOffset(startLine); if(startLine < endLine){ StringBuffer sb = new StringBuffer(); for(int i = endLine; i > startLine; i--){ String line = buffer.getLineText(i); sb.append(line).append('\n'); } // appending first line here, so a check // can be made to see whether to append // a newline (don't if the original line // was the last line of the buffer) sb.append(buffer.getLineText(startLine)); if(endLine < buffer.getLineCount() - 1) sb.append('\n'); String reversed = sb.toString(); buffer.remove(startOffset, reversed.length()); buffer.insert(startOffset, reversed); } } } buffer.endCompoundEdit(); } ReverseLines(textArea);