FR: commentSelection and unCommentSelection for CodeEditorComponent


#1

It would be very nice to have a Keyboard Shortcut for commenting the selected lines in the CodeEditorComponent. ‘Command+/’ (like in Xcode) to insert or remove two ‘/’ slashes at the front of each selected line. I can probably manage the keypresses from outside the component by becoming an but i wouldn’t be able to undo it.
So pretty please?


#2

I’ll add it to the backlog, but I’m afraid it’s going to be way down the list.


#3

Added something myself, this works for me:

void CodeEditorComponent::commentSelection()
{
if (! readOnly)
{
    newTransaction();

    CodeDocument::Position oldSelectionStart (selectionStart), oldSelectionEnd (selectionEnd), oldCaret (caretPos);
    oldSelectionStart.setPositionMaintained (true);
    oldSelectionEnd.setPositionMaintained (true);
    oldCaret.setPositionMaintained (true);

    const int lineStart = selectionStart.getLineNumber();
    int lineEnd = selectionEnd.getLineNumber();

    if (lineEnd > lineStart && selectionEnd.getIndexInLine() == 0)
        --lineEnd;

    for (int line = lineStart; line <= lineEnd; ++line)
    {
        const String lineText (document.getLine (line));
			

        if (lineText.trimStart().isNotEmpty())
        {
            const CodeDocument::Position wsStart (document, line, 0);
				const CodeDocument::Position wsEnd (document, line, 2);

				if (lineText.startsWith("//"))
					document.deleteSection(wsStart, wsEnd);
				else
					document.insertText (wsStart, "//");
        }
    }

    selectionStart = oldSelectionStart;
    selectionEnd = oldSelectionEnd;
    caretPos = oldCaret;
}
}

#4

Thanks - that’s a decent starting point, but I can immediately see some bugs and edge-cases in that code which we’d need to sort out before it’d be ready for a real release!