Add comment toggle feature

This commit is contained in:
2021-02-23 16:44:26 +01:00
parent 0ba350395b
commit 302b10a5a6
9 changed files with 170 additions and 5 deletions

View File

@@ -15,6 +15,7 @@ import org.fxmisc.richtext.model.TwoDimensional.Position;
import app.events.EditorChangedEvent;
import app.events.LanguageChangedEvent;
import app.events.ToggleCommentEvent;
import app.events.FileSaveStateChangedEvent;
import app.model.Model;
import app.service.LanguageOperations;
@@ -63,6 +64,41 @@ public class EditorController implements Initializable, Controller {
this.setHighlighting(LanguageOperations.syntaxHighlight(this.editor.getText(), Model.getLanguage()));
}
/**
* Uses Model.language to determine whether the current line/selection
* is commented or not, and toggles the comment.
*/
private void toggleComment() {
if (editor.getSelectedText().equals("")) {
String currentLine = editor.getText(editor.getCurrentParagraph());
String newText;
if (Model.getLanguage().isCommentedLine(currentLine))
newText = Model.getLanguage().unCommentLine(currentLine);
else
newText = Model.getLanguage().commentLine(currentLine);
editor.replaceText(
editor.getCurrentParagraph(),
0,
editor.getCurrentParagraph(),
currentLine.length(),
newText
);
} else { // Comment selection
String newText;
if (Model.getLanguage().isCommentedSelection(editor.getSelectedText()))
newText = Model.getLanguage().unCommentSelection(editor.getSelectedText());
else
newText = Model.getLanguage().commentSelection(editor.getSelectedText());
editor.replaceSelection(newText);
}
}
/**
* Handles the event whenever the content of the editor is changed.
*/
@@ -71,7 +107,6 @@ public class EditorController implements Initializable, Controller {
Position pos = this.editor.offsetToPosition(offset, Bias.Forward);
this.eventBus.post(new EditorChangedEvent(pos.getMajor() + 1, pos.getMinor()));
if (Model.getFileIsSaved())
this.eventBus.post(new FileSaveStateChangedEvent(false));
@@ -80,11 +115,20 @@ public class EditorController implements Initializable, Controller {
/**
* Refreshes the editor whenever the language is changed.
* @param event Which language was switched to
* @param event
*/
@Subscribe
private void handle(LanguageChangedEvent event) {
this.refreshHighlighting();
}
/**
* Toggles a language specific comment of the line/selection
* @param event
*/
@Subscribe
private void handle(ToggleCommentEvent event) {
this.toggleComment();
}
}