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

相关文章

使用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.

基于Qt开发一个简单的OFD阅读器

《基于Qt开发一个简单的OFD阅读器》这篇文章主要为大家详细介绍了如何使用Qt框架开发一个功能强大且性能优异的OFD阅读器,文中的示例代码讲解详细,有需要的小伙伴可以参考一下... 目录摘要引言一、OFD文件格式解析二、文档结构解析三、页面渲染四、用户交互五、性能优化六、示例代码七、未来发展方向八、结论摘要

在 VSCode 中配置 C++ 开发环境的详细教程

《在VSCode中配置C++开发环境的详细教程》本文详细介绍了如何在VisualStudioCode(VSCode)中配置C++开发环境,包括安装必要的工具、配置编译器、设置调试环境等步骤,通... 目录如何在 VSCode 中配置 C++ 开发环境:详细教程1. 什么是 VSCode?2. 安装 VSCo

IDEA常用插件之代码扫描SonarLint详解

《IDEA常用插件之代码扫描SonarLint详解》SonarLint是一款用于代码扫描的插件,可以帮助查找隐藏的bug,下载并安装插件后,右键点击项目并选择“Analyze”、“Analyzewit... 目录SonajavascriptrLint 查找隐藏的bug下载安装插件扫描代码查看结果总结Sona

C#图表开发之Chart详解

《C#图表开发之Chart详解》C#中的Chart控件用于开发图表功能,具有Series和ChartArea两个重要属性,Series属性是SeriesCollection类型,包含多个Series对... 目录OverviChina编程ewSeries类总结OverviewC#中,开发图表功能的控件是Char

鸿蒙开发搭建flutter适配的开发环境

《鸿蒙开发搭建flutter适配的开发环境》文章详细介绍了在Windows系统上如何创建和运行鸿蒙Flutter项目,包括使用flutterdoctor检测环境、创建项目、编译HAP包以及在真机上运... 目录环境搭建创建运行项目打包项目总结环境搭建1.安装 DevEco Studio NEXT IDE

Python开发围棋游戏的实例代码(实现全部功能)

《Python开发围棋游戏的实例代码(实现全部功能)》围棋是一种古老而复杂的策略棋类游戏,起源于中国,已有超过2500年的历史,本文介绍了如何用Python开发一个简单的围棋游戏,实例代码涵盖了游戏的... 目录1. 围棋游戏概述1.1 游戏规则1.2 游戏设计思路2. 环境准备3. 创建棋盘3.1 棋盘类