IntelliJ插件开发-Code Vision Hints

2023-12-17 22:30

本文主要是介绍IntelliJ插件开发-Code Vision Hints,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

简介

Code Vision Hints是idea Inlay提示中的一种类型,它只能提供block类型的inlay,可以把它添加到字段、方法、类等上面,一个元素如果包含多个提示的话,这些inlay会被展示在同一行上。

Code vision hints可以展示在元素的上面、右边、或者行末尾,具体展示的位置可以在IDE中修改:Preferences | Editor | Inlay Hints | Code vision。

目前已经有许多的插件都使用了Inlay,例如:

  • Java代码中,会在链式调用的每行展示返回类型信息
  • 版本控制的项目中,会展示提交者信息

有两个扩展点可以用于实现code vision:

  • DaemonBoundCodeVisionProvider : PSI改变后会得到通知,例如usages,其他文件变动后会继续计算被使用信息
  • CodeVisionProvider : 不依赖PSI改变通知,例如git的提交信息。

目前在2022.2这个版本测试中,发现CodeVisionProvider有很多bug,很多废弃的方法也需要实现,也许在新版本已经解决了这个问题,如果你依赖IDE版本较老,建议还是直接实现DaemonBoundCodeVisionProvider。

代码示例

实现DaemonBoundCodeVisionProvider
  1. 新建VisionProvider的实现类
public class MyCodeVisionProvider implements DaemonBoundCodeVisionProvider {public static final String GROUP_ID = "com.demo";public static final String ID = "myPlugin";public static final String NAME = "my plugin";@NotNull@Overridepublic CodeVisionAnchorKind getDefaultAnchor() {// 默认展示在元素的顶部return CodeVisionAnchorKind.Top;}@NotNull@Overridepublic String getId() {return ID;}@NotNull@Overridepublic String getGroupId() {return GROUP_ID;}@Nls@NotNull@Overridepublic String getName() {return NAME;}@NotNull@Overridepublic List<CodeVisionRelativeOrdering> getRelativeOrderings() {// 设置展示顺序为第一个return List.of(CodeVisionRelativeOrdering.CodeVisionRelativeOrderingFirst.INSTANCE);}// 设置展示场景:java文件的方法上展示@NotNull@Overridepublic List<Pair<TextRange, CodeVisionEntry>> computeForEditor(@NotNull Editor editor, @NotNull PsiFile file) {List<Pair<TextRange, CodeVisionEntry>> lenses = new ArrayList<>();String languageId = file.getLanguage().getID();if (!"JAVA".equalsIgnoreCase(languageId)) {return lenses;}SyntaxTraverser<PsiElement> traverser = SyntaxTraverser.psiTraverser(file);for (PsiElement element : traverser) {if (!(element instanceof PsiMethod)) {continue;}if (!InlayHintsUtils.isFirstInLine(element)) {continue;}String hint = getName();TextRange range = InlayHintsUtils.INSTANCE.getTextRangeWithoutLeadingCommentsAndWhitespaces(element);lenses.add(new Pair(range, new ClickableTextCodeVisionEntry(hint, getId(), new MyClickHandler((PsiMethod) element), null, hint, "", List.of())));}return lenses;}@NotNull@Override@Deprecatedpublic List<Pair<TextRange, CodeVisionEntry>> computeForEditor(@NotNull Editor editor) {// 过时方法,不用实现return List.of();}// Inlay被点击后的处理逻辑@Overridepublic void handleClick(@NotNull Editor editor, @NotNull TextRange textRange, @NotNull CodeVisionEntry entry) {if (entry instanceof CodeVisionPredefinedActionEntry) {((CodeVisionPredefinedActionEntry)entry).onClick(editor);}}@RequiredArgsConstructorstatic class MyClickHandler implements Function2<MouseEvent, Editor, Unit> {private final PsiMethod psiMethod;// 点击inlay后的响应:打开一个popup显示一组菜单public Unit invoke(MouseEvent event, Editor editor) {TextRange range = InlayHintsUtils.INSTANCE.getTextRangeWithoutLeadingCommentsAndWhitespaces(psiMethod);int startOffset = range.getStartOffset();int endOffset = range.getEndOffset();editor.getSelectionModel().setSelection(startOffset, endOffset);AnAction action1 = ActionManager.getInstance().getAction("MyPlugin.Action1");AnAction action2 = ActionManager.getInstance().getAction("MyPlugin.Action2");DefaultActionGroup actionGroup = new DefaultActionGroup(List.of(action1, action2));ListPopup popup = JBPopupFactory.getInstance().createActionGroupPopup(null, actionGroup, EditorUtil.getEditorDataContext(editor), JBPopupFactory.ActionSelectionAid.SPEEDSEARCH, true);popup.show(new RelativePoint(event));return null;}}
}
  1. 注册VisionProvider的实现类
<idea-plugin><extensions defaultExtensionNs="com.intellij"><codeInsight.daemonBoundCodeVisionProvider implementation="com.demo.MyCodeVisionProvider"/></extensions>
</idea-plugin>
实现CodeVisionProvider
  1. 新建VisionProvider的实现类
public class MyCodeVisionProvider implements CodeVisionProvider<Unit> {public static final String GROUP_ID = "com.demo";public static final String ID = "myPlugin";public static final String NAME = "my plugin";private static final Key<Long> MODIFICATION_STAMP_KEY = Key.create("myPlugin.modificationStamp");private static final Key<Integer> MODIFICATION_STAMP_COUNT_KEY = KeyWithDefaultValue.create("myPlugin.modificationStampCount", 0);// 每次文档事件都会调用2次shouldRecomputeForEditor,这里设置4因为编辑器刚打开的时候,没关闭的文件首次刷新可能导致渲染了宽度为0的Inlay。private static final int MAX_MODIFICATION_STAMP_COUNT = 4;@NotNull@Overridepublic CodeVisionAnchorKind getDefaultAnchor() {return CodeVisionAnchorKind.Top;}@NotNull@Overridepublic String getGroupId() {return GROUP_ID;}@NotNull@Overridepublic String getId() {return ID;}@Nls@NotNull@Overridepublic String getName() {return NAME;}@NotNull@Overridepublic List<CodeVisionRelativeOrdering> getRelativeOrderings() {return List.of(CodeVisionRelativeOrdering.CodeVisionRelativeOrderingFirst.INSTANCE);}@NotNull@Override@Deprecated(message = "use getPlaceholderCollector")// 已被废弃,不用实现public List<TextRange> collectPlaceholders(@NotNull Editor editor) {return List.of();}@Nullable@Override// 不需要实现,computeCodeVision做了相同的事情public CodeVisionPlaceholderCollector getPlaceholderCollector(@NotNull Editor editor, @Nullable PsiFile psiFile) {return null;}@NotNull@Override@Deprecated(message = "Use computeCodeVision instead")// 已被废弃,不用实现public List<Pair<TextRange, CodeVisionEntry>> computeForEditor(@NotNull Editor editor, Unit uiData) {return List.of();}@NotNull@Overridepublic CodeVisionState computeCodeVision(@NotNull Editor editor, Unit uiData) {List<PsiMethod> psiMethods = getPsiMethods(editor);List<Pair<TextRange, CodeVisionEntry>> lenses = new ArrayList<>();for (PsiMethod psiMethod : psiMethods) {TextRange range = InlayHintsUtils.INSTANCE.getTextRangeWithoutLeadingCommentsAndWhitespaces(psiMethod);MyClickHandler handler = new MyClickHandler(psiMethod);CodeVisionEntry entry = new ClickableTextCodeVisionEntry(getName(), getId(), handler, null, getName(), getName(), List.of());lenses.add(new Pair<>(range, entry));}return new CodeVisionState.Ready(lenses);}private List<PsiMethod> getPsiMethods(Editor editor) {return ApplicationManager.getApplication().runReadAction((Computable<List<PsiMethod>>) () -> {List<PsiMethod> psiMethods = new ArrayList<>();PsiFile psiFile = PsiDocumentManager.getInstance(Objects.requireNonNull(editor.getProject())).getPsiFile(editor.getDocument());if (psiFile == null) {return psiMethods;}List<Pair<TextRange, CodeVisionEntry>> lenses = new ArrayList<>();SyntaxTraverser<PsiElement> traverser = SyntaxTraverser.psiTraverser(psiFile);for (PsiElement element : traverser) {if (!(element instanceof PsiMethod)) {continue;}if (!InlayHintsUtils.isFirstInLine(element)) {continue;}psiMethods.add((PsiMethod)element);}return psiMethods;});}@Overridepublic void handleClick(@NotNull Editor editor, @NotNull TextRange textRange, @NotNull CodeVisionEntry entry) {if (entry instanceof CodeVisionPredefinedActionEntry) {((CodeVisionPredefinedActionEntry)entry).onClick(editor);}}@Overridepublic void handleExtraAction(@NotNull Editor editor, @NotNull TextRange textRange, @NotNull String s) {}@Overridepublic Unit precomputeOnUiThread(@NotNull Editor editor) {return null;}@Overridepublic boolean shouldRecomputeForEditor(@NotNull Editor editor, @Nullable Unit uiData) {return ApplicationManager.getApplication().runReadAction((Computable<Boolean>) () -> {if (editor.isDisposed() || !editor.isInsertMode()) {return false;}Project project = editor.getProject();if (project == null) {return false;}Document document = editor.getDocument();PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(document);if (psiFile == null) {return false;}String languageId = psiFile.getLanguage().getID();if (!"JAVA".equalsIgnoreCase(languageId)) {return false;}Long prevStamp = MODIFICATION_STAMP_KEY.get(editor);long nowStamp = getDocumentStamp(editor.getDocument());if (prevStamp == null || prevStamp != nowStamp) {Integer count = MODIFICATION_STAMP_COUNT_KEY.get(editor);if (count + 1 < MAX_MODIFICATION_STAMP_COUNT) {MODIFICATION_STAMP_COUNT_KEY.set(editor, count + 1);return true;} else {MODIFICATION_STAMP_COUNT_KEY.set(editor, 0);MODIFICATION_STAMP_KEY.set(editor, nowStamp);return true;}}return false;});}private static long getDocumentStamp(@NotNull Document document) {if (document instanceof DocumentEx) {return ((DocumentEx)document).getModificationSequence();}return document.getModificationStamp();}@RequiredArgsConstructorstatic class MyClickHandler implements Function2<MouseEvent, Editor, Unit> {private final PsiMethod psiMethod;public Unit invoke(MouseEvent event, Editor editor) {TextRange range = InlayHintsUtils.INSTANCE.getTextRangeWithoutLeadingCommentsAndWhitespaces(psiMethod);int startOffset = range.getStartOffset();int endOffset = range.getEndOffset();editor.getSelectionModel().setSelection(startOffset, endOffset);AnAction action1 = ActionManager.getInstance().getAction("MyPlugin.Action1");AnAction action2 = ActionManager.getInstance().getAction("MyPlugin.Action2");DefaultActionGroup actionGroup = new DefaultActionGroup(List.of(action1, action2));ListPopup popup = JBPopupFactory.getInstance().createActionGroupPopup(null, actionGroup, EditorUtil.getEditorDataContext(editor), JBPopupFactory.ActionSelectionAid.SPEEDSEARCH, true);popup.show(new RelativePoint(event));return null;}}
}
  1. 注册CodeVisionProviders实现类
<idea-plugin><extensions defaultExtensionNs="com.intellij"><codeInsight.codeVisionProvider implementation="com.demo.MyCodeVisionProvider"/></extensions>
</idea-plugin>

参考文献

Code Vision Provider

这篇关于IntelliJ插件开发-Code Vision Hints的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/506092

相关文章

基于Python开发PDF转Doc格式小程序

《基于Python开发PDF转Doc格式小程序》这篇文章主要为大家详细介绍了如何基于Python开发PDF转Doc格式小程序,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 用python实现PDF转Doc格式小程序以下是一个使用Python实现PDF转DOC格式的GUI程序,采用T

使用Python开发一个图像标注与OCR识别工具

《使用Python开发一个图像标注与OCR识别工具》:本文主要介绍一个使用Python开发的工具,允许用户在图像上进行矩形标注,使用OCR对标注区域进行文本识别,并将结果保存为Excel文件,感兴... 目录项目简介1. 图像加载与显示2. 矩形标注3. OCR识别4. 标注的保存与加载5. 裁剪与重置图像

Android开发中gradle下载缓慢的问题级解决方法

《Android开发中gradle下载缓慢的问题级解决方法》本文介绍了解决Android开发中Gradle下载缓慢问题的几种方法,本文给大家介绍的非常详细,感兴趣的朋友跟随小编一起看看吧... 目录一、网络环境优化二、Gradle版本与配置优化三、其他优化措施针对android开发中Gradle下载缓慢的问

使用Go语言开发一个命令行文件管理工具

《使用Go语言开发一个命令行文件管理工具》这篇文章主要为大家详细介绍了如何使用Go语言开发一款命令行文件管理工具,支持批量重命名,删除,创建,移动文件,需要的小伙伴可以了解下... 目录一、工具功能一览二、核心代码解析1. 主程序结构2. 批量重命名3. 批量删除4. 创建文件/目录5. 批量移动三、如何安

Android 悬浮窗开发示例((动态权限请求 | 前台服务和通知 | 悬浮窗创建 )

《Android悬浮窗开发示例((动态权限请求|前台服务和通知|悬浮窗创建)》本文介绍了Android悬浮窗的实现效果,包括动态权限请求、前台服务和通知的使用,悬浮窗权限需要动态申请并引导... 目录一、悬浮窗 动态权限请求1、动态请求权限2、悬浮窗权限说明3、检查动态权限4、申请动态权限5、权限设置完毕后

基于Python开发PPTX压缩工具

《基于Python开发PPTX压缩工具》在日常办公中,PPT文件往往因为图片过大而导致文件体积过大,不便于传输和存储,所以本文将使用Python开发一个PPTX压缩工具,需要的可以了解下... 目录引言全部代码环境准备代码结构代码实现运行结果引言在日常办公中,PPT文件往往因为图片过大而导致文件体积过大,

使用DeepSeek API 结合VSCode提升开发效率

《使用DeepSeekAPI结合VSCode提升开发效率》:本文主要介绍DeepSeekAPI与VisualStudioCode(VSCode)结合使用,以提升软件开发效率,具有一定的参考价值... 目录引言准备工作安装必要的 VSCode 扩展配置 DeepSeek API1. 创建 API 请求文件2.

基于Python开发电脑定时关机工具

《基于Python开发电脑定时关机工具》这篇文章主要为大家详细介绍了如何基于Python开发一个电脑定时关机工具,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1. 简介2. 运行效果3. 相关源码1. 简介这个程序就像一个“忠实的管家”,帮你按时关掉电脑,而且全程不需要你多做

Java中的Opencv简介与开发环境部署方法

《Java中的Opencv简介与开发环境部署方法》OpenCV是一个开源的计算机视觉和图像处理库,提供了丰富的图像处理算法和工具,它支持多种图像处理和计算机视觉算法,可以用于物体识别与跟踪、图像分割与... 目录1.Opencv简介Opencv的应用2.Java使用OpenCV进行图像操作opencv安装j

使用IntelliJ IDEA创建简单的Java Web项目完整步骤

《使用IntelliJIDEA创建简单的JavaWeb项目完整步骤》:本文主要介绍如何使用IntelliJIDEA创建一个简单的JavaWeb项目,实现登录、注册和查看用户列表功能,使用Se... 目录前置准备项目功能实现步骤1. 创建项目2. 配置 Tomcat3. 项目文件结构4. 创建数据库和表5.