/**
 * Inserts a blockquote character at the cursor, or prefixes selected
 * lines with blockquote characters
 */

action.performWithContext = function(context, outError) {
	// Initialize variables we'll probably need
	var range, snippet, recipe = new CETextRecipe(),
		linesRange, lines, offset,
		firstLineRange;
	for (var i = 0, count = context.selectedRanges.length; i < count; i++) {
		range = context.selectedRanges[i];
		firstLineRange = context.lineStorage.lineRangeForIndex(range.location);
		// If the range is a selection, then prefix all selected lines with blockquote characters
		if (range.length > 0) {
			linesRange = context.lineStorage.lineRangeForRange(range);
			lines = context.substringWithRange(linesRange).match(/^.*((?:\r\n|\r|\n)|$)/gm);
			offset = linesRange.location;
			for (var j = 0, lineCount = lines.length; j < lineCount; j++) {
				if (j === (lineCount - 1) && lines[j] === '') {
					// Thanks to the way that the the regex chops lines up, there might be a trailing empty line; if so, do not prefix it
					break;
				}
				recipe.insertAtIndex(offset, '> ');
				offset += lines[j].length;
			}
		} else if (/^\s*$/.test(context.substringWithRange(new Range(firstLineRange.location, range.location - firstLineRange.location)))) {
			// We are working with a cursor, and it is at the beginning of a line with nothing but whitespace prior; insert a blockquote character at the cursor
			return context.insertTextSnippet(new CETextSnippet('> $0'));
		} else {
			// The cursor is somewhere in a non-empty line, so prefix the line
			recipe.insertAtIndex(firstLineRange.location, '> ');
		}
	}
	// Apply our recipe
	return context.applyTextRecipe(recipe);
};
