加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
extension.js 2.33 KB
一键复制 编辑 原始数据 按行查看 历史
LiJun 提交于 2022-06-08 18:33 . 修改翻译显示
const vscode = require("vscode");
const axios = require("axios");
const qs = require("qs");
async function youdaoTranslate(text) {
var args = {
keyfrom: "YouDaoCV",
key: "659600698",
type: "data",
doctype: "json",
version: "1.1",
q: text,
};
return new Promise((resolve, reject) => {
var url = "http://fanyi.youdao.com/openapi.do";
axios
.post(url, qs.stringify(args), {})
.then((res) => {
try {
resolve(res.data.translation[0]);
} catch (error) {
resolve("单词未找到释义");
}
})
.catch((err) => {
console.log(err);
reject(err.data);
});
});
}
//缓存
let Cache = [];
let translate = "";
/**
* @param {vscode.ExtensionContext} context
*/
function activate(context) {
console.log('Congratulations, your extension "ztrans" is now active!');
let disposable = vscode.commands.registerCommand(
"ztrans.translate",
async () => {
const { activeTextEditor } = vscode.window; //获取当前聚焦的文本编辑器
const currentSelect = activeTextEditor.document.getText(
activeTextEditor.selection
); //根据范围选取文本
let result = await youdaoTranslate(currentSelect);
//转换驼峰
result = result
.split(" ")
.map((v, i) => {
return i !== 0
? v.charAt(0).toLocaleUpperCase() + v.slice(1).toLocaleLowerCase()
: v.toLocaleLowerCase();
})
.join("")
.replace(/[.,;':]/g, "");
activeTextEditor.edit((editBuilder) => {
editBuilder.replace(activeTextEditor.selection, result); //将翻译内容替换
});
}
);
//悬浮翻译
vscode.languages.registerHoverProvider("*", {
provideHover: async (document, position) => {
const word = document.getText(document.getWordRangeAtPosition(position)); //获取悬浮区域文本
if (word in Cache) {
translate = Cache[word]; //读取缓存的翻译
} else {
translate = await youdaoTranslate(word);
Cache[word] = "[cache] " + translate;
}
return new vscode.Hover("中文翻译: " + translate);
},
});
context.subscriptions.push(disposable);
}
// this method is called when your extension is deactivated
function deactivate() {}
module.exports = {
activate,
deactivate,
};
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化