Skip to content

Instantly share code, notes, and snippets.

@andresdominguez
Created December 2, 2016 04:47
Show Gist options
  • Save andresdominguez/ea8aa8747b2473d29af7409c0d5e1f37 to your computer and use it in GitHub Desktop.
Save andresdominguez/ea8aa8747b2473d29af7409c0d5e1f37 to your computer and use it in GitHub Desktop.
public class InjectTestAction extends AnAction {
@Override
public void actionPerformed(AnActionEvent e) {
Project project = getEventProject(e);
Editor editor = e.getData(PlatformDataKeys.EDITOR);
PsiFile file = e.getData(PlatformDataKeys.PSI_FILE);
Caret caret = e.getData(PlatformDataKeys.CARET);
JSParameterList injectParameterList = findInjectParameterList(file);
// Subtract 1 because it ends with ).
int paramListOffset = injectParameterList.getTextRange().getEndOffset() - 1;
// Surround injectable with underscores.
String injectableWithUnderscores = "_" + caret.getSelectedText() + "_";
// Add comma if this is the second+ parameter.
boolean hasParams = injectParameterList.getChildren().length > 0;
String injectParam = hasParams ? ", " + injectableWithUnderscores : injectableWithUnderscores;
Document document = editor.getDocument();
CommandProcessor.getInstance().executeCommand(project, () -> {
ApplicationManager.getApplication().runWriteAction(() -> {
// Assign the variable <selection> = _<selection>_;
document.insertString(caret.getSelectionEnd(), " = " + injectableWithUnderscores + ";");
// Add injectable at the end of the parameter list.
document.insertString(paramListOffset, injectParam);
});
}, "inject test", null);
}
JSParameterList findInjectParameterList(PsiFile file) {...}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment