This is the fourth day of my participation in the August More text Challenge. For details, see: August More Text Challenge
The paper
Since HBuilderX 2.7+, the plug-in extension mechanism has been opened. Developers can customize and enhance HBuilderX by writing HBuilderX plug-ins in JavaScript language to create more handy tools.
What can plug-in extensions do?
HBuilderX’s plug-in is nodeJs based, and all NodeJS apis can be used, such as file manipulation and invoking other Node commands.
In addition, HBuilderX provides a large number of JS apis (compatible with VSCode), you can customize many HBuilderX functions and interfaces, such as
- Add a new
The menu
- Add a new
The command
And shortcuts - Extend the new
The code block
- Add a new View
view
For example, add a new “TODO” view next to the project manager on the left side of the interface - Edit the document in various ways, adding, deleting and changing text content, cursor and selection
- Verify the document
- Logs, operation status bar messages, and various prompt boxes and selection boxes are displayed on the console
Note: The plug-in runs within a separate plug-in process, which is a Node.js process that makes interface calls through inter-process RPC communication and HBuilderX. So plug-ins can use all of Node’s own apis. Currently, the integrated Node version is V8.10.0.
Create the plug-in
New plug-in Extension
In HBuilderX, use the new button or CTRL + N to open the New menu and select the project, as shown in the picture below, select common Project – Plug-in Extension development
Note: The plug-in name can only use letters and digits. Chinese characters and Spaces are not supported.
Run the plugin
After the plug-in project is set up, select the project or open a file under the project, then click the Run button on the toolbar or CTRL + R to open the Run menu, select Run plug-in XXX to open a new HBuilderX form, which will automatically load the plug-in. The following figure
The running effect is as follows:
The plug-in extension development template example registers a Hello World menu in the code editor right click menu. At this point, we open a document and right-click to see the Hello World menu. Click this menu to run and a prompt box will appear in the window. The following figure
In other words, after writing the plug-in code in the old form, saving the plug-in code, preview the effect in the new form.
You need to run the plug-in again after modifying the plug-in code
Print log
The running plug-in, in the old form console, prints a log.
Developers can use the console.log, console.error and other apis to print information to the debugging console of the old form.
Plug-in Code description
package.json
Package. json must be present in each plug-in and contains information about the plug-in and configuration extension points. Here is the package.json code description for the example plug-in
{
// Note that you cannot copy this code directly into the editor. Package. json does not currently support comments. The comments in this section of code are intended to explain the code only.
// Plug-in name, mandatory field
"name": "your extension name"."description": "your extension description".// Plug-in version number, used for version upgrade judgment, mandatory field
"version": "0.0.0"."publisher": "your name".// Minimum HBuilder version number required, mandatory field
"engines": {
"HBuilderX": "^ 2.6.8." "
},
// Plugin classification
"categories": [
"Other"].// The plugin's program entry js file is called when the plugin is activated
"main": "./extension".// Plugin activation event registration. The plugin will only be activated when the following events occur.
"activationEvents": [
//onCommand indicates that the event is triggered when a command is about to be executed. This example indicates that the plug-in is activated only when 'extension.helloWorld' is about to be executed
"onCommand:extension.helloWorld"].// Configure the extension point
"contributes": {
// The 'command' extension point, used to declare a 'command', all extended 'commands' must be declared through this extension point
"commands": [{
// Unique identifier of 'command'
"command": "extension.helloWorld".// The name of the 'command', which will be used when associated with a menu if no menu name is configured.
"title": "Hello World"}].// The 'menu' extension point is used to register a 'menu'
"menus": {
// Editor right-click menu
"editor/context": [{// The unique identifier of the associated 'command'
"command": "extension.helloWorld".// Register to the menu location
"group": "z_commands".// Under what conditions
"when": "editorTextFocus"
},
{
// Menu extensions that are not associated with 'commands' represent a divider
"group": "z_commands"}}},"dependencies": {}}Copy the code
Plug-in entry file
The plug-in entry file for this example is extension.js, and the plug-in entry file must have the exportsActivate method, which is called when the plug-in is activated. The code is described as follows:
var hx = require("hbuilderx");
// This method is called when the plug-in is activatedfunction activate(context) { let disposable = hx.commands.registerCommand('extension.helloWorld', () = > {hx. Window. ShowInformationMessage (' hello, this is my first plug-in extension. '); console.log("Hello My First HBuilderX Extension.");
});
// Subscribe to the destruct hook, which is automatically logged out when the plugin is disabled.
context.subscriptions.push(disposable)
}
// This method will be called when the plug-in is disabled (currently triggered when the plug-in is uninstalled)
function deactivate() {
}
module.exports = {
activate,
deactivate
}
Copy the code
Other plug-in examples
hbuilderx-extension-samples
Development of guidelines
Plugin instructions
Plug-in extensions are divided into two parts, a plug-in API and a configuration extension point.
Plug-in API Description
The plugin for HBuilderX runs in a separate Node.js process. In addition to the list of apis provided by HBuilderX, node.js supports apis that can also be called. A list of currently open plug-in apis can be found here.
Configure extension point description
Configuring extension points is a configuration that is registered under the contributes node in the plug-in description file package.json. A complete list of configuration extension points is available here.
Why introduceConfiguring extension Points
The concept of?
HBuilderX is very performance intensive, and extension points are configured for performance purposes. When a user installs a plug-in, each additional plug-in will increase the startup and loading time of the main program. In order not to affect the startup time of the main program, HBuilderX adds a plug-in lazy loading mechanism, that is, HBuilderX will not automatically activate the installed plug-ins when it starts. Instead, you simply parse the configuration extension points in the plug-in’s configuration file package.json to add the menus, commands, configurations, and so on that the plug-in wants to register. When the user actually activates a menu or command, the plugin is deactivated by the onXXX event. This satisfies the ability of plug-in extension and reduces the impact on the performance of the main program. See the Plug-in activation mechanism for a detailed description of lazy loading
How to Register a command
A command refers to a custom function that is registered in the plug-in and is invoked when the command is triggered. Registering a new command is divided into two steps:
1. Declare this command in package.json by configuring extension points with Commands.
"contributes": {
"commands": [{
"command": "extension.helloWorld"."title": "Hello World"}}]Copy the code
2. In the plug-in activation via API hx.com mands. RegisterCommand or hx.com mands. RegisterTextEditorCommand to implement the above statement command, pay attention to the command identifier must be consistent. The relevant code is as follows:
let disposable = hx.commands.registerCommand('extension.helloWorld', () => {
//do something
});
context.subscriptions.push(disposable)
Copy the code
How to register menu
Menu extensions are registered by configuring extension points, typically associated with a command. Json contributes node by adding a menu extension point. The relevant code is as follows:
"contributes": {
"menus": {
"editor/context": [{"command": "extension.helloWorld"."group": "z_commands"."when": "editorTextFocus"
},
{
"group": "z_commands"}}}]Copy the code
How do I register a view
TreeView
This version is supported starting from HBuilderX 2.7.12 or laterCopy the code
Extending a new TreeView view (view) takes two steps:
- through
viewContainers
andviews
The configuration extension point declares what to extendview
/ / package. Json;
/ /... NOTE: Package. json does not support comments
"contributes": {"viewsContainers": {"activitybar": [{"id":"demoview"."title":"DemoView"}},"views": {"demoview": [{// This id must be the same as the viewId parameter in window.createTreeView
"id":"extensions.treedemo"."name":"DemoView"}}}]Copy the code
- At plug-in activation via API:
window.createTreeView
Implement the above extensionview
// extension.js
var hx = require("hbuilderx");
classDemoTreeDataProvider extends hx.TreeDataProvider{
constructor(demoData){
super(a);this._demoData = demoData;
}
getChildren(element){
let demoData =this._demoData;
returnnewPromise(resolve= >{
if(! element){ resolve(demoData); }else{ resolve(element.children); }}); }getTreeItem(element){
return{
label:element.name,
collapsibleState:element.children ?1:0.command: {command:element.children ?"":"extension.helloWorld".arguments:[
element.name
]
}
}
}
}
// This method is called when the plug-in is activated
function activate(context){
let demoData =[
{
name:"Root1".children:[
{
name:"child1"
},
{
name:"child2"}]}, {name:"Root2".children:[
{
name:"child3"}, {name:"child4"
}
]
}
]
hx.commands.registerCommand("extension.helloWorld".function(param){
hx.window.showInformationMessage("Selected TreeItem:"+ param[0]);
});
hx.window.createTreeView("extensions.treedemo", {showCollapseAll:true.treeDataProvider:newDemoTreeDataProvider(demoData)
});
}
// This method will be called when the plug-in is disabled (currently triggered when the plug-in is uninstalled)
function deactivate(){}module.exports ={
activate,
deactivate
}
Copy the code
The extended view can be opened through the menu View – Show extension view
rendering
WebView
Support for HBuilderX 2.8.1 or laterCopy the code
Extending a new WebView view (view) takes two steps:
- through
viewContainers
和views
The configuration extension point declares what to extendview
/ / package. Json;
/ /... NOTE: Package. json does not support comments
"contributes": {"viewsContainers": {"rightside": [{"id":"WebViewcontainerId"."title":"The webview show"}},"views": {"WebViewcontainerId": [{"id":"extension.WebView"."title":"Webview - Display"}}],... }Copy the code
- At plug-in activation via API:
window.createWebView
Implement the above extensionview
const hx = require('hbuilderx');
/ * * *@description Display the webview * /
function showWebView(webviewPanel){
let webview = webviewPanel.WebView;
var background =' ';
let config = hx.workspace.getConfiguration();
let colorScheme = config.get('editor.colorScheme');
if(colorScheme =='Monokai'){
background ='RGB (39,40,34)'
}elseif(colorScheme =='Atom One Dark'){
background ='RGB (40,44,53)'
}else{
background ='RGB (255250232).
};
webview.html =
`
<body style="background-color:${background}; border:1px solid${background};" > <div style="max-width:200px;" > <img src="https://download1.dcloud.net.cn/uploads/images/hbuilderx/[email protected]" style="position: absolute; bottom: 0; left: 0; right: 0; width: 100%; margin: auto;" > < / div > < script > / / the following two written equivalent hbuilderx. OnDidReceiveMessage ((MSG) = > {}); window.addEventListener("message",(msg)=>{}); hbuiderx.postMessage({ command:'alert', text:'HelloWorld' }); </script> </body> `;
webview.postMessage({
command:"test"
});
webview.onDidReceiveMessage((msg) = >{
if(msg.command =='alert'){ hx.window.showInformationMessage(msg.text); }}); };module.exports ={
showWebView
}
Copy the code
-
The extended view can be opened through the menu View – Show extension view
How to Edit a Document
Before modifying a document, you must first get the editor associated with the document. There are two ways to get the editor:
1. By hx. Window. GetActiveTextEditor ()
The code is as follows:
let editorPromise = hx.window.getActiveTextEditor();
editorPromise.then((editor) = >{
let document = editor.document;
let selection = editor.selection;
// Get the word within the selection
let word = document.getText(selection);
let reversed = word.split(' ').reverse().join(' ');
editor.edit(editBuilder= > {
editBuilder.replace(selection, reversed);
});
});
Copy the code
2. Through the editor commands, hx.com mands registerTextEditorCommand (” id “, (editor) = > {});
The code is as follows:
hx.commands.registerTextEditorCommand('extension.reverseSelectWord'.(editor) = >{
let document = editor.document;
let selection = editor.selection;
// Get the word within the selection
let word = document.getText(selection);
let reversed = word.split(' ').reverse().join(' ');
editor.edit(editBuilder= > {
editBuilder.replace(selection, reversed);
});
});
Copy the code
How do I write a validator
There are three triggers for file validation:
- Verification is triggered by clicking on one of the registration menus
- Listen for real-time validation of document modification events
- Listen for document save event validation
The following code sends the list of validated errors to HBuilderX for display:
let editorPromise = hx.window.getActiveTextEditor();
editorPromise.then((editor) = >{
let doc = editor.document;
/ / do the validation document.
//doValidateDocument(doc);
let diagnositics = hx.languages.createDiagnosticCollection('validation name');
diagnositics.set(doc.uri,[
{
column: 0.line: 0.message: 'a error message.'
},
...
]);
});
Copy the code
Plug-in release
Release and Installation
Release in the plug-in market
The HBuilderX plugin is released in DCloud’s unified plugin market, ext.dcloud.net.cn/.
- In the upper right corner of the plugin market page, click
Release the plugin
. (If not registered, you need to register and log in) - On the Publish plug-in page, select the plug-in category as
HBuilderX
And then fill in the form and publish it
Plug-in users can install plug-ins on the plug-in market Web interface.
Installing plug-ins Offline
Copy the plug-in to the HBuilderX installation directory /plugins and restart HBuilderX for the plug-in to take effect.
If the developer is in the Intranet environment, click the web interface of the plug-in market to download the ZIP plug-in. Then, put the ZIP package into the Intranet environment and decompress it to the HBuilderX directory.
The API documentation
The HBuilderX API root object can be introduced by require(‘ HBuilderX ‘).
const hx = require('hbuilderx')
Copy the code
The following is a list of currently available apis
commands
Commands secondary module object that handles command – related logic. Command contains two parts: a unique ID and a custom function, can be by registerCommand or registerTextEditorCommand registration. The command can be triggered in the following ways:
-
Menus: Associate commands with a menu via a menus extension point.
-
A command is declared via the Commands extension point, which is then associated with the menus
{ "contributes": {"commands":[ { "command":"extension.firstExtension"."title":"My First Extension"}]."menus": {"editor/context":[ { "command": "extension.firstExtension"."group": "z_commands"."when": "editorTextFocus"}}}Copy the code
-
Register the command in the plug-in’s Activate callback
hx.commands.registerCommand('extension.firstExtension',()=>{ hx.window.showInformationMessage("Hello My First Extension."); }); Copy the code
-
-
User-defined shortcuts: Users using the plug-in can configure a shortcut key by getting the ID of the command (which is usually declared in package.json) and using custom shortcuts.
// Keybindings.json;[{"key":"ctrl+shift+0"."command":"extension.firstExtension"}]Copy the code
executeCommand
The command with the specified ID is executed. In addition to the commands extended by the plug-in, you can also execute HBuilderX’s built-in commands. The complete list of built-in commands can be found through HBuilderX’s top menu tool – Custom Shortcuts, and then find all the command fields listed in the left section of the open configuration file
Parameters that
The parameter name | The parameter types | describe |
---|---|---|
command | String | To perform theThe command id |
The return value
The return type | describe |
---|---|
Promise | Promise object |
The sample
// Execute the plugin extension command
hx.commands.executeCommand('extension.firstExtension')
// Execute the built-in commands (close all open editors)
hx.commands.executeCommand('workbench.action.closeAllEditors')
Copy the code
registerCommand
Registers a command with a specified ID and associates it with a custom function
Parameters that
The parameter name | The parameter types | describe |
---|---|---|
commandId | String | The command id |
handler | Function | The command The function that is executed when fired |
The return value
The return type | describe |
---|---|
Disposable | theThe command You can place this object into the context.subscriptions array of the plug-in and it will be automatically deactivated when the plug-in is unsubscribedThe command |
The sample
let disposable = hx.commands.registerCommand('extension.firstExtension'.() = >{
hx.window.showInformationMessage("Hello My First Extension.");
});
context.subscriptions.push(disposable);
Copy the code
registerTextEditorCommand
Register an editor command with the specified ID
Parameters that
The parameter name | The parameter types | describe |
---|---|---|
commandId | String | The command id |
handler | Function(TextEditor) | The command The function that is executed when fired |
The return value
The return type | describe |
---|---|
Disposable | theThe command You can place this object into the context.subscriptions array of the plug-in and it will be automatically deactivated when the plug-in is unsubscribedThe command |
The sample
let disposable = hx.commands.registerTextEditorCommand('extension.firstExtension'.(editor) = >{
hx.window.showInformationMessage(editor.document.fileName);
});
context.subscriptions.push(disposable);
Copy the code
languages
Languages level-2 module object, used to process programming language-related logic, currently only supports creating lists of questions when validating documents.
createDiagnosticCollection
Creates a list of issues that can be used to display a wavy line in the error area of a document during document validation.
Parameters that
The parameter name | The parameter types | describe |
---|---|---|
name | String | The name of the problem list that appears in ToolTips when you mouse over the tilde line |
The return value
The return type | describe |
---|---|
DiagnosticCollection | List of issues created |
The sample
let activeEditor = hx.window.getActiveTextEditor();
activeEditor.then(function(editor) {
// Obtain the file path
let file_url = editor.document.uri.fsPath;
// Use editor.document to obtain the document object for verification
// Create a test problem set
let collections = [{
column: 0.line: 3.message: "error for test".severity: 'error'}];let diagnostics = hx.languages.createDiagnosticCollection('eslint');
diagnostics.set(file_url, collections);
});
Copy the code
window
Window Secondary module object that handles the logic associated with the main window.
setStatusBarMessage
Set HBuilderX bottom status bar message
Parameters that
The parameter name | The parameter types | describe |
---|---|---|
text | String | The message content |
hideAfterTimeout | Number | Optional. The unit is ms. The default value is 0: no automatic hiding |
level | String | [Optional] Message level. The value can be [‘ WARN ‘, ‘info’, ‘error’]. Default value: ‘info’. |
The return value
The return type | describe |
---|---|
Disposable | The dispose method can be called to clean up the status bar messages |
The sample
hx.window.setStatusBarMessage('Verifying XXX document... '.600.'info');
Copy the code
clearStatusBarMessage
Clear status bar messages
Parameters that
There is no
The return value
There is no
The sample
hx.window.clearStatusBarMessage();
Copy the code
showErrorMessage
Displays an error notification box in the lower right corner of the window
Parameters that
The parameter name | The parameter types | describe |
---|---|---|
message | String | Message content, HTML tags are supported |
buttons | Array | Group of buttons in the notification box |
The return value
The return type | describe |
---|---|
Promise | If a button is set, return to which button the user clicked |
The sample
let resultPromise = hx.window.showErrorMessage('Do you want to delete the file? '['is'.'no']);
resultPromise.then((result) = >{
if(result == 'is') {console.log("Yes");
}else if(result === 'no') {console.log("Chose no."); }});Copy the code
showInformationMessage
The message notification box is displayed in the lower right corner of the window
Parameters that
The parameter name | The parameter types | describe |
---|---|---|
message | String | Message content, HTML tags are supported |
buttons | Array | Group of buttons in the notification box |
The return value
The return type | describe |
---|---|
Promise | If a button is set, return to which button the user clicked |
The sample
hx.window.showInformationMessage('For details, visit the reference documentation ');
Copy the code
showWarningMessage
The warning message notification box is displayed in the lower right corner of the window
Parameters that
The parameter name | The parameter types | describe |
---|---|---|
message | String | Message content, HTML tags are supported |
buttons | Array | Group of buttons in the notification box |
The return value
The return type | describe |
---|---|
Promise | If a button is set, return to which button the user clicked |
The sample
let resultPromise = hx.window.showWarningMessage('Do you want to delete the file? '['is'.'no']);
resultPromise.then((result) = >{
if(result == 'is') {console.log("Yes");
}else if(result === 'no') {console.log("Chose no."); }});Copy the code
showQuickPick
A list of searchable suggestions pops up in the middle of the window
Parameters that
The parameter name | The parameter types | describe |
---|---|---|
items | Array | Recommended selection list |
options | QuickPickOptions | Set up the |
The return value
The return type | describe |
---|---|
Promise | Returns a list item selected by the user |
The sample
const pickResult = hx.window.showQuickPick([
{
label: '.. / '.description: 'Go back to the next level'.backPath: 'foo/bar'}, {placeHolder: 'Please select a directory or file'});
pickResult.then(function(result) {
if(! result) {return;
}
let backPath = result.backPath;
//do something with result
})
Copy the code
getActiveTextEditor
Gets the currently active editor, returning undefined if no editor is open
Parameters that
There is no
The return value
The return type | describe |
---|---|
Promise | Returns the currently active editor |
The sample
let activeEditor = hx.window.getActiveTextEditor();
activeEditor.then(function(editor){
console.log(editor.document.fileName);
});
Copy the code
showInputBox
An input box pops up in the middle of the window to get user input. The prompt method is similar to the browser.
Parameters that
The parameter name | The parameter types | describe |
---|---|---|
options | InputBoxOptions | Input box Settings |
The return value
The return type | describe |
---|---|
Promise | The result of user input |
The sample
let inputPromise = hx.window.showInputBox({
prompt:"Please enter your password".password:true
});
inputPromise.then((result) = >{
console.log("The password entered is:",result);
});
Copy the code
createOutputChannel
Creates an output console channel that can be used to output text content to the console.
Parameters that
The parameter name | The parameter types | describe |
---|---|---|
channel | String | The name of the console channel, which is printed as a prefix when adding content to the console, eg:[${channel}] this is the content to be printed. |
The return value
The return type | describe |
---|---|
OutputChannel | Console channel |
The sample
let outputChannel = hx.window.createOutputChannel("foo");
outputChannel.show();
outputChannel.appendLine("Hello World");
Copy the code
createTreeView
This version is supported starting from HBuilderX 2.7.12 or laterCopy the code
Create a view with the specified viewId, creating a TAB in the left area of the form that is the same as the project manager. The TAB content area is a tree control that can load nodes by itself.
The viewId needs to be declared in the config extension point views in the package.json file. For the complete extension view process see how do I register a new View?
Parameters that
The parameter name | The parameter types | describe |
---|---|---|
viewId | String | View Id, which needs to be configured first in the extension pointviews In a statement. |
options | TreeViewOptions | Settings required when creating a TreeView. |
The return value
There is no
The sample
class DemoTreeDataProvider extends hx.TreeDataProvider{
constructor(demoData) {
super(a);this._demoData = demoData;
}
getChildren(element) {
let demoData = this._demoData;
return new Promise(resolve= > {
if(! element) { resolve(demoData); }else{ resolve(element.children); }}); }getTreeItem(element) {
return {
label:element.name,
collapsibleState:element.children ? 1 : 0.command: {command:element.children ? "":"extension.helloWorld".arguments:[
element.name
]
}
}
}
}
let demoData = [
{
name:"Root1".children:[
{
name:"child1"
},
{
name:"child2"}]}, {name:"Root2".children:[
{
name:"child3"}, {name:"child4"
}
]
}
]
hx.commands.registerCommand("extension.helloWorld".function(param){
hx.window.showInformationMessage("Selected TreeItem:" + param[0]);
});
hx.window.createTreeView("extensions.treedemo", {showCollapseAll:true.treeDataProvider:new DemoTreeDataProvider(demoData);
});
Copy the code
createWebView
Support for HBuilderX 2.8.1 or laterCopy the code
Create a WebView control view with the specified viewId, creating a TAB item in the left or right area of the form. TAB content is webView, WebView can load HTML page, can be more flexible rendering custom content.
The viewId needs to be declared in the configuration extension point views in the package.json file
Parameters that
The parameter name | The parameter types | describe |
---|---|---|
viewId | String | View Id, which needs to be configured first in the extension pointviews In a statement. |
options | WebViewOptions | The WebView properties |
The return value
The return type | describe | |
---|---|---|
WebViewPanel | WebViewPanel | WebViewPanel properties |
The sample
let webviewPanel = hx.window.createWebView("viewId", {enableScritps:true
});
let webview = webviewPanel.WebView;
webview.html = ` < script > / / the following two written equivalent hbuilderx. OnDidReceiveMessage ((MSG) = > {}); window.addEventListener("message",(msg)=>{ }); hbuiderx.postMessage({ command: 'alert', text: 'HelloWorld' }); `;
webview.postMessage({
command:"test"
});
webview.onDidReceiveMessage((msg) = >{
if(msg.command == 'alert'){ hx.window.showInformationMessage(msg.text); }});Copy the code
registerUriHandler
Support for HBuilderX 2.8.1 or laterCopy the code
Register a custom network request handler (SCHEMA) that relies on the HBuilderX protocol. The format is:
hbuilderx://requestExtension/exampleid/examplerequest/example? example1=example2&...\... \ __________________ / \... \ __________________________________________ / | | | | agreement custom plug-in request any custom tag plugin id informationCopy the code
When you enter a URL in the above format in the browser address bar or jump to a URL in the above format, The system with HBuilderX installed will feed the request to HBuilderX, which will identify the request and check whether onUri is declared in the configuration information (package.json) of the corresponding plug-in (exampleID in the example above). At this point, if the current plug-in is not activated, HBuilderX activates the plug-in first and forwards the request to the handler registered by the registerUriHandler method.
If the exampleID plug-in is not installed, HBuilderX prompts you whether to install the plug-in.
Applicable Scenarios
- You need to launch HBuilderX from an external application such as a browser and then respond to requests by specifying a plug-in
Parameters that
The parameter name | The parameter types | describe |
---|---|---|
handler | UriHandler | Scheme processor |
context | ExtensionContext | The parameter object (context) passed to the plug-in activate method |
The return value
The return type | describe |
---|---|
Disposable | A registered UriHandler destructor can place this object into the context.subscriptions array of the plug-in, which will be automatically deregistered when the plug-in is uninstalled |
The sample
hx.window.registerUriHanlder({
handleUri:function(uri){
// Process scheme requests
let path = uri.path;
let params = uri.query;
hx.window.showInformationMessage(uri.toString());
}
}, context);
Copy the code
The above example, assume that the plug-in id for foo, enter in the browser address bar hbuilderx: / / requestExtension/foo? When param= ABC, the plug-in is automatically activated and the handleUri function is executed. The value of URI is the address entered in the address bar. In the example, the value of uri.query is param= ABC.
workspace
Workspace secondary module object that handles logic related to workspace and document events
getWorkspaceFolders
This version is supported starting from HBuilderX 2.7.12 or laterCopy the code
Get all project objects under project Manager (excluding closed projects)
Parameters that
There is no
The return value
The return type | describe |
---|---|
Promise<Array> | All projects under project Manager |
The sample
var wsPromise = hx.workspace.getWorkspaceFolders();
wsPromise.then(function(wsFolders) {
console.log("Number of projects contained in project Manager:",wsFolders.length);
});
Copy the code
getWorkspaceFolder
This version is supported starting from HBuilderX 2.7.12 or laterCopy the code
Gets the project where a file resides
Parameters that
The parameter name | The parameter types | describe |
---|---|---|
uri | String or Uri | File absolute path or file Uri |
The return value
The return type | describe |
---|---|
Promise | The project where the file resides |
The sample
var wsPromise = hx.workspace.getWorkspaceFolder("%fsPath%"); Then (function(wsFolder) {console.log(" file project: ", wsFold.name); });Copy the code
openTextDocument
Opens a document file with the specified URI
Parameters that
The parameter name | The parameter types | describe |
---|---|---|
uri | String orUri | The document address |
The return value
The return type | describe |
---|---|
Promise | Returns the open document |
The sample
var documentPromise = hx.workspace.openTextDocument("foo/bar.js");
documentPromise.then(function(document) {
console.log("Open the document :".document.fileName);
});
Copy the code
onDidChangeConfiguration
Support for HBuilderX 2.7.10 or laterCopy the code
Global configuration change events, such as “editor.fontSize” changes, or configuration items that are extended by plug-ins.
Parameters that
The parameter name | The parameter types | describe |
---|---|---|
listener | Function(ConfigurationChangeEvent) | Configure modify event callback |
The return value
The return type | describe |
---|---|
Disposable | The event callback destructor can be placed into the context.subscriptions array of the plug-in, which will be automatically deregister when the plug-in is unsubscribedEvent callback |
The sample
let configurationChangeDisplose = hx.workspace.onDidChangeConfiguration(function(event){
if(event.affectsConfiguration("editor.fontSize")) {console.log("Changed font size"); }});Copy the code
onDidChangeWorkspaceFolders
Support for HBuilderX 2.7.10 or laterCopy the code
Events that occur when a project is added or removed in the project Manager
Parameters that
The parameter name | The parameter types | describe |
---|---|---|
listener | Function(WorkspaceFoldersChangeEvent) | Event callbacks for new or removed items |
The return value
The return type | describe |
---|---|
Disposable | The event callback destructor can be placed into the context.subscriptions array of the plug-in, which will be automatically deregister when the plug-in is unsubscribedEvent callback |
The sample
let wsFoldersChangeDisplose = hx.workspace.onDidChangeWorkspaceFolders(function(event){
if(event.added){
event.added.forEach(item= >console.log("Added item :",item.name));
}
if(event.removed){
event.removed.forEach(item= >console.log("Removal of item :",item.name)); }});Copy the code
onWillSaveTextDocument
Note that this event is a synchronous invocation, which will block the user interface. In order to avoid blocking the interface for a long time, the timeout mechanism is currently set, and the timeout period is 2s.
Note that the logic you execute in the event callback should not take too long, and unpredictable problems can occur if the event times out.
Parameters that
The parameter name | The parameter types | describe |
---|---|---|
listener | Function(TextDocumentWillSaveEvent) | Event callback |
The return value
The return type | describe |
---|---|
Disposable | The event callback destructor can be placed into the context.subscriptions array of the plug-in, which will be automatically deregister when the plug-in is unsubscribedEvent callback |
The sample
let onDidChangeTextDocumentEventDispose = hx.workspace.onDidChangeTextDocument(function(event){
let document = event.document;
//do something with document.
});
Copy the code
onDidChangeTextDocument
The event when the document is modified
Parameters that
The parameter name | The parameter types | describe |
---|---|---|
listener | Function(TextDocumentChangeEvent) | Event callback |
The return value
The return type | describe |
---|---|
Disposable | The event callback destructor can be placed into the context.subscriptions array of the plug-in, which will be automatically deregister when the plug-in is unsubscribedEvent callback |
The sample
let onDidChangeTextDocumentEventDispose = hx.workspace.onDidChangeTextDocument(function(event){
let document = event.document;
//do something with document.
});
Copy the code
onDidSaveTextDocument
The event when the document is saved
Parameters that
The parameter name | The parameter types | describe |
---|---|---|
listener | Function(TextDocument) | Event callback |
The return value
The return type | describe |
---|---|
Disposable | The event callback destructor can be placed into the context.subscriptions array of the plug-in, which will be automatically deregister when the plug-in is unsubscribedEvent callback |
The sample
let onDidSaveTextDocumentEventDispose = hx.workspace.onDidSaveTextDocument(function(document){
//do something with document.
});
Copy the code
onDidOpenTextDocument
Support for HBuilderX 2.7.6 or laterCopy the code
The event when the document is opened
Parameters that
The parameter name | The parameter types | describe |
---|---|---|
listener | Function(TextDocument) | Event callback |
The return value
The return type | describe |
---|---|
Disposable | The event callback destructor can be placed into the context.subscriptions array of the plug-in, which will be automatically deregister when the plug-in is unsubscribedEvent callback |
The sample
let onDidOpenTextDocumentEventDispose = hx.workspace.onDidOpenTextDocument(function(document){
//do something with document.
});
context.subscriptions.push(onDidOpenTextDocumentEventDispose);
Copy the code
applyEdit
Edits the document according to the specified WorkspaceEdit object. Within the WorkspaceEdit object, the URI of the document to be modified and the TextEdit action object to be modified are set.
Parameters that
The parameter name | The parameter types | describe |
---|---|---|
edit | WorkspaceEdit | Document editing operation |
The return value
The return type | describe |
---|---|
Promise | Promise |
The sample
let editorPromise = hx.window.getActiveTextEditor();
editorPromise.then((editor) = >{
let workspaceEdit = new hx.WorkspaceEdit();
let edits = [];
edits.push(new hx.TextEdit({
start: 0.end: 0
}, "foo"));
workspaceEdit.set(editor.document.uri,edits);
hx.workspace.applyEdit(workspaceEdit);
});
Copy the code
getConfiguration
Gets the configuration for the specified section
Parameters that
The parameter name | The parameter types | describe |
---|---|---|
section | String | Category name of the configuration item |
The return value
The return type | describe |
---|---|
Configuration | Returns the configuration |
The sample
let config = hx.workspace.getConfiguration()
let fontSize = config.get("editor.fontSize");
// Or it could be
let config = hx.workspace.getConfiguration("editor")
let fontSize = config.get("fontSize");
Copy the code
env
Support for HBuilderX 2.7.6 or laterCopy the code
Env secondary module object that contains runtime environment information and methods associated with system interactions
Property list
The property name | Attribute types | describe |
---|---|---|
appName | String | Application name: HBuilder X |
appVersion | String | Application major version number, can be viewed in the menu [Help] – [about] |
appRoot | String | Application installation path |
appData | String | Path for storing application data |
clipboard | Clipboard | Clipboard object that can be used to read and write contents to the clipboard. Currently, only text format is supported |
openExternal
Open an external link, such as https://www.dcloud.io, mailto:[email protected]
Parameters that
The parameter name | The parameter types | describe |
---|---|---|
uri | String | External link address |
The return value
The return type | describe |
---|---|
Promise | A message is displayed indicating whether the service is successfully opened |
The sample
var openPromise = hx.env.openExternal("https://www.dcloud.io");
openPromise.then(function(success) {
console.log("Open link result:",success);
});
Copy the code
Clipboard
Support for HBuilderX 2.7.6 or laterCopy the code
Clipboard object that can be used to read and write contents to the clipboard. Currently, only text format is supported
readText
Read the clipboard
Parameters that
There is no
The return value
The return type | describe |
---|---|
Promise | Return to the clipboard contents |
The sample
var readPromise = hx.env.clipboard.readText();
readPromise.then(function(text) {
console.log("Read clipboard contents:",text);
});
Copy the code
writeText
Write the contents of the clipboard
Parameters that
The parameter name | The parameter types | describe |
---|---|---|
value | String | The string to write to the clipboard |
The return value
The return type | describe |
---|---|
Promise | Promise |
The sample
hx.env.clipboard.writeText("Hello Clipboard.");
Copy the code
ConfigurationChangeEvent
Event generated by a configuration change
affectsConfiguration
Determine which configuration item value is changed by the event
Parameters that
The parameter name | The parameter types | describe |
---|---|---|
section | String | Key of the configuration item, such as “editor.fontsize” |
The return value
The return type | describe |
---|---|
Boolean | true Indicates that the configuration item is modified.false Indicates that the configuration item is not modified |
The sample
let configurationChangeDisplose = hx.workspace.onDidChangeConfiguration(function(event){
if(event.affectsConfiguration("editor.fontSize")) {console.log("Changed font size"); }});Copy the code
WorkspaceFoldersChangeEvent
The type of event generated when a project is added or removed in the project Manager
Property list
The property name | Attribute types | describe |
---|---|---|
added | Array | List of new items |
removed | Array | List of removed items |
The sample
let wsFoldersChangeDisplose = hx.workspace.onDidChangeWorkspaceFolders(function(event){
if(event.added){
event.added.forEach(item= >console.log("Added item :",item.name));
}
if(event.removed){
event.removed.forEach(item= >console.log("Removal of item :",item.name)); }});Copy the code
TextDocumentWillSaveEvent
The event that the document is about to save
Property list
The property name | Attribute types | describe |
---|---|---|
document | TextDocument | The document associated with the event |
- TextDocumentChangeEvent
- Property list
TextDocumentChangeEvent
The event when the document is modified
Property list
The property name | Attribute types | describe |
---|---|---|
document | TextDocument | The document associated with the event |
TextEditor
Text editor object
Property list
The property name | Attribute types | describe |
---|---|---|
document | TextDocument | The document associated with the editor |
selection | TextSelection | The current position of the cursor |
selections | Array | The collection of positions currently selected by multiple cursors |
options | TextEditorOptions | Settings for the editor |
edit
Modifies the document that is currently open in the editor
Parameters that
The parameter name | The parameter types | describe |
---|---|---|
callback | Function(TextEditorEdit) | Callback for document editing operations |
The return value
The return type | describe |
---|---|
Promise | Promise |
The sample
let editorPromise = hx.window.getActiveTextEditor();
editorPromise.then(function(editor) {
let selection = editor.selection;
let document = editor.document;
let word = document.getText(selection);
let reversed = word.split(' ').reverse().join(' ');
editor.edit(editBuilder= > {
editBuilder.replace(selection, reversed);
});
});
Copy the code
setSelection
Set the main selection area, and the API will first clear the original cursor selection. If you want to use multiple cursors, use the addSelection method
Parameters that
The parameter name | The parameter types | describe |
---|---|---|
active | Number | Select the side of the area with the cursor |
anchor | Number | Select the side of the area without the cursor. See the following figure for details |
The return value
The return type | describe |
---|---|
Promise | Promise |
The sample
let editor = hx.window.getActiveTextEditor();
editor.then((editor) = >{
editor.setSelection(10.12);
})
Copy the code
addSelection
Adds a new selection area that will append a new cursor to the editor.
Parameters that
The parameter name | The parameter types | describe |
---|---|---|
active | Number | Select the side of the area with the cursor |
anchor | Number | Select the side of the area without the cursor. See the following figure for details |
The return value
The return type | describe |
---|---|
Promise | Promise |
The sample
let editorPromise = hx.window.getActiveTextEditor();
editorPromise.then((editor) = >{
editor.setSelection(10.12).then(() = >{
editor.addSelection(16.18);
});
})
Copy the code
TextDocument
The document file opened by the editor
Property list
The property name | Attribute types | describe |
---|---|---|
fileName | String | The file name |
isDirty | Boolean | Whether to modify the status |
isUntitled | Boolean | Whether the file has no title |
lineCount | Number | The total number of rows in the document |
uri | Uri | If the file is a local file, you can obtain the local file path through uri.fspath |
languageId | String | Programming language ids such as’ javascript ‘, ‘HTML’, etc. See below for a complete list of ids |
workspaceFolder | WorkspaceFolder | The project object to which the document file belongs |
getText
Gets the text in the specified area
The parameter name | The parameter types | describe |
---|---|---|
range | Range | Optional. Text area. If this parameter is not passed, the entire document content is obtained |
The return value
The return type | describe |
---|---|
String | Text string |
lineAt
Gets line information for the specified line number
The parameter name | The parameter types | describe |
---|---|---|
lineno | Number | Line number, starting at 0 |
The return value
The return type | describe |
---|---|
Promise | Text line object |
lineFromPosition
Gets the cursor line based on the cursor position.
The parameter name | The parameter types | describe |
---|---|---|
pos | Number | The cursor position |
The return value
The return type | describe |
---|---|
Promise | Text line object |
languageId
Here is a list of currently supported programming language ids:
- txt
- actionscript
- ada
- asm
- asp
- autoit
- baanc
- bash
- batch
- c
- cs
- cmake
- cpp
- css
- caml
- cobol
- coffeescript
- d
- dart
- ejs
- fortran
- fortran77
- html
- html_es6
- handlebars
- haskell
- inno
- json
- json_tm
- java
- javascript
- javascriptreact
- javascript_es6
- kix
- less
- lisp
- lua
- markdown
- matlab
- njs
- nml
- nsis
- nss
- objc
- php
- pascal
- perl
- postscript
- powershell
- python
- r
- rc
- ruby
- sql
- sass
- scheme
- scss
- smalltalk
- stylus
- swift
- tcl
- typescript
- typescriptreact
- ux
- vb
- vhdl
- verilog
- vue
- wxml
- xml
- yaml
- pug
TextLine
A line in the document
Property list
The property name | Attribute types | describe |
---|---|---|
start | Number | Line start position |
end | Number | The end of a line without calculating a newline |
text | String | Line content, without a newline character |
Range
The text area
Property list
The property name | Attribute types | describe |
---|---|---|
start | Number | The starting position |
end | Number | End position |
OutputChannel
Output channel, which is prefixed with the channel name when adding content to the console, eg:[${channel}] this is the content to output.
Property list
The property name | Attribute types | describe |
---|---|---|
name | String | The name of the channel |
appendLine
Parameters that
The parameter name | The parameter types | describe |
---|---|---|
line | String | Output to the console |
The return value
The return type | describe |
---|---|
Promise | Promise |
The sample
let outputChannel = hx.window.createOutputChannel("foo");
outputChannel.show();
outputChannel.appendLine("Hello World");
Copy the code
show
Parameters that
There is no
The return value
The return type | describe |
---|---|
Promise | Promise |
The sample
let outputChannel = hx.window.createOutputChannel("foo");
outputChannel.show();
outputChannel.appendLine("Hello World");
Copy the code
Configuration
Global configuration
get
Parameters that
The parameter name | The parameter types | describe |
---|---|---|
section | String | Key of the configuration item |
defaultValue | Any | Default value, returned if the key does not exist |
The return value
The return type | describe |
---|---|
Any | Value of the configuration item |
The sample
let eslintConfig = hx.workspace.getConfiguration("eslint-js")
let validateOnDocumentChanged = eslintConfig.get("validateOnDocumentChanged".false);
Copy the code
update
Parameters that
The parameter name | The parameter types | describe |
---|---|---|
section | String | Key of the configuration item |
value | Any | Value of the configuration item |
The return value
The return type | describe |
---|---|
Promise | Promise |
The sample
let eslintConfig = hx.workspace.getConfiguration("eslint-js")
eslintConfig.update("validateOnDocumentChanged".true).then(() = >{
console.log("Configuration update succeeded.");
});
Copy the code
DiagnosticCollection
Problem set
Property list
The property name | Attribute types | describe |
---|---|---|
name | String | Problem set name |
set
Parameters that
The parameter name | The parameter types | describe |
---|---|---|
uri | String or Uri | The document address |
diagnostics | Array | Problem set |
The return value
The return type | describe |
---|---|
Promise | Promise |
The sample
let diagnositics = hx.languages.createDiagnosticCollection('eslint');
diagnositics.set("foo.js"[{column: 0.line: 0.message: 'a error message.'}]);Copy the code
DiagnosticItem
The problem items
Property list
The property name | Attribute types | describe |
---|---|---|
line | String | How many lines in the document |
column | String | In which column of the document |
message | String | Problem Details |
severity | String | Problem level, value range: ‘error’, ‘WARN’, default value: ‘error’ |
WorkspaceEdit
A set of editing operations for a workspace
set
Parameters that
The parameter name | The parameter types | describe |
---|---|---|
uri | String or Uri | The document address |
edits | Array | Edit Operation Array |
The return value
The return type | describe |
---|---|
Promise | Promise |
The sample
let workspaceEdit = new hx.WorkspaceEdit();
let edits = [];
edits.push(new hx.TextEdit({
start: 0.end: 0
}, "foo"));
workspaceEdit.set(doc.uri, edits);
hx.workspace.applyEdit(workspaceEdit);
Copy the code
TextEdit
Document editing
Property list
The property name | Attribute types | describe |
---|---|---|
range | Range | The area to modify |
newText | String | New content to insert |
replace static
Parameters that
The parameter name | The parameter types | describe |
---|---|---|
range | Range | The area to modify |
newText | String | New content to insert |
The return value
The return type | describe |
---|---|
TextEdit | Document editing object |
WorkspaceFolder
The project directory under the workspace. Each project in the project manager on the left represents a WorkspaceFolder
Property list
The property name | Attribute types | describe |
---|---|---|
uri | String orUri | Project directory Address |
name | String | Project directory Name |
nature | String | Project type |
id | String | Item Unique ID |
InputBoxOptions
Input box Settings
Property list
The property name | Attribute types | describe |
---|---|---|
prompt | String | Enter a description of the box |
value | String | Default value for input box |
placeHolder | String | Placeholder content when the input field content is empty |
password | Boolean | Yes Password box |
QuickPickOptions
Quick select box Settings
Property list
The property name | Attribute types | describe |
---|---|---|
placeHolder | String | Placeholder text when the search box on the quick select box is empty |
QuickPickItem
Quickly select candidates
Property list
The property name | Attribute types | describe |
---|---|---|
label | String | Candidate name |
description | String | Candidate description |
If you want to pass additional data, you can append custom attributes that, when the user selects the item, return which candidate was selected through a callback
TreeViewOptions
The configuration items required to create a TreeView
Property list
The property name | Attribute types | describe |
---|---|---|
showCollapseAll | Boolean | Whether to display collapsed all |
treeDataProvider | TreeDataProvider | TreeView tree control to get data interface, you need to write a subclass to implement the interface. |
- WebViewOptions
- Property list
WebViewOptions
Support for HBuilderX 2.8.1 or laterCopy the code
Call createWebView to createWebView configuration items
Property list
The property name | Attribute types | describe |
---|---|---|
enableScripts | Boolean | Whether to enable JavaScript scripting |
- WebViewPanel
- Property list
WebViewPanel
Support for HBuilderX 2.8.1 or laterCopy the code
Call createWebView returns the WebViewPanel object
Property list
The parameter name | The parameter types | describe |
---|---|---|
webView | WebView | The WebView object associated with the WebView |
dispose() | The dispose method | Call to close the extended view |
WebView
Support for HBuilderX 2.8.1 or laterCopy the code
Call createWebView to create the WebView object
Property list
The parameter name | The parameter types | describe |
---|---|---|
options | WebViewOptions | Options parameter passed when createWebView is called to create the WebView |
html | String | The HTML content to be displayed in the WebView |
onDidReceiveMessage
The callback function is called when a message from hBuilderx.postMessage is received.
Parameters that
The parameter name | The parameter types | describe |
---|---|---|
callback | Function | Callback in response to the received message |
The return value
The return type |
---|
There is no |
The sample
webview.onDidReceiveMessage((message)=>{ console.log(message) });
Copy the code
postMessage(message: any): Thenable
Send the message in the WebView
Parameters that
The parameter name | The parameter types | describe |
---|---|---|
message | Any | The message content |
The return value
The return type | describe |
---|---|
Thenable | Javascript asynchronous delay after execution |
TreeDataProvider
TreeView tree control to get data interface, can not directly instantiate the object, you need to write their own subclass to implement the interface, each custom treeDataProvider needs to implement the interface listed methods
getChildren
Gets the child node of a node. If the parameter is empty, the root node is to be obtained
Parameters that
The parameter name | The parameter types | describe |
---|---|---|
element | Any? | Gets the list of child nodes under this node. If the parameter is empty, the root node list is to be obtained |
The return value
The return type | describe |
---|---|
Promise<Any[]> | Promise |
getTreeItem
Gets the TreeItem object used to display the custom data Element (the object obtained through getChildren)
Parameters that
The parameter name | The parameter types | describe |
---|---|---|
element | Any? | An item in the list object obtained through getChildren |
The return value
The return type | describe |
---|---|
TreeItem | The node information is saved |
TreeItem
The node information is saved
Property list
The property name | Attribute types | describe |
---|---|---|
collapsibleState | Number | The value can be: 0: cannot be expanded. 1: expands |
label | String | The display name of the item |
contextValue | String | The context information for this item is passedmenus The extension pointview/item/context When the category registers the right menu, use the when expressionviewItem Variable control menu display. For example:viewItem == 'test' |
command | CommandInfo | To execute when the item is selectedThe command |
tooltip | String | Hover over a Tooltip message on the item |
CommandInfo
Configure the information objects required by a command
Property list
The property name | Attribute types | describe |
---|---|---|
command | String | To perform theThe command id |
arguments | any[] | Perform theThe command Parameter passed when |
Disposable
Resource release interface, the open part of HBuilderX API returns this object and adds it to the context.subscriptions array when the plug-in is activated. The resource will be automatically freed when the plug-in is unsubscribed.
dispose
Parameters that
There is no
The return value
There is no
UriHandler
Uri Handler interface
handleUri
Parameters that
The parameter name | The parameter types | describe |
---|---|---|
uri | Uri | Request corresponding uri scheme, eg: hbuilderx: / / requestExtension/extensionId? foo=bar |
The return value
There is no
- Uri
- Property list
Uri
Uniform resource accessor
Property list
The property name | Attribute types | describe |
---|---|---|
fsPath | String | Local File Address |
authority | String | Authorities in the Uri |
fragment | String | Fragments of the Uri |
path | String | The path of the Uri |
query | String | The Uri query |
scheme | String | The Uri scheme |
The extension point
Extension points are jSON-formatted configuration items defined by the contributes node in the plug-in package.json file. Here is a list of the extension points currently supported by HBuilderX:
configuration
The Configuration extension point registers the extended configuration items in HBuilderX’s global Visual Configuration Settings – Plug-in Configuration.
Property list
title
The configuration for each plug-in extension is assigned to the same group, and the title refers to the name of the group, usually the plug-in name.
properties
The key of the jSONObject is the ID of the configuration item to be extended. The value is a JSONObject that conforms to the JSON Schema specification. Currently, the supported fields include:
- Type type. The supported types are string, Boolean, and Number.
- The description described
- The default default value
- Enum This value is optional. Currently, the value is available only when type is string or number
The sample
"contributes": {
"configuration": {"title":"eslint-js"."properties": {"eslint-js.autoFixOnSave": {"type":"boolean"."default":true."description":"Auto-fix on save"
},
"eslint-js.validateOnDocumentChanged": {"type":"boolean"."default":false."description":"Enable real-time verification"}}}}Copy the code
commands
Commands extension points are used to declare a command that can be associated with the menus through the menus extension points
Note: When a command is about to be executed, an activationEvent of onCommand:${commandId} is fired to activate the plug-in listening for the command
The sample
"contributes": {
"commands": [{"command": "extension.firstExtension"."title": "Hello World"}}]Copy the code
snippets
Snippets extension points extend blocks of code in a specific programming language. A list of extensible programming language ids is shown here. The extension example code is as follows:
"contributes": {
"snippets": [{"language": "css"."path": "./snippets/css.json"
},
{
"project":"uni-app"."language": "css"."path": "./snippets/condition_comment.json"}}]Copy the code
Property list
The attribute name | Attribute types | Whether must | describe |
---|---|---|---|
project | String | no | Specifies whether this parameter is valid only for the specified project type. The current value can be “Web”, “App”, “Wap2App”, or “uni-app”. To support multiple project types, use commas to separate them, for example: “Web,uni-app, app” |
language | String | is | Programming language ID, which is used to qualify only the specified language. For a list of language ids, seehere |
path | String | is | The code block list file path to be extended, and the file content format is shown below |
Block format
The following table describes each configuration item:
The name of the | describe |
---|---|
key |
The code block displays the name, which is displayed in the code helper list, and “console.log” is a key in the following example. |
prefix | The triggering character of the code block is what letter is typed to match the code block. |
body | The contents of the code block. The content has the following special format: 1, if there is preset data in this position, write as {1: foo1 / foo2 / foo3}; 0 represents the final position of the cursor after the code block is entered (you can also press Enter to skip it). Double quotes are escaped by \ “, newlines are expressed by multiple arrays, one array per line, enclosed by double quotes and separated by commas, indentation is indicated by \t, cannot be indented directly! |
triggerAssist | True means that the code block entered into the document immediately triggers a code prompt on the first TabStop to pull out the code helper, which defaults to False. |
Code Block Example
// ./snippets/javascript.json
{
"console.log": {
"prefix": "logtwo"."body": [
"console.log('$1');"."\tconsole.log('${2:foo/bar}');"]."triggerAssist": false."description": "Log output to console twice"}}Copy the code
Plug-in activation
Plug-in activation is controlled by the activationEvents field in the package.json file. The plug-in is activated when an event configured with activationEvents occurs. If activationEvents is empty, the plug-in will be automatically activated when HBuilderX starts.
We strongly recommend that you do
activationEvents
, activating the plug-in at startup will reduce the startup performance of HBuilderX.
The following is a list of currently available activation events:
- onCommand
- onView
- workspaceContains
- onUri
-
onCommand
This activation event is generated when a plug-in command is about to be triggered.
"activationEvents": [ "onCommand:extension.firstExtension"]
Copy the code
onView
This activation event is triggered when an extension view is about to open for display, usually when an extension view is selected from the view – Show Extension View menu.
"activationEvents": [ "onView:extension.demoview"]
Copy the code
workspaceContains
The activation event is triggered when a project contains a specified file whose path is relative to the project.
Note: This type of event is only triggered when HBuilderX is started. This type of event is not triggered when HBuilderX is started and the corresponding file is created.
"ActivationEvents" : / / / as a project manager of a project under exist. FTP/FTP. The json file is triggered when the event. "workspaceContains: FTP/FTP. Json"]Copy the code
onUri
Declarations can respond to Scheme protocol requests. When a scheme specifies that a plug-in is to be requested, it is automatically activated if the plug-in declares a post-onURI event, and not otherwise.
"ActivationEvents ": [// declare that it can respond to scheme protocol request "onUri"]Copy the code
The event * means that the plug-in will be activated as soon as HBuilderX starts, just as if activationEvents were not configured.
The best practice is to listen for only the events that need to be listened for and try to let the plug-in load lazily
Plug-in directory name
The plug-in directory name is the unique ID of the plug-in and cannot conflict with other plug-ins. The name can only be English words and cannot be separated by Spaces.
package.json
All plug-ins must have a package.json file in the root directory. This file inherits from the NPM specification and extends some fields. Here’s what each field means:
The field names | type | Whether must | describe |
---|---|---|---|
name | String | is | The plug-in name |
displayName | String | is | The name used to display in the list of plug-ins |
version | String | is | The plug-in version number, which is used when checking for upgrades |
engines | Object | is | The property of this Object must contain at leastHBuilderX Is the compatible major version number. If the version of HBuilderX is earlier than this version, the system prompts the user to upgrade HBuilderX. For example: {” HBuilderX “:” ^ 2.7.0 “}. |
description | String | is | A short description of the plug-in, no more than 30 words |
main | String | no | Plug-in code entry file, optional for configuration plug-ins |
activationEvents | Array | no | The list of activation events, if empty, indicates that the plug-in does not load lazily |
contributes | Object | no | A configuration extension point for the plug-in |
extensionDependencies | Array | no | Other plug-in ids that the plug-in depends on |
The sample
{
"name": "helloworld"."displayName":"Simple plug-in Example"."description": "Simple plug-in example to test the plug-in API"."version": "1.0.0"."publisher": "coder"."engines": {
"HBuilderX": "^ 2.7.0"
},
"categories": [
"Other"]."main": "./extension"."activationEvents": [
"onCommand:extension.helloWorld"."onView:extensions.treedemo"]."contributes": {},
"extensionDependencies": [
"foo1"."bar1"]."dependencies": {}}Copy the code