Java Code Examples for org.eclipse.lsp4j.CodeAction#setKind()

The following examples show how to use org.eclipse.lsp4j.CodeAction#setKind() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CodeActionFactory.java    From lemminx with Eclipse Public License 2.0 6 votes vote down vote up
public static CodeAction replaceAt(String title, String replaceText, TextDocumentItem document,
		Diagnostic diagnostic, Collection<Range> ranges) {
	CodeAction insertContentAction = new CodeAction(title);
	insertContentAction.setKind(CodeActionKind.QuickFix);
	insertContentAction.setDiagnostics(Arrays.asList(diagnostic));

	VersionedTextDocumentIdentifier versionedTextDocumentIdentifier = new VersionedTextDocumentIdentifier(
			document.getUri(), document.getVersion());
	List<TextEdit> edits = new ArrayList<TextEdit>();
	for (Range range : ranges) {
		TextEdit edit = new TextEdit(range, replaceText);
		edits.add(edit);
	}
	TextDocumentEdit textDocumentEdit = new TextDocumentEdit(versionedTextDocumentIdentifier, edits);
	WorkspaceEdit workspaceEdit = new WorkspaceEdit(Collections.singletonList(Either.forLeft(textDocumentEdit)));

	insertContentAction.setEdit(workspaceEdit);
	return insertContentAction;
}
 
Example 2
Source File: CodeActionFactory.java    From lemminx with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Makes a CodeAction to create a file and add content to the file.
 * 
 * @param title      The displayed name of the CodeAction
 * @param docURI     The file to create
 * @param content    The text to put into the newly created document.
 * @param diagnostic The diagnostic that this CodeAction will fix
 */
public static CodeAction createFile(String title, String docURI, String content, Diagnostic diagnostic) {

	List<Either<TextDocumentEdit, ResourceOperation>> actionsToTake = new ArrayList<>(2);

	// 1. create an empty file
	actionsToTake.add(Either.forRight(new CreateFile(docURI, new CreateFileOptions(false, true))));

	// 2. update the created file with the given content
	VersionedTextDocumentIdentifier identifier = new VersionedTextDocumentIdentifier(docURI, 0);
	TextEdit te = new TextEdit(new Range(new Position(0, 0), new Position(0, 0)), content);
	actionsToTake.add(Either.forLeft(new TextDocumentEdit(identifier, Collections.singletonList(te))));

	WorkspaceEdit createAndAddContentEdit = new WorkspaceEdit(actionsToTake);

	CodeAction codeAction = new CodeAction(title);
	codeAction.setEdit(createAndAddContentEdit);
	codeAction.setDiagnostics(Collections.singletonList(diagnostic));
	codeAction.setKind(CodeActionKind.QuickFix);

	return codeAction;
}
 
Example 3
Source File: CodeActionAcceptor.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/** Adds a quick-fix code action with the given title, edit and command */
public void acceptQuickfixCodeAction(QuickfixContext context, String title, WorkspaceEdit edit, Command command) {
	if (edit == null && command == null) {
		return;
	}
	CodeAction codeAction = new CodeAction();
	codeAction.setTitle(title);
	codeAction.setEdit(edit);
	codeAction.setCommand(command);
	codeAction.setKind(CodeActionKind.QuickFix);
	if (context.options != null && context.options.getCodeActionParams() != null) {
		CodeActionContext cac = context.options.getCodeActionParams().getContext();
		if (cac != null && cac.getDiagnostics() != null) {
			codeAction.setDiagnostics(cac.getDiagnostics());
		}
	}
	codeActions.add(Either.forRight(codeAction));
}
 
Example 4
Source File: CodeActionProvider.java    From vscode-as3mxml with Apache License 2.0 6 votes vote down vote up
private void createCodeActionsForUnusedImport(Path path, Diagnostic diagnostic, WorkspaceFolderData folderData, List<Either<Command, CodeAction>> codeActions)
{
    String fileText = fileTracker.getText(path);
    if(fileText == null)
    {
        return;
    }

    Range range = diagnostic.getRange();
    WorkspaceEdit edit = CodeActionsUtils.createWorkspaceEditForRemoveUnusedImport(fileText, path.toUri().toString(), diagnostic.getRange());
    if (edit == null)
    {
        return;
    }

    int startOffset = LanguageServerCompilerUtils.getOffsetFromPosition(new StringReader(fileText), range.getStart());
    int endOffset = LanguageServerCompilerUtils.getOffsetFromPosition(new StringReader(fileText), range.getEnd());

    String importText = fileText.substring(startOffset, endOffset);
    CodeAction codeAction = new CodeAction();
    codeAction.setTitle("Remove " + importText);
    codeAction.setEdit(edit);
    codeAction.setKind(CodeActionKind.QuickFix);
    codeAction.setDiagnostics(Collections.singletonList(diagnostic));
    codeActions.add(Either.forRight(codeAction));
}
 
Example 5
Source File: CodeActionsUtils.java    From vscode-as3mxml with Apache License 2.0 6 votes vote down vote up
private static void createCodeActionsForGenerateGetterAndSetter(IVariableNode variableNode, String uri, String fileText, Range codeActionsRange, List<Either<Command, CodeAction>> codeActions)
{
    WorkspaceEdit getSetEdit = createWorkspaceEditForGenerateGetterAndSetter(
        variableNode, uri, fileText, true, true);
    CodeAction getAndSetCodeAction = new CodeAction();
    getAndSetCodeAction.setTitle("Generate 'get' and 'set' accessors");
    getAndSetCodeAction.setEdit(getSetEdit);
    getAndSetCodeAction.setKind(CodeActionKind.RefactorRewrite);
    codeActions.add(Either.forRight(getAndSetCodeAction));
    
    WorkspaceEdit getterEdit = createWorkspaceEditForGenerateGetterAndSetter(
        variableNode, uri, fileText, true, false);
    CodeAction getterCodeAction = new CodeAction();
    getterCodeAction.setTitle("Generate 'get' accessor (make read-only)");
    getterCodeAction.setEdit(getterEdit);
    getterCodeAction.setKind(CodeActionKind.RefactorRewrite);
    codeActions.add(Either.forRight(getterCodeAction));

    WorkspaceEdit setterEdit = createWorkspaceEditForGenerateGetterAndSetter(
        variableNode, uri, fileText, false, true);
    CodeAction setterCodeAction = new CodeAction();
    setterCodeAction.setTitle("Generate 'set' accessor (make write-only)");
    setterCodeAction.setEdit(setterEdit);
    setterCodeAction.setKind(CodeActionKind.RefactorRewrite);
    codeActions.add(Either.forRight(setterCodeAction));
}
 
Example 6
Source File: SourceAssistProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private Optional<Either<Command, CodeAction>> getOverrideMethodsAction(CodeActionParams params) {
	if (!preferenceManager.getClientPreferences().isOverrideMethodsPromptSupported()) {
		return Optional.empty();
	}

	Command command = new Command(ActionMessages.OverrideMethodsAction_label, COMMAND_ID_ACTION_OVERRIDEMETHODSPROMPT, Collections.singletonList(params));
	if (preferenceManager.getClientPreferences().isSupportedCodeActionKind(JavaCodeActionKind.SOURCE_OVERRIDE_METHODS)) {
		CodeAction codeAction = new CodeAction(ActionMessages.OverrideMethodsAction_label);
		codeAction.setKind(JavaCodeActionKind.SOURCE_OVERRIDE_METHODS);
		codeAction.setCommand(command);
		codeAction.setDiagnostics(Collections.EMPTY_LIST);
		return Optional.of(Either.forRight(codeAction));
	} else {
		return Optional.of(Either.forLeft(command));
	}
}
 
Example 7
Source File: SourceAssistProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private Optional<Either<Command, CodeAction>> getGetterSetterAction(CodeActionParams params, IInvocationContext context, IType type) {
	try {
		AccessorField[] accessors = GenerateGetterSetterOperation.getUnimplementedAccessors(type);
		if (accessors == null || accessors.length == 0) {
			return Optional.empty();
		} else if (accessors.length == 1 || !preferenceManager.getClientPreferences().isAdvancedGenerateAccessorsSupported()) {
			GenerateGetterSetterOperation operation = new GenerateGetterSetterOperation(type, context.getASTRoot(), preferenceManager.getPreferences().isCodeGenerationTemplateGenerateComments());
			TextEdit edit = operation.createTextEdit(null, accessors);
			return convertToWorkspaceEditAction(params.getContext(), context.getCompilationUnit(), ActionMessages.GenerateGetterSetterAction_label, JavaCodeActionKind.SOURCE_GENERATE_ACCESSORS, edit);
		} else {
			Command command = new Command(ActionMessages.GenerateGetterSetterAction_ellipsisLabel, COMMAND_ID_ACTION_GENERATEACCESSORSPROMPT, Collections.singletonList(params));
			if (preferenceManager.getClientPreferences().isSupportedCodeActionKind(JavaCodeActionKind.SOURCE_GENERATE_ACCESSORS)) {
				CodeAction codeAction = new CodeAction(ActionMessages.GenerateGetterSetterAction_ellipsisLabel);
				codeAction.setKind(JavaCodeActionKind.SOURCE_GENERATE_ACCESSORS);
				codeAction.setCommand(command);
				codeAction.setDiagnostics(Collections.EMPTY_LIST);
				return Optional.of(Either.forRight(codeAction));
			} else {
				return Optional.of(Either.forLeft(command));
			}
		}
	} catch (OperationCanceledException | CoreException e) {
		JavaLanguageServerPlugin.logException("Failed to generate Getter and Setter source action", e);
		return Optional.empty();
	}
}
 
Example 8
Source File: SourceAssistProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private Optional<Either<Command, CodeAction>> convertToWorkspaceEditAction(CodeActionContext context, ICompilationUnit cu, String name, String kind, TextEdit edit) {
	WorkspaceEdit workspaceEdit = convertToWorkspaceEdit(cu, edit);
	if (!ChangeUtil.hasChanges(workspaceEdit)) {
		return Optional.empty();
	}

	Command command = new Command(name, CodeActionHandler.COMMAND_ID_APPLY_EDIT, Collections.singletonList(workspaceEdit));
	if (preferenceManager.getClientPreferences().isSupportedCodeActionKind(kind)) {
		CodeAction codeAction = new CodeAction(name);
		codeAction.setKind(kind);
		codeAction.setCommand(command);
		codeAction.setDiagnostics(context.getDiagnostics());
		return Optional.of(Either.forRight(codeAction));
	} else {
		return Optional.of(Either.forLeft(command));
	}
}
 
Example 9
Source File: CodeActionProvider.java    From vscode-as3mxml with Apache License 2.0 5 votes vote down vote up
private void createCodeActionForMissingCatchOrFinally(Path path, Diagnostic diagnostic, WorkspaceFolderData folderData, List<Either<Command, CodeAction>> codeActions)
  {
      ILspProject project = folderData.project;
      Position position = diagnostic.getRange().getStart();
      IncludeFileData includeFileData = folderData.includedFiles.get(path.toString());
int currentOffset = LanguageServerCompilerUtils.getOffsetFromPosition(fileTracker.getReader(path), position, includeFileData);
      IASNode offsetNode = workspaceFolderManager.getOffsetNode(path, currentOffset, folderData);
      if(!(offsetNode instanceof ITryNode))
      {
          return;
      }
      ITryNode tryNode = (ITryNode) offsetNode;
      String fileText = fileTracker.getText(path);
      if(fileText == null)
      {
          return;
      }

      WorkspaceEdit edit = CodeActionsUtils.createWorkspaceEditForGenerateCatch(
          tryNode, path.toUri().toString(), fileText, project);
      if(edit == null)
      {
          return;
      }

      CodeAction codeAction = new CodeAction();
      codeAction.setDiagnostics(Collections.singletonList(diagnostic));
      codeAction.setTitle("Generate catch");
      codeAction.setEdit(edit);
      codeAction.setKind(CodeActionKind.QuickFix);
      codeActions.add(Either.forRight(codeAction));
  }
 
Example 10
Source File: CodeActionFactory.java    From lemminx with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Create a CodeAction to insert a new content at the end of the given range.
 * 
 * @param title
 * @param range
 * @param insertText
 * @param document
 * @param diagnostic
 * 
 * @return the CodeAction to insert a new content at the end of the given range.
 */
public static CodeAction insert(String title, Position position, String insertText, TextDocumentItem document,
		Diagnostic diagnostic) {
	CodeAction insertContentAction = new CodeAction(title);
	insertContentAction.setKind(CodeActionKind.QuickFix);
	insertContentAction.setDiagnostics(Arrays.asList(diagnostic));
	TextDocumentEdit textDocumentEdit = insertEdit(insertText, position, document);
	WorkspaceEdit workspaceEdit = new WorkspaceEdit(Collections.singletonList(Either.forLeft(textDocumentEdit)));

	insertContentAction.setEdit(workspaceEdit);
	return insertContentAction;
}
 
Example 11
Source File: NonProjectFixProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private Either<Command, CodeAction> getDiagnosticsFixes(String message, String uri, String scope, boolean syntaxOnly) {
	Command command = new Command(message, REFRESH_DIAGNOSTICS_COMMAND, Arrays.asList(uri, scope, syntaxOnly));
	if (preferenceManager.getClientPreferences().isSupportedCodeActionKind(CodeActionKind.QuickFix)) {
		CodeAction codeAction = new CodeAction(message);
		codeAction.setKind(CodeActionKind.QuickFix);
		codeAction.setCommand(command);
		codeAction.setDiagnostics(Collections.EMPTY_LIST);
		return Either.forRight(codeAction);
	} else {
		return Either.forLeft(command);
	}
}
 
Example 12
Source File: SourceAssistProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private Optional<Either<Command, CodeAction>> getGenerateToStringAction(CodeActionParams params) {
	if (!preferenceManager.getClientPreferences().isGenerateToStringPromptSupported()) {
		return Optional.empty();
	}
	Command command = new Command(ActionMessages.GenerateToStringAction_label, COMMAND_ID_ACTION_GENERATETOSTRINGPROMPT, Collections.singletonList(params));
	if (preferenceManager.getClientPreferences().isSupportedCodeActionKind(JavaCodeActionKind.SOURCE_GENERATE_TO_STRING)) {
		CodeAction codeAction = new CodeAction(ActionMessages.GenerateToStringAction_label);
		codeAction.setKind(JavaCodeActionKind.SOURCE_GENERATE_TO_STRING);
		codeAction.setCommand(command);
		codeAction.setDiagnostics(Collections.EMPTY_LIST);
		return Optional.of(Either.forRight(codeAction));
	} else {
		return Optional.of(Either.forLeft(command));
	}
}
 
Example 13
Source File: SourceAssistProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private Optional<Either<Command, CodeAction>> getHashCodeEqualsAction(CodeActionParams params) {
	if (!preferenceManager.getClientPreferences().isHashCodeEqualsPromptSupported()) {
		return Optional.empty();
	}
	Command command = new Command(ActionMessages.GenerateHashCodeEqualsAction_label, COMMAND_ID_ACTION_HASHCODEEQUALSPROMPT, Collections.singletonList(params));
	if (preferenceManager.getClientPreferences().isSupportedCodeActionKind(JavaCodeActionKind.SOURCE_GENERATE_HASHCODE_EQUALS)) {
		CodeAction codeAction = new CodeAction(ActionMessages.GenerateHashCodeEqualsAction_label);
		codeAction.setKind(JavaCodeActionKind.SOURCE_GENERATE_HASHCODE_EQUALS);
		codeAction.setCommand(command);
		codeAction.setDiagnostics(Collections.EMPTY_LIST);
		return Optional.of(Either.forRight(codeAction));
	} else {
		return Optional.of(Either.forLeft(command));
	}
}
 
Example 14
Source File: SourceAssistProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private Optional<Either<Command, CodeAction>> getOrganizeImportsAction(CodeActionParams params) {
	Command command = new Command(CorrectionMessages.ReorgCorrectionsSubProcessor_organizeimports_description, COMMAND_ID_ACTION_ORGANIZEIMPORTS, Collections.singletonList(params));
	CodeAction codeAction = new CodeAction(CorrectionMessages.ReorgCorrectionsSubProcessor_organizeimports_description);
	codeAction.setKind(CodeActionKind.SourceOrganizeImports);
	codeAction.setCommand(command);
	codeAction.setDiagnostics(Collections.EMPTY_LIST);
	return Optional.of(Either.forRight(codeAction));

}
 
Example 15
Source File: CodeActionAcceptor.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void acceptSourceAction(String title, String kind, String commandId, Object... arguments) {
	if (!CodeActionUtils.isSpecialKindOf(kind, CodeActionKind.Source)) {
		throw new IllegalArgumentException("not a source action kind: " + kind);
	}
	CodeAction codeAction = new CodeAction();
	codeAction.setTitle(title);
	codeAction.setKind(kind);
	Command command = new Command(title, commandId, Arrays.asList(arguments));
	codeAction.setCommand(command);
	codeActions.add(Either.forRight(codeAction));
}
 
Example 16
Source File: AbstractQuickfix.java    From camel-language-server with Apache License 2.0 5 votes vote down vote up
protected CodeAction createCodeAction(CodeActionParams params, Diagnostic diagnostic, String possibleProperty) {
	CodeAction codeAction = new CodeAction("Did you mean "+possibleProperty + "?");
	codeAction.setDiagnostics(Collections.singletonList(diagnostic));
	codeAction.setKind(CodeActionKind.QuickFix);
	Map<String, List<TextEdit>> changes = new HashMap<>();
	TextEdit textEdit = new TextEdit(diagnostic.getRange(), possibleProperty);
	changes.put(params.getTextDocument().getUri(), Arrays.asList(textEdit));
	codeAction.setEdit(new WorkspaceEdit(changes));
	return codeAction;
}
 
Example 17
Source File: CodeActionProvider.java    From vscode-as3mxml with Apache License 2.0 4 votes vote down vote up
private void createCodeActionsForImport(Path path, Diagnostic diagnostic, WorkspaceFolderData folderData, List<Either<Command, CodeAction>> codeActions)
  {
      ILspProject project = folderData.project;
      Position position = diagnostic.getRange().getStart();
      IncludeFileData includeFileData = folderData.includedFiles.get(path.toString());
int currentOffset = LanguageServerCompilerUtils.getOffsetFromPosition(fileTracker.getReader(path), position, includeFileData);
      IASNode offsetNode = workspaceFolderManager.getOffsetNode(path, currentOffset, folderData);
      IMXMLTagData offsetTag = null;
      boolean isMXML = path.toUri().toString().endsWith(FILE_EXTENSION_MXML);
      if (isMXML)
      {
          MXMLData mxmlData = workspaceFolderManager.getMXMLDataForPath(path, folderData);
          if (mxmlData != null)
          {
              offsetTag = MXMLDataUtils.getOffsetMXMLTag(mxmlData, currentOffset);
          }
      }
      if (offsetNode instanceof IMXMLInstanceNode && offsetTag != null)
      {
          //workaround for bug in Royale compiler
          Position newPosition = new Position(position.getLine(), position.getCharacter() + 1);
          int newOffset = LanguageServerCompilerUtils.getOffsetFromPosition(fileTracker.getReader(path), newPosition, includeFileData);
          offsetNode = workspaceFolderManager.getEmbeddedActionScriptNodeInMXMLTag(offsetTag, path, newOffset, folderData);
      }
      if (offsetNode == null || !(offsetNode instanceof IIdentifierNode))
      {
          return;
      }
      ImportRange importRange = null;
      if (offsetTag != null)
      {
          importRange = ImportRange.fromOffsetTag(offsetTag, currentOffset);
      }
      else
      {
          importRange = ImportRange.fromOffsetNode(offsetNode);
      }
      String uri = importRange.uri;
      String fileText = fileTracker.getText(path);
      if(fileText == null)
      {
          return;
      }

      IIdentifierNode identifierNode = (IIdentifierNode) offsetNode;
      String typeString = identifierNode.getName();

      List<IDefinition> types = ASTUtils.findTypesThatMatchName(typeString, project.getCompilationUnits());
      for (IDefinition definitionToImport : types)
      {
          WorkspaceEdit edit = CodeActionsUtils.createWorkspaceEditForAddImport(definitionToImport, fileText, uri, importRange);
          if (edit == null)
          {
              continue;
          }
          CodeAction codeAction = new CodeAction();
          codeAction.setTitle("Import " + definitionToImport.getQualifiedName());
          codeAction.setEdit(edit);
          codeAction.setKind(CodeActionKind.QuickFix);
          codeAction.setDiagnostics(Collections.singletonList(diagnostic));
          codeActions.add(Either.forRight(codeAction));
      }
  }
 
Example 18
Source File: CodeActionProvider.java    From vscode-as3mxml with Apache License 2.0 4 votes vote down vote up
private void createCodeActionForUnimplementedMethods(Path path, Diagnostic diagnostic, WorkspaceFolderData folderData, List<Either<Command, CodeAction>> codeActions)
  {
      ILspProject project = folderData.project;
      Position position = diagnostic.getRange().getStart();
      IncludeFileData includeFileData = folderData.includedFiles.get(path.toString());
int currentOffset = LanguageServerCompilerUtils.getOffsetFromPosition(fileTracker.getReader(path), position, includeFileData);
      IASNode offsetNode = workspaceFolderManager.getOffsetNode(path, currentOffset, folderData);
      if (offsetNode == null)
      {
          return;
      }

      IClassNode classNode = (IClassNode) offsetNode.getAncestorOfType(IClassNode.class);
      if (classNode == null)
      {
          return;
      }

      String fileText = fileTracker.getText(path);
      if(fileText == null)
      {
          return;
      }

      for (IExpressionNode exprNode : classNode.getImplementedInterfaceNodes())
      {
          IInterfaceDefinition interfaceDefinition = (IInterfaceDefinition) exprNode.resolve(project);
          if (interfaceDefinition == null)
          {
              continue;
          }
          WorkspaceEdit edit = CodeActionsUtils.createWorkspaceEditForImplementInterface(
              classNode, interfaceDefinition, path.toUri().toString(), fileText, project);
          if (edit == null)
          {
              continue;
          }

          CodeAction codeAction = new CodeAction();
          codeAction.setDiagnostics(Collections.singletonList(diagnostic));
          codeAction.setTitle("Implement interface '" + interfaceDefinition.getBaseName() + "'");
          codeAction.setEdit(edit);
          codeAction.setKind(CodeActionKind.QuickFix);
          codeActions.add(Either.forRight(codeAction));
      }
  }
 
Example 19
Source File: CodeActionProvider.java    From vscode-as3mxml with Apache License 2.0 4 votes vote down vote up
private void createCodeActionForMissingField(Path path, Diagnostic diagnostic, WorkspaceFolderData folderData, List<Either<Command, CodeAction>> codeActions)
  {
      Position position = diagnostic.getRange().getStart();
      IncludeFileData includeFileData = folderData.includedFiles.get(path.toString());
int currentOffset = LanguageServerCompilerUtils.getOffsetFromPosition(fileTracker.getReader(path), position, includeFileData);
      IASNode offsetNode = workspaceFolderManager.getOffsetNode(path, currentOffset, folderData);
      if (offsetNode instanceof IMXMLInstanceNode)
      {
          MXMLData mxmlData = workspaceFolderManager.getMXMLDataForPath(path, folderData);
          if (mxmlData != null)
          {
              IMXMLTagData offsetTag = MXMLDataUtils.getOffsetMXMLTag(mxmlData, currentOffset);
              if(offsetTag != null)
              {
                  //workaround for bug in Royale compiler
                  Position newPosition = new Position(position.getLine(), position.getCharacter() + 1);
                  int newOffset = LanguageServerCompilerUtils.getOffsetFromPosition(fileTracker.getReader(path), newPosition, includeFileData);
                  offsetNode = workspaceFolderManager.getEmbeddedActionScriptNodeInMXMLTag(offsetTag, path, newOffset, folderData);
              }
          }
      }
      IIdentifierNode identifierNode = null;
      if (offsetNode instanceof IIdentifierNode)
      {
          IASNode parentNode = offsetNode.getParent();
          if (parentNode instanceof IMemberAccessExpressionNode)
          {
              IMemberAccessExpressionNode memberAccessExpressionNode = (IMemberAccessExpressionNode) offsetNode.getParent();
              IExpressionNode leftOperandNode = memberAccessExpressionNode.getLeftOperandNode();
              if (leftOperandNode instanceof ILanguageIdentifierNode)
              {
                  ILanguageIdentifierNode leftIdentifierNode = (ILanguageIdentifierNode) leftOperandNode;
                  if (leftIdentifierNode.getKind() == ILanguageIdentifierNode.LanguageIdentifierKind.THIS)
                  {
                      identifierNode = (IIdentifierNode) offsetNode;
                  }
              }
          }
          else //no member access
          {
              identifierNode = (IIdentifierNode) offsetNode;
          }
      }
      if (identifierNode == null)
      {
          return;
      }
      String fileText = fileTracker.getText(path);
      if(fileText == null)
      {
          return;
      }
      WorkspaceEdit edit = CodeActionsUtils.createWorkspaceEditForGenerateFieldVariable(
          identifierNode, path.toUri().toString(), fileText);
      if(edit == null)
      {
          return;
      }
      
      CodeAction codeAction = new CodeAction();
      codeAction.setDiagnostics(Collections.singletonList(diagnostic));
      codeAction.setTitle("Generate Field Variable");
      codeAction.setEdit(edit);
      codeAction.setKind(CodeActionKind.QuickFix);
      codeActions.add(Either.forRight(codeAction));
  }
 
Example 20
Source File: CodeActionProvider.java    From vscode-as3mxml with Apache License 2.0 4 votes vote down vote up
private void createCodeActionForMissingLocalVariable(Path path, Diagnostic diagnostic, WorkspaceFolderData folderData, List<Either<Command, CodeAction>> codeActions)
  {
      Position position = diagnostic.getRange().getStart();
      IncludeFileData includeFileData = folderData.includedFiles.get(path.toString());
int currentOffset = LanguageServerCompilerUtils.getOffsetFromPosition(fileTracker.getReader(path), position, includeFileData);
      IASNode offsetNode = workspaceFolderManager.getOffsetNode(path, currentOffset, folderData);
      if (offsetNode instanceof IMXMLInstanceNode)
      {
          MXMLData mxmlData = workspaceFolderManager.getMXMLDataForPath(path, folderData);
          if (mxmlData != null)
          {
              IMXMLTagData offsetTag = MXMLDataUtils.getOffsetMXMLTag(mxmlData, currentOffset);
              if(offsetTag != null)
              {
                  //workaround for bug in Royale compiler
                  Position newPosition = new Position(position.getLine(), position.getCharacter() + 1);
                  int newOffset = LanguageServerCompilerUtils.getOffsetFromPosition(fileTracker.getReader(path), newPosition, includeFileData);
                  offsetNode = workspaceFolderManager.getEmbeddedActionScriptNodeInMXMLTag(offsetTag, path, newOffset, folderData);
              }
          }
      }
      IIdentifierNode identifierNode = null;
      if (offsetNode instanceof IIdentifierNode)
      {
          identifierNode = (IIdentifierNode) offsetNode;
      }
      if (identifierNode == null)
      {
          return;
      }
      String fileText = fileTracker.getText(path);
      if(fileText == null)
      {
          return;
      }

      WorkspaceEdit edit = CodeActionsUtils.createWorkspaceEditForGenerateLocalVariable(
          identifierNode, path.toUri().toString(), fileText);
      if(edit == null)
      {
          return;
      }

      CodeAction codeAction = new CodeAction();
      codeAction.setDiagnostics(Collections.singletonList(diagnostic));
      codeAction.setTitle("Generate Local Variable");
      codeAction.setEdit(edit);
      codeAction.setKind(CodeActionKind.QuickFix);
      codeActions.add(Either.forRight(codeAction));
  }