"""
Reverse_Lines.py - A Jython macro for jEdit that reverses the
order of lines in the current buffer. If any lines are selected
the lines within the selections are reversed, otherwise all lines
are reversed. Note: this macro doesn't to work with rectangular
selections.

Copyright 2002 (C) Ollie Rutherfurd <oliver@rutherfurd.net>

$Id: Reverse_Lines.py 28 2003-03-25 22:40:28Z oliver $
"""

__version__ = '$Revision: 1.4 $'[11:-2]
__author__ = 'Ollie Rutherfurd'

from org.gjt.sp.jedit import Macros
import org.gjt.sp.jedit.textarea as textarea


def reverseLines(view):

	textArea = view.getTextArea()
	b = textArea.getBuffer()
	selections = textArea.getSelection()

	if filter(lambda s: isinstance(s,textarea.Selection.Rect), selections):
		Macros.error(view, "Sorry, this macro doesn't work with Rectangular selections.")
		return

	b.beginCompoundEdit()

	# if no selection, reverse entire buffer
	if not selections:
		lines = textArea.getText().split('\n')
		lines.reverse()
		b.remove(0,b.getLength())
		b.insert(0,'\n'.join(lines))
	else:
		for selection in selections:
			startLine, endLine = selection.getStartLine(), selection.getEndLine()
			startOffset = b.getLineStartOffset(startLine)
			endOffset = b.getLineEndOffset(endLine)
			# only reverses multiple line selections
			if startLine < endLine:
				lines = b.getText(startOffset, (endOffset - startOffset) - 1).split('\n')
				lines.reverse()
				text = '\n'.join(lines)
				b.remove(startOffset, len(text))
				b.insert(startOffset, text)

	b.endCompoundEdit()


if __name__ in ('__main__','main'):
	reverseLines(init.view)

# :indentSize=4:lineSeparator=\n:noTabs=false:tabSize=4:

