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

相关文章

浏览器插件cursor实现自动注册、续杯的详细过程

《浏览器插件cursor实现自动注册、续杯的详细过程》Cursor简易注册助手脚本通过自动化邮箱填写和验证码获取流程,大大简化了Cursor的注册过程,它不仅提高了注册效率,还通过友好的用户界面和详细... 目录前言功能概述使用方法安装脚本使用流程邮箱输入页面验证码页面实战演示技术实现核心功能实现1. 随机

SpringBoot开发中十大常见陷阱深度解析与避坑指南

《SpringBoot开发中十大常见陷阱深度解析与避坑指南》在SpringBoot的开发过程中,即使是经验丰富的开发者也难免会遇到各种棘手的问题,本文将针对SpringBoot开发中十大常见的“坑... 目录引言一、配置总出错?是不是同时用了.properties和.yml?二、换个位置配置就失效?搞清楚加

Python中对FFmpeg封装开发库FFmpy详解

《Python中对FFmpeg封装开发库FFmpy详解》:本文主要介绍Python中对FFmpeg封装开发库FFmpy,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐... 目录一、FFmpy简介与安装1.1 FFmpy概述1.2 安装方法二、FFmpy核心类与方法2.1 FF

基于Python开发Windows屏幕控制工具

《基于Python开发Windows屏幕控制工具》在数字化办公时代,屏幕管理已成为提升工作效率和保护眼睛健康的重要环节,本文将分享一个基于Python和PySide6开发的Windows屏幕控制工具,... 目录概述功能亮点界面展示实现步骤详解1. 环境准备2. 亮度控制模块3. 息屏功能实现4. 息屏时间

Python实例题之pygame开发打飞机游戏实例代码

《Python实例题之pygame开发打飞机游戏实例代码》对于python的学习者,能够写出一个飞机大战的程序代码,是不是感觉到非常的开心,:本文主要介绍Python实例题之pygame开发打飞机... 目录题目pygame-aircraft-game使用 Pygame 开发的打飞机游戏脚本代码解释初始化部

使用Python开发一个现代化屏幕取色器

《使用Python开发一个现代化屏幕取色器》在UI设计、网页开发等场景中,颜色拾取是高频需求,:本文主要介绍如何使用Python开发一个现代化屏幕取色器,有需要的小伙伴可以参考一下... 目录一、项目概述二、核心功能解析2.1 实时颜色追踪2.2 智能颜色显示三、效果展示四、实现步骤详解4.1 环境配置4.

Python使用smtplib库开发一个邮件自动发送工具

《Python使用smtplib库开发一个邮件自动发送工具》在现代软件开发中,自动化邮件发送是一个非常实用的功能,无论是系统通知、营销邮件、还是日常工作报告,Python的smtplib库都能帮助我们... 目录代码实现与知识点解析1. 导入必要的库2. 配置邮件服务器参数3. 创建邮件发送类4. 实现邮件

CnPlugin是PL/SQL Developer工具插件使用教程

《CnPlugin是PL/SQLDeveloper工具插件使用教程》:本文主要介绍CnPlugin是PL/SQLDeveloper工具插件使用教程,具有很好的参考价值,希望对大家有所帮助,如有错... 目录PL/SQL Developer工具插件使用安装拷贝文件配置总结PL/SQL Developer工具插

基于Python开发一个有趣的工作时长计算器

《基于Python开发一个有趣的工作时长计算器》随着远程办公和弹性工作制的兴起,个人及团队对于工作时长的准确统计需求日益增长,本文将使用Python和PyQt5打造一个工作时长计算器,感兴趣的小伙伴可... 目录概述功能介绍界面展示php软件使用步骤说明代码详解1.窗口初始化与布局2.工作时长计算核心逻辑3

maven中的maven-antrun-plugin插件示例详解

《maven中的maven-antrun-plugin插件示例详解》maven-antrun-plugin是Maven生态中一个强大的工具,尤其适合需要复用Ant脚本或实现复杂构建逻辑的场景... 目录1. 核心功能2. 典型使用场景3. 配置示例4. 关键配置项5. 优缺点分析6. 最佳实践7. 常见问题