org.eclipse.lsp4j.Range Java Examples

The following examples show how to use org.eclipse.lsp4j.Range. 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: FilePathCompletionParticipant.java    From lemminx with Eclipse Public License 2.0 6 votes vote down vote up
private void createFilePathCompletionItem(File f, Range replaceRange, ICompletionResponse response, String slash) {
	CompletionItem item = new CompletionItem();
	String fName = f.getName();
	if(isWindows && fName.isEmpty()) { // Edge case for Windows drive letter
		fName = f.getPath();
		fName = fName.substring(0, fName.length() - 1);
	}
	String insertText;
	insertText = slash + fName;
	item.setLabel(insertText);

	CompletionItemKind kind = f.isDirectory()? CompletionItemKind.Folder : CompletionItemKind.File;
	item.setKind(kind);
	
	item.setSortText(CompletionSortTextHelper.getSortText(kind));
	item.setFilterText(insertText);
	item.setTextEdit(new TextEdit(replaceRange, insertText));
	response.addCompletionItem(item);
}
 
Example #2
Source File: ContentModelCompletionParticipant.java    From lemminx with Eclipse Public License 2.0 6 votes vote down vote up
private void fillAttributesWithCMAttributeDeclarations(DOMElement parentElement, Range fullRange,
		CMElementDeclaration cmElement, boolean canSupportSnippet, boolean generateValue,
		ICompletionRequest request, ICompletionResponse response) {

	Collection<CMAttributeDeclaration> attributes = cmElement.getAttributes();
	if (attributes == null) {
		return;
	}
	for (CMAttributeDeclaration cmAttribute : attributes) {
		String attrName = cmAttribute.getName();
		if (!parentElement.hasAttribute(attrName)) {
			CompletionItem item = new AttributeCompletionItem(attrName, canSupportSnippet, fullRange, generateValue,
					cmAttribute.getDefaultValue(), cmAttribute.getEnumerationValues(), request.getSharedSettings());
			MarkupContent documentation = XMLGenerator.createMarkupContent(cmAttribute, cmElement, request);
			item.setDocumentation(documentation);
			response.addCompletionAttribute(item);
		}
	}
}
 
Example #3
Source File: LSIncompleteCompletionProposal.java    From intellij-quarkus with Eclipse Public License 2.0 6 votes vote down vote up
private int computeNewOffset(List<TextEdit> additionalTextEdits, int insertionOffset, Document doc) {
    if (additionalTextEdits != null && !additionalTextEdits.isEmpty()) {
        int adjustment = 0;
        for (TextEdit edit : additionalTextEdits) {
            try {
                Range rng = edit.getRange();
                int start = LSPIJUtils.toOffset(rng.getStart(), doc);
                if (start <= insertionOffset) {
                    int end = LSPIJUtils.toOffset(rng.getEnd(), doc);
                    int orgLen = end - start;
                    int newLeng = edit.getNewText().length();
                    int editChange = newLeng - orgLen;
                    adjustment += editChange;
                }
            } catch (RuntimeException e) {
                LOGGER.warn(e.getLocalizedMessage(), e);
            }
        }
        return insertionOffset + adjustment;
    }
    return insertionOffset;
}
 
Example #4
Source File: PsiUtilsImpl.java    From intellij-quarkus with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public Location toLocation(PsiMember psiMember) {
    PsiElement sourceElement = psiMember.getNavigationElement();
    if (sourceElement != null) {
        PsiFile file = sourceElement.getContainingFile();
        Location location = new Location();
        location.setUri(VfsUtilCore.convertToURL(file.getVirtualFile().getUrl()).toExternalForm());
        Document document = PsiDocumentManager.getInstance(psiMember.getProject()).getDocument(file);
        TextRange range = sourceElement.getTextRange();
        int startLine = document.getLineNumber(range.getStartOffset());
        int startLineOffset = document.getLineStartOffset(startLine);
        int endLine = document.getLineNumber(range.getEndOffset());
        int endLineOffset = document.getLineStartOffset(endLine);
        location.setRange(new Range(LSPIJUtils.toPosition(range.getStartOffset(), document), LSPIJUtils.toPosition(range.getEndOffset(), document)));
        return location;
    }
    return null;
}
 
Example #5
Source File: XMLHover.java    From lemminx with Eclipse Public License 2.0 6 votes vote down vote up
private Range getTagNameRange(TokenType tokenType, int startOffset, int offset, DOMDocument document) {
	Scanner scanner = XMLScanner.createScanner(document.getText(), startOffset);
	TokenType token = scanner.scan();
	while (token != TokenType.EOS
			&& (scanner.getTokenEnd() < offset || scanner.getTokenEnd() == offset && token != tokenType)) {
		token = scanner.scan();
	}
	if (token == tokenType && offset <= scanner.getTokenEnd()) {
		try {
			return new Range(document.positionAt(scanner.getTokenOffset()),
					document.positionAt(scanner.getTokenEnd()));
		} catch (BadLocationException e) {
			LOGGER.log(Level.SEVERE, "While creating Range in XMLHover the Scanner's Offset was a BadLocation", e);
			return null;
		}
	}
	return null;
}
 
Example #6
Source File: Utils.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static void open(String targetUri, Range targetRange) {
    try {
        URI target = URI.create(targetUri);
        FileObject targetFile = URLMapper.findFileObject(target.toURL());

        if (targetFile != null) {
            LineCookie lc = targetFile.getLookup().lookup(LineCookie.class);

            //TODO: expecting lc != null!

            Line line = lc.getLineSet().getCurrent(targetRange.getStart().getLine());

            SwingUtilities.invokeLater(() ->
                line.show(Line.ShowOpenType.OPEN, Line.ShowVisibilityType.FOCUS, targetRange.getStart().getCharacter())
            );
        } else {
            //TODO: beep
        }
    } catch (MalformedURLException ex) {
        Exceptions.printStackTrace(ex);
    }
}
 
Example #7
Source File: ChangeConverter2.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
protected void _handleReplacements(IEmfResourceChange change) {
	try {
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		String uri = uriExtensions.toUriString(change.getResource().getURI());
		change.getResource().save(outputStream, null);
		String newContent = new String(outputStream.toByteArray(), getCharset(change.getResource()));
		access.doRead(uri, (ILanguageServerAccess.Context context) -> {
			Document document = context.getDocument();
			Range range = new Range(document.getPosition(0), document.getPosition(document.getContents().length()));
			TextEdit textEdit = new TextEdit(range, newContent);
			return addTextEdit(uri, document, textEdit);
		}).get();
	} catch (InterruptedException | ExecutionException | IOException e) {
		throw Exceptions.sneakyThrow(e);
	}
}
 
Example #8
Source File: SemanticHighlightingTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
protected void changeDocument(ICompilationUnit unit, String content, int version, Range range, int length) {
	DidChangeTextDocumentParams changeParms = new DidChangeTextDocumentParams();
	VersionedTextDocumentIdentifier textDocument = new VersionedTextDocumentIdentifier();
	textDocument.setUri(JDTUtils.toURI(unit));
	textDocument.setVersion(version);
	changeParms.setTextDocument(textDocument);
	TextDocumentContentChangeEvent event = new TextDocumentContentChangeEvent();
	if (range != null) {
		event.setRange(range);
		event.setRangeLength(length);
	}
	event.setText(content);
	List<TextDocumentContentChangeEvent> contentChanges = new ArrayList<>();
	contentChanges.add(event);
	changeParms.setContentChanges(contentChanges);
	lifeCycleHandler.didChange(changeParms);
}
 
Example #9
Source File: CamelCompletionInsertAndReplaceTest.java    From camel-language-server with Apache License 2.0 6 votes vote down vote up
@Test
void testComponent() throws Exception {
	CamelLanguageServer camelLanguageServer = initializeLanguageServer("<from uri=\"ahc-wss:httpUri?binding=#true&amp;bufferSize=10&amp;synchronous=true\" xmlns=\"http://camel.apache.org/schema/blueprint\"/>\n", ".xml");
	Position positionInMiddleOfcomponentPart = new Position(0, 15);
	CompletableFuture<Either<List<CompletionItem>, CompletionList>> completions = getCompletionFor(camelLanguageServer, positionInMiddleOfcomponentPart);
	List<CompletionItem> items = completions.get().getLeft();
	assertThat(items).hasSize(2);
	for (CompletionItem completionItem : items) {
		TextEdit textEdit = completionItem.getTextEdit();
		Range range = textEdit.getRange();
		assertThat(range.getStart().getLine()).isZero();
		assertThat(range.getStart().getCharacter()).isEqualTo(11 /*start of URI */);
		assertThat(range.getEnd().getLine()).isZero();
		assertThat(range.getEnd().getCharacter()).isEqualTo(26 /* just before the '?' */);
	}
}
 
Example #10
Source File: CodeActionHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testCodeAction_removeUnterminatedString() throws Exception{
	ICompilationUnit unit = getWorkingCopy(
			"src/java/Foo.java",
			"public class Foo {\n"+
					"	void foo() {\n"+
					"String s = \"some str\n" +
					"	}\n"+
			"}\n");

	CodeActionParams params = new CodeActionParams();
	params.setTextDocument(new TextDocumentIdentifier(JDTUtils.toURI(unit)));
	final Range range = CodeActionUtil.getRange(unit, "some str");
	params.setRange(range);
	params.setContext(new CodeActionContext(Arrays.asList(getDiagnostic(Integer.toString(IProblem.UnterminatedString), range))));
	List<Either<Command, CodeAction>> codeActions = getCodeActions(params);
	Assert.assertNotNull(codeActions);
	Assert.assertFalse(codeActions.isEmpty());
	Assert.assertEquals(codeActions.get(0).getRight().getKind(), CodeActionKind.QuickFix);
	Command c = codeActions.get(0).getRight().getCommand();
	Assert.assertEquals(CodeActionHandler.COMMAND_ID_APPLY_EDIT, c.getCommand());
}
 
Example #11
Source File: AbstractFixMissingGrammarCodeAction.java    From lemminx with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void doCodeAction(Diagnostic diagnostic, Range range, DOMDocument document, List<CodeAction> codeActions,
		SharedSettings sharedSettings, IComponentProvider componentProvider) {

	String missingFilePath = getPathFromDiagnostic(diagnostic);
	if (StringUtils.isEmpty(missingFilePath)) {
		return;
	}
	Path p = Paths.get(missingFilePath);
	if (p.toFile().exists()) {
		return;
	}

	// Generate XSD from the DOM document
	FileContentGeneratorManager generator = componentProvider.getComponent(FileContentGeneratorManager.class);
	String schemaTemplate = generator.generate(document, sharedSettings, getFileContentGeneratorSettings());

	// Create code action to create the XSD file with the generated XSD content
	CodeAction makeSchemaFile = CodeActionFactory.createFile("Generate missing file '" + p.toFile().getName() + "'",
			"file:///" + missingFilePath, schemaTemplate, diagnostic);

	codeActions.add(makeSchemaFile);
}
 
Example #12
Source File: RenameProvider.java    From groovy-language-server with Apache License 2.0 6 votes vote down vote up
private TextEdit createTextEditToRenameMethodNode(MethodNode methodNode, String newName, String text, Range range) {
	// the AST doesn't give us access to the name location, so we
	// need to find it manually
	Pattern methodPattern = Pattern.compile("\\b" + methodNode.getName() + "\\b(?=\\s*\\()");
	Matcher methodMatcher = methodPattern.matcher(text);
	if (!methodMatcher.find()) {
		// couldn't find the name!
		return null;
	}

	Position start = range.getStart();
	Position end = range.getEnd();
	end.setCharacter(start.getCharacter() + methodMatcher.end());
	start.setCharacter(start.getCharacter() + methodMatcher.start());

	TextEdit textEdit = new TextEdit();
	textEdit.setRange(range);
	textEdit.setNewText(newName);
	return textEdit;
}
 
Example #13
Source File: XMLPositionUtility.java    From lemminx with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Returns the range covering the first child of the node located at offset.
 * 
 * Returns null if node is not a DOMElement, or if a node does not exist at
 * offset.
 * 
 * @param offset
 * @param document
 * @return range covering the first child of the node located at offset
 */
public static Range selectFirstChild(int offset, DOMDocument document) {
	DOMNode node = document.findNodeAt(offset);
	if (node == null || !node.isElement()) {
		return null;
	}

	DOMElement element = (DOMElement) node;
	DOMNode child = element.getFirstChild();

	if (child == null) {
		return null;
	}

	int startOffset = child.getStart();
	int endOffset = child.getEnd();

	try {
		Position startPosition = document.positionAt(startOffset);
		Position endPosition = document.positionAt(endOffset);
		return new Range(startPosition, endPosition);
	} catch (BadLocationException e) {
		return null;
	}
}
 
Example #14
Source File: CodeActionsUtils.java    From vscode-as3mxml with Apache License 2.0 6 votes vote down vote up
public static WorkspaceEdit createWorkspaceEditForRemoveUnusedImport(String fileText, String uri, Range range)
{
    TextEdit textEdit = createTextEditForRemoveUnusedImport(fileText, range);
    if (textEdit == null)
    {
        return null;
    }

    WorkspaceEdit workspaceEdit = new WorkspaceEdit();
    HashMap<String,List<TextEdit>> changes = new HashMap<>();
    List<TextEdit> edits = new ArrayList<>();
    edits.add(textEdit);
    changes.put(uri, edits);
    workspaceEdit.setChanges(changes);
    return workspaceEdit;
}
 
Example #15
Source File: BslValidator.java    From ru.capralow.dt.bslls.validator with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private static Integer[] getOffsetAndLength(Range range, Document doc)
{
    Integer offset = 0;
    Integer length = 0;
    try
    {
        offset = doc.getLineOffset(range.getStart().getLine()) + range.getStart().getCharacter();
        Integer endOffset = doc.getLineOffset(range.getEnd().getLine()) + range.getEnd().getCharacter();
        length = endOffset - offset;

    }
    catch (BadLocationException e)
    {
        BslValidatorPlugin.log(
            BslValidatorPlugin.createErrorStatus(Messages.BslValidator_Bad_Location_Exception, e));

    }

    Integer[] result = new Integer[2];
    result[0] = offset;
    result[1] = length;

    return result;
}
 
Example #16
Source File: XMLPositionUtility.java    From lemminx with Eclipse Public License 2.0 6 votes vote down vote up
public static Range getElementDeclMissingContentOrCategory(int offset, DOMDocument document) {
	DOMNode node = document.findNodeAt(offset);
	if (node instanceof DTDElementDecl) {
		DTDElementDecl declNode = (DTDElementDecl) node;
		List<DTDDeclParameter> params = declNode.getParameters();
		if (params.isEmpty()) {
			return null;
		}
		if (params.size() == 1) {
			DTDDeclParameter param = params.get(0);
			return createRange(param.getEnd(), param.getEnd() + 1, document);
		} else {
			return createRange(params.get(1).getStart(), params.get(1).getEnd(), document);
		}
	}
	return null;
}
 
Example #17
Source File: XMLPositionUtility.java    From lemminx with Eclipse Public License 2.0 5 votes vote down vote up
public static Range selectEndTagName(int offset, DOMDocument document) {
	DOMNode node = document.findNodeAt(offset);
	if (node != null && node.isElement()) {
		DOMElement element = (DOMElement) node;
		return selectEndTagName(element);
	}
	return null;
}
 
Example #18
Source File: XMLPositionUtility.java    From lemminx with Eclipse Public License 2.0 5 votes vote down vote up
public static Range selectAttributeNameFromGivenNameAt(String attrName, int offset, DOMDocument document) {
	DOMNode element = document.findNodeAt(offset);
	if (element != null && element.hasAttributes()) {
		DOMAttr attr = element.getAttributeNode(attrName);
		if (attr != null) {
			return createAttrNameRange(attr, document);
		}
	}
	return null;
}
 
Example #19
Source File: CamelDiagnosticTest.java    From camel-language-server with Apache License 2.0 5 votes vote down vote up
@Test
void testSeveralUnknowPropertyOnNonLenientPropertiesComponent() throws Exception {
	testDiagnostic("camel-with-2-unknownParameters", 2, ".xml");
	Range range1 = lastPublishedDiagnostics.getDiagnostics().get(0).getRange();
	checkRange(range1, 9, 33, 9, 46);
	Range range2 = lastPublishedDiagnostics.getDiagnostics().get(1).getRange();
	checkRange(range2, 9, 56, 9, 69);
}
 
Example #20
Source File: XMLPositionUtility.java    From lemminx with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Finds the offset of the first tag it comes across behind the given offset.
 * 
 * <p>
 * This will include the tag it starts in if the offset is within a tag's
 * content:
 * </p>
 * <p>
 * {@code  <a> <b> | </b> </a> } , will give {@code </b>}
 * </p>
 * 
 * or within an unclosed end tag:
 * 
 * <p>
 * {@code  <a> <b>  </b> </a| <c>} , will give {@code </a>}
 * </p>
 * 
 * 
 * <p>
 * {@code  <a> <b|>  </b> </a>} , will give {@code </a>}
 * </p>
 * 
 */
public static Range selectPreviousNodesEndTag(int offset, DOMDocument document) {

	DOMNode node = null;
	DOMNode nodeAt = document.findNodeAt(offset);
	if (nodeAt != null && nodeAt.isElement()) {
		node = nodeAt;
	} else {
		DOMNode nodeBefore = document.findNodeBefore(offset);
		if (nodeBefore != null && nodeBefore.isElement()) {
			node = nodeBefore;
		}
	}
	if (node != null) {
		DOMElement element = (DOMElement) node;
		if (element.isClosed() && !element.isEndTagClosed()) {
			return selectEndTagName(element.getEnd(), document);
		}
	}

	// boolean firstBracket = false;
	int i = offset;
	char c = document.getText().charAt(i);
	while (i >= 0) {
		if (c == '>') {
			return selectEndTagName(i, document);
		}
		i--;
		c = document.getText().charAt(i);
	}
	return null;
}
 
Example #21
Source File: InvertConditionTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testInvertEqualsOperator() throws Exception {
	IPackageFragment pack1 = testSourceFolder.createPackageFragment("test", false, null);

	StringBuilder buf = new StringBuilder();
	buf.append("package test;\n");
	buf.append("public class E {\n");
	buf.append("    public void foo() {\n");
	buf.append("        if (3 == 5)\n");
	buf.append("            return;\n");
	buf.append("    }\n");
	buf.append("}\n");

	ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null);

	buf = new StringBuilder();
	buf.append("package test;\n");
	buf.append("public class E {\n");
	buf.append("    public void foo() {\n");
	buf.append("        if (3 != 5)\n");
	buf.append("            return;\n");
	buf.append("    }\n");
	buf.append("}\n");

	Expected expected = new Expected("Invert conditions", buf.toString(), CodeActionKind.Refactor);
	Range replacedRange = CodeActionUtil.getRange(cu, "3 == 5", "3 == 5".length());
	assertCodeActions(cu, replacedRange, expected);

	Range nonSelectionRange = CodeActionUtil.getRange(cu, "3 == 5", 0);
	assertCodeActions(cu, nonSelectionRange, expected);
}
 
Example #22
Source File: PrepareRenameTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testPrepareRenameFqn_in_ok() {
  try {
    StringConcatenation _builder = new StringConcatenation();
    _builder.append("package foo.bar {");
    _builder.newLine();
    _builder.append("  ");
    _builder.append("type A {");
    _builder.newLine();
    _builder.append("    ");
    _builder.append("foo.bar.MyType bar");
    _builder.newLine();
    _builder.append("  ");
    _builder.append("}");
    _builder.newLine();
    _builder.append("  ");
    _builder.append("type MyType { }");
    _builder.newLine();
    _builder.append("}");
    _builder.newLine();
    final String model = _builder.toString();
    this.initializeWithPrepareSupport();
    final String uri = this.writeFile("my-type-valid.testlang", model);
    TextDocumentIdentifier _textDocumentIdentifier = new TextDocumentIdentifier(uri);
    Position _position = new Position(2, 14);
    final PrepareRenameParams params = new PrepareRenameParams(_textDocumentIdentifier, _position);
    final Range range = this.languageServer.prepareRename(params).get().getLeft();
    this.assertEquals("MyType", new Document(Integer.valueOf(0), model).getSubstring(range));
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #23
Source File: InvertConditionTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testCombinedConditionWithPartialSelection() throws Exception {
	IPackageFragment pack1 = testSourceFolder.createPackageFragment("test", false, null);

	StringBuilder buf = new StringBuilder();
	buf.append("package test;\n");
	buf.append("public class E {\n");
	buf.append("    public boolean isValid() {\n");
	buf.append("        return true;\n");
	buf.append("    }\n");
	buf.append("    public void foo() {\n");
	buf.append("        if (isValid() || 3 < 5)\n");
	buf.append("            return;\n");
	buf.append("    }\n");
	buf.append("}\n");

	ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null);

	buf = new StringBuilder();
	buf.append("package test;\n");
	buf.append("public class E {\n");
	buf.append("    public boolean isValid() {\n");
	buf.append("        return true;\n");
	buf.append("    }\n");
	buf.append("    public void foo() {\n");
	buf.append("        if (!isValid() || 3 < 5)\n");
	buf.append("            return;\n");
	buf.append("    }\n");
	buf.append("}\n");

	Expected expected = new Expected("Invert conditions", buf.toString(), CodeActionKind.Refactor);
	Range replacedRange = CodeActionUtil.getRange(cu, "isValid()", "isValid()".length());
	assertCodeActions(cu, replacedRange, expected);
}
 
Example #24
Source File: EntityNotDeclaredCodeAction.java    From lemminx with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void doCodeAction(Diagnostic diagnostic, Range range, DOMDocument document, List<CodeAction> codeActions,
		SharedSettings sharedSettings, IComponentProvider componentProvider) {

	try {
		String entityName = getEntityName(diagnostic, range, document);

		if (entityName == null) {
			return;
		}
		
		DOMDocumentType docType = document.getDoctype();
		if (docType != null) {

			// Case 1: <!DOCTYPE exists
			// Add <!ENTITY nbsp "entity-value"> in the subset.
			// If the subset does not exist, add subset too
			
			// ie:
			// <!DOCTYPE article [
			// <!ELEMENT article (#PCDATA)>
			// <!ENTITY nbsp "entity-value">
			// ]>
			addEntityCodeAction(entityName, diagnostic, document, sharedSettings, codeActions);
		} else {
			// Case 2: <!DOCTYPE does not exist
			// Generate:
			// <!DOCTYPE article [
			//     <!ENTITY nbsp "entity-value">
			// ]>
			addDoctypeAndEntityCodeAction(entityName, diagnostic, document, sharedSettings, codeActions);
		}
	} catch (BadLocationException e) {
		LOGGER.log(Level.SEVERE, "In EntityNotDeclaredCodeAction the DOMDocument offset(s) is at a BadLocation", e);
	}
}
 
Example #25
Source File: CodeActionUtil.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static CodeActionParams constructCodeActionParams(ICompilationUnit unit, Range range) {
	CodeActionParams params = new CodeActionParams();
	params.setTextDocument(new TextDocumentIdentifier(JDTUtils.toURI(unit)));
	params.setRange(range);
	params.setContext(new CodeActionContext(Collections.emptyList()));
	return params;
}
 
Example #26
Source File: PrepareRenameTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testPrepareRenameFqn_end_ok() {
  try {
    StringConcatenation _builder = new StringConcatenation();
    _builder.append("package foo.bar {");
    _builder.newLine();
    _builder.append("  ");
    _builder.append("type A {");
    _builder.newLine();
    _builder.append("    ");
    _builder.append("foo.bar.MyType bar");
    _builder.newLine();
    _builder.append("  ");
    _builder.append("}");
    _builder.newLine();
    _builder.append("  ");
    _builder.append("type MyType { }");
    _builder.newLine();
    _builder.append("}");
    _builder.newLine();
    final String model = _builder.toString();
    this.initializeWithPrepareSupport();
    final String uri = this.writeFile("my-type-valid.testlang", model);
    TextDocumentIdentifier _textDocumentIdentifier = new TextDocumentIdentifier(uri);
    Position _position = new Position(2, 18);
    final PrepareRenameParams params = new PrepareRenameParams(_textDocumentIdentifier, _position);
    final Range range = this.languageServer.prepareRename(params).get().getLeft();
    this.assertEquals("MyType", new Document(Integer.valueOf(0), model).getSubstring(range));
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #27
Source File: InvertVariableTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testComplexInvertVariable() throws Exception {
	IPackageFragment pack1 = testSourceFolder.createPackageFragment("test", false, null);

	StringBuilder buf = new StringBuilder();
	buf.append("package test;\n");
	buf.append("public class E {\n");
	buf.append("    public boolean foo() {\n");
	buf.append("        boolean a = 3 != 5;\n");
	buf.append("        boolean b = !a;\n");
	buf.append("        boolean c = bar(a);\n");
	buf.append("        return a;\n");
	buf.append("    }\n");
	buf.append("    public boolean bar(boolean value) {\n");
	buf.append("        return !value;\n");
	buf.append("    }\n");
	buf.append("}\n");

	ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null);

	buf = new StringBuilder();
	buf.append("package test;\n");
	buf.append("public class E {\n");
	buf.append("    public boolean foo() {\n");
	buf.append("        boolean notA = 3 == 5;\n");
	buf.append("        boolean b = notA;\n");
	buf.append("        boolean c = bar(!notA);\n");
	buf.append("        return !notA;\n");
	buf.append("    }\n");
	buf.append("    public boolean bar(boolean value) {\n");
	buf.append("        return !value;\n");
	buf.append("    }\n");
	buf.append("}\n");

	Expected expected = new Expected(INVERT_BOOLEAN_VARIABLE, buf.toString(), CodeActionKind.Refactor);
	Range replacedRange = CodeActionUtil.getRange(cu, "a = 3 != 5", 0);
	assertCodeActions(cu, replacedRange, expected);
}
 
Example #28
Source File: EntitiesDefinitionParticipant.java    From lemminx with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Search the given entity name in the external entities.
 * 
 * @param document      the DOM document.
 * @param entityName    the entity name.
 * @param entityRange   the entity range.
 * @param locations     the location links
 * @param request       the definition request.
 * @param cancelChecker the cancel checker.
 */
private static void searchInExternalEntities(String entityName, Range entityRange, DOMDocument document,
		List<LocationLink> locations, IDefinitionRequest request, CancelChecker cancelChecker) {
	ContentModelManager contentModelManager = request.getComponent(ContentModelManager.class);
	Collection<CMDocument> cmDocuments = contentModelManager.findCMDocument(document, null, false);
	for (CMDocument cmDocument : cmDocuments) {
		List<Entity> entities = cmDocument.getEntities();
		for (Entity entity : entities) {
			fillEntityLocation((DTDEntityDecl) entity, entityName, entityRange, locations);
		}
	}
}
 
Example #29
Source File: AdvancedExtractTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testMoveInstanceMethod() throws Exception {
	when(preferenceManager.getClientPreferences().isMoveRefactoringSupported()).thenReturn(true);

	IPackageFragment pack1 = fSourceFolder.createPackageFragment("test1", false, null);
	//@formatter:off
	pack1.createCompilationUnit("Second.java", "package test1;\n"
			+ "\n"
			+ "public class Second {\n"
			+ "    public void bar() {\n"
			+ "    }\n"
			+ "}",
			false, null);
	//@formatter:on

	StringBuilder buf = new StringBuilder();
	buf.append("package test1;\n");
	buf.append("\n");
	buf.append("public class E {\n");
	buf.append("    Second s;\n");
	buf.append("    public void print() {\n");
	buf.append("        /*[*//*]*/s.bar();\n");
	buf.append("    }\n");
	buf.append("}");

	ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null);
	Range selection = getRange(cu, null);
	List<Either<Command, CodeAction>> codeActions = evaluateCodeActions(cu, selection);
	Assert.assertNotNull(codeActions);
	Either<Command, CodeAction> moveAction = CodeActionHandlerTest.findAction(codeActions, JavaCodeActionKind.REFACTOR_MOVE);
	Assert.assertNotNull(moveAction);
	Command moveCommand = CodeActionHandlerTest.getCommand(moveAction);
	Assert.assertNotNull(moveCommand);
	Assert.assertEquals(RefactorProposalUtility.APPLY_REFACTORING_COMMAND_ID, moveCommand.getCommand());
	Assert.assertNotNull(moveCommand.getArguments());
	Assert.assertEquals(3, moveCommand.getArguments().size());
	Assert.assertEquals(RefactorProposalUtility.MOVE_INSTANCE_METHOD_COMMAND, moveCommand.getArguments().get(0));
	Assert.assertTrue(moveCommand.getArguments().get(2) instanceof RefactorProposalUtility.MoveMemberInfo);
	Assert.assertEquals("print()", ((RefactorProposalUtility.MoveMemberInfo) moveCommand.getArguments().get(2)).displayName);
}
 
Example #30
Source File: JavaDiagnosticsContext.java    From intellij-quarkus with Eclipse Public License 2.0 5 votes vote down vote up
public Diagnostic createDiagnostic(String uri, String message, Range range, String source, IJavaErrorCode code) {
	Diagnostic diagnostic = new Diagnostic();
	diagnostic.setSource(source);
	diagnostic.setMessage(message);
	diagnostic.setSeverity(DiagnosticSeverity.Warning);
	diagnostic.setRange(range);
	if (code != null) {
		diagnostic.setCode(code.getCode());
	}
	return diagnostic;
}