2014-10-30 125 views
0

向PhpStorm(或其他JetBrains IDE's)添加'意图'时,如何检测PsiElement是否是字符串?我将我的代码建立在我能找到的唯一意图示例上。我似乎无法找到适当的文件。这是据我得到:检查PsiElement是否为字符串

@NonNls public class SomeIntention extends PsiElementBaseIntentionAction implements IntentionAction { 

    public boolean isAvailable(@NotNull Project project, Editor editor, @Nullable PsiElement element) { 
     if (element == null || !(element instanceof /* String? */) { 
      return false; 
     } 
    } 

} 

instanceof String显然是行不通的,但即使使用PsiViewer我无法弄清楚如何测试它是否是一个字符串。

回答

1

下的工作检查,如果我们当前节点是一个字符串(双引号或单引号):

ASTNode ast_node = element.getNode(); 

if(ast_node == null) { 
    return false; 
} 

IElementType element_type = ast_node.getElementType(); 

if(element_type != PhpTokenTypes.STRING_LITERAL 
&& element_type != PhpTokenTypes.STRING_LITERAL_SINGLE_QUOTE) { 
    return false; 
} 

return true; 

就我而言,我只是想“原始字符串”,而不是与变量或级联串。如果字符串中存在任何变量或连接符号,那么PSI会将它们看作是独立的兄弟。所以我可以通过排除兄弟姐妹的字符串来找到原始字符串:

// Disregards strings with variables, concatenation, etc. 
if (element.getPrevSibling() != null || element.getNextSibling() != null) { 
    return false; 
} 

return true; 
3

我会建议查看intellij社区源代码,日志记录,调试和使用PsiViewer插件,然后你会发现某些类型的PsiJavaToken包含一个字符串。