How to get line number from SearchMatch object?
in my plug in after performing search, each matches are sent to acceptsearchmatch(searchmatch) function as objects of searchmatch.I want to get the line n开发者_运维百科umbers where the match happened.cant use getoffset because it gives relative to source buffer.how can i get the line number?help
thanks
The trick is: a SearchMatch
give you a SearchRange
, meaning several lines can potentially be included in that Range.
The solution is to parse the Document associated to the object returned by the SearchMatch in order to compute those line numbers.
The relevant method is getLineOfOffset(int offset)
You have here an example, in the case where the object is a IMember
ISourceRange range = member.getSourceRange();
if (range == null){
return null;
}
IBuffer buf = null;
ISourceModule compilationUnit = member.getSourceModule();
if (!compilationUnit.isConsistent()) {
return null;
}
buf = compilationUnit.getBuffer();
final int start = range.getOffset();
String contents = buf.getContents();
Document doc = new Document(contents);
try {
int line = doc.getLineOfOffset(start);
...
This should work:
private int getLineNumber(SearchMatch match) throws BadLocationException,
IOException, CoreException {
IResource resource = match.getResource();
if (!(resource instanceof IFile)) {
// Log Error
return -1;
}
IFile file = (IFile) resource;
int offset = match.getOffset();
byte[] bytes = new byte[offset];
int read = file.getContents().read(bytes, 0, offset);
if (read != offset) {
// Log error
return -1;
}
String contents = new String(bytes);
Document fileSource = new Document(contents);
return fileSource.getLineOfOffset(offset) + 1;
}
精彩评论