下面列出了org.eclipse.lsp4j.RenameParams#org.eclipse.lsp4j.TextEdit 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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);
}
}
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);
}
@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);
}
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);
}
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();
}
/**
* 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;
}
/**
* 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);
}
/**
* 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;
}
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();
}
/**
* 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);
}
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);
}
}
@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);
});
}
}
@Test
void testAttribute() throws Exception {
CamelLanguageServer camelLanguageServer = initializeLanguageServer("<from uri=\"ahc-wss:httpUri?binding=#true&bufferSize=10&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' */);
}
}
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);
}
}
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;
}
/**
* Reformat the text currently selected in the editor
*/
public void reformatSelection() {
pool(() -> {
if (editor.isDisposed()) {
return;
}
DocumentRangeFormattingParams params = new DocumentRangeFormattingParams();
params.setTextDocument(identifier);
SelectionModel selectionModel = editor.getSelectionModel();
int start = computableReadAction(selectionModel::getSelectionStart);
int end = computableReadAction(selectionModel::getSelectionEnd);
Position startingPos = DocumentUtils.offsetToLSPPos(editor, start);
Position endPos = DocumentUtils.offsetToLSPPos(editor, end);
params.setRange(new Range(startingPos, endPos));
// Todo - Make Formatting Options configurable
FormattingOptions options = new FormattingOptions();
params.setOptions(options);
CompletableFuture<List<? extends TextEdit>> request = requestManager.rangeFormatting(params);
if (request == null) {
return;
}
request.thenAccept(formatting -> {
if (formatting == null) {
return;
}
invokeLater(() -> {
if (!editor.isDisposed()) {
applyEdit((List<TextEdit>) formatting, "Reformat selection", false);
}
});
});
});
}
/**
* Resolves missing import statements by re-using content assist and {@link ImportsAwareReferenceProposalCreator}
*/
@Fix(value = org.eclipse.xtext.diagnostics.Diagnostic.LINKING_DIAGNOSTIC, multiFix = false)
public void addImportForUnresolvedReference(QuickfixContext context, ICodeActionAcceptor acceptor) {
Script script = context.resource.getScriptResolved();
Document doc = context.options.getDocument();
Diagnostic diagnostic = context.getDiagnostic();
if (script == null || doc == null || diagnostic == null) {
return;
}
EObject model = getEObject(context);
List<ReferenceResolution> resolutions = importHelper.findResolutionsForUnresolvedReference(model,
context.options.getCancelIndicator());
for (ReferenceResolution resolution : resolutions) {
ImportDescriptor importToBeAdded = resolution.importToBeAdded;
if (importToBeAdded == null) {
continue;
}
ReplaceRegion replacement = importHelper.getReplacementForImport(script, importToBeAdded);
if (replacement != null) {
String description = resolution.description;
TextEdit textEdit = ChangeProvider.replace(doc, replacement);
acceptor.acceptQuickfixCodeAction(context, "Add import from module " + description,
Collections.singletonList(textEdit));
}
}
}
@Test
public void testRangeFormatting() throws Exception {
ICompilationUnit unit = getWorkingCopy("src/org/sample/Baz.java",
//@formatter:off
"package org.sample;\n" +
" public class Baz {\n"+
"\tvoid foo(){\n" +
" }\n"+
" }\n"
//@formatter:on
);
String uri = JDTUtils.toURI(unit);
TextDocumentIdentifier textDocument = new TextDocumentIdentifier(uri);
Range range = new Range(new Position(2, 0), new Position(3, 5));// range around foo()
DocumentRangeFormattingParams params = new DocumentRangeFormattingParams(range);
params.setTextDocument(textDocument);
params.setOptions(new FormattingOptions(3, true));// ident == 3 spaces
List<? extends TextEdit> edits = server.rangeFormatting(params).get();
//@formatter:off
String expectedText =
"package org.sample;\n" +
" public class Baz {\n"+
" void foo() {\n" +
" }\n"+
" }\n";
//@formatter:on
String newText = TextEditUtil.apply(unit, edits);
assertEquals(expectedText, newText);
}
/**
* Create the text edits for the formatter. Executed in a read request.
*/
protected List<? extends TextEdit> rangeFormatting(OpenFileContext ofc, DocumentRangeFormattingParams params,
CancelIndicator cancelIndicator) {
URI uri = ofc.getURI();
FormattingService formatterService = getService(uri, FormattingService.class);
if ((formatterService == null)) {
return Collections.emptyList();
}
XtextResource res = ofc.getResource();
XDocument doc = ofc.getDocument();
return formatterService.format(doc, res, params, cancelIndicator);
}
@Test // typing new_line after closing a block should format the that block
public void testFormattingOnTypeReturnAfterClosedBlock() throws Exception {
ICompilationUnit unit = getWorkingCopy("src/org/sample/Baz.java",
//@formatter:off
"package org.sample;\n"
+ "\n"
+ " public class Baz { \n"
+ "String name ;\n"
+ "} \n"//typed \n 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, 3), "\n");
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"
+ "}\n";
//@formatter:on
String newText = TextEditUtil.apply(unit, edits);
assertEquals(expectedText, newText);
}
@Override
public CompletableFuture<List<? extends TextEdit>> formatting(DocumentFormattingParams params) {
return computeAsync((cancelChecker) -> {
String uri = params.getTextDocument().getUri();
TextDocument document = getDocument(uri);
CompositeSettings settings = new CompositeSettings(getSharedSettings(), params.getOptions());
return getXMLLanguageService().format(document, null, settings);
});
}
private String getOrganizeImportResult(ICompilationUnit cu, WorkspaceEdit we) throws BadLocationException, CoreException {
List<TextEdit> change = we.getChanges().get(JDTUtils.toURI(cu));
if (change == null) {
return cu.getSource();
}
Document doc = new Document();
doc.set(cu.getSource());
return TextEditUtil.apply(doc, change);
}
private void collectionRegionProposals(ICompletionRequest request, ICompletionResponse response) {
// Completion for #region
try {
int offset = request.getOffset();
TextDocument document = request.getXMLDocument().getTextDocument();
Position pos = document.positionAt(offset);
String lineText = document.lineText(pos.getLine());
String lineUntilPos = lineText.substring(0, pos.getCharacter());
Matcher match = regionCompletionRegExpr.matcher(lineUntilPos);
if (match.find()) {
InsertTextFormat insertFormat = request.getInsertTextFormat();
Range range = new Range(new Position(pos.getLine(), pos.getCharacter() + match.regionStart()), pos);
String text = request.isCompletionSnippetsSupported() ? "<!-- #region $1-->" : "<!-- #region -->";
CompletionItem beginProposal = new CompletionItem("#region");
beginProposal.setTextEdit(new TextEdit(range, text));
beginProposal.setDocumentation("Insert Folding Region Start");
beginProposal.setFilterText(match.group());
beginProposal.setSortText("za");
beginProposal.setKind(CompletionItemKind.Snippet);
beginProposal.setInsertTextFormat(insertFormat);
response.addCompletionAttribute(beginProposal);
CompletionItem endProposal = new CompletionItem("#endregion");
endProposal.setTextEdit(new TextEdit(range, "<!-- #endregion-->"));
endProposal.setDocumentation("Insert Folding Region End");
endProposal.setFilterText(match.group());
endProposal.setSortText("zb");
endProposal.setKind(CompletionItemKind.Snippet);
endProposal.setInsertTextFormat(InsertTextFormat.PlainText);
response.addCompletionAttribute(endProposal);
}
} catch (BadLocationException e) {
LOGGER.log(Level.SEVERE, "While performing collectRegionCompletion", e);
}
}
@Test // typing new_line after opening a block should only format the current line
public void testFormattingOnTypeReturnAfterOpeningBlock() throws Exception {
ICompilationUnit unit = getWorkingCopy("src/org/sample/Baz.java",
//@formatter:off
"package org.sample;\n"
+ "\n"
+ " public class Baz { \n"//typed \n here
+ "String name ;\n"
+ "} \n"
//@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(2, 33), "\n");
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"
+ "} \n";
//@formatter:on
String newText = TextEditUtil.apply(unit, edits);
assertEquals(expectedText, newText);
}
@Test
public void testCompletion_import_package() throws JavaModelException{
ICompilationUnit unit = getWorkingCopy(
"src/java/Foo.java",
"import java.sq \n" +
"public class Foo {\n"+
" void foo() {\n"+
" }\n"+
"}\n");
int[] loc = findCompletionLocation(unit, "java.sq");
CompletionList list = server.completion(JsonMessageHelper.getParams(createCompletionRequest(unit, loc[0], loc[1]))).join().getRight();
assertNotNull(list);
assertEquals(1, list.getItems().size());
CompletionItem item = list.getItems().get(0);
// Check completion item
assertNull(item.getInsertText());
assertEquals("java.sql",item.getLabel());
assertEquals("(package) java.sql", item.getDetail());
assertEquals(CompletionItemKind.Module, item.getKind() );
assertEquals("999999215", item.getSortText());
assertNotNull(item.getTextEdit());
TextEdit te = item.getTextEdit();
assertNotNull(te);
assertEquals("java.sql.*;",te.getNewText());
assertNotNull(te.getRange());
Range range = te.getRange();
assertEquals(0, range.getStart().getLine());
assertEquals(7, range.getStart().getCharacter());
assertEquals(0, range.getEnd().getLine());
//Not checking the range end character
}
private List<TextEdit> getTagNameRenameTextEdits(DOMDocument xmlDocument, DOMElement element, Position position, String newText) {
Range startTagRange = getTagNameRange(TokenType.StartTag, element.getStart(), xmlDocument);
Range endTagRange = element.hasEndTag() ? getTagNameRange(TokenType.EndTag, element.getEndTagOpenOffset(), xmlDocument)
: null;
//Check if xsd namespace rename
String fullNodeName = element.getNodeName();
int indexOfColon = fullNodeName.indexOf(":");
if(indexOfColon > 0) {
Position startTagStartPosition = startTagRange.getStart();
Position startTagPrefixPosition = new Position(startTagStartPosition.getLine(), startTagStartPosition.getCharacter() + indexOfColon);
Position endTagStartPosition = endTagRange.getStart();
Position endTagPrefixPosition = new Position(endTagStartPosition.getLine(), endTagStartPosition.getCharacter() + indexOfColon);
Range startTagPrefixRange = new Range(startTagStartPosition, startTagPrefixPosition);
Range endTagPrefixRange = new Range(endTagStartPosition, endTagPrefixPosition);
if (doesTagCoverPosition(startTagPrefixRange, endTagPrefixRange, position)) {// Element prefix rename
String prefix = element.getPrefix();
return renameElementNamespace(xmlDocument, element, prefix.length(), newText);
} else { //suffix rename without wiping namespace
String suffixName = element.getLocalName();
int suffixLength = suffixName.length();
Position startTagEndPosition = startTagRange.getEnd();
Position suffixStartPositionStart = new Position(startTagEndPosition.getLine(), startTagEndPosition.getCharacter() - suffixLength);
Position endTagEndPosition = endTagRange.getEnd();
Position suffixEndPositionStart = new Position(endTagEndPosition.getLine(), endTagEndPosition.getCharacter() - suffixLength);
Range suffixRangeStart = new Range(suffixStartPositionStart, startTagEndPosition);
Range suffixRangeEnd = new Range(suffixEndPositionStart, endTagEndPosition);
return getRenameList(suffixRangeStart, suffixRangeEnd, newText);
}
}
//Regular tag name rename
return getRenameList(startTagRange, endTagRange, newText);
}
/**
* 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;
}
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);
}
}
@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);
}
}
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));
}
}