“This is the first day of my participation in the First Challenge 2022. For details: First Challenge 2022”

preface

When it comes to which plug-in improves productivity the most, there may be different recommendations. But I would like to say that for beginners, as well as students with a little poor English: translation is an essential part of daily development. After searching N VSCode translation plug-ins, I found a magic artifact:

VSCode Extension: Google Translate Extension

Unlike other Hanhan plug-ins, which require either scientific Internet access or strongly bound shortcuts, this plugin has the most intuitive function: select hover translation

This… That’s cheating. Programming ability +1s.

Since I have been engaged in the secondary/plug-in development of VSCode for the past two years, this function is very popular in my heart, so I want to make a little effort to see if I can learn from it

Don’t talk, do it!

1. Code catalog analysis

The code logic is in the SRC directory.

command.js // All commands
extension.js // Plug-in entry file
tranlate.js // The translation tool function
Copy the code

Start with the entry file extension.js:

// The module 'vscode' contains the VS Code extensibility API // Import the module and reference it with the alias vscode in your code below const command = require('./command') function activate(context) { console.log('Congratulations, your extension "vsc-google-translate" is now active! '); command.initSetting(context); context.subscriptions.push(command.hoverDisposable); context.subscriptions.push(command.tranDisposable); context.subscriptions.push(command.switchDisposable); context.subscriptions.push(command.copyDisposable); context.subscriptions.push(command.replaceDisposable); context.subscriptions.push(command.canDisposable); context.subscriptions.push(command.switchLangDisposable); context.subscriptions.push(command.fromLangDisposable); context.subscriptions.push(command.settingsDisposable); } exports.activate = activate; function deactivate() { } exports.deactivate = deactivate;Copy the code

It can be seen that it is quite neat, among which only hoverDisposable and tranDisposable are the functions we focus on. I have simplified them for convenience. Cut from 500 to 100 lines.

2. Source code analysis

Simplified entry file:

// The module 'vscode' contains the VS Code extensibility API // Import the module and reference it with the alias vscode in your code below const command = require('./command') function activate(context) { console.log('Congratulations, your extension "vsc-google-translate" is now active! '); command.initSetting(context); context.subscriptions.push(command.hoverDisposable); } exports.activate = activate; function deactivate() { } exports.deactivate = deactivate;Copy the code

2.1 Initial Configuration

/ / get the user state, to prevent the repeated use of the function initSetting (CXT) {hoverOpen = CXT. GlobalState. Get (' hover ') | | false; langFrom = cxt.globalState.get('fromLang') || 'auto' if (! translate.languages.isSupported(langFrom)) langFrom = 'auto'; cxt.globalState.update('hover', hoverOpen); }Copy the code

2.2 Writing trigger functions

/ / the simple way to offer the file type hover content let hoverDisposable = vscode. Languages. RegisterHoverProvider ({scheme: 'file'}, {provideHover: Async (document, the position, token) = > {/ / access is activated editor window area let editor = vscode. Window. ActiveTextEditor; if (! editor || ! hoverOpen) { return; // No open text editor } let length = editor.selections.length; for (let i = 0; i < length; i++) { let selection = editor.selections[i]; let line = { begin: Math.min(selection.anchor.line, selection.active.line), end: Math.max(selection.anchor.line, selection.active.line) }, character = { begin: Math.min(selection.anchor.character, selection.active.character), end: Math.max(selection.anchor.character, selection.active.character) }; // Here is the check from back to front or front to back selection. if (line.begin > position.line || character.begin > position.character) continue; if (line.end < position.line || character.end < position.character) continue; Try {// start translating let trans = await translate(editor.document.gettext (selection), langTo); if (! trans) return; Let word = trans. Word // Let pre = '**[Google Translate](https://translate.google.cn/?sl=auto&tl=${trans.lang.to}&text=${encodeURI(trans.text)})**\n\n`; console.log("word", word); return new vscode.Hover(pre + word.replace(/\r\n/g, ' \r\n')); } catch (error) { return new vscode.Hover('**[Error](https://github.com/imlinhanchao/vsc-google-translate/issues)**\n\n'  + error.message); }}}})Copy the code

A few key points:

  1. vscode.languages.registerHoverProvider({scheme: 'file'},{... }: A simple way to provide hover content to a file type.
  2. The two ends of the middleif: Verify that the content selected from back or front to back meets the requirements.

Then comes the hover call

await translate(editor.document.getText(selection), langTo);
Copy the code

2.3 Trigger translation

Going back to Tranlate.js, I’ve simplified it a bit:

const vscode = require('vscode'); const translator = require('@imlinhanchao/google-translate-api'); let config = {}; async function translate(text, lang) { try{ let result = await translator(text, { from: lang.from == 'auto' ? undefined : lang.from, to: lang.to, }) return { lang, text, word: result.text || '', candidate: result.candidates }; } catch (err) { throw new Error(`Translate failed, Error message: '${err.message}'. Please post an issues for me.`); } } function getConfig() { let keys = [ 'google-translate.firstLanguage', 'google-translate.secondLanguage', ]; let values = {}; keys.forEach(k => values[k] = vscode.workspace.getConfiguration().get(k)) return values; } module.exports = async (word, l, from='auto') => { if (word == '') return null; config = getConfig(); let lang = { from, to: l || config['google-translate.firstLanguage'] }; // Parse the hump function. word = word.replace(/([a-z])([A-Z])/g, "$1 $2") .replace(/([_])/g, " ").replace(/=/g, ' = ') .replace(/(\b)\.(\b)/g, '$1 \n{>}\n $2 '); let tran = await translate(word, lang); / / if translation without results, then call translated as a second language if (tran. Word. Replace (/ \ s/g, ") = = word. Replace (/ \ s/g, ' ') | |! tran.word.trim()) { lang.to = config['google-translate.secondLanguage']; let tranSecond = await translate(word, lang); if (tranSecond.word) tran = tranSecond; } / / remove excess tran. Word = tran. Word. Replace (/ {>} \ n \ n/g, '. '); tran.candidate = tran.candidate.map(c => c.replace(/{([^>]*?) >}/g, '$1\n{>}').replace(/\n{>}\n/g, '.')); return tran; }; module.exports.getConfig = getConfig; module.exports.languages = translator.languages;Copy the code
  1. @imlinhanchao/google-translate-api: is the author’s integrated translation API.
  2. getConfig: Get the currentvscodeFirst and second choice languages, if not automatically translated (default English -> Chinese).

The entire file exports a translation method.

In the middle, you can resolve the hump function

word = word.replace(/([a-z])([A-Z])/g, "$1 $2")
        .replace(/([_])/g, " ").replace(/=/g, ' = ')
        .replace(/(\b)\.(\b)/g, '$1 \n{>}\n $2 ');
Copy the code

2.4 Display hovering

Back to hoverDisposable:

let trans = await translate(editor.document.getText(selection), langTo); if (! trans) return; let word = trans.word let pre = `**[Google Translate](https://translate.google.cn/?sl=auto&tl=${trans.lang.to}&text=${encodeURI(trans.text)})**\n\n`; return new vscode.Hover(pre + word.replace(/\r\n/g, ' \r\n'));Copy the code

After receiving the translation result, the trigger display is:

An interesting point here is that you have assembled an open link to Google Translate, which is very thoughtful.

As a vscode plug-in development experience, this plug-in is good.

2.5 Additional minor findings:google-translate-api

A free and unlimited API for Google Translate 💵

conclusion

I haven’t written an article for about a year. I’ve been fishing and working out all this time. Both writing vscode secondary/plug-in development. Less attention is paid to new technology. Ready to go again, full account.

Source:

VSCode Extension: Google Translate Extension

Simplified: https://github.com/roger-hiro/vscode-google-translate

If you don’t want to pull code, you can try CS custom templates

From:https://cloudstudio.net/templates/5oulv1ZVoy