下面列出了怎么用org.eclipse.lsp4j.DocumentHighlight的API类实例代码及写法,或者点击链接到github查看源代码。
public List<DocumentHighlight> findDocumentHighlights(DOMDocument xmlDocument, Position position,
CancelChecker cancelChecker) {
int offset = -1;
try {
offset = xmlDocument.offsetAt(position);
} catch (BadLocationException e) {
LOGGER.log(Level.SEVERE, "In XMLHighlighting the client provided Position is at a BadLocation", e);
return Collections.emptyList();
}
DOMNode node = xmlDocument.findNodeAt(offset);
if (node == null) {
return Collections.emptyList();
}
List<DocumentHighlight> highlights = new ArrayList<>();
fillWithDefaultHighlights(node, position, offset, highlights, cancelChecker);
fillWithCustomHighlights(node, position, offset, highlights, cancelChecker);
return highlights;
}
public static void testHighlightsFor(String value, String fileURI, DocumentHighlight... expected)
throws BadLocationException {
int offset = value.indexOf('|');
value = value.substring(0, offset) + value.substring(offset + 1);
TextDocument document = new TextDocument(value, fileURI != null ? fileURI : "test://test/test.xml");
Position position = document.positionAt(offset);
XMLLanguageService xmlLanguageService = new XMLLanguageService();
ContentModelSettings settings = new ContentModelSettings();
settings.setUseCache(false);
xmlLanguageService.doSave(new SettingsSaveContext(settings));
DOMDocument xmlDocument = DOMParser.getInstance().parse(document,
xmlLanguageService.getResolverExtensionManager());
xmlLanguageService.setDocumentProvider((uri) -> xmlDocument);
List<? extends DocumentHighlight> actual = xmlLanguageService.findDocumentHighlights(xmlDocument, position,
() -> {
});
assertDocumentHighlight(actual, expected);
}
public static void assertHighlights(String value, int[] expectedMatches, String elementName)
throws BadLocationException {
int offset = value.indexOf("|");
value = value.substring(0, offset) + value.substring(offset + 1);
DOMDocument document = DOMParser.getInstance().parse(value, "test://test/test.html", null);
Position position = document.positionAt(offset);
XMLLanguageService languageService = new XMLLanguageService();
List<DocumentHighlight> highlights = languageService.findDocumentHighlights(document, position);
assertEquals(expectedMatches.length, highlights.size());
for (int i = 0; i < highlights.size(); i++) {
DocumentHighlight highlight = highlights.get(i);
int actualStartOffset = document.offsetAt(highlight.getRange().getStart());
assertEquals(expectedMatches[i], actualStartOffset);
int actualEndOffset = document.offsetAt(highlight.getRange().getEnd());
assertEquals(expectedMatches[i] + (elementName != null ? elementName.length() : 0), actualEndOffset);
assertEquals(elementName, document.getText().substring(actualStartOffset, actualEndOffset).toLowerCase());
}
}
private DocumentHighlight convertToHighlight(ITypeRoot unit, OccurrenceLocation occurrence)
throws JavaModelException {
DocumentHighlight h = new DocumentHighlight();
if ((occurrence.getFlags() | IOccurrencesFinder.F_WRITE_OCCURRENCE) == IOccurrencesFinder.F_WRITE_OCCURRENCE) {
h.setKind(DocumentHighlightKind.Write);
} else if ((occurrence.getFlags()
| IOccurrencesFinder.F_READ_OCCURRENCE) == IOccurrencesFinder.F_READ_OCCURRENCE) {
h.setKind(DocumentHighlightKind.Read);
}
int[] loc = JsonRpcHelpers.toLine(unit.getBuffer(), occurrence.getOffset());
int[] endLoc = JsonRpcHelpers.toLine(unit.getBuffer(), occurrence.getOffset() + occurrence.getLength());
h.setRange(new Range(
new Position(loc[0], loc[1]),
new Position(endLoc[0],endLoc[1])
));
return h;
}
@Test
public void withNull() {
List<? extends DocumentHighlight> input = sort(
Lists.newArrayList(null, newHighlight(DocumentHighlightKind.Text, newRange(1, 1, 1, 1)),
newHighlight(DocumentHighlightKind.Write, newRange(1, 1, 1, 1)),
newHighlight(DocumentHighlightKind.Read, newRange(1, 1, 1, 1))));
assertEquals(1, input.get(0).getRange().getStart().getLine());
assertEquals(1, input.get(0).getRange().getStart().getCharacter());
assertEquals(1, input.get(0).getRange().getEnd().getLine());
assertEquals(1, input.get(0).getRange().getEnd().getCharacter());
assertEquals(DocumentHighlightKind.Text, input.get(0).getKind());
assertEquals(1, input.get(1).getRange().getStart().getLine());
assertEquals(1, input.get(1).getRange().getStart().getCharacter());
assertEquals(1, input.get(1).getRange().getEnd().getLine());
assertEquals(1, input.get(1).getRange().getEnd().getCharacter());
assertEquals(DocumentHighlightKind.Read, input.get(1).getKind());
assertEquals(1, input.get(2).getRange().getStart().getLine());
assertEquals(1, input.get(2).getRange().getStart().getCharacter());
assertEquals(1, input.get(2).getRange().getEnd().getLine());
assertEquals(1, input.get(2).getRange().getEnd().getCharacter());
assertEquals(DocumentHighlightKind.Write, input.get(2).getKind());
assertNull(IterableExtensions.last(input));
}
private static void fillHighlightsList(Range startTagRange, Range endTagRange, List<DocumentHighlight> result) {
if (startTagRange != null) {
result.add(new DocumentHighlight(startTagRange, DocumentHighlightKind.Read));
}
if (endTagRange != null) {
result.add(new DocumentHighlight(endTagRange, DocumentHighlightKind.Read));
}
}
private void fillWithCustomHighlights(DOMNode node, Position position, int offset,
List<DocumentHighlight> highlights, CancelChecker cancelChecker) {
// Consume highlighting participant
for (IHighlightingParticipant highlightingParticipant : extensionsRegistry.getHighlightingParticipants()) {
highlightingParticipant.findDocumentHighlights(node, position, offset,highlights, cancelChecker);
}
}
@Override
public CompletableFuture<List<? extends DocumentHighlight>> documentHighlight(TextDocumentPositionParams params) {
URI uri = getURI(params);
return openFilesManager.runInOpenFileContext(uri, "documentHighlight", (ofc, ci) -> {
return documentHighlight(ofc, params, ci);
});
}
/**
* Compute the document highlights. Executed in a read request.
*/
protected List<? extends DocumentHighlight> documentHighlight(OpenFileContext ofc,
TextDocumentPositionParams params, CancelIndicator cancelIndicator) {
URI uri = ofc.getURI();
IDocumentHighlightService service = getService(uri, IDocumentHighlightService.class);
if (service == null) {
return Collections.emptyList();
}
XtextResource res = ofc.getResource();
XDocument doc = ofc.getDocument();
return service.getDocumentHighlights(doc, res, params, cancelIndicator);
}
private void assertHighlights(List<? extends DocumentHighlight> highlights, String... expected) {
Set<String> stringHighlights = new HashSet<>();
for (DocumentHighlight h : highlights) {
DocumentHighlightKind kind = h.getKind();
stringHighlights.add((kind != null ? kind.name() : "<none>") + ":" +
h.getRange().getStart().getLine() + ":" + h.getRange().getStart().getCharacter() + "-" +
h.getRange().getEnd().getLine() + ":" + h.getRange().getEnd().getCharacter());
}
assertEquals(new HashSet<>(Arrays.asList(expected)),
stringHighlights);
}
private OffsetsBag computeHighlights(Document doc, int caretPos) {
AttributeSet attr = getColoring(doc);
OffsetsBag result = new OffsetsBag(doc);
FileObject file = NbEditorUtilities.getFileObject(doc);
if (file == null) {
return result;
}
LSPBindings server = LSPBindings.getBindings(file);
if (server == null) {
return result;
}
Boolean hasDocumentHighlight = server.getInitResult().getCapabilities().getDocumentHighlightProvider();
if (hasDocumentHighlight == null || !hasDocumentHighlight) {
return result;
}
String uri = Utils.toURI(file);
try {
List<? extends DocumentHighlight> highlights =
server.getTextDocumentService().documentHighlight(new TextDocumentPositionParams(new TextDocumentIdentifier(uri), Utils.createPosition(doc, caretPos))).get();
for (DocumentHighlight h : highlights) {
result.addHighlight(Utils.getOffset(doc, h.getRange().getStart()), Utils.getOffset(doc, h.getRange().getEnd()), attr);
}
return result;
} catch (BadLocationException | InterruptedException | ExecutionException ex) {
Exceptions.printStackTrace(ex);
return result;
}
}
private List<DocumentHighlight> computeOccurrences(ITypeRoot unit, int line, int column, IProgressMonitor monitor) {
if (unit != null) {
try {
int offset = JsonRpcHelpers.toOffset(unit.getBuffer(), line, column);
OccurrencesFinder finder = new OccurrencesFinder();
CompilationUnit ast = CoreASTProvider.getInstance().getAST(unit, CoreASTProvider.WAIT_YES, monitor);
if (ast != null) {
String error = finder.initialize(ast, offset, 0);
if (error == null){
List<DocumentHighlight> result = new ArrayList<>();
OccurrenceLocation[] occurrences = finder.getOccurrences();
if (occurrences != null) {
for (OccurrenceLocation loc : occurrences) {
if (monitor.isCanceled()) {
return Collections.emptyList();
}
result.add(convertToHighlight(unit, loc));
}
}
return result;
}
}
} catch (JavaModelException e) {
JavaLanguageServerPlugin.logException("Problem with compute occurrences for" + unit.getElementName(), e);
}
}
return Collections.emptyList();
}
@Test
public void testDocumentHighlightHandler() throws Exception {
String uri = ClassFileUtil.getURI(project, "org.sample.Highlight");
TextDocumentIdentifier identifier = new TextDocumentIdentifier(uri);
TextDocumentPositionParams params = new TextDocumentPositionParams(identifier, new Position(5, 10));
List<? extends DocumentHighlight> highlights = handler.documentHighlight(params, monitor);
assertEquals(4, highlights.size());
assertHighlight(highlights.get(0), 5, 9, 15, DocumentHighlightKind.Write);
assertHighlight(highlights.get(1), 6, 2, 8, DocumentHighlightKind.Read);
assertHighlight(highlights.get(2), 7, 2, 8, DocumentHighlightKind.Write);
assertHighlight(highlights.get(3), 8, 2, 8, DocumentHighlightKind.Read);
}
@Test
public void withoutNull() {
List<? extends DocumentHighlight> input = sort(
Lists.newArrayList(newHighlight(DocumentHighlightKind.Text, newRange(2, 2, 2, 2)),
newHighlight(DocumentHighlightKind.Text, newRange(1, 1, 1, 1)),
newHighlight(DocumentHighlightKind.Write, newRange(2, 2, 2, 2)),
newHighlight(DocumentHighlightKind.Write, newRange(1, 1, 1, 1)),
newHighlight(DocumentHighlightKind.Read, newRange(2, 2, 2, 2)),
newHighlight(DocumentHighlightKind.Read, newRange(1, 1, 1, 1))));
assertEquals(1, input.get(0).getRange().getStart().getLine());
assertEquals(1, input.get(0).getRange().getStart().getCharacter());
assertEquals(1, input.get(0).getRange().getEnd().getLine());
assertEquals(1, input.get(0).getRange().getEnd().getCharacter());
assertEquals(DocumentHighlightKind.Text, input.get(0).getKind());
assertEquals(1, input.get(1).getRange().getStart().getLine());
assertEquals(1, input.get(1).getRange().getStart().getCharacter());
assertEquals(1, input.get(1).getRange().getEnd().getLine());
assertEquals(1, input.get(1).getRange().getEnd().getCharacter());
assertEquals(DocumentHighlightKind.Read, input.get(1).getKind());
assertEquals(1, input.get(2).getRange().getStart().getLine());
assertEquals(1, input.get(2).getRange().getStart().getCharacter());
assertEquals(1, input.get(2).getRange().getEnd().getLine());
assertEquals(1, input.get(2).getRange().getEnd().getCharacter());
assertEquals(DocumentHighlightKind.Write, input.get(2).getKind());
assertEquals(2, input.get(3).getRange().getStart().getLine());
assertEquals(2, input.get(3).getRange().getStart().getCharacter());
assertEquals(2, input.get(3).getRange().getEnd().getLine());
assertEquals(2, input.get(3).getRange().getEnd().getCharacter());
assertEquals(DocumentHighlightKind.Text, input.get(3).getKind());
assertEquals(2, input.get(4).getRange().getStart().getLine());
assertEquals(2, input.get(4).getRange().getStart().getCharacter());
assertEquals(2, input.get(4).getRange().getEnd().getLine());
assertEquals(2, input.get(4).getRange().getEnd().getCharacter());
assertEquals(DocumentHighlightKind.Read, input.get(4).getKind());
assertEquals(2, input.get(5).getRange().getStart().getLine());
assertEquals(2, input.get(5).getRange().getStart().getCharacter());
assertEquals(2, input.get(5).getRange().getEnd().getLine());
assertEquals(2, input.get(5).getRange().getEnd().getCharacter());
assertEquals(DocumentHighlightKind.Write, input.get(5).getKind());
}
protected String _toExpectation(final DocumentHighlight it) {
String _xblockexpression = null;
{
StringConcatenation _builder = new StringConcatenation();
{
Range _range = it.getRange();
boolean _tripleEquals = (_range == null);
if (_tripleEquals) {
_builder.append("[NaN, NaN]:[NaN, NaN]");
} else {
String _expectation = this.toExpectation(it.getRange());
_builder.append(_expectation);
}
}
final String rangeString = _builder.toString();
StringConcatenation _builder_1 = new StringConcatenation();
{
DocumentHighlightKind _kind = it.getKind();
boolean _tripleEquals_1 = (_kind == null);
if (_tripleEquals_1) {
_builder_1.append("NaN");
} else {
String _expectation_1 = this.toExpectation(it.getKind());
_builder_1.append(_expectation_1);
}
}
_builder_1.append(" ");
_builder_1.append(rangeString);
_xblockexpression = _builder_1.toString();
}
return _xblockexpression;
}
/**
* Compute the document highlights. Executed in a read request.
* @since 2.20
*/
protected List<? extends DocumentHighlight> documentHighlight(DocumentHighlightParams params,
CancelIndicator cancelIndicator) {
URI uri = getURI(params);
IDocumentHighlightService service = getService(uri, IDocumentHighlightService.class);
if (service == null) {
return Collections.emptyList();
}
return workspaceManager.doRead(uri,
(doc, resource) -> service.getDocumentHighlights(doc, resource, params, cancelIndicator));
}
@Override
public DocumentHighlight apply(final Document document, final ITextRegion region,
final DocumentHighlightKind kind) {
Preconditions.checkNotNull(document, "document");
Preconditions.checkNotNull(region, "region");
Preconditions.checkNotNull(kind, "kind");
final int offset = region.getOffset();
final Position start = document.getPosition(offset);
final Position end = document.getPosition(offset + region.getLength());
return new DocumentHighlight(new Range(start, end), kind);
}
@Override
public CompletableFuture<List<? extends DocumentHighlight>> documentHighlight(DocumentHighlightParams params) {
return computeDOMAsync(params.getTextDocument(), (cancelChecker, xmlDocument) -> {
return getXMLLanguageService().findDocumentHighlights(xmlDocument, params.getPosition(), cancelChecker);
});
}
void findDocumentHighlights(DOMNode node, Position position, int offset, List<DocumentHighlight> highlights,
CancelChecker cancelChecker);
public List<DocumentHighlight> findDocumentHighlights(DOMDocument xmlDocument, Position position) {
return findDocumentHighlights(xmlDocument, position, NULL_CHECKER);
}
public List<DocumentHighlight> findDocumentHighlights(DOMDocument xmlDocument, Position position,
CancelChecker cancelChecker) {
return highlighting.findDocumentHighlights(xmlDocument, position, cancelChecker);
}
@Override
public void findDocumentHighlights(DOMNode node, Position position, int offset, List<DocumentHighlight> highlights,
CancelChecker cancelChecker) {
boolean findReferences = false;
DTDDeclParameter parameter = null;
DTDElementDecl elementDecl = null;
if (node.isDTDElementDecl()) {
elementDecl = (DTDElementDecl) node;
if (elementDecl.isInNameParameter(offset)) {
// <!ELEMENT na|me --> here cursor is in the name of <!ELEMENT
// we must find all references from the <!ELEMENT which defines the name
findReferences = true;
parameter = elementDecl.getNameParameter();
} else {
// <!ELEMENT name (chi|ld --> here cursor is in the child element
// we must find only the <!ELEMENT child
parameter = elementDecl.getParameterAt(offset);
}
} else if (node.isDTDAttListDecl()) {
DTDAttlistDecl attlistDecl = (DTDAttlistDecl) node;
if (attlistDecl.isInNameParameter(offset)) {
// <!ATTLIST na|me --> here cusror is in the name of <!ATTLIST
// we must find only the <!ELEMENT name
parameter = attlistDecl.getNameParameter();
}
}
if (parameter == null) {
return;
}
if (findReferences) {
// case with <!ELEMENT na|me
// highlight <!ELEMENT na|me
DTDDeclParameter originNode = parameter;
highlights.add(
new DocumentHighlight(XMLPositionUtility.createRange(originNode), DocumentHighlightKind.Write));
// highlight all references of na|me in ATTLIST and child of <!ELEMENT
DTDUtils.searchDTDOriginElementDecls(elementDecl, (origin, target) -> {
highlights
.add(new DocumentHighlight(XMLPositionUtility.createRange(origin), DocumentHighlightKind.Read));
}, cancelChecker);
} else {
// case with
// - <!ELEMENT name (chi|ld
// - <!ATTLIST na|me
// highlight <!ELEMENT name (chi|ld or <!ATTLIST na|me
DTDDeclParameter targetNode = parameter;
highlights
.add(new DocumentHighlight(XMLPositionUtility.createRange(targetNode), DocumentHighlightKind.Read));
// highlight the target <!ELEMENT nam|e
DTDUtils.searchDTDTargetElementDecl(parameter, true, targetName -> {
highlights.add(
new DocumentHighlight(XMLPositionUtility.createRange(targetName), DocumentHighlightKind.Write));
});
}
}
public static void testHighlightsFor(String xml, DocumentHighlight... expected) throws BadLocationException {
testHighlightsFor(xml, null, expected);
}
public static void assertDocumentHighlight(List<? extends DocumentHighlight> actual,
DocumentHighlight... expected) {
assertEquals(expected.length, actual.size());
assertArrayEquals(expected, actual.toArray());
}
public static DocumentHighlight hl(Range range) {
return hl(range, DocumentHighlightKind.Read);
}
public static DocumentHighlight hl(Range range, DocumentHighlightKind kind) {
return new DocumentHighlight(range, kind);
}
@Override
public CompletableFuture<List<? extends DocumentHighlight>> documentHighlight(DocumentHighlightParams position) {
LOGGER.info("documentHighlight: {}", position.getTextDocument());
return CompletableFuture.completedFuture(Collections.emptyList());
}
@Override
public CompletableFuture<List<? extends DocumentHighlight>> documentHighlight(TextDocumentPositionParams position) {
LOGGER.debug("documentHighlight: {}", position.getTextDocument());
List<DocumentHighlight> result = new ArrayList<DocumentHighlight>();
return CompletableFuture.completedFuture(result);
}
public List<? extends DocumentHighlight> documentHighlight(TextDocumentPositionParams position, IProgressMonitor monitor) {
ITypeRoot type = JDTUtils.resolveTypeRoot(position.getTextDocument().getUri());
return computeOccurrences(type, position.getPosition().getLine(),
position.getPosition().getCharacter(), monitor);
}
@Override
public CompletableFuture<List<? extends DocumentHighlight>> documentHighlight(DocumentHighlightParams position) {
logInfo(">> document/documentHighlight");
DocumentHighlightHandler handler = new DocumentHighlightHandler();
return computeAsync((monitor) -> handler.documentHighlight(position, monitor));
}