org.eclipse.lsp4j.TextEdit Java Examples

The following examples show how to use org.eclipse.lsp4j.TextEdit. 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: DocumentTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testUpdate_nonIncrementalChange() {
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("hello world");
  _builder.newLine();
  _builder.append("foo");
  _builder.newLine();
  _builder.append("bar");
  String _normalize = this.normalize(_builder);
  Document _document = new Document(Integer.valueOf(1), _normalize);
  final Procedure1<Document> _function = (Document it) -> {
    TextEdit _textEdit = this.textEdit(null, null, " foo ");
    Assert.assertEquals(" foo ", it.applyChanges(
      Collections.<TextEdit>unmodifiableList(CollectionLiterals.<TextEdit>newArrayList(_textEdit))).getContents());
  };
  ObjectExtensions.<Document>operator_doubleArrow(_document, _function);
}
 
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: CamelCompletionInsertAndReplaceTest.java    From camel-language-server with Apache License 2.0 6 votes vote down vote up
@Test
void testAttribute() 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 positionBeforeBufferSizeAttribute = new Position(0, 45);
	CompletableFuture<Either<List<CompletionItem>, CompletionList>> completions = getCompletionFor(camelLanguageServer, positionBeforeBufferSizeAttribute);
	List<CompletionItem> items = completions.get().getLeft();
	assertThat(items).hasSize(14);
	for (CompletionItem completionItem : items) {
		TextEdit textEdit = completionItem.getTextEdit();
		Range range = textEdit.getRange();
		assertThat(range.getStart().getLine()).isZero();
		assertThat(range.getStart().getCharacter()).isEqualTo(45 /* just before 'bufferSize' */);
		assertThat(range.getEnd().getLine()).isZero();
		assertThat(range.getEnd().getCharacter()).isEqualTo(55 /* end of 'bufferSize' */);
	}
}
 
Example #4
Source File: XMLReferencesCompletionParticipant.java    From lemminx with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void onXMLContent(ICompletionRequest request, ICompletionResponse response) throws Exception {
	int offset = request.getOffset();
	final DOMNode node = getNodeAt(request.getNode(), offset);	
	if (node != null) {			
		XMLReferencesManager.getInstance().collect(node, n -> {
			DOMDocument doc = n.getOwnerDocument();
			Range range = XMLPositionUtility.createRange(node.getStart(), node.getEnd(), doc);
			String label = n.getNodeValue();
			CompletionItem item = new CompletionItem();
			item.setLabel(label);
			String insertText = label;
			item.setKind(CompletionItemKind.Property);
			item.setDocumentation(Either.forLeft(label));
			item.setFilterText(insertText);
			item.setTextEdit(new TextEdit(range, insertText));
			item.setInsertTextFormat(InsertTextFormat.PlainText);
			response.addCompletionItem(item);
		});
	}
}
 
Example #5
Source File: AbstractLanguageServerTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
protected void testFormatting(final Procedure1<? super DocumentFormattingParams> paramsConfigurator, final Procedure1<? super FormattingConfiguration> configurator) {
  try {
    @Extension
    final FormattingConfiguration configuration = new FormattingConfiguration();
    configuration.setFilePath(("MyModel." + this.fileExtension));
    configurator.apply(configuration);
    final FileInfo fileInfo = this.initializeContext(configuration);
    DocumentFormattingParams _documentFormattingParams = new DocumentFormattingParams();
    final Procedure1<DocumentFormattingParams> _function = (DocumentFormattingParams it) -> {
      String _uri = fileInfo.getUri();
      TextDocumentIdentifier _textDocumentIdentifier = new TextDocumentIdentifier(_uri);
      it.setTextDocument(_textDocumentIdentifier);
      if ((paramsConfigurator != null)) {
        paramsConfigurator.apply(it);
      }
    };
    DocumentFormattingParams _doubleArrow = ObjectExtensions.<DocumentFormattingParams>operator_doubleArrow(_documentFormattingParams, _function);
    final CompletableFuture<List<? extends TextEdit>> changes = this.languageServer.formatting(_doubleArrow);
    String _contents = fileInfo.getContents();
    final Document result = new Document(Integer.valueOf(1), _contents).applyChanges(ListExtensions.<TextEdit>reverse(CollectionLiterals.<TextEdit>newArrayList(((TextEdit[])Conversions.unwrapArray(changes.get(), TextEdit.class)))));
    this.assertEqualsStricter(configuration.getExpectedText(), result.getContents());
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #6
Source File: LSPIJUtils.java    From intellij-quarkus with Eclipse Public License 2.0 6 votes vote down vote up
public static void applyEdit(Editor editor, TextEdit textEdit, Document document) {
    RangeMarker marker = document.createRangeMarker(LSPIJUtils.toOffset(textEdit.getRange().getStart(), document), LSPIJUtils.toOffset(textEdit.getRange().getEnd(), document));
    int startOffset = marker.getStartOffset();
    int endOffset = marker.getEndOffset();
    String text = textEdit.getNewText();
    if (text != null) {
        text = text.replaceAll("\r", "");
    }
    if (text == null || "".equals(text)) {
        document.deleteString(startOffset, endOffset);
    } else if (endOffset - startOffset <= 0) {
        document.insertString(startOffset, text);
    } else {
        document.replaceString(startOffset, endOffset, text);
    }
    if (text != null && !"".equals(text)) {
        editor.getCaretModel().moveCaretRelatively(text.length(), 0, false, false, true);
    }
    marker.dispose();
}
 
Example #7
Source File: Formatter.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void rangeFormat(FileObject fo, LSPBindings bindings) throws BadLocationException {
    DocumentRangeFormattingParams drfp = new DocumentRangeFormattingParams();
    drfp.setTextDocument(new TextDocumentIdentifier(Utils.toURI(fo)));
    drfp.setOptions(new FormattingOptions(
        IndentUtils.indentLevelSize(ctx.document()),
        IndentUtils.isExpandTabs(ctx.document())));
    drfp.setRange(new Range(
        Utils.createPosition(ctx.document(), ctx.startOffset()),
        Utils.createPosition(ctx.document(), ctx.endOffset())));
    List<TextEdit> edits = new ArrayList<>();
    try {
        edits = new ArrayList<>(bindings.getTextDocumentService().rangeFormatting(drfp).get());
    } catch (InterruptedException | ExecutionException ex) {
        LOG.log(Level.INFO,
            String.format("LSP document rangeFormat failed for {0}", fo),
            ex);
    }

    applyTextEdits(edits);
}
 
Example #8
Source File: AbstractLanguageServerTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
protected void testRangeFormatting(final Procedure1<? super DocumentRangeFormattingParams> paramsConfigurator, final Procedure1<? super RangeFormattingConfiguration> configurator) {
  try {
    @Extension
    final RangeFormattingConfiguration configuration = new RangeFormattingConfiguration();
    configuration.setFilePath(("MyModel." + this.fileExtension));
    configurator.apply(configuration);
    final FileInfo fileInfo = this.initializeContext(configuration);
    DocumentRangeFormattingParams _documentRangeFormattingParams = new DocumentRangeFormattingParams();
    final Procedure1<DocumentRangeFormattingParams> _function = (DocumentRangeFormattingParams it) -> {
      String _uri = fileInfo.getUri();
      TextDocumentIdentifier _textDocumentIdentifier = new TextDocumentIdentifier(_uri);
      it.setTextDocument(_textDocumentIdentifier);
      it.setRange(configuration.getRange());
      if ((paramsConfigurator != null)) {
        paramsConfigurator.apply(it);
      }
    };
    DocumentRangeFormattingParams _doubleArrow = ObjectExtensions.<DocumentRangeFormattingParams>operator_doubleArrow(_documentRangeFormattingParams, _function);
    final CompletableFuture<List<? extends TextEdit>> changes = this.languageServer.rangeFormatting(_doubleArrow);
    String _contents = fileInfo.getContents();
    final Document result = new Document(Integer.valueOf(1), _contents).applyChanges(ListExtensions.<TextEdit>reverse(CollectionLiterals.<TextEdit>newArrayList(((TextEdit[])Conversions.unwrapArray(changes.get(), TextEdit.class)))));
    this.assertEqualsStricter(configuration.getExpectedText(), result.getContents());
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #9
Source File: XMLFormatter.java    From lemminx with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Returns a List containing a single TextEdit, containing the newly formatted
 * changes of this.textDocument
 * 
 * @return List containing a single TextEdit
 * @throws BadLocationException
 */
public List<? extends TextEdit> format() throws BadLocationException {
	this.fullDomDocument = DOMParser.getInstance().parse(textDocument.getText(), textDocument.getUri(), null,
			false);

	if (isRangeFormatting()) {
		setupRangeFormatting(range);
	} else {
		setupFullFormatting(range);
	}

	this.indentLevel = getStartingIndentLevel();
	format(this.rangeDomDocument);

	List<? extends TextEdit> textEdits = getFormatTextEdit();
	return textEdits;
}
 
Example #10
Source File: Formatter.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void documentFormat(FileObject fo, LSPBindings bindings) throws BadLocationException {
    DocumentFormattingParams dfp = new DocumentFormattingParams();
    dfp.setTextDocument(new TextDocumentIdentifier(Utils.toURI(fo)));
    dfp.setOptions(new FormattingOptions(
        IndentUtils.indentLevelSize(ctx.document()),
        IndentUtils.isExpandTabs(ctx.document())));
    List<TextEdit> edits = new ArrayList<>();
    try {
        edits.addAll(bindings.getTextDocumentService().formatting(dfp).get());
    } catch (InterruptedException | ExecutionException ex) {
        LOG.log(Level.INFO,
            String.format("LSP document format failed for {0}", fo),
            ex);
    }

    applyTextEdits(edits);
}
 
Example #11
Source File: XMLRename.java    From lemminx with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Renames all occurences of the namespace in a document, that match
 * the given old namespace.
 * @param document
 * @param oldNamespace
 * @param newNamespace
 * @param rootAttr
 * @return
 */
private static List<TextEdit> renameAllNamespaceOccurrences(DOMDocument document, String oldNamespace, String newNamespace, @Nullable DOMAttr rootAttr) {
	DOMElement rootElement = document.getDocumentElement();
	
	List<TextEdit> edits = new ArrayList<TextEdit>();

	// Renames the xmlns:NAME_SPACE attribute
	if(rootAttr != null) {
		Position start;
		try {
			start = document.positionAt(rootAttr.getStart() + "xmlns:".length());
		} catch (BadLocationException e) {
			start = null;
		}
	
		if(start != null) {
			Position end = new Position(start.getLine(), start.getCharacter() + oldNamespace.length());
			edits.add(new TextEdit(new Range(start, end), newNamespace));
		}
	}

	//Renames all elements with oldNamespace
	List<DOMNode> children = Arrays.asList(rootElement);
	return renameElementsNamespace(document, edits, children, oldNamespace, newNamespace);
}
 
Example #12
Source File: TextEditUtil.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
public static String apply(Document doc, Collection<? extends TextEdit> edits) throws BadLocationException {
	Assert.isNotNull(doc);
	Assert.isNotNull(edits);
	List<TextEdit> sortedEdits = new ArrayList<>(edits);
	sortByLastEdit(sortedEdits);
	String text = doc.get();
	for (int i = sortedEdits.size() - 1; i >= 0; i--) {
		TextEdit te = sortedEdits.get(i);
		Range r = te.getRange();
		if (r != null && r.getStart() != null && r.getEnd() != null) {
			int start = getOffset(doc, r.getStart());
			int end = getOffset(doc, r.getEnd());
			text = text.substring(0, start)
					+ te.getNewText()
					+ text.substring(end, text.length());
		}
	}
	return text;
}
 
Example #13
Source File: AttributeCompletionItem.java    From lemminx with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Attribute completion item.
 * 
 * @param attrName           attribute name
 * @param canSupportSnippets true if snippets is supported to generate attribute
 *                           value and false otherwise
 * @param fullRange          the range to edit.
 * @param generateValue      true if attribute value must be generated and false
 *                           otherwise.
 * @param defaultValue       the default value of attribute.
 * @param enumerationValues  the enumeration values of attribute.
 * @param sharedSettings     the settings containing quote preferences
 */
public AttributeCompletionItem(String attrName, boolean canSupportSnippets, Range fullRange, boolean generateValue,
		String defaultValue, Collection<String> enumerationValues, SharedSettings sharedSettings) {
	super.setLabel(attrName);
	super.setKind(CompletionItemKind.Unit);
	super.setFilterText(attrName);
	StringBuilder attributeContent = new StringBuilder(attrName);
	if (generateValue) {
		// Generate attribute value content
		String attributeValue = XMLGenerator.generateAttributeValue(defaultValue, enumerationValues,
				canSupportSnippets, 1, true, sharedSettings);
		attributeContent.append(attributeValue);
	}
	super.setTextEdit(new TextEdit(fullRange, attributeContent.toString()));
	super.setInsertTextFormat(canSupportSnippets ? InsertTextFormat.Snippet : InsertTextFormat.PlainText);
}
 
Example #14
Source File: XMLRename.java    From lemminx with Eclipse Public License 2.0 6 votes vote down vote up
private List<TextEdit> getRenameTextEdits(DOMDocument xmlDocument, DOMNode node, Position position, String newText) {

		DOMElement element = getAssociatedElement(node);
		if (node == null) {
			return Collections.emptyList();
		}

		if (node.isCDATA()) {
			return getCDATARenameTextEdits(xmlDocument, element, position, newText);
		}

		if (isRenameTagName(xmlDocument, element, position)) {
			return getTagNameRenameTextEdits(xmlDocument, element, position, newText);
		}

		if (element.isDocumentElement()) { // If attribute xmlns:ATT_NAME was renamed
			return getXmlnsAttrRenameTextEdits(xmlDocument, element, position, newText);
		}

		return Collections.emptyList();
	}
 
Example #15
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 #16
Source File: XMLAssert.java    From lemminx with Eclipse Public License 2.0 5 votes vote down vote up
public static CodeAction ca(Diagnostic d, TextEdit... te) {
	CodeAction codeAction = new CodeAction();
	codeAction.setTitle("");
	codeAction.setDiagnostics(Arrays.asList(d));

	VersionedTextDocumentIdentifier versionedTextDocumentIdentifier = new VersionedTextDocumentIdentifier(FILE_URI,
			0);

	TextDocumentEdit textDocumentEdit = new TextDocumentEdit(versionedTextDocumentIdentifier, Arrays.asList(te));
	WorkspaceEdit workspaceEdit = new WorkspaceEdit(Collections.singletonList(Either.forLeft(textDocumentEdit)));
	codeAction.setEdit(workspaceEdit);
	return codeAction;
}
 
Example #17
Source File: N4JSQuickfixProvider.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Remove the question mark qualifier from optional fields from the old location and put it at the new location.
 */
@Fix(IssueCodes.CLF_FIELD_OPTIONAL_OLD_SYNTAX)
public void fixOldSyntaxForOptionalFields(QuickfixContext context, ICodeActionAcceptor acceptor) {
	Document doc = context.options.getDocument();
	int offsetNameEnd = getOffsetOfNameEnd(getEObject(context).eContainer());
	List<TextEdit> textEdits = new ArrayList<>();
	// removes the ? at the old location
	int endOffset = doc.getOffSet(context.getDiagnostic().getRange().getEnd());
	textEdits.add(replace(doc, endOffset - 1, 1, ""));
	// inserts a ? at the new location (behind the field or accessor name)
	if (offsetNameEnd != -1) {
		textEdits.add(replace(doc, offsetNameEnd, 0, "?"));
	}
	acceptor.acceptQuickfixCodeAction(context, "Change to new syntax", textEdits);
}
 
Example #18
Source File: MissingEnumQuickFixTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private TextEdit getTextEdit(Either<Command, CodeAction> codeAction) {
	Command c = codeAction.isLeft() ? codeAction.getLeft() : codeAction.getRight().getCommand();
	Assert.assertEquals(CodeActionHandler.COMMAND_ID_APPLY_EDIT, c.getCommand());
	Assert.assertNotNull(c.getArguments());
	Assert.assertTrue(c.getArguments().get(0) instanceof WorkspaceEdit);
	WorkspaceEdit we = (WorkspaceEdit) c.getArguments().get(0);
	Iterator<Entry<String, List<TextEdit>>> editEntries = we.getChanges().entrySet().iterator();
	Entry<String, List<TextEdit>> entry = editEntries.next();
	TextEdit edit = entry.getValue().get(0);
	return edit;
}
 
Example #19
Source File: XLanguageServerImpl.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public CompletableFuture<List<? extends TextEdit>> rangeFormatting(DocumentRangeFormattingParams params) {
	URI uri = getURI(params.getTextDocument());
	return openFilesManager.runInOpenFileContext(uri, "rangeFormatting", (ofc, ci) -> {
		return rangeFormatting(ofc, params, ci);
	});
}
 
Example #20
Source File: MissingEnumQuickFixTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testMissingEnumConstant() throws Exception {
	IPackageFragment pack1 = fSourceFolder.createPackageFragment("test1", false, null);
	StringBuilder buf = new StringBuilder();
	buf.append("package test1;\n");
	buf.append("public class E {\n");
	buf.append("   public enum Numbers { One, Two};\n");
	buf.append("    public void testing() {\n");
	buf.append("        Numbers n = Numbers.One;\n");
	buf.append("        switch (n) {\n");
	buf.append("        case Two:\n");
	buf.append("            return;\n");
	buf.append("        }\n");
	buf.append("    }\n");
	buf.append("}\n");
	ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null);
	Range range = new Range(new Position(5, 16), new Position(5, 17));
	setIgnoredCommands(ActionMessages.GenerateConstructorsAction_ellipsisLabel, ActionMessages.GenerateConstructorsAction_label);
	List<Either<Command, CodeAction>> codeActions = evaluateCodeActions(cu, range);
	assertEquals(2, codeActions.size());
	Either<Command, CodeAction> codeAction = codeActions.get(0);
	CodeAction action = codeAction.getRight();
	assertEquals(CodeActionKind.QuickFix, action.getKind());
	assertEquals("Add 'default' case", action.getTitle());
	TextEdit edit = getTextEdit(codeAction);
	assertEquals("\n        default:\n            break;", edit.getNewText());
	codeAction = codeActions.get(1);
	action = codeAction.getRight();
	assertEquals(CodeActionKind.QuickFix, action.getKind());
	assertEquals("Add missing case statements", action.getTitle());
	edit = getTextEdit(codeAction);
	assertEquals("\n        case One:\n            break;\n        default:\n            break;", edit.getNewText());
}
 
Example #21
Source File: LanguageServerImpl.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Create the text edits for the formatter. Executed in a read request.
 * @since 2.20
 */
protected List<? extends TextEdit> rangeFormatting(DocumentRangeFormattingParams params,
		CancelIndicator cancelIndicator) {
	URI uri = getURI(params.getTextDocument());
	FormattingService formatterService = getService(uri, FormattingService.class);
	if (formatterService == null) {
		return Collections.emptyList();
	}
	return workspaceManager.doRead(uri,
			(document, resource) -> formatterService.format(document, resource, params, cancelIndicator));
}
 
Example #22
Source File: CompletionHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testCompletion_overwrite() throws Exception {
	ICompilationUnit unit = getCompletionOverwriteReplaceUnit();
	//@formatter:on
	int[] loc = findCompletionLocation(unit, "method(t.");
	CompletionList list = server.completion(JsonMessageHelper.getParams(createCompletionRequest(unit, loc[0], loc[1]))).join().getRight();
	assertNotNull(list);
	CompletionItem ci = list.getItems().stream().filter(item -> item.getLabel().startsWith("testInt : int")).findFirst().orElse(null);
	assertNotNull(ci);
	assertEquals("testInt", ci.getInsertText());
	assertEquals(CompletionItemKind.Field, ci.getKind());
	assertEquals("999998554", ci.getSortText());
	assertNotNull(ci.getTextEdit());
	List<TextEdit> edits = new ArrayList<>();
	edits.add(ci.getTextEdit());
	String returned = TextEditUtil.apply(unit, edits);
	//@formatter:off
		String expected =
			"package foo.bar;\n\n" +
			"public class BaseTest {\n" +
			"    public int testInt;\n\n" +
			"    public boolean method(int x, int y, int z) {\n" +
			"        return true;\n" +
			"    } \n\n" +
			"    public void update() {\n" +
			"        BaseTest t = new BaseTest();\n" +
			"        t.method(t.testInt.testInt, this.testInt);\n" +
			"    }\n" +
			"}\n";
	//@formatter:on
	assertEquals(returned, expected);
}
 
Example #23
Source File: XSDRenameParticipant.java    From lemminx with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void doRename(IRenameRequest request, List<TextEdit> locations) {
	DOMDocument xmlDocument = request.getXMLDocument();

	if (!DOMUtils.isXSD(xmlDocument)) {
		return;
	}
	for (TextEdit textEdit: getRenameTextEdits(request)) {
		locations.add(textEdit);
	}

}
 
Example #24
Source File: FormatterHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test // typing } should format the previous block
public void testFormattingOnTypeCloseBlock() throws Exception {
	ICompilationUnit unit = getWorkingCopy("src/org/sample/Baz.java",
	//@formatter:off
		  "package org.sample;\n"
		+ "\n"
		+ "    public      class     Baz {  \n"
		+ "String          name       ;\n"
		+ "}  "//typed } here
	//@formatter:on
	);

	String uri = JDTUtils.toURI(unit);
	TextDocumentIdentifier textDocument = new TextDocumentIdentifier(uri);
	FormattingOptions options = new FormattingOptions(4, true);// ident == 4 spaces

	DocumentOnTypeFormattingParams params = new DocumentOnTypeFormattingParams(new Position(4, 0), "}");
	params.setTextDocument(textDocument);
	params.setOptions(options);

	preferenceManager.getPreferences().setJavaFormatOnTypeEnabled(true);
	List<? extends TextEdit> edits = server.onTypeFormatting(params).get();
	assertNotNull(edits);

	//@formatter:off
	String expectedText =
		  "package org.sample;\n"
		+ "\n"
		+ "public class Baz {\n"
		+ "    String name;\n"
		+ "}";
	//@formatter:on

	String newText = TextEditUtil.apply(unit, edits);
	assertEquals(expectedText, newText);
}
 
Example #25
Source File: XMLAssert.java    From lemminx with Eclipse Public License 2.0 5 votes vote down vote up
public static CompletionItem c(String label, TextEdit textEdit, String filterText, String documentation,
		String kind) {
	CompletionItem item = new CompletionItem();
	item.setLabel(label);
	item.setFilterText(filterText);
	item.setTextEdit(textEdit);
	if (kind == null) {
		item.setDocumentation(documentation);
	} else {
		item.setDocumentation(new MarkupContent(kind, documentation));
	}
	return item;
}
 
Example #26
Source File: RootElementTypeMustMatchDoctypedeclCodeAction.java    From lemminx with Eclipse Public License 2.0 5 votes vote down vote up
private void addTextEdits(DOMElement root, String newText, List<TextEdit> replace) {
	replace.add(new TextEdit(XMLPositionUtility.selectStartTagName(root), newText));

	if (root.isClosed() && !root.isSelfClosed())  {
		replace.add(new TextEdit(XMLPositionUtility.selectEndTagName(root), newText));
	}
}
 
Example #27
Source File: ChangeProvider.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Delete line containing the given offset (the offset need not point to the beginning of the line). Will do nothing
 * if 'deleteOnlyIfEmpty' is set to <code>true</code> and the given line is non-empty, i.e. contains characters
 * other than {@link Character#isWhitespace(char) white space}.
 */
public static TextEdit deleteLine(Document doc, int offset, boolean deleteOnlyIfEmpty) {
	Position offPosition = doc.getPosition(offset);
	String lineContent = doc.getLineContent(offPosition.getLine());
	if (deleteOnlyIfEmpty && !lineContent.isBlank()) {
		return null;
	}

	Position posStart = new Position(offPosition.getLine(), 0);
	Position posEnd = new Position(offPosition.getLine() + 1, 0);
	Range range = new Range(posStart, posEnd);
	return new TextEdit(range, "");
}
 
Example #28
Source File: Utils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static void applyEdits(String uri, List<TextEdit> edits) {
    try {
        FileObject file = URLMapper.findFileObject(new URI(uri).toURL());
        EditorCookie ec = file.getLookup().lookup(EditorCookie.class);
        Document doc = ec != null ? ec.openDocument() : null;
        if (doc == null) {
            return ;
        }
        NbDocument.runAtomic((StyledDocument) doc, () -> {
            applyEditsNoLock(doc, edits);
        });
    } catch (URISyntaxException | IOException ex) {
        Exceptions.printStackTrace(ex);
    }
}
 
Example #29
Source File: SemanticChangeProvider.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns IChange to add @Internal annotation to the element.
 */
private TextEdit addInternalAnnotation(Document document, AnnotableElement element) {
	if (getAnnotationWithName(element, INTERNAL_ANNOTATION) != null) {
		return null; // Annotation already exists
	}

	if (element instanceof ModifiableElement) {
		var offset = internalAnnotationOffset((ModifiableElement) element);
		return ChangeProvider.replace(document, offset, 0, "@" + INTERNAL_ANNOTATION + " ");
	}

	return null;
}
 
Example #30
Source File: FormatterHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testDocumentFormattingWithTabs() throws Exception {
	javaProject.setOption(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, JavaCore.SPACE);

	ICompilationUnit unit = getWorkingCopy("src/org/sample/Baz.java",
	//@formatter:off
		"package org.sample;\n\n" +
		"public class Baz {\n"+
		"    void foo(){\n"+
		"}\n"+
		"}\n"
	//@formatter:on
	);

	String uri = JDTUtils.toURI(unit);
	TextDocumentIdentifier textDocument = new TextDocumentIdentifier(uri);
	FormattingOptions options = new FormattingOptions(2, false);// ident == tab
	DocumentFormattingParams params = new DocumentFormattingParams(textDocument, options);
	List<? extends TextEdit> edits = server.formatting(params).get();
	assertNotNull(edits);

	//@formatter:off
	String expectedText =
		"package org.sample;\n"+
		"\n"+
		"public class Baz {\n"+
		"\tvoid foo() {\n"+
		"\t}\n"+
		"}\n";
	//@formatter:on
	String newText = TextEditUtil.apply(unit, edits);
	assertEquals(expectedText, newText);
}