/*
 * 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-2004 Ollie Rutherfurd, oliver@rutherfurd.net
 *
 * :mode=beanshell:tabSize=4:indentSize=4:maxLineLen=0:noTabs=false:
 * :indentOnTab=true:indentOnEnter=true:folding=explicit:collapseFolds=1:
 *
 * $Id: Reverse_Lines.bsh 9126 2007-03-10 19:14:30Z Vampire0 $
 */

void reverseLines(textArea)
{
	JEditBuffer 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)
		{
			Macros.error(view, "Sorry, this macro doesn't work with Rectangular Selections.");
			return;
		}
	}

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

if(buffer.isReadOnly())
	Macros.error(view, "Buffer is read-only.");
else
	reverseLines(textArea);

/*
	Macro index entry (in DocBook XML)

<listitem>
	<para><filename>Reverse_Lines.bsh</filename></para>
	<abstract><para>
		Reverses the selected lines or the entire buffer if no
		lines are selected.  Does not support Rectangular
		Selections.
	</para></abstract>
</listitem>
*/
