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开发一个带EPUB转换功能的Markdown编辑器

《使用Python开发一个带EPUB转换功能的Markdown编辑器》Markdown因其简单易用和强大的格式支持,成为了写作者、开发者及内容创作者的首选格式,本文将通过Python开发一个Markd... 目录应用概览代码结构与核心组件1. 初始化与布局 (__init__)2. 工具栏 (setup_t

Spring Shell 命令行实现交互式Shell应用开发

《SpringShell命令行实现交互式Shell应用开发》本文主要介绍了SpringShell命令行实现交互式Shell应用开发,能够帮助开发者快速构建功能丰富的命令行应用程序,具有一定的参考价... 目录引言一、Spring Shell概述二、创建命令类三、命令参数处理四、命令分组与帮助系统五、自定义S

Python通过模块化开发优化代码的技巧分享

《Python通过模块化开发优化代码的技巧分享》模块化开发就是把代码拆成一个个“零件”,该封装封装,该拆分拆分,下面小编就来和大家简单聊聊python如何用模块化开发进行代码优化吧... 目录什么是模块化开发如何拆分代码改进版:拆分成模块让模块更强大:使用 __init__.py你一定会遇到的问题模www.

Spring Security基于数据库的ABAC属性权限模型实战开发教程

《SpringSecurity基于数据库的ABAC属性权限模型实战开发教程》:本文主要介绍SpringSecurity基于数据库的ABAC属性权限模型实战开发教程,本文给大家介绍的非常详细,对大... 目录1. 前言2. 权限决策依据RBACABAC综合对比3. 数据库表结构说明4. 实战开始5. MyBA

使用Python开发一个简单的本地图片服务器

《使用Python开发一个简单的本地图片服务器》本文介绍了如何结合wxPython构建的图形用户界面GUI和Python内建的Web服务器功能,在本地网络中搭建一个私人的,即开即用的网页相册,文中的示... 目录项目目标核心技术栈代码深度解析完整代码工作流程主要功能与优势潜在改进与思考运行结果总结你是否曾经

Spring Boot + MyBatis Plus 高效开发实战从入门到进阶优化(推荐)

《SpringBoot+MyBatisPlus高效开发实战从入门到进阶优化(推荐)》本文将详细介绍SpringBoot+MyBatisPlus的完整开发流程,并深入剖析分页查询、批量操作、动... 目录Spring Boot + MyBATis Plus 高效开发实战:从入门到进阶优化1. MyBatis

Python基于wxPython和FFmpeg开发一个视频标签工具

《Python基于wxPython和FFmpeg开发一个视频标签工具》在当今数字媒体时代,视频内容的管理和标记变得越来越重要,无论是研究人员需要对实验视频进行时间点标记,还是个人用户希望对家庭视频进行... 目录引言1. 应用概述2. 技术栈分析2.1 核心库和模块2.2 wxpython作为GUI选择的优

利用Python开发Markdown表格结构转换为Excel工具

《利用Python开发Markdown表格结构转换为Excel工具》在数据管理和文档编写过程中,我们经常使用Markdown来记录表格数据,但它没有Excel使用方便,所以本文将使用Python编写一... 目录1.完整代码2. 项目概述3. 代码解析3.1 依赖库3.2 GUI 设计3.3 解析 Mark

利用Go语言开发文件操作工具轻松处理所有文件

《利用Go语言开发文件操作工具轻松处理所有文件》在后端开发中,文件操作是一个非常常见但又容易出错的场景,本文小编要向大家介绍一个强大的Go语言文件操作工具库,它能帮你轻松处理各种文件操作场景... 目录为什么需要这个工具?核心功能详解1. 文件/目录存javascript在性检查2. 批量创建目录3. 文件

基于Python开发批量提取Excel图片的小工具

《基于Python开发批量提取Excel图片的小工具》这篇文章主要为大家详细介绍了如何使用Python中的openpyxl库开发一个小工具,可以实现批量提取Excel图片,有需要的小伙伴可以参考一下... 目前有一个需求,就是批量读取当前目录下所有文件夹里的Excel文件,去获取出Excel文件中的图片,并