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 Project: lemminx   Author: eclipse   File: XMLPositionUtility.java    License: 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 #2
Source Project: ru.capralow.dt.bslls.validator   Author: DoublesunRUS   File: BslValidator.java    License: 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 #3
Source Project: vscode-as3mxml   Author: BowlerHatLLC   File: CodeActionsUtils.java    License: 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 #4
Source Project: groovy-language-server   Author: prominic   File: RenameProvider.java    License: 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 #5
Source Project: lemminx   Author: eclipse   File: AbstractFixMissingGrammarCodeAction.java    License: 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 #6
Source Project: xtext-core   Author: eclipse   File: ChangeConverter2.java    License: 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 #7
Source Project: intellij-quarkus   Author: redhat-developer   File: LSIncompleteCompletionProposal.java    License: 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 #8
Source Project: intellij-quarkus   Author: redhat-developer   File: PsiUtilsImpl.java    License: 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 #9
Source Project: camel-language-server   Author: camel-tooling   File: CamelCompletionInsertAndReplaceTest.java    License: 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 Project: lemminx   Author: eclipse   File: ContentModelCompletionParticipant.java    License: 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 #11
Source Project: lemminx   Author: eclipse   File: XMLHover.java    License: 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 #12
Source Project: netbeans   Author: apache   File: Utils.java    License: 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 #13
Source Project: eclipse.jdt.ls   Author: eclipse   File: SemanticHighlightingTest.java    License: 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 #14
Source Project: lemminx   Author: eclipse   File: FilePathCompletionParticipant.java    License: 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 #15
Source Project: eclipse.jdt.ls   Author: eclipse   File: CodeActionHandlerTest.java    License: 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 #16
Source Project: lemminx   Author: eclipse   File: XMLPositionUtility.java    License: 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 #17
Source Project: xtext-core   Author: eclipse   File: HoverService.java    License: Eclipse Public License 2.0 5 votes vote down vote up
protected Hover hover(HoverContext context) {
	if (context == null) {
		return IHoverService.EMPTY_HOVER;
	}
	MarkupContent contents = getMarkupContent(context);
	if (contents == null) {
		return IHoverService.EMPTY_HOVER;
	}
	Range range = getRange(context);
	if (range == null) {
		return IHoverService.EMPTY_HOVER;
	}
	return new Hover(contents, range);
}
 
Example #18
Source Project: syndesis   Author: syndesisio   File: DdlTokenAnalyzer.java    License: Apache License 2.0 5 votes vote down vote up
public void addException(Token startToken, Token endToken, String errorMessage) {
    Position startPosition = new Position(startToken.beginLine, startToken.beginColumn);
    Position endPosition = new Position(endToken.endLine, endToken.endColumn + 1);
    DdlAnalyzerException exception = new DdlAnalyzerException(DiagnosticSeverity.Error, errorMessage,
            new Range(startPosition, endPosition)); // $NON-NLS-1$);
    this.addException(exception);
}
 
Example #19
Source Project: eclipse.jdt.ls   Author: eclipse   File: CompletionHandlerTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testCompletion_package() throws JavaModelException{
	ClientPreferences mockCapabilies = Mockito.mock(ClientPreferences.class);
	Mockito.when(preferenceManager.getClientPreferences()).thenReturn(mockCapabilies);

	ICompilationUnit unit = getWorkingCopy(
			"src/org/sample/Baz.java",
			"package o"+
					"public class Baz {\n"+
			"}\n");

	int[] loc = findCompletionLocation(unit, "package o");

	CompletionList list = server.completion(JsonMessageHelper.getParams(createCompletionRequest(unit, loc[0], loc[1]))).join().getRight();

	assertNotNull(list);
	List<CompletionItem> items = new ArrayList<>(list.getItems());
	assertFalse(items.isEmpty());
	items.sort((i1, i2) -> i1.getSortText().compareTo(i2.getSortText()));

	CompletionItem item = items.get(0);
	// current package should appear 1st
	assertEquals("org.sample",item.getLabel());

	CompletionItem resolvedItem = server.resolveCompletionItem(item).join();
	assertNotNull(resolvedItem);
	TextEdit te = item.getTextEdit();
	assertNotNull(te);
	assertEquals("org.sample", te.getNewText());
	assertNotNull(te.getRange());
	Range range = te.getRange();
	assertEquals(0, range.getStart().getLine());
	assertEquals(8, range.getStart().getCharacter());
	assertEquals(0, range.getEnd().getLine());
	assertEquals(15, range.getEnd().getCharacter());
}
 
Example #20
Source Project: eclipse.jdt.ls   Author: eclipse   File: InvertConditionTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testInvertGreaterOperator() 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 #21
Source Project: n4js   Author: eclipse   File: XLanguageServerImpl.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Prepare the rename operation. Executed in a read request.
 */
protected Either<Range, PrepareRenameResult> prepareRename(OpenFileContext ofc, TextDocumentPositionParams params,
		CancelIndicator cancelIndicator) {
	URI uri = ofc.getURI();
	IRenameService2 renameService = getService(uri, IRenameService2.class);
	if (renameService == null) {
		throw new UnsupportedOperationException();
	}
	IRenameService2.PrepareRenameOptions options = new IRenameService2.PrepareRenameOptions();
	options.setLanguageServerAccess(access);
	options.setParams(params);
	options.setCancelIndicator(cancelIndicator);
	return renameService.prepareRename(options);
}
 
Example #22
Source Project: groovy-language-server   Author: prominic   File: CompletionProvider.java    License: Apache License 2.0 5 votes vote down vote up
private TextEdit createAddImportTextEdit(String className, Range range) {
	TextEdit edit = new TextEdit();
	StringBuilder builder = new StringBuilder();
	builder.append("import ");
	builder.append(className);
	builder.append("\n");
	edit.setNewText(builder.toString());
	edit.setRange(range);
	return edit;
}
 
Example #23
Source Project: eclipse.jdt.ls   Author: eclipse   File: CompletionHandlerTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testCompletion_constructor() throws Exception{
	ICompilationUnit unit = getWorkingCopy(
			"src/java/Foo.java",
			"public class Foo {\n"+
					"	void foo() {\n"+
					"		Object o = new O\n"+
					"	}\n"+
			"}\n");
	int[] loc = findCompletionLocation(unit, "new O");
	CompletionList list = server.completion(JsonMessageHelper.getParams(createCompletionRequest(unit, loc[0], loc[1]))).join().getRight();
	assertNotNull(list);
	assertFalse("No proposals were found",list.getItems().isEmpty());

	List<CompletionItem> items = new ArrayList<>(list.getItems());
	Comparator<CompletionItem> comparator = (CompletionItem a, CompletionItem b) -> a.getSortText().compareTo(b.getSortText());
	Collections.sort(items, comparator);
	CompletionItem ctor = items.get(0);
	assertEquals("Object()", ctor.getLabel());
	assertEquals("java.lang.Object.Object()", ctor.getDetail());
	assertEquals("Object", ctor.getInsertText());

	CompletionItem resolvedItem = server.resolveCompletionItem(ctor).join();
	assertNotNull(resolvedItem);
	TextEdit te = resolvedItem.getTextEdit();
	assertNotNull(te);
	assertEquals("Object()",te.getNewText());
	assertNotNull(te.getRange());
	Range range = te.getRange();
	assertEquals(2, range.getStart().getLine());
	assertEquals(17, range.getStart().getCharacter());
	assertEquals(2, range.getEnd().getLine());
	assertEquals(18, range.getEnd().getCharacter());
}
 
Example #24
Source Project: eclipse.jdt.ls   Author: eclipse   File: CodeActionHandlerTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private Diagnostic getDiagnostic(String code, Range range){
	Diagnostic $ = new Diagnostic();
	$.setCode(code);
	$.setRange(range);
	$.setSeverity(DiagnosticSeverity.Error);
	$.setMessage("Test Diagnostic");
	return $;
}
 
Example #25
Source Project: xtext-core   Author: eclipse   File: LanguageServerImpl.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Convert the given issue to a diagnostic.
 */
protected Diagnostic toDiagnostic(Issue issue) {
	Diagnostic result = new Diagnostic();
	result.setCode(issue.getCode());
	result.setMessage(issue.getMessage());
	result.setSeverity(toDiagnosticSeverity(issue.getSeverity()));

	// line and column numbers in LSP are 0-based
	Position start = new Position(Math.max(0, issue.getLineNumber() - 1), Math.max(0, issue.getColumn() - 1));
	Position end = new Position(Math.max(0, issue.getLineNumberEnd() - 1), Math.max(0, issue.getColumnEnd() - 1));
	result.setRange(new Range(start, end));
	return result;
}
 
Example #26
Source Project: eclipse.jdt.ls   Author: eclipse   File: DiagnosticHandlerTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testMultipleLineRange() throws Exception {
	IJavaProject javaProject = newEmptyProject();
	Hashtable<String, String> options = JavaCore.getOptions();
	options.put(JavaCore.COMPILER_PB_DEAD_CODE, JavaCore.WARNING);
	javaProject.setOptions(options);
	IPackageFragmentRoot sourceFolder = javaProject.getPackageFragmentRoot(javaProject.getProject().getFolder("src"));
	IPackageFragment pack1 = sourceFolder.createPackageFragment("test1", false, null);

	StringBuilder buf = new StringBuilder();
	buf.append("package test1;\n");
	buf.append("public class E {\n");
	buf.append("    public boolean foo(boolean b1) {\n");
	buf.append("        if (false) {\n");
	buf.append("            return true;\n");
	buf.append("        }\n");
	buf.append("        return false;\n");
	buf.append("    }\n");
	buf.append("}\n");
	ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null);

	CompilationUnit astRoot = CoreASTProvider.getInstance().getAST(cu, CoreASTProvider.WAIT_YES, monitor);
	IProblem[] problems = astRoot.getProblems();
	List<Diagnostic> diagnostics = DiagnosticsHandler.toDiagnosticsArray(cu, Arrays.asList(problems), true);
	assertEquals(1, diagnostics.size());
	Range range = diagnostics.get(0).getRange();
	assertNotEquals(range.getStart().getLine(), range.getEnd().getLine());
}
 
Example #27
Source Project: vscode-as3mxml   Author: BowlerHatLLC   File: CodeActionsUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static TextEdit createTextEditForGenerateFieldVariable(
    IIdentifierNode identifierNode, String text)
{
    LineAndIndent lineAndIndent = findLineAndIndent(identifierNode, text);
    if(lineAndIndent == null)
    {
        return null;
    }

    StringBuilder builder = new StringBuilder();
    builder.append(NEW_LINE);
    builder.append(lineAndIndent.indent);
    builder.append(IASKeywordConstants.PUBLIC);
    builder.append(" ");
    builder.append(IASKeywordConstants.VAR);
    builder.append(" ");
    builder.append(identifierNode.getName());
    builder.append(":");
    builder.append(IASLanguageConstants.Object);
    builder.append(";");
    builder.append(NEW_LINE);

    TextEdit textEdit = new TextEdit();
    textEdit.setNewText(builder.toString());
    Position editPosition = new Position(lineAndIndent.line, 0);
    textEdit.setRange(new Range(editPosition, editPosition));
    return textEdit;
}
 
Example #28
Source Project: lemminx   Author: eclipse   File: PrologModel.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private static void createCompletionItem(String attrName, boolean canSupportSnippet, boolean generateValue,
		Range editRange, String defaultValue, Collection<String> enumerationValues, String documentation,
		ICompletionResponse response, SharedSettings sharedSettings) {
	CompletionItem item = new AttributeCompletionItem(attrName, canSupportSnippet, editRange, generateValue,
			defaultValue, enumerationValues, sharedSettings);
	MarkupContent markup = new MarkupContent();
	markup.setKind(MarkupKind.MARKDOWN);

	markup.setValue(StringUtils.getDefaultString(documentation));
	item.setDocumentation(markup);
	response.addCompletionItem(item);
}
 
Example #29
Source Project: eclipse.jdt.ls   Author: eclipse   File: AssignToVariableRefactorTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private void testAssignField(ICompilationUnit cu, Range range) throws JavaModelException {
	List<Either<Command, CodeAction>> codeActions = evaluateCodeActions(cu, range);
	assertEquals(1, codeActions.size());
	Either<Command, CodeAction> codeAction = codeActions.get(0);
	CodeAction action = codeAction.getRight();
	assertEquals(JavaCodeActionKind.REFACTOR_ASSIGN_FIELD, action.getKind());
	assertEquals("Assign statement to new field", action.getTitle());
	Command c = action.getCommand();
	assertEquals(RefactorProposalUtility.APPLY_REFACTORING_COMMAND_ID, c.getCommand());
	assertNotNull(c.getArguments());
	assertEquals(RefactorProposalUtility.ASSIGN_FIELD_COMMAND, c.getArguments().get(0));
}
 
Example #30
Source Project: corrosion   Author: eclipse   File: SnippetContentAssistProcessor.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Override
public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int offset) {
	IDocument document = viewer.getDocument();
	String textToOffset = document.get().substring(0, offset);
	if (isOffsetInComment(textToOffset)) {
		return new ICompletionProposal[0];
	}

	Matcher matcher = ENDS_WITH_WORD_PATTERN.matcher(textToOffset.substring(textToOffset.lastIndexOf('\n') + 1));
	matcher.matches();
	String indent = matcher.group("indent"); //$NON-NLS-1$
	String prefix = matcher.group("prefix"); //$NON-NLS-1$

	// Use range from selection (if available) to support "surround with" style
	// completions
	Range range = getRangeFromSelection(document, viewer).orElseGet(() -> {
		// no selection available: get range from prefix
		try {
			int line = document.getLineOfOffset(offset);
			int lineOffset = offset - document.getLineOffset(line);
			Position start = new Position(line, lineOffset - prefix.length());
			Position end = new Position(line, lineOffset);
			return new Range(start, end);
		} catch (BadLocationException e) {
			return null;
		}
	});
	if (range == null) {
		return new ICompletionProposal[] {};
	}

	Collection<LSPDocumentInfo> infos = LanguageServiceAccessor.getLSPDocumentInfosFor(document,
			capabilities -> Boolean.TRUE.equals(capabilities.getReferencesProvider()));
	LSPDocumentInfo docInfo = infos.iterator().next();

	ICompletionProposal[] proposals = snippets.stream().filter(s -> s.matchesPrefix(prefix))
			.map(s -> s.convertToCompletionProposal(offset, docInfo, prefix, indent, range))
			.toArray(ICompletionProposal[]::new);
	return proposals;
}