Skip to content

How to write an extension with Node.js

Daniel Di Sarli edited this page Jun 24, 2015 · 16 revisions

How to write an extension with Node.js

What you'll need

You'll need Node.js (of course). Notepadqq supports Node 0.12. We will assume that you have a basic understanding of this platform.

API Reference: http://notepadqq.altervista.org/wp/api/

Let's begin

Create a new empty directory for your extension. We need two special files inside this directory: nqq-manifest.json and package.json.

nqq-manifest.json contains information for Notepadqq about your extension (details here):

{
  "name": "Hello World",
  "unique_name": "com.example.my-hello-world",
  "author": "John Doe",
  "version": "1.0.0",
  "description": "My first extension",
  "runtime": "nodejs",
  "main": "main.js"
}

The other file, package.json, is a basic package file for Node that specifies our dependencies:

{
  "name": "hello-world",
  "version": "1.0.0",
  "dependencies": { },
  "private": true
}

Include the Notepadqq APIs

Notepadqq communicates with the extensions via JSON messages (see Extensions-Communication-Protocol). You can (and should!) download a library to abstract from this dirty work. For Node, you find it here: https://www.npmjs.com/package/notepadqq-api

So, install notepadqq-api by running the following command from your extension directory:

npm install notepadqq-api --save

This will automatically update your package.json.

Start to code

Create a new empty text file within your extension folder. For our example, let's call it main.js as specified in nqq-manifest.json. Now your directory structure should look like this:

hello-world/
  main.js
  node_modules/
  nqq-manifest.json
  package.json

It's time to write main.js:

// First, require the module 
var NotepadqqApi = require("notepadqq-api").NotepadqqApi
 
// Connect to Notepadqq 
NotepadqqApi.connect(function(api) {
 
    // Print the version of Notepadqq to the console 
    console.log("Version " + api.notepadqq.version())
 
    // We initialize each window here 
    api.onWindowInitialization(function(window) {
 
        // Add a new menu item 
        var menu = window.addExtensionMenuItem(api.extensionId, "My menu")
 
        // Add an handler to the "triggered" event of the menu item: it 
        // will be called when the user clicks on the menu. 
        menu.on("triggered", function() {
 
            // Replace the selected text in the currently opened tab 
            // with the string "Hello World" 
            window.currentEditor().setSelectionsText(["Hello World"]);
 
        });
 
    });
 
});

Packaging

To build a package, run the following command from the extension's folder:

$ node /usr/share/notepadqq/extension_tools/pack.js . npm

This will create the package hello-world-1.0.0.nqqext in the current directory. You're ready to test and distribute it!