前端人开发intellij插件,一边哭一边学java...
API
PSI
PSI
(Program Structure Interface) 文件是表示一个文件的内容作为在一个特定的编程语言元素的层次结构的结构的根。
PsiFile 类是所有PSI文件共同的基类, 在特定语言中的文件通常使用它的子类表示。比如,PsiJavaFile 类表示一个java文件, XmlFile 类表示xml文件。
和 VirtualFile
以及 Document
的应用作用域不同(即使打开多个projects,仍然只有一个对应的实例),PSI的作用域是项目级(多个projects中同时打开同一个文件,会有多个实例)。
如何获取PSI文件?
e.getData(PlatformDataKeys.VIRTUAL_FILE)
,如果是多选,使用e.getData(PlatformDataKeys.VIRTUAL_FILE_ARRAY)LocalFileSystem.getInstance().findFileByIoFile()
psiFile.getVirtualFile()
,如果PSI FILE仅存在内存中,则返回空FileDocumentManager.getInstance().getFile()
监听文件改变
PsiTreeChangeListener
BulkFileListener 批量文件监听
1.添加
beforeChildrenChange
beforeChildAddition
beforeChildAddition
beforeChildAddition
childAdded
childAdded
childAdded
childrenChanged
2.删除
beforeChildrenChange
beforeChildRemoval
beforeChildRemoval
beforeChildRemoval
childRemoved
childRemoved
childRemoved
childrenChanged
3.修改名称
propertyChanged
childrenChanged
System.out.println("------"+e.getPropertyName());
// getPropertyName == fileName
System.out.println("e.getOldValue()"+e.getOldValue());
System.out.println("e.getNewValue()"+e.getNewValue());
监听文件打开
FileEditorManagerListener
配置
右键菜单
tools工具栏
快捷键
action分组
获取选中文本
public class PopupAction extends AnAction {
@Override
public void actionPerformed(AnActionEvent e) {
//获取当前编辑器对象
Editor editor = e.getRequiredData(CommonDataKeys.EDITOR);
//获取选择的数据模型
SelectionModel selectionModel = editor.getSelectionModel();
//获取当前选择的文本
String selectedText = selectionModel.getSelectedText();
System.out.println(selectedText);
}
}
用户选择文档生成目录
createBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
VirtualFile virtualFile = FileChooser.chooseFile(FileChooserDescriptorFactory.createSingleFolderDescriptor(), project, project.getBaseDir());
if(virtualFile!=null){
String path = virtualFile.getPath();
System.out.println(path);
}
}
});
行标记
public class HaloLineMarker implements LineMarkerProvider {
@Nullable
@Override
public LineMarkerInfo getLineMarkerInfo(@NotNull PsiElement psiElement) {
LineMarkerInfo lineMarkerInfo= null;
try {
lineMarkerInfo = null;
String anno="org.springframework.boot.autoconfigure.SpringBootApplication";
if(!judgeHaveAnnotation(psiElement,anno)){
return lineMarkerInfo;
}
PsiClassImpl field = ((PsiClassImpl) psiElement);
PsiAnnotation psiAnnotation = field.getAnnotation(anno);
lineMarkerInfo = new LineMarkerInfo<>(psiAnnotation, psiAnnotation.getTextRange(), IconLoader.findIcon("/icons/right/HaloBasic.png"),
new FunctionTooltip("快速导航"),
new AppMgmtNavigationHandler(),
GutterIconRenderer.Alignment.LEFT);
} catch (Exception e) {
e.printStackTrace();
}
return lineMarkerInfo;
}
@Override
public void collectSlowLineMarkers(@NotNull List list, @NotNull Collection collection) {
}
private boolean judgeHaveAnnotation(@NotNull PsiElement psiElement, String anno) {
if (psiElement instanceof PsiClass) {
PsiClassImpl field = ((PsiClassImpl) psiElement);
PsiAnnotation psiAnnotation = field.getAnnotation(anno);
if (null != psiAnnotation) {
return true;
}
return false;
}
return false;
}
}
生成文档
public interface Processor{
public void process(SourceNoteData sourceNoteData) throws Exception;
}
编写Freemarker的抽象类
public abstract class AbstractFreeMarkerProcessor implements Processor{
protected abstract Template getTemplate() throws IOException, Exception;
protected abstract Object getModel(SourceNoteData sourceNoteData);
protected abstract Writer getWriter(SourceNoteData sourceNoteData) throws FileNotFoundException, Exception;
@Override
public final void process(SourceNoteData sourceNoteData) throws Exception{
Template template = getTemplate();
Object model = getModel(sourceNoteData);
Writer writer = getWriter(sourceNoteData);
template.process(model, writer);
}
}
编写MDFreeMarkProcessor继承AbstractFreeMarkerProcessor。实现抽象方法
public class MDFreeMarkProcessor extends AbstractFreeMarkerProcessor{
@Override
protected Template getTemplate() throws Exception{
//加载模板字符串
String templateString = UrlUtil.loadText(MDFreeMarkProcessor.class.getResource("/template/md.ftl"));
//创建模板配置
Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);
//创建字符串模板的导入器
StringTemplateLoader stringTemplateLoader=new StringTemplateLoader();
//导入字符串模板
stringTemplateLoader.putTemplate("MDTemplate",templateString);
configuration.setTemplateLoader(stringTemplateLoader);
//获取模板
return configuration.getTemplate("MDTemplate");
}
@Override
protected Object getModel(SourceNoteData sourceNoteData){
HashMap model = new HashMap();
model.put("topic",sourceNoteData.getNoteTopic());
model.put("noteList",sourceNoteData.getNoteDataList());
return model;
}
@Override
protected Writer getWriter(SourceNoteData sourceNoteData) throws Exception{
String filePath = sourceNoteData.getFilePath();
File file = new File(filePath);
return new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file),"utf-8"));
}
}
添加处理操作
createBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e){
VirtualFile virtualFile = FileChooser.chooseFile(FileChooserDescriptorFactory.createSingleFolderDescriptor(), project, project.getBaseDir());
if (virtualFile != null) {
String path = virtualFile.getPath();
String topic = topicEtf.getText();
String filePath = path + "/" + topic + ".md";
Processor processor = new MDFreeMarkProcessor();
try {
processor.process(new DefaultSourceNoteData(topic, filePath, DataCenter.NOTE_LIST));
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
});
粘贴
CopyPasteManager.getInstance().setContents(new StringSelection(xml));
CopyPasteManager.getInstance().setContents(new SimpleTransferable(table.toString(), DataFlavor.allHtmlFlavor));
界面
下拉框
private JComboBox kind;
kind.addItem(seleType);
kind.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
SelectedTypeModel selectedTypeModel = (SelectedTypeModel) e.getItem();
switch (selectedTypeModel.getValue()) {
case HaloConstant.COMBOX_CONTROLLER:
NewRightContext.setClassType(HaloConstant.COMBOX_CONTROLLER);
break;
default:
NewRightContext.setClassType(null);
}![在这里插入图片描述](https://gitee.com/Lovxy/private-notes/raw/master/doc/show.gif#pic_center)
}
});
通知
NotificationGroup notificationGroup = new NotificationGroup("testid", NotificationDisplayType.BALLOON, false);
/**
* content : 通知内容
* type :通知的类型,warning,info,error
*/
Notification notification = notificationGroup.createNotification("测试通知", MessageType.INFO);
Notifications.Bus.notify(notification);
非模态框式通知
NotificationGroup notificationGroup = new NotificationGroup("notificationGroup", NotificationDisplayType.BALLOON, true);
Notification notification = notificationGroup.createNotification("notification",NotificationType.ERROR);
Notifications.Bus.notify(notification);
高版本不兼容NotificationGroup 直接采用 new Notification
Notification notification = new Notification("PNGroup", "Private Notes Message", content, type);
其中,NotificationDisplayType
可以是以下几种:
NONE
:无弹框,不展示BALLOON
:自动消失STICKY_BALLOON
:用户点击关闭按钮消失TOOL_WINDOW
:实例效果同STICKY_BALLOON
Toast
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.ui.popup.Balloon;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.wm.StatusBar;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.ui.awt.RelativePoint;
import javax.swing.*;
public class Toast {
/**
* Display simple notification of given type
*
* @param jComponent
* @param type
* @param text
*/
public static void make(JComponent jComponent, MessageType type, String text) {
JBPopupFactory.getInstance()
.createHtmlTextBalloonBuilder(text, type, null)
.setFadeoutTime(7500)
.createBalloon()
.show(RelativePoint.getCenterOf(jComponent), Balloon.Position.above);
}
/**
* Display simple notification of given type
*
* @param project
* @param type
* @param text
*/
public static void make(Project project, MessageType type, String text) {
StatusBar statusBar = WindowManager.getInstance().getStatusBar(project);
JBPopupFactory.getInstance()
.createHtmlTextBalloonBuilder(text, type, null)
.setFadeoutTime(7500)
.createBalloon()
.show(RelativePoint.getCenterOf(statusBar.getComponent()), Balloon.Position.atRight);
}
}
持久化
ApplicationSettingsConfigurable
是settins配置页面
// ConfigPersistence
/**
* 配置持久化
*/
@State(name = "yapi2ts", storages = {@Storage(value = "yapi2ts.xml")})
public class ConfigPersistence implements PersistentStateComponent {
private MyPersistenceConfiguration config;
@Nullable
@Override
public MyPersistenceConfiguration getState() {
if (config == null) {
config = new MyPersistenceConfiguration();
List configDTOS = new ArrayList<>();
config.setConfigs(configDTOS);
}
return config;
}
public static ConfigPersistence getInstance() {
return ApplicationManager.getApplication().getService(ConfigPersistence.class);
}
@Override
public void loadState(@NotNull MyPersistenceConfiguration state) {
XmlSerializerUtil.copyBean(state, Objects.requireNonNull(getState()));
}
}
public class MyPersistenceConfiguration {
private List configs;
public List getConfigs() {
return configs;
}
public void setConfigs(List configs) {
this.configs = configs;
}
}
实战
开发了一个idea 小插件,可以在编辑器里面输入yapi文档接口详情的链接自动生成所需要的请求体ts类型或者返回数据的ts类型,提高前端开发者的工具效率。
安装
Using IDE built-in plugin system:
Settings/Preferences > Plugins > Marketplace > Search for "yapi2ts" >
Install Plugin
使用前注意
!!!务必先配置项目token: settings -> tools -> yapi2ts