/*
 * Greedy_Delete.bsh - If a buffer is using soft tabs,
 * this macro will delete tabSize number of spaces, if
 * all the characters between the caret and the next tab
 * stop are spaces.  In all other cases a single character
 * is deleted.
 *
 * Copyright (C) 2004 Ollie Rutherfurd <oliver@jedit.org>
 *
 * $Id: Greedy_Delete.bsh 23971 2015-08-08 19:37:35Z daleanson $
 */

/**
 * @param onlyFullTabs if true, multiple spaces are only
 *                     removed if they would constitute
 *                     a 'complete' tab.
 */
void greedyDelete(View view, boolean onlyFullTabs)
{
	JEditTextArea textArea = view.getTextArea();
	JEditBuffer buffer = textArea.getBuffer();
	int caret = textArea.getCaretPosition();
	int caretLine = textArea.getCaretLine();
	int lineStart = textArea.getLineStartOffset(caretLine);
	int lineEnd = textArea.getLineEndOffset(caretLine);

	if(buffer.getBooleanProperty("noTabs") == true)
	{
		// if anything is selected, use standard 
		if(textArea.getSelection().length != 0)
		{
			textArea.delete();
		}
		// if at the end of the line, go to the 
		// start of the next line (+1 for \n)
		else if(caret+1 >= lineEnd)
		{
			textArea.delete();
		}
		else
		{
			int col = caret - lineStart;
			int tabSize = buffer.getIntegerProperty("tabSize",8);

			// unlikely, but just in case
			if(tabSize <= 0)
			{
				textArea.delete();
			}
			else
			{
				int toTabStop = (((col+tabSize)-1) % tabSize) + 1;
				// don't wrap to next line
				if(caret+toTabStop > lineEnd){
					textArea.delete();
					return;
				}

				int count = 0;
				for(int i=0; i < toTabStop; i++)
				{
					if(!" ".equals(buffer.getText(caret+i,1)))
						break;
					count += 1;
				}

				// if onlyFullTabs must be only spaces to
				// the tabStop and must have tabSize number 
				// of spaces to remove them all.
				if(onlyFullTabs == false || count == tabSize){
					buffer.remove(caret,count);
				}
				else{
					textArea.delete();
				}
			}
		}
	}
	else
		textArea.delete();
}

	greedyDelete(view,true);

