Home  >  Article  >  Development Tools  >  vscode practical development of a complete translation plug-in

vscode practical development of a complete translation plug-in

青灯夜游
青灯夜游forward
2020-10-22 20:09:415455browse

vscode practical development of a complete translation plug-in

Video tutorial recommendation: vscode basic tutorial

##Required The effect is as follows, it is a translation function~


vscode practical development of a complete translation plug-in

You need to prepare

    Baidu Translation developer account, obtain the appid and key
  • npm install -g yo generator-code
Key vscodeAPI

    Get the text selected by the current active editor
  • vscode.window.activeTextEditor.document.getText(range?: Range)
    Calling the quick selection panel
  • vscode.window.showQuickPick(items: string[] | Thenable<string[]>, options?: QuickPickOptions)
Start CODING

Scaffolding creation folder code

yo code

Select JavaScript (Extension), then press Enter for everything Default That’s it.

Baidu Translate API Code

Create

translate-api.jsFile

You need to know how to get the user configuration here, after all, the same appid and key The number of calls is limited. The following steps are required.

  • Register for contribution points

In vscode, menus, commands, views, etc., all functions that need to be displayed in front of the user are You need to register contribution points in package.json


The contribution configuration items are as follows

  "contributes": {
    "configuration": [
      {
        "title": "translateNamed",
        "properties": {
          "translate.appid": {
            "type": "string",
            "default": "20200921000570318",
            "description": "百度翻译API-appid"
          },
          "translate.secret": {
            "type": "string",
            "default": "8iaGzb7v0225xQ8SVxqq",
            "description": "百度翻译API-密钥"
          }
        }
      }
    ]
  },
    Find the user configuration
  • ok, after registering the contribution points, you can Find the configuration item you just registered through the API

  • vscode.workspace.getConfiguration().get((section: string))
    Calling the API
  • I am used to using

    axiosSoyarn add axios md5, where md5 is required by Baidu Translation API.

OK, the following is the code of

translate-api.js.

const axios = require("axios")
const vscode = require("vscode")
const md5 = require("md5")
const appid = vscode.workspace.getConfiguration().get("translate.appid")
const secret = vscode.workspace.getConfiguration().get("translate.secret")

module.exports = {
  /**
   * 翻译方法
   * @param {string} q 查询字符串
   * @param {string} from 源语言
   * @param {string} to 目标语言
   * @returns {{data: {trans_result:[{src: string, dst: string}]}}} Promise翻译结果
   */
  translate(q, from, to) {
    var salt = Math.random()
    return axios({
      method: "get",
      url: "https://fanyi-api.baidu.com/api/trans/vip/translate",
      params: {
        q,
        appid,
        from,
        to,
        salt,
        sign: md5(appid + q + salt + secret),
      },
    })
  },
}

If you need to replace it with another translation API, such as google translate, you only need to change this

translate-api.jscode.

Operation vscode

Return to

extension.js.

The first step is to find the text currently selected in the editor.

const currentEditor = vscode.window.activeTextEditor
const currentSelect = currentEditor.document.getText(currentEditor.selection)

The

currentEditor.document.getText method requires Range, but since selection inherits from Range, it can Directly put currentEditor.selection into the parameters.

The second step is to split the words.

The translated words are generally separated by spaces, so just use spaces to separate them.

const list = result.split(" ")
const arr = []
// - 号连接
arr.push(list.map((v) => v.toLocaleLowerCase()).join("-"))
// 下划线连接
arr.push(list.map((v) => v.toLocaleLowerCase()).join("_"))
// 大驼峰
arr.push(list.map((v) => v.charAt(0).toLocaleUpperCase() + v.slice(1)).join(""))
// 小驼峰
arr.push(
  list
    .map((v, i) => {
      if (i !== 0) {
        return v.charAt(0).toLocaleUpperCase() + v.slice(1)
      }
      return v.toLocaleLowerCase()
    })
    .join("")
)

Step 3 Put the results into the quick selection panel.

let selectWord = await vscode.window.showQuickPick(arr, {
  placeHolder: "请选择要替换的变量名",
})

The fourth step is to replace the selected text with the selected result

if (selectWord) {
  currentEditor.edit((editBuilder) => {
    editBuilder.replace(currentEditor.selection, selectWord)
  })
}

To view all the codes, you can go to github: github

The entry file is

extension.js

For more convenience, the registration menu

For more convenience, the registration menu contributes points.

  "menus": {
    "editor/context": [
      {
        "when": "editorHasSelection",
        "command": "translate.zntoen",
        "group": "navigation"
      }
    ]
  }

Among them,

when refers to when the menu option appears, and editorHasSelection refers to when there is selected text in the editor. Check what options are available when? vscode when contribution point document

command refers to the command that needs to be executed when clicking the menu

group refers to Where is the menu placed? View group and what options are available? vscode group document

Add icon

Configure in package.json

"icon": "images/icon.png",

where images/icon.png is a 128*128 pixel image.

Add git repository, modify readme, etc.

If you do not add git repository, there will be a warning when publishing.

If the readme is not modified, it will not be published!

Create account token

First you must create a Microsoft account. After creation, open the following link

https://aka.ms/SignupAzureDevOps

Click User Settings in the upper right corner-> Personal access tokens


vscode practical development of a complete translation plug-in

According to the prompt new token

When selecting the range, select like this

vscode practical development of a complete translation plug-in

Login

vsce create-publisher your-publisher-name

Publish

vsce publish

Plug-in address: https://marketplace.visualstudio.com/items?itemName=chendm.translate&ssr=false#overview

vscode search

translateNamed to experience it.

View the code on github: https://github.com/chendonming/translate

For more programming-related knowledge, please visit:

Introduction to Programming! !

The above is the detailed content of vscode practical development of a complete translation plug-in. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete