├── GENERATOR_DOC.md ├── README.md ├── api ├── Global.d.ts ├── Joplin.d.ts ├── JoplinCommands.d.ts ├── JoplinContentScripts.d.ts ├── JoplinData.d.ts ├── JoplinFilters.d.ts ├── JoplinInterop.d.ts ├── JoplinPlugins.d.ts ├── JoplinSettings.d.ts ├── JoplinViews.d.ts ├── JoplinViewsDialogs.d.ts ├── JoplinViewsMenuItems.d.ts ├── JoplinViewsMenus.d.ts ├── JoplinViewsPanels.d.ts ├── JoplinViewsToolbarButtons.d.ts ├── JoplinWorkspace.d.ts ├── index.ts └── types.ts ├── package-lock.json ├── package.json ├── plugin.config.json ├── screenshot_after.png ├── screenshot_before.png ├── src ├── index.ts └── manifest.json ├── tsconfig.json └── webpack.config.js /GENERATOR_DOC.md: -------------------------------------------------------------------------------- 1 | # generator-joplin 2 | 3 | Scaffolds out a new Joplin plugin 4 | 5 | ## Installation 6 | 7 | First, install [Yeoman](http://yeoman.io) and generator-joplin using [npm](https://www.npmjs.com/) (we assume you have pre-installed [node.js](https://nodejs.org/)). 8 | 9 | ```bash 10 | npm install -g yo 11 | npm install -g generator-joplin 12 | ``` 13 | 14 | Then generate your new project: 15 | 16 | ```bash 17 | yo joplin 18 | ``` 19 | 20 | ## Development 21 | 22 | To test the generator for development purposes, follow the instructions there: https://yeoman.io/authoring/#running-the-generator 23 | This is a template to create a new Joplin plugin. 24 | 25 | ## Structure 26 | 27 | The main two files you will want to look at are: 28 | 29 | - `/src/index.ts`, which contains the entry point for the plugin source code. 30 | - `/src/manifest.json`, which is the plugin manifest. It contains information such as the plugin a name, version, etc. 31 | 32 | The file `/plugin.config.json` could also be useful if you intend to use [external scripts](#external-script-files), such as content scripts or webview scripts. 33 | 34 | ## Building the plugin 35 | 36 | The plugin is built using Webpack, which creates the compiled code in `/dist`. A JPL archive will also be created at the root, which can use to distribute the plugin. 37 | 38 | To build the plugin, simply run `npm run dist`. 39 | 40 | The project is setup to use TypeScript, although you can change the configuration to use plain JavaScript. 41 | 42 | ## Publishing the plugin 43 | 44 | To publish the plugin, add it to npmjs.com by running `npm publish`. Later on, a script will pick up your plugin and add it automatically to the Joplin plugin repository as long as the package satisfies these conditions: 45 | 46 | - In `package.json`, the name starts with "joplin-plugin-". For example, "joplin-plugin-toc". 47 | - In `package.json`, the keywords include "joplin-plugin". 48 | - In the `publish/` directory, there should be a .jpl and .json file (which are built by `npm run dist`) 49 | 50 | In general all this is done automatically by the plugin generator, which will set the name and keywords of package.json, and will put the right files in the "publish" directory. But if something doesn't work and your plugin doesn't appear in the repository, double-check the above conditions. 51 | 52 | ## Updating the plugin framework 53 | 54 | To update the plugin framework, run `npm run update`. 55 | 56 | In general this command tries to do the right thing - in particular it's going to merge the changes in package.json and .gitignore instead of overwriting. It will also leave "/src" as well as README.md untouched. 57 | 58 | The file that may cause problem is "webpack.config.js" because it's going to be overwritten. For that reason, if you want to change it, consider creating a separate JavaScript file and include it in webpack.config.js. That way, when you update, you only have to restore the line that include your file. 59 | 60 | ## External script files 61 | 62 | By default, the compiler (webpack) is going to compile `src/index.ts` only (as well as any file it imports), and any other file will simply be copied to the plugin package. In some cases this is sufficient, however if you have [content scripts](https://joplinapp.org/api/references/plugin_api/classes/joplincontentscripts.html) or [webview scripts](https://joplinapp.org/api/references/plugin_api/classes/joplinviewspanels.html#addscript) you might want to compile them too, in particular in these two cases: 63 | 64 | - The script is a TypeScript file - in which case it has to be compiled to JavaScript. 65 | 66 | - The script requires modules you've added to package.json. In that case, the script, whether JS or TS, must be compiled so that the dependencies are bundled with the JPL file. 67 | 68 | To get such an external script file to compile, you need to add it to the `extraScripts` array in `plugin.config.json`. The path you add should be relative to /src. For example, if you have a file in "/src/webviews/index.ts", the path should be set to "webviews/index.ts". Once compiled, the file will always be named with a .js extension. So you will get "webviews/index.js" in the plugin package, and that's the path you should use to reference the file. 69 | 70 | ## License 71 | 72 | MIT © Laurent Cozic 73 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Make all possible links 2 | 3 | This plugin searches the current note for mentions of other notes, then makes the corresponding links. 4 | Just click the new icon in the toolbar. 5 | 6 | This plugin is experimental and comes with absolutely no warranty of any kind. Use at your own risk. 7 | 8 | ### Before 9 | ![](screenshot_before.png) 10 | ### After clicking the icon 11 | ![](screenshot_after.png) 12 | 13 | 14 | ## Joplin Plugin 15 | 16 | The main two files you will want to look at are: 17 | 18 | - `/src/index.ts`, which contains the entry point for the plugin source code. 19 | - `/src/manifest.json`, which is the plugin manifest. It contains information such as the plugin a name, version, etc. 20 | 21 | The plugin is built using webpack, which create the compiled code in `/dist`. The project is setup to use TypeScript, although you can change the configuration to use plain JavaScript. 22 | 23 | ## Building the plugin 24 | 25 | To build the plugin, simply run `npm run dist`. 26 | -------------------------------------------------------------------------------- /api/Global.d.ts: -------------------------------------------------------------------------------- 1 | import Plugin from '../Plugin'; 2 | import Joplin from './Joplin'; 3 | /** 4 | * @ignore 5 | */ 6 | /** 7 | * @ignore 8 | */ 9 | export default class Global { 10 | private joplin_; 11 | constructor(implementation: any, plugin: Plugin, store: any); 12 | get joplin(): Joplin; 13 | get process(): any; 14 | } 15 | -------------------------------------------------------------------------------- /api/Joplin.d.ts: -------------------------------------------------------------------------------- 1 | import Plugin from '../Plugin'; 2 | import JoplinData from './JoplinData'; 3 | import JoplinPlugins from './JoplinPlugins'; 4 | import JoplinWorkspace from './JoplinWorkspace'; 5 | import JoplinFilters from './JoplinFilters'; 6 | import JoplinCommands from './JoplinCommands'; 7 | import JoplinViews from './JoplinViews'; 8 | import JoplinInterop from './JoplinInterop'; 9 | import JoplinSettings from './JoplinSettings'; 10 | import JoplinContentScripts from './JoplinContentScripts'; 11 | /** 12 | * This is the main entry point to the Joplin API. You can access various services using the provided accessors. 13 | * 14 | * **This is a beta API** 15 | * 16 | * Please note that the plugin API is relatively new and should be considered Beta state. Besides possible bugs, what it means is that there might be necessary breaking changes from one version to the next. Whenever such change is needed, best effort will be done to: 17 | * 18 | * - Maintain backward compatibility; 19 | * - When possible, deprecate features instead of removing them; 20 | * - Document breaking changes in the changelog; 21 | * 22 | * So if you are developing a plugin, please keep an eye on the changelog as everything will be in there with information about how to update your code. There won't be any major API rewrite or architecture changes, but possibly small tweaks like function signature change, type change, etc. 23 | * 24 | * Eventually, the plugin API will be versioned to make this process smoother. 25 | */ 26 | export default class Joplin { 27 | private data_; 28 | private plugins_; 29 | private workspace_; 30 | private filters_; 31 | private commands_; 32 | private views_; 33 | private interop_; 34 | private settings_; 35 | private contentScripts_; 36 | constructor(implementation: any, plugin: Plugin, store: any); 37 | get data(): JoplinData; 38 | get plugins(): JoplinPlugins; 39 | get workspace(): JoplinWorkspace; 40 | get contentScripts(): JoplinContentScripts; 41 | /** 42 | * @ignore 43 | * 44 | * Not sure if it's the best way to hook into the app 45 | * so for now disable filters. 46 | */ 47 | get filters(): JoplinFilters; 48 | get commands(): JoplinCommands; 49 | get views(): JoplinViews; 50 | get interop(): JoplinInterop; 51 | get settings(): JoplinSettings; 52 | /** 53 | * It is not possible to bundle native packages with a plugin, because they 54 | * need to work cross-platforms. Instead access to certain useful native 55 | * packages is provided using this function. 56 | * 57 | * Currently these packages are available: 58 | * 59 | * - [sqlite3](https://www.npmjs.com/package/sqlite3) 60 | * - [fs-extra](https://www.npmjs.com/package/fs-extra) 61 | * 62 | * [View the demo plugin](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/nativeModule) 63 | */ 64 | require(_path: string): any; 65 | } 66 | -------------------------------------------------------------------------------- /api/JoplinCommands.d.ts: -------------------------------------------------------------------------------- 1 | import { Command } from './types'; 2 | /** 3 | * This class allows executing or registering new Joplin commands. Commands 4 | * can be executed or associated with 5 | * {@link JoplinViewsToolbarButtons | toolbar buttons} or 6 | * {@link JoplinViewsMenuItems | menu items}. 7 | * 8 | * [View the demo plugin](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/register_command) 9 | * 10 | * ## Executing Joplin's internal commands 11 | * 12 | * It is also possible to execute internal Joplin's commands which, as of 13 | * now, are not well documented. You can find the list directly on GitHub 14 | * though at the following locations: 15 | * 16 | * * [Main screen commands](https://github.com/laurent22/joplin/tree/dev/packages/app-desktop/gui/MainScreen/commands) 17 | * * [Global commands](https://github.com/laurent22/joplin/tree/dev/packages/app-desktop/commands) 18 | * * [Editor commands](https://github.com/laurent22/joplin/tree/dev/packages/app-desktop/gui/NoteEditor/commands/editorCommandDeclarations.ts) 19 | * 20 | * To view what arguments are supported, you can open any of these files 21 | * and look at the `execute()` command. 22 | * 23 | * ## Executing editor commands 24 | * 25 | * There might be a situation where you want to invoke editor commands 26 | * without using a {@link JoplinContentScripts | contentScript}. For this 27 | * reason Joplin provides the built in `editor.execCommand` command. 28 | * 29 | * `editor.execCommand` should work with any core command in both the 30 | * [CodeMirror](https://codemirror.net/doc/manual.html#execCommand) and 31 | * [TinyMCE](https://www.tiny.cloud/docs/api/tinymce/tinymce.editorcommands/#execcommand) editors, 32 | * as well as most functions calls directly on a CodeMirror editor object (extensions). 33 | * 34 | * * [CodeMirror commands](https://codemirror.net/doc/manual.html#commands) 35 | * * [TinyMCE core editor commands](https://www.tiny.cloud/docs/advanced/editor-command-identifiers/#coreeditorcommands) 36 | * 37 | * `editor.execCommand` supports adding arguments for the commands. 38 | * 39 | * ```typescript 40 | * await joplin.commands.execute('editor.execCommand', { 41 | * name: 'madeUpCommand', // CodeMirror and TinyMCE 42 | * args: [], // CodeMirror and TinyMCE 43 | * ui: false, // TinyMCE only 44 | * value: '', // TinyMCE only 45 | * }); 46 | * ``` 47 | * 48 | * [View the example using the CodeMirror editor](https://github.com/laurent22/joplin/blob/dev/packages/app-cli/tests/support/plugins/codemirror_content_script/src/index.ts) 49 | * 50 | */ 51 | export default class JoplinCommands { 52 | /** 53 | * desktop Executes the given 54 | * command. 55 | * 56 | * The command can take any number of arguments, and the supported 57 | * arguments will vary based on the command. For custom commands, this 58 | * is the `args` passed to the `execute()` function. For built-in 59 | * commands, you can find the supported arguments by checking the links 60 | * above. 61 | * 62 | * ```typescript 63 | * // Create a new note in the current notebook: 64 | * await joplin.commands.execute('newNote'); 65 | * 66 | * // Create a new sub-notebook under the provided notebook 67 | * // Note: internally, notebooks are called "folders". 68 | * await joplin.commands.execute('newFolder', "SOME_FOLDER_ID"); 69 | * ``` 70 | */ 71 | execute(commandName: string, ...args: any[]): Promise; 72 | /** 73 | * desktop Registers a new command. 74 | * 75 | * ```typescript 76 | * // Register a new commmand called "testCommand1" 77 | * 78 | * await joplin.commands.register({ 79 | * name: 'testCommand1', 80 | * label: 'My Test Command 1', 81 | * iconName: 'fas fa-music', 82 | * execute: () => { 83 | * alert('Testing plugin command 1'); 84 | * }, 85 | * }); 86 | * ``` 87 | */ 88 | register(command: Command): Promise; 89 | } 90 | -------------------------------------------------------------------------------- /api/JoplinContentScripts.d.ts: -------------------------------------------------------------------------------- 1 | import Plugin from '../Plugin'; 2 | import { ContentScriptType } from './types'; 3 | export default class JoplinContentScripts { 4 | private plugin; 5 | constructor(plugin: Plugin); 6 | /** 7 | * Registers a new content script. Unlike regular plugin code, which runs in 8 | * a separate process, content scripts run within the main process code and 9 | * thus allow improved performances and more customisations in specific 10 | * cases. It can be used for example to load a Markdown or editor plugin. 11 | * 12 | * Note that registering a content script in itself will do nothing - it 13 | * will only be loaded in specific cases by the relevant app modules (eg. 14 | * the Markdown renderer or the code editor). So it is not a way to inject 15 | * and run arbitrary code in the app, which for safety and performance 16 | * reasons is not supported. 17 | * 18 | * The plugin generator provides a way to build any content script you might 19 | * want to package as well as its dependencies. See the [Plugin Generator 20 | * doc](https://github.com/laurent22/joplin/blob/dev/packages/generator-joplin/README.md) 21 | * for more information. 22 | * 23 | * * [View the renderer demo plugin](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/content_script) 24 | * * [View the editor demo plugin](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/codemirror_content_script) 25 | * 26 | * See also the [postMessage demo](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/post_messages) 27 | * 28 | * @param type Defines how the script will be used. See the type definition for more information about each supported type. 29 | * @param id A unique ID for the content script. 30 | * @param scriptPath Must be a path relative to the plugin main script. For example, if your file content_script.js is next to your index.ts file, you would set `scriptPath` to `"./content_script.js`. 31 | */ 32 | register(type: ContentScriptType, id: string, scriptPath: string): Promise; 33 | /** 34 | * Listens to a messages sent from the content script using postMessage(). 35 | * See {@link ContentScriptType} for more information as well as the 36 | * [postMessage 37 | * demo](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/post_messages) 38 | */ 39 | onMessage(contentScriptId: string, callback: any): Promise; 40 | } 41 | -------------------------------------------------------------------------------- /api/JoplinData.d.ts: -------------------------------------------------------------------------------- 1 | import { Path } from './types'; 2 | /** 3 | * This module provides access to the Joplin data API: https://joplinapp.org/api/references/rest_api/ 4 | * This is the main way to retrieve data, such as notes, notebooks, tags, etc. 5 | * or to update them or delete them. 6 | * 7 | * This is also what you would use to search notes, via the `search` endpoint. 8 | * 9 | * [View the demo plugin](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/simple) 10 | * 11 | * In general you would use the methods in this class as if you were using a REST API. There are four methods that map to GET, POST, PUT and DELETE calls. 12 | * And each method takes these parameters: 13 | * 14 | * * `path`: This is an array that represents the path to the resource in the form `["resouceName", "resourceId", "resourceLink"]` (eg. ["tags", ":id", "notes"]). The "resources" segment is the name of the resources you want to access (eg. "notes", "folders", etc.). If not followed by anything, it will refer to all the resources in that collection. The optional "resourceId" points to a particular resources within the collection. Finally, an optional "link" can be present, which links the resource to a collection of resources. This can be used in the API for example to retrieve all the notes associated with a tag. 15 | * * `query`: (Optional) The query parameters. In a URL, this is the part after the question mark "?". In this case, it should be an object with key/value pairs. 16 | * * `data`: (Optional) Applies to PUT and POST calls only. The request body contains the data you want to create or modify, for example the content of a note or folder. 17 | * * `files`: (Optional) Used to create new resources and associate them with files. 18 | * 19 | * Please refer to the [Joplin API documentation](https://joplinapp.org/api/references/rest_api/) for complete details about each call. As the plugin runs within the Joplin application **you do not need an authorisation token** to use this API. 20 | * 21 | * For example: 22 | * 23 | * ```typescript 24 | * // Get a note ID, title and body 25 | * const noteId = 'some_note_id'; 26 | * const note = await joplin.data.get(['notes', noteId], { fields: ['id', 'title', 'body'] }); 27 | * 28 | * // Get all folders 29 | * const folders = await joplin.data.get(['folders']); 30 | * 31 | * // Set the note body 32 | * await joplin.data.put(['notes', noteId], null, { body: "New note body" }); 33 | * 34 | * // Create a new note under one of the folders 35 | * await joplin.data.post(['notes'], null, { body: "my new note", title: "some title", parent_id: folders[0].id }); 36 | * ``` 37 | */ 38 | export default class JoplinData { 39 | private api_; 40 | private pathSegmentRegex_; 41 | private serializeApiBody; 42 | private pathToString; 43 | get(path: Path, query?: any): Promise; 44 | post(path: Path, query?: any, body?: any, files?: any[]): Promise; 45 | put(path: Path, query?: any, body?: any, files?: any[]): Promise; 46 | delete(path: Path, query?: any): Promise; 47 | } 48 | -------------------------------------------------------------------------------- /api/JoplinFilters.d.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * @ignore 3 | * 4 | * Not sure if it's the best way to hook into the app 5 | * so for now disable filters. 6 | */ 7 | export default class JoplinFilters { 8 | on(name: string, callback: Function): Promise; 9 | off(name: string, callback: Function): Promise; 10 | } 11 | -------------------------------------------------------------------------------- /api/JoplinInterop.d.ts: -------------------------------------------------------------------------------- 1 | import { ExportModule, ImportModule } from './types'; 2 | /** 3 | * Provides a way to create modules to import external data into Joplin or to export notes into any arbitrary format. 4 | * 5 | * [View the demo plugin](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/json_export) 6 | * 7 | * To implement an import or export module, you would simply define an object with various event handlers that are called 8 | * by the application during the import/export process. 9 | * 10 | * See the documentation of the [[ExportModule]] and [[ImportModule]] for more information. 11 | * 12 | * You may also want to refer to the Joplin API documentation to see the list of properties for each item (note, notebook, etc.) - https://joplinapp.org/api/references/rest_api/ 13 | */ 14 | export default class JoplinInterop { 15 | registerExportModule(module: ExportModule): Promise; 16 | registerImportModule(module: ImportModule): Promise; 17 | } 18 | -------------------------------------------------------------------------------- /api/JoplinPlugins.d.ts: -------------------------------------------------------------------------------- 1 | import Plugin from '../Plugin'; 2 | import { ContentScriptType, Script } from './types'; 3 | /** 4 | * This class provides access to plugin-related features. 5 | */ 6 | export default class JoplinPlugins { 7 | private plugin; 8 | constructor(plugin: Plugin); 9 | /** 10 | * Registers a new plugin. This is the entry point when creating a plugin. You should pass a simple object with an `onStart` method to it. 11 | * That `onStart` method will be executed as soon as the plugin is loaded. 12 | * 13 | * ```typescript 14 | * joplin.plugins.register({ 15 | * onStart: async function() { 16 | * // Run your plugin code here 17 | * } 18 | * }); 19 | * ``` 20 | */ 21 | register(script: Script): Promise; 22 | /** 23 | * @deprecated Use joplin.contentScripts.register() 24 | */ 25 | registerContentScript(type: ContentScriptType, id: string, scriptPath: string): Promise; 26 | /** 27 | * Gets the plugin own data directory path. Use this to store any 28 | * plugin-related data. Unlike [[installationDir]], any data stored here 29 | * will be persisted. 30 | */ 31 | dataDir(): Promise; 32 | /** 33 | * Gets the plugin installation directory. This can be used to access any 34 | * asset that was packaged with the plugin. This directory should be 35 | * considered read-only because any data you store here might be deleted or 36 | * re-created at any time. To store new persistent data, use [[dataDir]]. 37 | */ 38 | installationDir(): Promise; 39 | /** 40 | * @deprecated Use joplin.require() 41 | */ 42 | require(_path: string): any; 43 | } 44 | -------------------------------------------------------------------------------- /api/JoplinSettings.d.ts: -------------------------------------------------------------------------------- 1 | import Plugin from '../Plugin'; 2 | import { SettingItem, SettingSection } from './types'; 3 | export interface ChangeEvent { 4 | /** 5 | * Setting keys that have been changed 6 | */ 7 | keys: string[]; 8 | } 9 | export declare type ChangeHandler = (event: ChangeEvent)=> void; 10 | /** 11 | * This API allows registering new settings and setting sections, as well as getting and setting settings. Once a setting has been registered it will appear in the config screen and be editable by the user. 12 | * 13 | * Settings are essentially key/value pairs. 14 | * 15 | * Note: Currently this API does **not** provide access to Joplin's built-in settings. This is by design as plugins that modify user settings could give unexpected results 16 | * 17 | * [View the demo plugin](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/settings) 18 | */ 19 | export default class JoplinSettings { 20 | private plugin_; 21 | constructor(plugin: Plugin); 22 | private get keyPrefix(); 23 | private namespacedKey; 24 | /** 25 | * Registers new settings. 26 | * Note that registering a setting item is dynamic and will be gone next time Joplin starts. 27 | * What it means is that you need to register the setting every time the plugin starts (for example in the onStart event). 28 | * The setting value however will be preserved from one launch to the next so there is no risk that it will be lost even if for some 29 | * reason the plugin fails to start at some point. 30 | */ 31 | registerSettings(settings: Record): Promise; 32 | /** 33 | * @deprecated Use joplin.settings.registerSettings() 34 | * 35 | * Registers a new setting. 36 | */ 37 | registerSetting(key: string, settingItem: SettingItem): Promise; 38 | /** 39 | * Registers a new setting section. Like for registerSetting, it is dynamic and needs to be done every time the plugin starts. 40 | */ 41 | registerSection(name: string, section: SettingSection): Promise; 42 | /** 43 | * Gets a setting value (only applies to setting you registered from your plugin) 44 | */ 45 | value(key: string): Promise; 46 | /** 47 | * Sets a setting value (only applies to setting you registered from your plugin) 48 | */ 49 | setValue(key: string, value: any): Promise; 50 | /** 51 | * Gets a global setting value, including app-specific settings and those set by other plugins. 52 | * 53 | * The list of available settings is not documented yet, but can be found by looking at the source code: 54 | * 55 | * https://github.com/laurent22/joplin/blob/dev/packages/lib/models/Setting.ts#L142 56 | */ 57 | globalValue(key: string): Promise; 58 | /** 59 | * Called when one or multiple settings of your plugin have been changed. 60 | * - For performance reasons, this event is triggered with a delay. 61 | * - You will only get events for your own plugin settings. 62 | */ 63 | onChange(handler: ChangeHandler): Promise; 64 | } 65 | -------------------------------------------------------------------------------- /api/JoplinViews.d.ts: -------------------------------------------------------------------------------- 1 | import Plugin from '../Plugin'; 2 | import JoplinViewsDialogs from './JoplinViewsDialogs'; 3 | import JoplinViewsMenuItems from './JoplinViewsMenuItems'; 4 | import JoplinViewsMenus from './JoplinViewsMenus'; 5 | import JoplinViewsToolbarButtons from './JoplinViewsToolbarButtons'; 6 | import JoplinViewsPanels from './JoplinViewsPanels'; 7 | /** 8 | * This namespace provides access to view-related services. 9 | * 10 | * All view services provide a `create()` method which you would use to create the view object, whether it's a dialog, a toolbar button or a menu item. 11 | * In some cases, the `create()` method will return a [[ViewHandle]], which you would use to act on the view, for example to set certain properties or call some methods. 12 | */ 13 | export default class JoplinViews { 14 | private store; 15 | private plugin; 16 | private dialogs_; 17 | private panels_; 18 | private menuItems_; 19 | private menus_; 20 | private toolbarButtons_; 21 | private implementation_; 22 | constructor(implementation: any, plugin: Plugin, store: any); 23 | get dialogs(): JoplinViewsDialogs; 24 | get panels(): JoplinViewsPanels; 25 | get menuItems(): JoplinViewsMenuItems; 26 | get menus(): JoplinViewsMenus; 27 | get toolbarButtons(): JoplinViewsToolbarButtons; 28 | } 29 | -------------------------------------------------------------------------------- /api/JoplinViewsDialogs.d.ts: -------------------------------------------------------------------------------- 1 | import Plugin from '../Plugin'; 2 | import { ButtonSpec, ViewHandle, DialogResult } from './types'; 3 | /** 4 | * Allows creating and managing dialogs. A dialog is modal window that 5 | * contains a webview and a row of buttons. You can update the update the 6 | * webview using the `setHtml` method. Dialogs are hidden by default and 7 | * you need to call `open()` to open them. Once the user clicks on a 8 | * button, the `open` call will return an object indicating what button was 9 | * clicked on. 10 | * 11 | * ## Retrieving form values 12 | * 13 | * If your HTML content included one or more forms, a `formData` object 14 | * will also be included with the key/value for each form. 15 | * 16 | * ## Special button IDs 17 | * 18 | * The following buttons IDs have a special meaning: 19 | * 20 | * - `ok`, `yes`, `submit`, `confirm`: They are considered "submit" buttons 21 | * - `cancel`, `no`, `reject`: They are considered "dismiss" buttons 22 | * 23 | * This information is used by the application to determine what action 24 | * should be done when the user presses "Enter" or "Escape" within the 25 | * dialog. If they press "Enter", the first "submit" button will be 26 | * automatically clicked. If they press "Escape" the first "dismiss" button 27 | * will be automatically clicked. 28 | * 29 | * [View the demo 30 | * plugin](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/dialog) 31 | */ 32 | export default class JoplinViewsDialogs { 33 | private store; 34 | private plugin; 35 | private implementation_; 36 | constructor(implementation: any, plugin: Plugin, store: any); 37 | private controller; 38 | /** 39 | * Creates a new dialog 40 | */ 41 | create(id: string): Promise; 42 | /** 43 | * Displays a message box with OK/Cancel buttons. Returns the button index that was clicked - "0" for OK and "1" for "Cancel" 44 | */ 45 | showMessageBox(message: string): Promise; 46 | /** 47 | * Sets the dialog HTML content 48 | */ 49 | setHtml(handle: ViewHandle, html: string): Promise; 50 | /** 51 | * Adds and loads a new JS or CSS files into the dialog. 52 | */ 53 | addScript(handle: ViewHandle, scriptPath: string): Promise; 54 | /** 55 | * Sets the dialog buttons. 56 | */ 57 | setButtons(handle: ViewHandle, buttons: ButtonSpec[]): Promise; 58 | /** 59 | * Opens the dialog 60 | */ 61 | open(handle: ViewHandle): Promise; 62 | } 63 | -------------------------------------------------------------------------------- /api/JoplinViewsMenuItems.d.ts: -------------------------------------------------------------------------------- 1 | import { CreateMenuItemOptions, MenuItemLocation } from './types'; 2 | import Plugin from '../Plugin'; 3 | /** 4 | * Allows creating and managing menu items. 5 | * 6 | * [View the demo plugin](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/register_command) 7 | */ 8 | export default class JoplinViewsMenuItems { 9 | private store; 10 | private plugin; 11 | constructor(plugin: Plugin, store: any); 12 | /** 13 | * Creates a new menu item and associate it with the given command. You can specify under which menu the item should appear using the `location` parameter. 14 | */ 15 | create(id: string, commandName: string, location?: MenuItemLocation, options?: CreateMenuItemOptions): Promise; 16 | } 17 | -------------------------------------------------------------------------------- /api/JoplinViewsMenus.d.ts: -------------------------------------------------------------------------------- 1 | import { MenuItem, MenuItemLocation } from './types'; 2 | import Plugin from '../Plugin'; 3 | /** 4 | * Allows creating menus. 5 | * 6 | * [View the demo plugin](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/menu) 7 | */ 8 | export default class JoplinViewsMenus { 9 | private store; 10 | private plugin; 11 | constructor(plugin: Plugin, store: any); 12 | private registerCommandAccelerators; 13 | /** 14 | * Creates a new menu from the provided menu items and place it at the given location. As of now, it is only possible to place the 15 | * menu as a sub-menu of the application build-in menus. 16 | */ 17 | create(id: string, label: string, menuItems: MenuItem[], location?: MenuItemLocation): Promise; 18 | } 19 | -------------------------------------------------------------------------------- /api/JoplinViewsPanels.d.ts: -------------------------------------------------------------------------------- 1 | import Plugin from '../Plugin'; 2 | import { ViewHandle } from './types'; 3 | /** 4 | * Allows creating and managing view panels. View panels currently are 5 | * displayed at the right of the sidebar and allows displaying any HTML 6 | * content (within a webview) and update it in real-time. For example it 7 | * could be used to display a table of content for the active note, or 8 | * display various metadata or graph. 9 | * 10 | * [View the demo plugin](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/toc) 11 | */ 12 | export default class JoplinViewsPanels { 13 | private store; 14 | private plugin; 15 | constructor(plugin: Plugin, store: any); 16 | private controller; 17 | /** 18 | * Creates a new panel 19 | */ 20 | create(id: string): Promise; 21 | /** 22 | * Sets the panel webview HTML 23 | */ 24 | setHtml(handle: ViewHandle, html: string): Promise; 25 | /** 26 | * Adds and loads a new JS or CSS files into the panel. 27 | */ 28 | addScript(handle: ViewHandle, scriptPath: string): Promise; 29 | /** 30 | * Called when a message is sent from the webview (using postMessage). 31 | * 32 | * To post a message from the webview to the plugin use: 33 | * 34 | * ```javascript 35 | * const response = await webviewApi.postMessage(message); 36 | * ``` 37 | * 38 | * - `message` can be any JavaScript object, string or number 39 | * - `response` is whatever was returned by the `onMessage` handler 40 | * 41 | * Using this mechanism, you can have two-way communication between the 42 | * plugin and webview. 43 | * 44 | * See the [postMessage 45 | * demo](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/post_messages) for more details. 46 | * 47 | */ 48 | onMessage(handle: ViewHandle, callback: Function): Promise; 49 | /** 50 | * Shows the panel 51 | */ 52 | show(handle: ViewHandle, show?: boolean): Promise; 53 | /** 54 | * Hides the panel 55 | */ 56 | hide(handle: ViewHandle): Promise; 57 | /** 58 | * Tells whether the panel is visible or not 59 | */ 60 | visible(handle: ViewHandle): Promise; 61 | } 62 | -------------------------------------------------------------------------------- /api/JoplinViewsToolbarButtons.d.ts: -------------------------------------------------------------------------------- 1 | import { ToolbarButtonLocation } from './types'; 2 | import Plugin from '../Plugin'; 3 | /** 4 | * Allows creating and managing toolbar buttons. 5 | * 6 | * [View the demo plugin](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/register_command) 7 | */ 8 | export default class JoplinViewsToolbarButtons { 9 | private store; 10 | private plugin; 11 | constructor(plugin: Plugin, store: any); 12 | /** 13 | * Creates a new toolbar button and associate it with the given command. 14 | */ 15 | create(id: string, commandName: string, location: ToolbarButtonLocation): Promise; 16 | } 17 | -------------------------------------------------------------------------------- /api/JoplinWorkspace.d.ts: -------------------------------------------------------------------------------- 1 | import { FolderEntity } from '../../database/types'; 2 | import { Disposable } from './types'; 3 | declare enum ItemChangeEventType { 4 | Create = 1, 5 | Update = 2, 6 | Delete = 3, 7 | } 8 | interface ItemChangeEvent { 9 | id: string; 10 | event: ItemChangeEventType; 11 | } 12 | interface SyncStartEvent { 13 | withErrors: boolean; 14 | } 15 | declare type ItemChangeHandler = (event: ItemChangeEvent)=> void; 16 | declare type SyncStartHandler = (event: SyncStartEvent)=> void; 17 | /** 18 | * The workspace service provides access to all the parts of Joplin that 19 | * are being worked on - i.e. the currently selected notes or notebooks as 20 | * well as various related events, such as when a new note is selected, or 21 | * when the note content changes. 22 | * 23 | * [View the demo plugin](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins) 24 | */ 25 | export default class JoplinWorkspace { 26 | private store; 27 | constructor(store: any); 28 | /** 29 | * Called when a new note or notes are selected. 30 | */ 31 | onNoteSelectionChange(callback: Function): Promise; 32 | /** 33 | * Called when the content of a note changes. 34 | * @deprecated Use `onNoteChange()` instead, which is reliably triggered whenever the note content, or any note property changes. 35 | */ 36 | onNoteContentChange(callback: Function): Promise; 37 | /** 38 | * Called when the content of the current note changes. 39 | */ 40 | onNoteChange(handler: ItemChangeHandler): Promise; 41 | /** 42 | * Called when an alarm associated with a to-do is triggered. 43 | */ 44 | onNoteAlarmTrigger(handler: Function): Promise; 45 | /** 46 | * Called when the synchronisation process is starting. 47 | */ 48 | onSyncStart(handler: SyncStartHandler): Promise; 49 | /** 50 | * Called when the synchronisation process has finished. 51 | */ 52 | onSyncComplete(callback: Function): Promise; 53 | /** 54 | * Gets the currently selected note 55 | */ 56 | selectedNote(): Promise; 57 | /** 58 | * Gets the currently selected folder. In some cases, for example during 59 | * search or when viewing a tag, no folder is actually selected in the user 60 | * interface. In that case, that function would return the last selected 61 | * folder. 62 | */ 63 | selectedFolder(): Promise; 64 | /** 65 | * Gets the IDs of the selected notes (can be zero, one, or many). Use the data API to retrieve information about these notes. 66 | */ 67 | selectedNoteIds(): Promise; 68 | } 69 | export {}; 70 | -------------------------------------------------------------------------------- /api/index.ts: -------------------------------------------------------------------------------- 1 | import type Joplin from './Joplin'; 2 | 3 | declare const joplin: Joplin; 4 | 5 | export default joplin; 6 | -------------------------------------------------------------------------------- /api/types.ts: -------------------------------------------------------------------------------- 1 | // ================================================================= 2 | // Command API types 3 | // ================================================================= 4 | 5 | export interface Command { 6 | /** 7 | * Name of command - must be globally unique 8 | */ 9 | name: string; 10 | 11 | /** 12 | * Label to be displayed on menu items or keyboard shortcut editor for example. 13 | * If it is missing, it's assumed it's a private command, to be called programmatically only. 14 | * In that case the command will not appear in the shortcut editor or command panel, and logically 15 | * should not be used as a menu item. 16 | */ 17 | label?: string; 18 | 19 | /** 20 | * Icon to be used on toolbar buttons for example 21 | */ 22 | iconName?: string; 23 | 24 | /** 25 | * Code to be ran when the command is executed. It may return a result. 26 | */ 27 | execute(...args: any[]): Promise; 28 | 29 | /** 30 | * Defines whether the command should be enabled or disabled, which in turns 31 | * affects the enabled state of any associated button or menu item. 32 | * 33 | * The condition should be expressed as a "when-clause" (as in Visual Studio 34 | * Code). It's a simple boolean expression that evaluates to `true` or 35 | * `false`. It supports the following operators: 36 | * 37 | * Operator | Symbol | Example 38 | * -- | -- | -- 39 | * Equality | == | "editorType == markdown" 40 | * Inequality | != | "currentScreen != config" 41 | * Or | \|\| | "noteIsTodo \|\| noteTodoCompleted" 42 | * And | && | "oneNoteSelected && !inConflictFolder" 43 | * 44 | * Joplin, unlike VSCode, also supports parenthesis, which allows creating 45 | * more complex expressions such as `cond1 || (cond2 && cond3)`. Only one 46 | * level of parenthesis is possible (nested ones aren't supported). 47 | * 48 | * Currently the supported context variables aren't documented, but you can 49 | * find the list below: 50 | * 51 | * - [Global When Clauses](https://github.com/laurent22/joplin/blob/dev/packages/lib/services/commands/stateToWhenClauseContext.ts) 52 | * - [Desktop app When Clauses](https://github.com/laurent22/joplin/blob/dev/packages/app-desktop/services/commands/stateToWhenClauseContext.ts) 53 | * 54 | * Note: Commands are enabled by default unless you use this property. 55 | */ 56 | enabledCondition?: string; 57 | } 58 | 59 | // ================================================================= 60 | // Interop API types 61 | // ================================================================= 62 | 63 | export enum FileSystemItem { 64 | File = 'file', 65 | Directory = 'directory', 66 | } 67 | 68 | export enum ImportModuleOutputFormat { 69 | Markdown = 'md', 70 | Html = 'html', 71 | } 72 | 73 | /** 74 | * Used to implement a module to export data from Joplin. [View the demo plugin](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/json_export) for an example. 75 | * 76 | * In general, all the event handlers you'll need to implement take a `context` object as a first argument. This object will contain the export or import path as well as various optional properties, such as which notes or notebooks need to be exported. 77 | * 78 | * To get a better sense of what it will contain it can be useful to print it using `console.info(context)`. 79 | */ 80 | export interface ExportModule { 81 | /** 82 | * The format to be exported, eg "enex", "jex", "json", etc. 83 | */ 84 | format: string; 85 | 86 | /** 87 | * The description that will appear in the UI, for example in the menu item. 88 | */ 89 | description: string; 90 | 91 | /** 92 | * Whether the module will export a single file or multiple files in a directory. It affects the open dialog that will be presented to the user when using your exporter. 93 | */ 94 | target: FileSystemItem; 95 | 96 | /** 97 | * Only applies to single file exporters or importers 98 | * It tells whether the format can package multiple notes into one file. 99 | * For example JEX or ENEX can, but HTML cannot. 100 | */ 101 | isNoteArchive: boolean; 102 | 103 | /** 104 | * The extensions of the files exported by your module. For example, it is `["htm", "html"]` for the HTML module, and just `["jex"]` for the JEX module. 105 | */ 106 | fileExtensions?: string[]; 107 | 108 | /** 109 | * Called when the export process starts. 110 | */ 111 | onInit(context: ExportContext): Promise; 112 | 113 | /** 114 | * Called when an item needs to be processed. An "item" can be any Joplin object, such as a note, a folder, a notebook, etc. 115 | */ 116 | onProcessItem(context: ExportContext, itemType: number, item: any): Promise; 117 | 118 | /** 119 | * Called when a resource file needs to be exported. 120 | */ 121 | onProcessResource(context: ExportContext, resource: any, filePath: string): Promise; 122 | 123 | /** 124 | * Called when the export process is done. 125 | */ 126 | onClose(context: ExportContext): Promise; 127 | } 128 | 129 | export interface ImportModule { 130 | /** 131 | * The format to be exported, eg "enex", "jex", "json", etc. 132 | */ 133 | format: string; 134 | 135 | /** 136 | * The description that will appear in the UI, for example in the menu item. 137 | */ 138 | description: string; 139 | 140 | /** 141 | * Only applies to single file exporters or importers 142 | * It tells whether the format can package multiple notes into one file. 143 | * For example JEX or ENEX can, but HTML cannot. 144 | */ 145 | isNoteArchive: boolean; 146 | 147 | /** 148 | * The type of sources that are supported by the module. Tells whether the module can import files or directories or both. 149 | */ 150 | sources: FileSystemItem[]; 151 | 152 | /** 153 | * Tells the file extensions of the exported files. 154 | */ 155 | fileExtensions?: string[]; 156 | 157 | /** 158 | * Tells the type of notes that will be generated, either HTML or Markdown (default). 159 | */ 160 | outputFormat?: ImportModuleOutputFormat; 161 | 162 | /** 163 | * Called when the import process starts. There is only one event handler within which you should import the complete data. 164 | */ 165 | onExec(context: ImportContext): Promise; 166 | } 167 | 168 | export interface ExportOptions { 169 | format?: string; 170 | path?: string; 171 | sourceFolderIds?: string[]; 172 | sourceNoteIds?: string[]; 173 | // modulePath?: string; 174 | target?: FileSystemItem; 175 | } 176 | 177 | export interface ExportContext { 178 | destPath: string; 179 | options: ExportOptions; 180 | 181 | /** 182 | * You can attach your own custom data using this propery - it will then be passed to each event handler, allowing you to keep state from one event to the next. 183 | */ 184 | userData?: any; 185 | } 186 | 187 | export interface ImportContext { 188 | sourcePath: string; 189 | options: any; 190 | warnings: string[]; 191 | } 192 | 193 | // ================================================================= 194 | // Misc types 195 | // ================================================================= 196 | 197 | export interface Script { 198 | onStart?(event: any): Promise; 199 | } 200 | 201 | export interface Disposable { 202 | // dispose():void; 203 | } 204 | 205 | // ================================================================= 206 | // Menu types 207 | // ================================================================= 208 | 209 | export interface CreateMenuItemOptions { 210 | accelerator: string; 211 | } 212 | 213 | export enum MenuItemLocation { 214 | File = 'file', 215 | Edit = 'edit', 216 | View = 'view', 217 | Note = 'note', 218 | Tools = 'tools', 219 | Help = 'help', 220 | 221 | /** 222 | * @deprecated Do not use - same as NoteListContextMenu 223 | */ 224 | Context = 'context', 225 | 226 | // If adding an item here, don't forget to update isContextMenuItemLocation() 227 | 228 | /** 229 | * When a command is called from the note list context menu, the 230 | * command will receive the following arguments: 231 | * 232 | * - `noteIds:string[]`: IDs of the notes that were right-clicked on. 233 | */ 234 | NoteListContextMenu = 'noteListContextMenu', 235 | 236 | EditorContextMenu = 'editorContextMenu', 237 | 238 | /** 239 | * When a command is called from a folder context menu, the 240 | * command will receive the following arguments: 241 | * 242 | * - `folderId:string`: ID of the folder that was right-clicked on 243 | */ 244 | FolderContextMenu = 'folderContextMenu', 245 | 246 | /** 247 | * When a command is called from a tag context menu, the 248 | * command will receive the following arguments: 249 | * 250 | * - `tagId:string`: ID of the tag that was right-clicked on 251 | */ 252 | TagContextMenu = 'tagContextMenu', 253 | } 254 | 255 | export function isContextMenuItemLocation(location: MenuItemLocation): boolean { 256 | return [ 257 | MenuItemLocation.Context, 258 | MenuItemLocation.NoteListContextMenu, 259 | MenuItemLocation.EditorContextMenu, 260 | MenuItemLocation.FolderContextMenu, 261 | MenuItemLocation.TagContextMenu, 262 | ].includes(location); 263 | } 264 | 265 | export interface MenuItem { 266 | /** 267 | * Command that should be associated with the menu item. All menu item should 268 | * have a command associated with them unless they are a sub-menu. 269 | */ 270 | commandName?: string; 271 | 272 | /** 273 | * Accelerator associated with the menu item 274 | */ 275 | accelerator?: string; 276 | 277 | /** 278 | * Menu items that should appear below this menu item. Allows creating a menu tree. 279 | */ 280 | submenu?: MenuItem[]; 281 | 282 | /** 283 | * Menu item label. If not specified, the command label will be used instead. 284 | */ 285 | label?: string; 286 | } 287 | 288 | // ================================================================= 289 | // View API types 290 | // ================================================================= 291 | 292 | export interface ButtonSpec { 293 | id: ButtonId; 294 | title?: string; 295 | onClick?(): void; 296 | } 297 | 298 | export type ButtonId = string; 299 | 300 | export enum ToolbarButtonLocation { 301 | /** 302 | * This toolbar in the top right corner of the application. It applies to the note as a whole, including its metadata. 303 | */ 304 | NoteToolbar = 'noteToolbar', 305 | 306 | /** 307 | * This toolbar is right above the text editor. It applies to the note body only. 308 | */ 309 | EditorToolbar = 'editorToolbar', 310 | } 311 | 312 | export type ViewHandle = string; 313 | 314 | export interface EditorCommand { 315 | name: string; 316 | value?: any; 317 | } 318 | 319 | export interface DialogResult { 320 | id: ButtonId; 321 | formData?: any; 322 | } 323 | 324 | // ================================================================= 325 | // Settings types 326 | // ================================================================= 327 | 328 | export enum SettingItemType { 329 | Int = 1, 330 | String = 2, 331 | Bool = 3, 332 | Array = 4, 333 | Object = 5, 334 | Button = 6, 335 | } 336 | 337 | // Redefine a simplified interface to mask internal details 338 | // and to remove function calls as they would have to be async. 339 | export interface SettingItem { 340 | value: any; 341 | type: SettingItemType; 342 | 343 | label: string; 344 | description?: string; 345 | 346 | /** 347 | * A public setting will appear in the Configuration screen and will be 348 | * modifiable by the user. A private setting however will not appear there, 349 | * and can only be changed programmatically. You may use this to store some 350 | * values that you do not want to directly expose. 351 | */ 352 | public: boolean; 353 | 354 | /** 355 | * You would usually set this to a section you would have created 356 | * specifically for the plugin. 357 | */ 358 | section?: string; 359 | 360 | /** 361 | * To create a setting with multiple options, set this property to `true`. 362 | * That setting will render as a dropdown list in the configuration screen. 363 | */ 364 | isEnum?: boolean; 365 | 366 | /** 367 | * This property is required when `isEnum` is `true`. In which case, it 368 | * should contain a map of value => label. 369 | */ 370 | options?: Record; 371 | 372 | /** 373 | * Reserved property. Not used at the moment. 374 | */ 375 | appTypes?: string[]; 376 | 377 | /** 378 | * Set this to `true` to store secure data, such as passwords. Any such 379 | * setting will be stored in the system keychain if one is available. 380 | */ 381 | secure?: boolean; 382 | 383 | /** 384 | * An advanced setting will be moved under the "Advanced" button in the 385 | * config screen. 386 | */ 387 | advanced?: boolean; 388 | 389 | /** 390 | * Set the min, max and step values if you want to restrict an int setting 391 | * to a particular range. 392 | */ 393 | minimum?: number; 394 | maximum?: number; 395 | step?: number; 396 | } 397 | 398 | export interface SettingSection { 399 | label: string; 400 | iconName?: string; 401 | description?: string; 402 | name?: string; 403 | } 404 | 405 | // ================================================================= 406 | // Data API types 407 | // ================================================================= 408 | 409 | /** 410 | * An array of at least one element and at most three elements. 411 | * 412 | * - **[0]**: Resource name (eg. "notes", "folders", "tags", etc.) 413 | * - **[1]**: (Optional) Resource ID. 414 | * - **[2]**: (Optional) Resource link. 415 | */ 416 | export type Path = string[]; 417 | 418 | // ================================================================= 419 | // Content Script types 420 | // ================================================================= 421 | 422 | export type PostMessageHandler = (id: string, message: any)=> Promise; 423 | 424 | /** 425 | * When a content script is initialised, it receives a `context` object. 426 | */ 427 | export interface ContentScriptContext { 428 | /** 429 | * The plugin ID that registered this content script 430 | */ 431 | pluginId: string; 432 | 433 | /** 434 | * The content script ID, which may be necessary to post messages 435 | */ 436 | contentScriptId: string; 437 | 438 | /** 439 | * Can be used by CodeMirror content scripts to post a message to the plugin 440 | */ 441 | postMessage: PostMessageHandler; 442 | } 443 | 444 | export enum ContentScriptType { 445 | /** 446 | * Registers a new Markdown-It plugin, which should follow the template 447 | * below. 448 | * 449 | * ```javascript 450 | * module.exports = { 451 | * default: function(context) { 452 | * return { 453 | * plugin: function(markdownIt, options) { 454 | * // ... 455 | * }, 456 | * assets: { 457 | * // ... 458 | * }, 459 | * } 460 | * } 461 | * } 462 | * ``` 463 | * See [the 464 | * demo](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/content_script) 465 | * for a simple Markdown-it plugin example. 466 | * 467 | * ## Exported members 468 | * 469 | * - The `context` argument is currently unused but could be used later on 470 | * to provide access to your own plugin so that the content script and 471 | * plugin can communicate. 472 | * 473 | * - The **required** `plugin` key is the actual Markdown-It plugin - check 474 | * the [official doc](https://github.com/markdown-it/markdown-it) for more 475 | * information. The `options` parameter is of type 476 | * [RuleOptions](https://github.com/laurent22/joplin/blob/dev/packages/renderer/MdToHtml.ts), 477 | * which contains a number of options, mostly useful for Joplin's internal 478 | * code. 479 | * 480 | * - Using the **optional** `assets` key you may specify assets such as JS 481 | * or CSS that should be loaded in the rendered HTML document. Check for 482 | * example the Joplin [Mermaid 483 | * plugin](https://github.com/laurent22/joplin/blob/dev/packages/renderer/MdToHtml/rules/mermaid.ts) 484 | * to see how the data should be structured. 485 | * 486 | * ## Posting messages from the content script to your plugin 487 | * 488 | * The application provides the following function to allow executing 489 | * commands from the rendered HTML code: 490 | * 491 | * ```javascript 492 | * const response = await webviewApi.postMessage(contentScriptId, message); 493 | * ``` 494 | * 495 | * - `contentScriptId` is the ID you've defined when you registered the 496 | * content script. You can retrieve it from the 497 | * {@link ContentScriptContext | context}. 498 | * - `message` can be any basic JavaScript type (number, string, plain 499 | * object), but it cannot be a function or class instance. 500 | * 501 | * When you post a message, the plugin can send back a `response` thus 502 | * allowing two-way communication: 503 | * 504 | * ```javascript 505 | * await joplin.contentScripts.onMessage(contentScriptId, (message) => { 506 | * // Process message 507 | * return response; // Can be any object, string or number 508 | * }); 509 | * ``` 510 | * 511 | * See {@link JoplinContentScripts.onMessage} for more details, as well as 512 | * the [postMessage 513 | * demo](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/post_messages). 514 | * 515 | * ## Registering an existing Markdown-it plugin 516 | * 517 | * To include a regular Markdown-It plugin, that doesn't make use of any 518 | * Joplin-specific features, you would simply create a file such as this: 519 | * 520 | * ```javascript 521 | * module.exports = { 522 | * default: function(context) { 523 | * return { 524 | * plugin: require('markdown-it-toc-done-right'); 525 | * } 526 | * } 527 | * } 528 | * ``` 529 | */ 530 | MarkdownItPlugin = 'markdownItPlugin', 531 | 532 | /** 533 | * Registers a new CodeMirror plugin, which should follow the template 534 | * below. 535 | * 536 | * ```javascript 537 | * module.exports = { 538 | * default: function(context) { 539 | * return { 540 | * plugin: function(CodeMirror) { 541 | * // ... 542 | * }, 543 | * codeMirrorResources: [], 544 | * codeMirrorOptions: { 545 | * // ... 546 | * }, 547 | * assets: { 548 | * // ... 549 | * }, 550 | * } 551 | * } 552 | * } 553 | * ``` 554 | * 555 | * - The `context` argument is currently unused but could be used later on 556 | * to provide access to your own plugin so that the content script and 557 | * plugin can communicate. 558 | * 559 | * - The `plugin` key is your CodeMirror plugin. This is where you can 560 | * register new commands with CodeMirror or interact with the CodeMirror 561 | * instance as needed. 562 | * 563 | * - The `codeMirrorResources` key is an array of CodeMirror resources that 564 | * will be loaded and attached to the CodeMirror module. These are made up 565 | * of addons, keymaps, and modes. For example, for a plugin that want's to 566 | * enable clojure highlighting in code blocks. `codeMirrorResources` would 567 | * be set to `['mode/clojure/clojure']`. 568 | * 569 | * - The `codeMirrorOptions` key contains all the 570 | * [CodeMirror](https://codemirror.net/doc/manual.html#config) options 571 | * that will be set or changed by this plugin. New options can alse be 572 | * declared via 573 | * [`CodeMirror.defineOption`](https://codemirror.net/doc/manual.html#defineOption), 574 | * and then have their value set here. For example, a plugin that enables 575 | * line numbers would set `codeMirrorOptions` to `{'lineNumbers': true}`. 576 | * 577 | * - Using the **optional** `assets` key you may specify **only** CSS assets 578 | * that should be loaded in the rendered HTML document. Check for example 579 | * the Joplin [Mermaid 580 | * plugin](https://github.com/laurent22/joplin/blob/dev/packages/renderer/MdToHtml/rules/mermaid.ts) 581 | * to see how the data should be structured. 582 | * 583 | * One of the `plugin`, `codeMirrorResources`, or `codeMirrorOptions` keys 584 | * must be provided for the plugin to be valid. Having multiple or all 585 | * provided is also okay. 586 | * 587 | * See also the [demo 588 | * plugin](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/codemirror_content_script) 589 | * for an example of all these keys being used in one plugin. 590 | * 591 | * ## Posting messages from the content script to your plugin 592 | * 593 | * In order to post messages to the plugin, you can use the postMessage 594 | * function passed to the {@link ContentScriptContext | context}. 595 | * 596 | * ```javascript 597 | * const response = await context.postMessage('messageFromCodeMirrorContentScript'); 598 | * ``` 599 | * 600 | * When you post a message, the plugin can send back a `response` thus 601 | * allowing two-way communication: 602 | * 603 | * ```javascript 604 | * await joplin.contentScripts.onMessage(contentScriptId, (message) => { 605 | * // Process message 606 | * return response; // Can be any object, string or number 607 | * }); 608 | * ``` 609 | * 610 | * See {@link JoplinContentScripts.onMessage} for more details, as well as 611 | * the [postMessage 612 | * demo](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/post_messages). 613 | * 614 | */ 615 | CodeMirrorPlugin = 'codeMirrorPlugin', 616 | } 617 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "joplin-plugin-make-all-links", 3 | "version": "1.0.3", 4 | "scripts": { 5 | "dist": "webpack --joplin-plugin-config buildMain && webpack --joplin-plugin-config buildExtraScripts && webpack --joplin-plugin-config createArchive", 6 | "prepare": "npm run dist", 7 | "update": "npm install -g generator-joplin && yo joplin --update" 8 | }, 9 | "license": "MIT", 10 | "keywords": [ 11 | "joplin-plugin" 12 | ], 13 | "devDependencies": { 14 | "@types/node": "^14.0.14", 15 | "chalk": "^4.1.0", 16 | "copy-webpack-plugin": "^6.1.0", 17 | "fs-extra": "^9.0.1", 18 | "glob": "^7.1.6", 19 | "on-build-webpack": "^0.1.0", 20 | "tar": "^6.0.5", 21 | "ts-loader": "^7.0.5", 22 | "typescript": "^3.9.3", 23 | "webpack": "^4.43.0", 24 | "webpack-cli": "^3.3.11", 25 | "yargs": "^16.2.0" 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /plugin.config.json: -------------------------------------------------------------------------------- 1 | { 2 | "extraScripts": [] 3 | } -------------------------------------------------------------------------------- /screenshot_after.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/S73ph4n/joplin_make_all_links/225cc8590db44631ea1a50e84ea0309d9e6f4c27/screenshot_after.png -------------------------------------------------------------------------------- /screenshot_before.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/S73ph4n/joplin_make_all_links/225cc8590db44631ea1a50e84ea0309d9e6f4c27/screenshot_before.png -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import joplin from 'api'; 2 | import { ToolbarButtonLocation } from 'api/types'; 3 | 4 | joplin.plugins.register({ 5 | onStart: async function() { 6 | joplin.commands.register({ 7 | name: 'makeAllLinks', 8 | label: 'Link to all notes mentionned in the current note.', 9 | iconName: 'fas fa-project-diagram', 10 | execute: async () => { 11 | var response = (await joplin.data.get(['notes'])); 12 | var notes = response.items; 13 | let pageNum = 1; 14 | while (response.has_more){ 15 | response = await joplin.data.get(['notes'], {page: pageNum++}); 16 | //console.info(response); 17 | notes = notes.concat(response.items); 18 | } 19 | const currentNote = await joplin.workspace.selectedNote(); 20 | //const selectedText = (await joplin.commands.execute('selectedText') as string); 21 | var body = currentNote.body.split('\n'); 22 | //console.info(body); 23 | 24 | for (var wordGpLength = 4; wordGpLength > 0; wordGpLength--){ //iterate over word group lengths (longer first) 25 | for (var n_line=0; n_line < body.length; n_line++){ //over every line 26 | var line = body[n_line].split(' '); 27 | for (var n_word=0; n_word <= line.length-wordGpLength; n_word++){ 28 | var selectedText = line.slice(n_word, n_word+wordGpLength).join(' '); 29 | if (selectedText.length > 2){ 30 | //console.info('Testing word group', wordGpLength, n_line, n_word, selectedText); 31 | 32 | var idLinkedNote = 0; 33 | for (let i in notes){ 34 | //console.info(notes[i].title); 35 | if (notes[i].title.toLowerCase() === selectedText.toLowerCase() && currentNote.title.toLowerCase() !== selectedText.toLowerCase()){ 36 | idLinkedNote = notes[i].id; 37 | console.info('Found note with title ', notes[i].title, selectedText ,idLinkedNote); 38 | const linkToNewNote = '[' + selectedText + '](:/' + idLinkedNote + ')'; 39 | const newLine = line.slice(0, n_word).concat([linkToNewNote], line.slice(n_word+wordGpLength)).join(' '); 40 | 41 | body = body.slice(0, n_line).concat([newLine], body.slice(n_line + 1)); 42 | console.info(body); 43 | break; 44 | } 45 | } 46 | } 47 | } 48 | } 49 | } 50 | // Change the corrected body : 51 | //await joplin.data.put(['notes', currentNote.id], null, { body: body.join('\n')}); 52 | await joplin.commands.execute("textSelectAll"); 53 | await joplin.commands.execute("replaceSelection", body.join('\n')); 54 | }, 55 | }); 56 | 57 | joplin.views.toolbarButtons.create('makeAllLinks','makeAllLinks', ToolbarButtonLocation.EditorToolbar); 58 | }, 59 | }); 60 | -------------------------------------------------------------------------------- /src/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "manifest_version": 1, 3 | "id": "com.s73ph4n.make_all_links", 4 | "app_min_version": "2.0", 5 | "version": "1.0.3", 6 | "name": "Make All Links", 7 | "description": "Searches the current note for mentions of other notes, then makes the corresponding links. Just click the new icon in the toolbar.", 8 | "author": "S73ph4n", 9 | "homepage_url": "https://github.com/S73ph4n", 10 | "repository_url": "https://github.com/S73ph4n/joplin_make_all_links", 11 | "keywords": [] 12 | } 13 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "outDir": "./dist/", 4 | "module": "commonjs", 5 | "target": "es2015", 6 | "jsx": "react", 7 | "allowJs": true, 8 | "baseUrl": "." 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /webpack.config.js: -------------------------------------------------------------------------------- 1 | // ----------------------------------------------------------------------------- 2 | // This file is used to build the plugin file (.jpl) and plugin info (.json). It 3 | // is recommended not to edit this file as it would be overwritten when updating 4 | // the plugin framework. If you do make some changes, consider using an external 5 | // JS file and requiring it here to minimize the changes. That way when you 6 | // update, you can easily restore the functionality you've added. 7 | // ----------------------------------------------------------------------------- 8 | 9 | const path = require('path'); 10 | const crypto = require('crypto'); 11 | const fs = require('fs-extra'); 12 | const chalk = require('chalk'); 13 | const CopyPlugin = require('copy-webpack-plugin'); 14 | const WebpackOnBuildPlugin = require('on-build-webpack'); 15 | const tar = require('tar'); 16 | const glob = require('glob'); 17 | const execSync = require('child_process').execSync; 18 | 19 | const rootDir = path.resolve(__dirname); 20 | const userConfigFilename = './plugin.config.json'; 21 | const userConfigPath = path.resolve(rootDir, userConfigFilename); 22 | const distDir = path.resolve(rootDir, 'dist'); 23 | const srcDir = path.resolve(rootDir, 'src'); 24 | const publishDir = path.resolve(rootDir, 'publish'); 25 | 26 | const userConfig = Object.assign({}, { 27 | extraScripts: [], 28 | }, fs.pathExistsSync(userConfigPath) ? require(userConfigFilename) : {}); 29 | 30 | const manifestPath = `${srcDir}/manifest.json`; 31 | const packageJsonPath = `${rootDir}/package.json`; 32 | const manifest = readManifest(manifestPath); 33 | const pluginArchiveFilePath = path.resolve(publishDir, `${manifest.id}.jpl`); 34 | const pluginInfoFilePath = path.resolve(publishDir, `${manifest.id}.json`); 35 | 36 | function validatePackageJson() { 37 | const content = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')); 38 | if (!content.name || content.name.indexOf('joplin-plugin-') !== 0) { 39 | console.warn(chalk.yellow(`WARNING: To publish the plugin, the package name should start with "joplin-plugin-" (found "${content.name}") in ${packageJsonPath}`)); 40 | } 41 | 42 | if (!content.keywords || content.keywords.indexOf('joplin-plugin') < 0) { 43 | console.warn(chalk.yellow(`WARNING: To publish the plugin, the package keywords should include "joplin-plugin" (found "${JSON.stringify(content.keywords)}") in ${packageJsonPath}`)); 44 | } 45 | 46 | if (content.scripts && content.scripts.postinstall) { 47 | console.warn(chalk.yellow(`WARNING: package.json contains a "postinstall" script. It is recommended to use a "prepare" script instead so that it is executed before publish. In ${packageJsonPath}`)); 48 | } 49 | } 50 | 51 | function fileSha256(filePath) { 52 | const content = fs.readFileSync(filePath); 53 | return crypto.createHash('sha256').update(content).digest('hex'); 54 | } 55 | 56 | function currentGitInfo() { 57 | try { 58 | let branch = execSync('git rev-parse --abbrev-ref HEAD', { stdio: 'pipe' }).toString().trim(); 59 | const commit = execSync('git rev-parse HEAD', { stdio: 'pipe' }).toString().trim(); 60 | if (branch === 'HEAD') branch = 'master'; 61 | return `${branch}:${commit}`; 62 | } catch (error) { 63 | const messages = error.message ? error.message.split('\n') : ['']; 64 | console.info(chalk.cyan('Could not get git commit (not a git repo?):', messages[0].trim())); 65 | console.info(chalk.cyan('Git information will not be stored in plugin info file')); 66 | return ''; 67 | } 68 | } 69 | 70 | function readManifest(manifestPath) { 71 | const content = fs.readFileSync(manifestPath, 'utf8'); 72 | const output = JSON.parse(content); 73 | if (!output.id) throw new Error(`Manifest plugin ID is not set in ${manifestPath}`); 74 | return output; 75 | } 76 | 77 | function createPluginArchive(sourceDir, destPath) { 78 | const distFiles = glob.sync(`${sourceDir}/**/*`, { nodir: true }) 79 | .map(f => f.substr(sourceDir.length + 1)); 80 | 81 | if (!distFiles.length) throw new Error('Plugin archive was not created because the "dist" directory is empty'); 82 | fs.removeSync(destPath); 83 | 84 | tar.create( 85 | { 86 | strict: true, 87 | portable: true, 88 | file: destPath, 89 | cwd: sourceDir, 90 | sync: true, 91 | }, 92 | distFiles 93 | ); 94 | 95 | console.info(chalk.cyan(`Plugin archive has been created in ${destPath}`)); 96 | } 97 | 98 | function createPluginInfo(manifestPath, destPath, jplFilePath) { 99 | const contentText = fs.readFileSync(manifestPath, 'utf8'); 100 | const content = JSON.parse(contentText); 101 | content._publish_hash = `sha256:${fileSha256(jplFilePath)}`; 102 | content._publish_commit = currentGitInfo(); 103 | fs.writeFileSync(destPath, JSON.stringify(content, null, '\t'), 'utf8'); 104 | } 105 | 106 | function onBuildCompleted() { 107 | try { 108 | fs.removeSync(path.resolve(publishDir, 'index.js')); 109 | createPluginArchive(distDir, pluginArchiveFilePath); 110 | createPluginInfo(manifestPath, pluginInfoFilePath, pluginArchiveFilePath); 111 | validatePackageJson(); 112 | } catch (error) { 113 | console.error(chalk.red(error.message)); 114 | } 115 | } 116 | 117 | const baseConfig = { 118 | mode: 'production', 119 | target: 'node', 120 | stats: 'errors-only', 121 | module: { 122 | rules: [ 123 | { 124 | test: /\.tsx?$/, 125 | use: 'ts-loader', 126 | exclude: /node_modules/, 127 | }, 128 | ], 129 | }, 130 | }; 131 | 132 | const pluginConfig = Object.assign({}, baseConfig, { 133 | entry: './src/index.ts', 134 | resolve: { 135 | alias: { 136 | api: path.resolve(__dirname, 'api'), 137 | }, 138 | // JSON files can also be required from scripts so we include this. 139 | // https://github.com/joplin/plugin-bibtex/pull/2 140 | extensions: ['.tsx', '.ts', '.js', '.json'], 141 | }, 142 | output: { 143 | filename: 'index.js', 144 | path: distDir, 145 | }, 146 | plugins: [ 147 | new CopyPlugin({ 148 | patterns: [ 149 | { 150 | from: '**/*', 151 | context: path.resolve(__dirname, 'src'), 152 | to: path.resolve(__dirname, 'dist'), 153 | globOptions: { 154 | ignore: [ 155 | // All TypeScript files are compiled to JS and 156 | // already copied into /dist so we don't copy them. 157 | '**/*.ts', 158 | '**/*.tsx', 159 | ], 160 | }, 161 | }, 162 | ], 163 | }), 164 | ], 165 | }); 166 | 167 | const extraScriptConfig = Object.assign({}, baseConfig, { 168 | resolve: { 169 | alias: { 170 | api: path.resolve(__dirname, 'api'), 171 | }, 172 | extensions: ['.tsx', '.ts', '.js', '.json'], 173 | }, 174 | }); 175 | 176 | const createArchiveConfig = { 177 | stats: 'errors-only', 178 | entry: './dist/index.js', 179 | output: { 180 | filename: 'index.js', 181 | path: publishDir, 182 | }, 183 | plugins: [new WebpackOnBuildPlugin(onBuildCompleted)], 184 | }; 185 | 186 | function resolveExtraScriptPath(name) { 187 | const relativePath = `./src/${name}`; 188 | 189 | const fullPath = path.resolve(`${rootDir}/${relativePath}`); 190 | if (!fs.pathExistsSync(fullPath)) throw new Error(`Could not find extra script: "${name}" at "${fullPath}"`); 191 | 192 | const s = name.split('.'); 193 | s.pop(); 194 | const nameNoExt = s.join('.'); 195 | 196 | return { 197 | entry: relativePath, 198 | output: { 199 | filename: `${nameNoExt}.js`, 200 | path: distDir, 201 | library: 'default', 202 | libraryTarget: 'commonjs', 203 | libraryExport: 'default', 204 | }, 205 | }; 206 | } 207 | 208 | function buildExtraScriptConfigs(userConfig) { 209 | if (!userConfig.extraScripts.length) return []; 210 | 211 | const output = []; 212 | 213 | for (const scriptName of userConfig.extraScripts) { 214 | const scriptPaths = resolveExtraScriptPath(scriptName); 215 | output.push(Object.assign({}, extraScriptConfig, { 216 | entry: scriptPaths.entry, 217 | output: scriptPaths.output, 218 | })); 219 | } 220 | 221 | return output; 222 | } 223 | 224 | function main(processArgv) { 225 | const yargs = require('yargs/yargs'); 226 | const argv = yargs(processArgv).argv; 227 | 228 | const configName = argv['joplin-plugin-config']; 229 | if (!configName) throw new Error('A config file must be specified via the --joplin-plugin-config flag'); 230 | 231 | // Webpack configurations run in parallel, while we need them to run in 232 | // sequence, and to do that it seems the only way is to run webpack multiple 233 | // times, with different config each time. 234 | 235 | const configs = { 236 | // Builds the main src/index.ts and copy the extra content from /src to 237 | // /dist including scripts, CSS and any other asset. 238 | buildMain: [pluginConfig], 239 | 240 | // Builds the extra scripts as defined in plugin.config.json. When doing 241 | // so, some JavaScript files that were copied in the previous might be 242 | // overwritten here by the compiled version. This is by design. The 243 | // result is that JS files that don't need compilation, are simply 244 | // copied to /dist, while those that do need it are correctly compiled. 245 | buildExtraScripts: buildExtraScriptConfigs(userConfig), 246 | 247 | // Ths config is for creating the .jpl, which is done via the plugin, so 248 | // it doesn't actually need an entry and output, however webpack won't 249 | // run without this. So we give it an entry that we know is going to 250 | // exist and output in the publish dir. Then the plugin will delete this 251 | // temporary file before packaging the plugin. 252 | createArchive: [createArchiveConfig], 253 | }; 254 | 255 | // If we are running the first config step, we clean up and create the build 256 | // directories. 257 | if (configName === 'buildMain') { 258 | fs.removeSync(distDir); 259 | fs.removeSync(publishDir); 260 | fs.mkdirpSync(publishDir); 261 | } 262 | 263 | return configs[configName]; 264 | } 265 | 266 | let exportedConfigs = []; 267 | 268 | try { 269 | exportedConfigs = main(process.argv); 270 | } catch (error) { 271 | console.error(chalk.red(error.message)); 272 | process.exit(1); 273 | } 274 | 275 | if (!exportedConfigs.length) { 276 | // Nothing to do - for example where there are no external scripts to 277 | // compile. 278 | process.exit(0); 279 | } 280 | 281 | module.exports = exportedConfigs; 282 | --------------------------------------------------------------------------------