代码拉取完成,页面将自动刷新
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,
};
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。