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 开发 Spring Boot 项目详细攻略

《基于Cursor开发SpringBoot项目详细攻略》Cursor是集成GPT4、Claude3.5等LLM的VSCode类AI编程工具,支持SpringBoot项目开发全流程,涵盖环境配... 目录cursor是什么?基于 Cursor 开发 Spring Boot 项目完整指南1. 环境准备2. 创建

SpringBoot 多环境开发实战(从配置、管理与控制)

《SpringBoot多环境开发实战(从配置、管理与控制)》本文详解SpringBoot多环境配置,涵盖单文件YAML、多文件模式、MavenProfile分组及激活策略,通过优先级控制灵活切换环境... 目录一、多环境开发基础(单文件 YAML 版)(一)配置原理与优势(二)实操示例二、多环境开发多文件版

使用docker搭建嵌入式Linux开发环境

《使用docker搭建嵌入式Linux开发环境》本文主要介绍了使用docker搭建嵌入式Linux开发环境,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面... 目录1、前言2、安装docker3、编写容器管理脚本4、创建容器1、前言在日常开发全志、rk等不同

RabbitMQ 延时队列插件安装与使用示例详解(基于 Delayed Message Plugin)

《RabbitMQ延时队列插件安装与使用示例详解(基于DelayedMessagePlugin)》本文详解RabbitMQ通过安装rabbitmq_delayed_message_exchan... 目录 一、什么是 RabbitMQ 延时队列? 二、安装前准备✅ RabbitMQ 环境要求 三、安装延时队

Python实战之SEO优化自动化工具开发指南

《Python实战之SEO优化自动化工具开发指南》在数字化营销时代,搜索引擎优化(SEO)已成为网站获取流量的重要手段,本文将带您使用Python开发一套完整的SEO自动化工具,需要的可以了解下... 目录前言项目概述技术栈选择核心模块实现1. 关键词研究模块2. 网站技术seo检测模块3. 内容优化分析模

Mac电脑如何通过 IntelliJ IDEA 远程连接 MySQL

《Mac电脑如何通过IntelliJIDEA远程连接MySQL》本文详解Mac通过IntelliJIDEA远程连接MySQL的步骤,本文通过图文并茂的形式给大家介绍的非常详细,感兴趣的朋友跟... 目录MAC电脑通过 IntelliJ IDEA 远程连接 mysql 的详细教程一、前缀条件确认二、打开 ID

解决Nginx启动报错Job for nginx.service failed because the control process exited with error code问题

《解决Nginx启动报错Jobfornginx.servicefailedbecausethecontrolprocessexitedwitherrorcode问题》Nginx启... 目录一、报错如下二、解决原因三、解决方式总结一、报错如下Job for nginx.service failed bec

基于Java开发一个极简版敏感词检测工具

《基于Java开发一个极简版敏感词检测工具》这篇文章主要为大家详细介绍了如何基于Java开发一个极简版敏感词检测工具,文中的示例代码简洁易懂,感兴趣的小伙伴可以跟随小编一起学习一下... 目录你是否还在为敏感词检测头疼一、极简版Java敏感词检测工具的3大核心优势1.1 优势1:DFA算法驱动,效率提升10

Python开发简易网络服务器的示例详解(新手入门)

《Python开发简易网络服务器的示例详解(新手入门)》网络服务器是互联网基础设施的核心组件,它本质上是一个持续运行的程序,负责监听特定端口,本文将使用Python开发一个简单的网络服务器,感兴趣的小... 目录网络服务器基础概念python内置服务器模块1. HTTP服务器模块2. Socket服务器模块

Java 与 LibreOffice 集成开发指南(环境搭建及代码示例)

《Java与LibreOffice集成开发指南(环境搭建及代码示例)》本文介绍Java与LibreOffice的集成方法,涵盖环境配置、API调用、文档转换、UNO桥接及REST接口等技术,提供... 目录1. 引言2. 环境搭建2.1 安装 LibreOffice2.2 配置 Java 开发环境2.3 配