"""
Center_Text.py - A Jython macro for jEdit that centers the
text of the current line by padding the left with whitespace.

Copyright (C) 2002 Ollie Rutherfurd <oliver@rutherfurd.net>

$Id: Center_Text.py 28 2003-03-25 22:40:28Z oliver $
"""

from org.gjt.sp.jedit import Macros
from org.gjt.sp.jedit import MiscUtilities

__version__ = '$Revision: 1.8 $'[11:-2]
__author__ = 'Ollie Rutherfurd'


def centerText(view):

	textArea = view.getTextArea()
	buff = textArea.getBuffer()

	# get tabSize property
	try:
		tabSize = int(buff.getProperty('tabSize'))
	except ValueError,e:
		Macros.error(view, 'Error getting tabSize: ' + e)
		return

	# get line caret is on
	line = textArea.getCaretLine()
	# line start offset (used later during removal and insertion)
	startOffset = textArea.getLineStartOffset(line)
	# get line text
	line_text = textArea.getLineText(line)
	# determine text length, with tabs expanded
	text_len = len(line_text.strip().expandtabs(tabSize))

	# find out how long a 'line' should be
	try:
		line_len = Macros.input(view, 'Line Length', '80')
		# in case user cancels
		if line_len is None:
			return
		line_len = int(line_len)
	except ValueError,e:
		Macros.error(view, 'Error getting Line Length: ' + e)
		return

	# text too long to center
	if text_len > line_len:
		Macros.error(view, \
			'Current line text is longer than desired line length.')
		return
	# can't center, lengths match
	elif text_len == line_len:
		return

	# get amount of padding needed
	pad_len = (line_len - text_len) / 2
	# determine number of tabs to use
	tabs = '\t' * (pad_len / tabSize)
	# determine number of spaces to use
	spaces = ' ' * (pad_len % tabSize)
	# padding is tabs + spaces
	padding = tabs + spaces
	# get current leading whitespace
	cur_pad_len = MiscUtilities.getLeadingWhiteSpace(line_text)

	try:
		# use compound edit, in case we do removal and insertion
		buff.beginCompoundEdit()

		# remove current padding, if any exists
		if cur_pad_len > 0:
			buff.remove(startOffset, cur_pad_len)

		# insert new padding
		buff.insert(startOffset, padding)

	finally:
		buff.endCompoundEdit()


if __name__ in ('__main__','main'):
	centerText(init.view)

# :indentSize=4:lineSeparator=\n:noTabs=false:tabSize=4:

