本文整理汇总了Java中org.netbeans.spi.java.hints.HintContext.getCaretLocation方法的典型用法代码示例。如果您正苦于以下问题:Java HintContext.getCaretLocation方法的具体用法?Java HintContext.getCaretLocation怎么用?Java HintContext.getCaretLocation使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类org.netbeans.spi.java.hints.HintContext
的用法示例。
在下文中一共展示了HintContext.getCaretLocation方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: computeWarning
import org.netbeans.spi.java.hints.HintContext; //导入方法依赖的package包/类
@Hint(id="org.netbeans.modules.java.hints.suggestions.InvertIf", displayName = "#DN_InvertIf", description = "#DESC_InvertIf", category = "suggestions", hintKind= Hint.Kind.ACTION)
@UseOptions(SHOW_ELSE_MISSING)
@TriggerPattern(value = "if ($cond) $then; else $else$;")
@Messages({"ERR_InvertIf=Invert If",
"FIX_InvertIf=Invert If"})
public static ErrorDescription computeWarning(HintContext ctx) {
TreePath cond = ctx.getVariables().get("$cond");
long conditionEnd = ctx.getInfo().getTrees().getSourcePositions().getEndPosition(cond.getCompilationUnit(), cond.getParentPath().getLeaf());
if (ctx.getCaretLocation() > conditionEnd) return null;
// parenthesized, then if
TreePath ifPath = cond.getParentPath().getParentPath();
if (ifPath.getLeaf().getKind() != Tree.Kind.IF) {
return null;
}
IfTree iv = (IfTree)ifPath.getLeaf();
if (iv.getElseStatement() == null &&
!ctx.getPreferences().getBoolean(SHOW_ELSE_MISSING, SHOW_ELSE_MISSING_DEFAULT)) {
return null;
}
return ErrorDescriptionFactory.forName(ctx, ctx.getPath(), Bundle.ERR_InvertIf(), new FixImpl(ctx.getInfo(), ctx.getPath()).toEditorFix());
}
示例2: caretInsidePreviousToken
import org.netbeans.spi.java.hints.HintContext; //导入方法依赖的package包/类
private static boolean caretInsidePreviousToken(HintContext ctx, long startAt, JavaTokenId lookFor) {
if (startAt < 0) {
return false;
}
TokenSequence<JavaTokenId> ts = ctx.getInfo().getTokenHierarchy().tokenSequence(JavaTokenId.language());
ts.move((int) startAt);
while (ts.movePrevious()) {
if (ts.token().id() == lookFor) {
int start = ts.offset();
int end = ts.offset() + ts.token().length();
return ctx.getCaretLocation() >= start && ctx.getCaretLocation() <= end;
}
}
return false;
}
示例3: if
import org.netbeans.spi.java.hints.HintContext; //导入方法依赖的package包/类
@Hint(displayName="#DN_ToOrIf", description="#DESC_ToOrIf", category="suggestions", hintKind=Hint.Kind.ACTION)
@TriggerPattern("if ($cond1) $then; else if ($cond2) $then; else $else$;")
@Messages({"ERR_ToOrIf=",
"FIX_ToOrIf=Join ifs using ||"})
public static ErrorDescription toOrIf(HintContext ctx) {
SourcePositions sp = ctx.getInfo().getTrees().getSourcePositions();
CompilationUnitTree cut = ctx.getInfo().getCompilationUnit();
boolean caretAccepted = ctx.getCaretLocation() <= sp.getStartPosition(cut, ctx.getPath().getLeaf()) + 2 || caretInsideToLevelElseKeyword(ctx);
if (!caretAccepted) return null;
return ErrorDescriptionFactory.forSpan(ctx, ctx.getCaretLocation(), ctx.getCaretLocation(), Bundle.ERR_ToOrIf(), JavaFixUtilities.rewriteFix(ctx, Bundle.FIX_ToOrIf(), ctx.getPath(), "if ($cond1 || $cond2) $then; else $else$;"));
}
示例4: extractIf
import org.netbeans.spi.java.hints.HintContext; //导入方法依赖的package包/类
@Hint(id="org.netbeans.modules.java.hints.suggestions.Tiny.extractIf", displayName = "#DN_org.netbeans.modules.java.hints.suggestions.Tiny.extractIf", description = "#DESC_org.netbeans.modules.java.hints.suggestions.Tiny.extractIf", category="suggestions", hintKind=org.netbeans.spi.java.hints.Hint.Kind.ACTION, severity=Severity.HINT)
@TriggerPattern(value="if ($firstCondition && $secondCondition) $body;")
public static ErrorDescription extractIf(HintContext ctx) {
int caret = ctx.getCaretLocation();
boolean braces = CodeStyle.getDefault(ctx.getInfo().getFileObject()).redundantIfBraces() != BracesGenerationStyle.ELIMINATE;
TreePath toSplit = null;
TreePath left = ctx.getVariables().get("$firstCondition"); // NOI18N
long leftStart = ctx.getInfo().getTrees().getSourcePositions().getStartPosition(ctx.getPath().getCompilationUnit(), left.getLeaf());
long leftEnd = ctx.getInfo().getTrees().getSourcePositions().getEndPosition(ctx.getPath().getCompilationUnit(), left.getLeaf());
if (leftStart <= caret && caret <= leftEnd) {
toSplit = left;
}
TreePath right = ctx.getVariables().get("$secondCondition"); // NOI18N
if (toSplit == null) {
long rightStart = ctx.getInfo().getTrees().getSourcePositions().getStartPosition(ctx.getPath().getCompilationUnit(), right.getLeaf());
long rightEnd = ctx.getInfo().getTrees().getSourcePositions().getEndPosition(ctx.getPath().getCompilationUnit(), right.getLeaf());
if (rightStart > caret || caret > rightEnd) {
return null;
}
}
ctx.getVariables().put("$firstCondition", unwrapParenthesized(left)); // NOI18N
ctx.getVariables().put("$secondCondition", unwrapParenthesized(right)); // NOI18N
String targetPattern = braces ? "if ($firstCondition) { if ($secondCondition) $body; }" : "if ($firstCondition) if ($secondCondition) $body;"; // NOI18N
Fix f = JavaFixUtilities.rewriteFix(ctx, Bundle.FIX_org_netbeans_modules_java_hints_suggestions_Tiny_extractIf(), ctx.getPath(), targetPattern);
return ErrorDescriptionFactory.forName(ctx, ctx.getPath(), Bundle.ERR_org_netbeans_modules_java_hints_suggestions_Tiny_extractIf(), f);
}
示例5: run
import org.netbeans.spi.java.hints.HintContext; //导入方法依赖的package包/类
@TriggerPattern("for ($type $varName : $expression) { $stmts$; }")
public static ErrorDescription run(HintContext ctx) {
TreePath tp = ctx.getPath();
EnhancedForLoopTree efl = (EnhancedForLoopTree) tp.getLeaf();
long statementStart = ctx.getInfo().getTrees().getSourcePositions().getStartPosition(ctx.getInfo().getCompilationUnit(), efl.getStatement());
int caret = ctx.getCaretLocation();
if (caret >= statementStart) {
return null;
}
TypeMirror expressionType = ctx.getInfo().getTrees().getTypeMirror(new TreePath(tp, efl.getExpression()));
if (expressionType == null || expressionType.getKind() != TypeKind.DECLARED) {
return null;
}
ExecutableElement iterator = findIterable(ctx.getInfo());
Types t = ctx.getInfo().getTypes();
if (iterator == null || !t.isSubtype(((DeclaredType) expressionType), t.erasure(iterator.getEnclosingElement().asType()))) {
return null;
}
FixImpl fix = new FixImpl(TreePathHandle.create(tp, ctx.getInfo()));
List<Fix> fixes = Collections.<Fix>singletonList(fix.toEditorFix());
return ErrorDescriptionFactory.createErrorDescription(ctx.getSeverity(),
NbBundle.getMessage(ExpandEnhancedForLoop.class, "ERR_ExpandEhancedForLoop"),
fixes,
ctx.getInfo().getFileObject(),
caret,
caret);
}
示例6: computeWarning
import org.netbeans.spi.java.hints.HintContext; //导入方法依赖的package包/类
@TriggerTreeKind(Tree.Kind.METHOD)
@Messages("ERR_CreateTestMethodsHint=Generate All Test Methods")
public static ErrorDescription computeWarning(HintContext context) {
final TreePath tp = context.getPath();
final MethodTree method = (MethodTree) tp.getLeaf();
if (method.getModifiers().getFlags().contains(Modifier.PRIVATE)) {
return null;
}
String methodName = method.getName().toString();
CompilationInfo info = context.getInfo();
SourcePositions sourcePositions = info.getTrees().getSourcePositions();
int startPos = (int) sourcePositions.getStartPosition(tp.getCompilationUnit(), method);
int caret = context.getCaretLocation();
String code = context.getInfo().getText();
if (startPos < 0 || caret < 0 || caret < startPos || caret >= code.length()) {
return null;
}
String headerText = code.substring(startPos, caret);
int idx = headerText.indexOf('{'); //NOI18N
if (idx >= 0) {
return null;
}
ClassPath cp = info.getClasspathInfo().getClassPath(ClasspathInfo.PathKind.SOURCE);
FileObject fileObject = info.getFileObject();
if(!fileObject.isValid()) { //File is probably deleted
return null;
}
FileObject root = cp.findOwnerRoot(fileObject);
if (root == null) { //File not part of any project
return null;
}
Collection<? extends TestCreatorProvider> providers = Lookup.getDefault().lookupAll(TestCreatorProvider.class);
Map<Object, List<String>> validCombinations = Utils.getValidCombinations(info, methodName);
if (validCombinations == null) { // no TestCreatorProvider found
return null;
}
for (TestCreatorProvider provider : providers) {
if (provider.enable(new FileObject[]{fileObject}) && !validCombinations.isEmpty()) {
List<Fix> fixes = new ArrayList<Fix>();
Fix fix;
for (Entry<Object, List<String>> entrySet : validCombinations.entrySet()) {
Object location = entrySet.getKey();
for (String testingFramework : entrySet.getValue()) {
fix = new CreateTestMethodsFix(new FileObject[]{fileObject}, location, testingFramework);
fixes.add(fix);
}
}
validCombinations.clear();
return ErrorDescriptionFactory.forTree(context, context.getPath(), Bundle.ERR_CreateTestMethodsHint(), fixes.toArray(new Fix[fixes.size()]));
}
}
validCombinations.clear();
return null;
}
示例7: computeWarning
import org.netbeans.spi.java.hints.HintContext; //导入方法依赖的package包/类
@TriggerTreeKind(Tree.Kind.CLASS)
@Messages("ERR_CreateTestClassHint=Create Test Class")
public static ErrorDescription computeWarning(HintContext context) {
TreePath tp = context.getPath();
ClassTree cls = (ClassTree) tp.getLeaf();
CompilationInfo info = context.getInfo();
SourcePositions sourcePositions = info.getTrees().getSourcePositions();
int startPos = (int) sourcePositions.getStartPosition(tp.getCompilationUnit(), cls);
int caret = context.getCaretLocation();
String code = context.getInfo().getText();
if (startPos < 0 || caret < 0 || caret < startPos || caret >= code.length()) {
return null;
}
String headerText = code.substring(startPos, caret);
int idx = headerText.indexOf('{'); //NOI18N
if (idx >= 0) {
return null;
}
ClassPath cp = info.getClasspathInfo().getClassPath(ClasspathInfo.PathKind.SOURCE);
FileObject fileObject = info.getFileObject();
if(!fileObject.isValid()) { //File is probably deleted
return null;
}
FileObject root = cp.findOwnerRoot(fileObject);
if (root == null) { //File not part of any project
return null;
}
Collection<? extends TestCreatorProvider> providers = Lookup.getDefault().lookupAll(TestCreatorProvider.class);
Map<Object, List<String>> validCombinations = Utils.getValidCombinations(info, null);
if (validCombinations == null) { // no TestCreatorProvider found
return null;
}
for (TestCreatorProvider provider : providers) {
if (provider.enable(new FileObject[]{fileObject}) && !validCombinations.isEmpty()) {
List<Fix> fixes = new ArrayList<Fix>();
Fix fix;
for (Entry<Object, List<String>> entrySet : validCombinations.entrySet()) {
Object location = entrySet.getKey();
for (String testingFramework : entrySet.getValue()) {
fix = new CreateTestClassFix(new FileObject[]{fileObject}, location, testingFramework);
fixes.add(fix);
}
}
validCombinations.clear();
return ErrorDescriptionFactory.forTree(context, context.getPath(), Bundle.ERR_CreateTestClassHint(), fixes.toArray(new Fix[fixes.size()]));
}
}
validCombinations.clear();
return null;
}
示例8: implementMethods
import org.netbeans.spi.java.hints.HintContext; //导入方法依赖的package包/类
@TriggerTreeKind(Kind.CLASS)
@Messages({
"# {0} - the FQN of the type whose methods will be implemented",
"ERR_ImplementMethods=Implement unimplemented abstract methods of {0}"
})
public static ErrorDescription implementMethods(HintContext ctx) {
ClassTree clazz = (ClassTree) ctx.getPath().getLeaf();
Element typeEl = ctx.getInfo().getTrees().getElement(ctx.getPath());
if (typeEl == null || !typeEl.getKind().isClass())
return null;
List<Tree> candidate = new ArrayList<Tree>(clazz.getImplementsClause());
candidate.add(clazz.getExtendsClause());
Tree found = null;
for (Tree cand : candidate) {
if ( ctx.getInfo().getTrees().getSourcePositions().getStartPosition(ctx.getInfo().getCompilationUnit(), cand) <= ctx.getCaretLocation()
&& ctx.getCaretLocation() <= ctx.getInfo().getTrees().getSourcePositions().getEndPosition(ctx.getInfo().getCompilationUnit(), cand)) {
found = cand;
break;
}
}
if (found == null) return null;
TreePath foundPath = new TreePath(ctx.getPath(), found);
Element supertype = ctx.getInfo().getTrees().getElement(foundPath);
if (supertype == null || (!supertype.getKind().isClass() && !supertype.getKind().isInterface()))
return null;
List<ExecutableElement> unimplemented = computeUnimplemented(ctx.getInfo(), typeEl, supertype);
if (!unimplemented.isEmpty()) {
return ErrorDescriptionFactory.forName(ctx, foundPath, Bundle.ERR_ImplementMethods(((TypeElement) supertype).getQualifiedName().toString()), new ImplementFix(ctx.getInfo(), ctx.getPath(), (TypeElement) typeEl, (TypeElement) supertype).toEditorFix());
}
return null;
}
示例9: check
import org.netbeans.spi.java.hints.HintContext; //导入方法依赖的package包/类
@TriggerTreeKind({Tree.Kind.CLASS, Tree.Kind.INTERFACE})
public static ErrorDescription check(HintContext context) {
TreePath tp = context.getPath();
ClassTree cls = (ClassTree) tp.getLeaf();
CompilationInfo info = context.getInfo();
SourcePositions sourcePositions = info.getTrees().getSourcePositions();
long startPos = sourcePositions.getStartPosition(tp.getCompilationUnit(), cls);
if (startPos > Integer.MAX_VALUE) {
return null;
}
int[] bodySpan = info.getTreeUtilities().findBodySpan(cls);
if (bodySpan == null || bodySpan[0] <= startPos) {
return null;
}
int caret = context.getCaretLocation();
if (startPos < 0 || caret < 0 || caret < startPos || caret >= bodySpan[0]) {
return null;
}
// #222487
// If there is a compile-time error on the class, then don't offer to
// create a subclass.
List<Diagnostic> errors = info.getDiagnostics();
if (!errors.isEmpty()) {
for (Diagnostic d : errors) {
if (d.getKind() != Diagnostic.Kind.ERROR) {
continue;
}
// Check that the error's start position is within the class header
// Note: d.getEndPosition() is not used because, for example,
// a "compiler.err.does.not.override.abstract" error ends at
// the end of the class tree.
if (startPos <= d.getStartPosition() && d.getStartPosition() <= bodySpan[0]) {
return null;
}
}
}
TypeElement typeElement = (TypeElement) info.getTrees().getElement(tp);
if (typeElement == null || typeElement.getModifiers().contains(Modifier.FINAL)) return null;
Element outer = typeElement.getEnclosingElement();
// do not offer the hint for non-static inner classes. Permit for classes nested into itnerface - no enclosing instance
if (outer != null && outer.getKind() != ElementKind.PACKAGE && outer.getKind() != ElementKind.INTERFACE) {
if (outer.getKind() != ElementKind.CLASS && outer.getKind() != ElementKind.ENUM) {
return null;
}
if (!typeElement.getModifiers().contains(Modifier.STATIC)) {
return null;
}
}
ClassPath cp = info.getClasspathInfo().getClassPath(PathKind.SOURCE);
FileObject root = cp.findOwnerRoot(info.getFileObject());
if (root == null) { //File not part of any project
return null;
}
PackageElement packageElement = (PackageElement) info.getElementUtilities().outermostTypeElement(typeElement).getEnclosingElement();
CreateSubclassFix fix = new CreateSubclassFix(info, root, packageElement.getQualifiedName().toString(), typeElement.getSimpleName().toString() + "Impl", typeElement); //NOI18N
return ErrorDescriptionFactory.forTree(context, context.getPath(), NbBundle.getMessage(CreateSubclass.class, typeElement.getKind() == ElementKind.CLASS
? typeElement.getModifiers().contains(Modifier.ABSTRACT) ? "ERR_ImplementAbstractClass" : "ERR_CreateSubclass" : "ERR_ImplementInterface"), fix); //NOI18N
}
示例10: fillSwitch
import org.netbeans.spi.java.hints.HintContext; //导入方法依赖的package包/类
@Hint(displayName = "#DN_org.netbeans.modules.java.hints.suggestions.Tiny.fillSwitch", description = "#DESC_org.netbeans.modules.java.hints.suggestions.Tiny.fillSwitch", category="suggestions", hintKind=Kind.ACTION, severity=Severity.HINT, customizerProvider=CustomizerProviderImpl.class)
@TriggerPattern(value="switch ($expression) { case $cases$; }",
[email protected](variable="$expression", type="java.lang.Enum"))
public static ErrorDescription fillSwitch(HintContext ctx) {
int caret = ctx.getCaretLocation();
SwitchTree st = (SwitchTree) ctx.getPath().getLeaf();
int switchStart = (int) ctx.getInfo().getTrees().getSourcePositions().getStartPosition(ctx.getPath().getCompilationUnit(), st);
LineMap lm = ctx.getPath().getCompilationUnit().getLineMap();
if (lm.getLineNumber(caret) != lm.getLineNumber(switchStart)) return null;
TreePath expression = ctx.getVariables().get("$expression");
Element possibleEnumElement = ctx.getInfo().getTypes().asElement(ctx.getInfo().getTrees().getTypeMirror(expression));
if (possibleEnumElement == null || !possibleEnumElement.getKind().isClass()) return null;
TypeElement enumType = (TypeElement) possibleEnumElement;
List<VariableElement> enumConstants = new ArrayList<VariableElement>(enumType.getEnclosedElements().size());
for (Element e : enumType.getEnclosedElements()) {
if (e.getKind() == ElementKind.ENUM_CONSTANT) {
enumConstants.add((VariableElement) e);
}
}
boolean hasDefault = false;
for (TreePath casePath : ctx.getMultiVariables().get("$cases$")) {
CaseTree ct = (CaseTree) casePath.getLeaf();
if (ct.getExpression() == null) {
hasDefault = true;
} else {
enumConstants.remove(ctx.getInfo().getTrees().getElement(new TreePath(casePath, ct.getExpression())));
}
}
boolean generateDefault = ctx.getPreferences().getBoolean(KEY_DEFAULT_ENABLED, DEF_DEFAULT_ENABLED);
if (enumConstants.isEmpty() && (hasDefault || !generateDefault)) return null;
List<String> names = new ArrayList<String>(enumConstants.size());
for (VariableElement constant : enumConstants) {
names.add(constant.getSimpleName().toString());
}
String defaultTemplate = generateDefault ? ctx.getPreferences().get(KEY_DEFAULT_SNIPPET, DEF_DEFAULT_SNIPPET) : null;
String errMessage = enumConstants.isEmpty() ? "ERR_Tiny.fillSwitchDefault" : !hasDefault && generateDefault ? "ERR_Tiny.fillSwitchCasesAndDefault" : "ERR_Tiny.fillSwitchCases";
String fixMessage = enumConstants.isEmpty() ? "FIX_Tiny.fillSwitchDefault" : !hasDefault && generateDefault ? "FIX_Tiny.fillSwitchCasesAndDefault" : "FIX_Tiny.fillSwitchCases";
return ErrorDescriptionFactory.forName(ctx, ctx.getPath(), NbBundle.getMessage(Tiny.class, errMessage), new AddSwitchCasesImpl(ctx.getInfo(), ctx.getPath(), fixMessage, names, defaultTemplate).toEditorFix());
}