环境准备

  • IntelliJ IDEA并安装Plugin DevKit插件 idea
  • JDK8

基于Gradle创建plugin项目

  1. File->New->Projects step1
  2. Next step2
  3. Next step3
  4. Next && Finish step4

修改build.gradle文件

打开build.gradle文件可以查看到当前idea版本是2018.3.6。且可以看到idea推荐的Gradle版本为4.10 versions 此时项目在自动构建时会失败,因为gradle-intellij-plugin版本为1.3.1和Gradle版本不匹配,需要修改合适的gradle-intellij-plugin版本。根据gradle-intellij-plugin查看到4.10的Gradle可以使用0.7.3gradle-intellij-plugin github-tags idea-plugin-version build.gradle修改后项目构建成功 build-success 至此,我们项目插件项目创建完成了。

翻译插件

创建Action

create-action definition-action

查看创建结果

action plugin-xml

编写翻译逻辑

public void actionPerformed(AnActionEvent e) {
    Editor editor = e.getDataContext().getData(CommonDataKeys.EDITOR);
    String q = editor.getSelectionModel().getSelectedText();
    String appId = "20190717000318901";
    String appKey = "R8OPnhJn7TP2m2n4g7za";
    String salt = RandomUtil.randomNumbers(3);
    MD5 md5 = MD5.create();
    String sign = md5.digestHex(appId + q + salt + appKey);

    String transUrl = "https://fanyi-api.baidu.com/api/trans/vip/translate";
    HttpGet httpGet = new HttpGet(transUrl + "?q=" + q
        + "&from=en&to=zh"
        + "&appid=" + appId
        + "&salt=" + salt
        + "&sign=" + sign);
    try (CloseableHttpClient httpclient = HttpClients.createDefault();
        CloseableHttpResponse response = httpclient.execute(httpGet)) {
        HttpEntity entity = response.getEntity();
        InputStream content = entity.getContent();
        String text = new BufferedReader(new InputStreamReader(content, StandardCharsets.UTF_8))
            .lines().collect(Collectors.joining("\n"));
        ResultSet resultSet = JSONUtil.toBean(text, ResultSet.class);
        if (CollUtil.isNotEmpty(resultSet.getTrans_result())) {
            Notifications.Bus.notify(buildNotification(resultSet.getTrans_result().get(0).getDst(), NotificationType.INFORMATION));
        }
    } catch (Exception ex) {
        //
    }
}

private Notification buildNotification(String content, NotificationType type) {
    String groupDisplayId = "translation";
    Notification notification = new Notification(groupDisplayId, null, type);
    notification.setContent(content);
    return notification;
}

runIde & 测试

run test1 test2

插件安装

buildPlugin

build zip-file

install

install 选择生成的zip文件后,重启idea即可。