use of org.ballerinalang.langserver.workspace.WorkspaceDocumentManager in project ballerina by ballerina-lang.
the class RenameUtil method getRenameTextEdits.
/**
* Get the list of rename related TextEdits.
*
* @param locationList List of locations of occurrences
* @param documentManager {@link WorkspaceDocumentManager} instance
* @param newName New name to be replaced with
* @param replaceSymbolName Symbol name being replaced
* @return {@link List} List of TextEdits
*/
public static List<TextDocumentEdit> getRenameTextEdits(List<Location> locationList, WorkspaceDocumentManager documentManager, String newName, String replaceSymbolName) {
Map<String, ArrayList<Location>> documentLocationMap = new HashMap<>();
List<TextDocumentEdit> documentEdits = new ArrayList<>();
Comparator<Location> locationComparator = (location1, location2) -> location1.getRange().getStart().getCharacter() - location2.getRange().getStart().getCharacter();
locationList.forEach(location -> {
if (documentLocationMap.containsKey(location.getUri())) {
documentLocationMap.get(location.getUri()).add(location);
} else {
documentLocationMap.put(location.getUri(), (ArrayList<Location>) Lists.of(location));
}
});
documentLocationMap.forEach((uri, locations) -> {
Collections.sort(locations, locationComparator);
String fileContent = documentManager.getFileContent(CommonUtil.getPath(new LSDocument(uri)));
String[] contentComponents = fileContent.split("\\n|\\r\\n|\\r");
int lastNewLineCharIndex = Math.max(fileContent.lastIndexOf("\n"), fileContent.lastIndexOf("\r"));
int lastCharCol = fileContent.substring(lastNewLineCharIndex + 1).length();
for (Location location : locations) {
int line = location.getRange().getStart().getLine();
StringBuilder lineComponent = new StringBuilder(contentComponents[line]);
int index = lineComponent.indexOf(replaceSymbolName);
while (index >= 0) {
char previousChar = lineComponent.charAt(index - 1);
if (Character.isLetterOrDigit(previousChar) || String.valueOf(previousChar).equals("_")) {
index = lineComponent.indexOf(replaceSymbolName, index + replaceSymbolName.length());
} else {
lineComponent.replace(index, index + replaceSymbolName.length(), newName);
index = lineComponent.indexOf(replaceSymbolName, index + newName.length());
}
}
contentComponents[line] = lineComponent.toString();
}
Range range = new Range(new Position(0, 0), new Position(contentComponents.length, lastCharCol));
TextEdit textEdit = new TextEdit(range, String.join("\r\n", Arrays.asList(contentComponents)));
VersionedTextDocumentIdentifier textDocumentIdentifier = new VersionedTextDocumentIdentifier();
textDocumentIdentifier.setUri(uri);
TextDocumentEdit textDocumentEdit = new TextDocumentEdit(textDocumentIdentifier, Collections.singletonList(textEdit));
documentEdits.add(textDocumentEdit);
});
return documentEdits;
}
Aggregations