/**
 * Automatically inserts the proper length of setext header based
 * on the number of characters in the previous line
 * 
 * setup:
 * - character (string): the character to repeat (- or =)
 */

var nonEmptyLineRegex = /\S/;

action.canPerformWithContext = function(context, outError) {
	// Only allow this action if we are at the beginning of a line, and there is a line with text above us
	var location = context.selectedRanges[0].location,
		lineStart = context.lineStorage.lineRangeForIndex(location).location,
		prevLine = (lineStart > 1 ? context.substringWithRange(context.lineStorage.lineRangeForIndex(lineStart - 1)) : '');
	return (lineStart === (location - 1) || lineStart === location) && nonEmptyLineRegex.test(prevLine);
};

action.performWithContext = function(context, outError) {
	// Grab our previous line length, trimmed of trailing whitespace
	/* Non-collapsed version:
	var location = context.selectedRanges[0].location,
		lineStart = context.lineStorage.lineRangeForIndex(location).location,
		prevLine = context.substringWithRange(context.lineStorage.lineRangeForIndex(lineStart - 1)).replace(/^([\s\S]+?)[\s\n\r]*$/, '$1'),
		numCharacters = prevLine.length;
	*/
	var numChars = context.substringWithRange(context.lineStorage.lineRangeForIndex(context.lineStorage.lineRangeForIndex(context.selectedRanges[0].location).location - 1)).replace(/^(.+?)\s*$/, '$1').length;
	return context.insertTextSnippet(new CETextSnippet(Array(numChars + 1).join(action.setup.character)));
};
