package com.andresdominguez.ngsort;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.editor.Editor;
import com.intellij.psi.PsiFile;

public class GoogVarAction extends AnAction {

  @Override
  public void actionPerformed(AnActionEvent e) {
    final Editor editor = e.getData(PlatformDataKeys.EDITOR);
    PsiFile psiFile = e.getData(CommonDataKeys.PSI_FILE);
    if (editor == null || psiFile == null) {
      return;
    }

  }
}

@@ -30,16 +30,184 @@
 gsort;%0A%0A
+import com.google.common.collect.Iterables;%0Aimport com.intellij.lang.javascript.psi.JSExpressionStatement;%0Aimport com.intellij.lang.javascript.psi.JSLiteralExpression;%0A
 import c
@@ -453,54 +453,285 @@
 api.
-editor.Editor;%0Aimport com.intellij.psi.PsiFile
+command.CommandProcessor;%0Aimport com.intellij.openapi.editor.Document;%0Aimport com.intellij.openapi.editor.Editor;%0Aimport com.intellij.psi.PsiElement;%0Aimport com.intellij.psi.PsiFile;%0Aimport com.intellij.psi.util.PsiTreeUtil;%0A%0Aimport java.util.ArrayList;%0Aimport java.util.Arrays
 ;%0A%0Ap
@@ -1023,14 +1023,1117 @@
 %0A    %7D%0A%0A
+    PsiElement currentElement = psiFile.findElementAt(editor.getCaretModel().getOffset());%0A    if (currentElement == null) %7B%0A      return;%0A    %7D%0A%0A    JSExpressionStatement exprStmt = PsiTreeUtil.getParentOfType(currentElement, JSExpressionStatement.class);%0A    if (exprStmt == null) %7B%0A      return;%0A    %7D%0A%0A    final Document document = editor.getDocument();%0A    final int offset = exprStmt.getTextOffset();%0A    final String varName = getVarName(exprStmt);%0A%0A    CommandProcessor.getInstance().executeCommand(getEventProject(e), new Runnable() %7B%0A      @Override%0A      public void run() %7B%0A        document.replaceString(offset, offset, varName);%0A      %7D%0A    %7D, %22ng sort%22, null);%0A  %7D%0A%0A  private String getVarName(JSExpressionStatement expressionStatement) %7B%0A    ArrayList%3CJSLiteralExpression%3E expressions = new ArrayList%3C%3E(%0A        PsiTreeUtil.findChildrenOfType(expressionStatement, JSLiteralExpression.class));%0A    String text = expressions.get(0).getText();%0A    String lastToken = Iterables.getLast(Arrays.asList(text.replaceAll(%22'%22, %22%22).split(%22%5C%5C.%22)));%0A    return String.format(%22var %25s = %22, lastToken);%0A
   %7D%0A%7D%0A

introduce goog var