VisualEditor/Gadgets

This is a non formal guide for writing gadgets for.


 * Motivation: is an interface for editing articles in Wikimedia projects. It is simple to use and preferred by new editors. Gadgets can extend and customize the visual editor and introduce new functionalities: to let more advanced users use more complicated options (such as timeline), to introduce work-flows that are project specific (such as deletion proposals), or to easily insert popular templates such as cite templates.
 * Note: is written in JavaScript, in fully object oriented mind - including the UI (dialogs, widgets, tools etc) and the model (which replace the simple Wikitext). If you want all technical details, read the live-updated documentation and for an overview the /API pages (which aren't yet fully written). However, if you just want to create gadgets that improve the user experience, read this guide.

Read the guide To understand how to hack VE   Go to code snippets For quick hacking

Getting around
First of all you need to access the code with one (or more) of the following options:
 * Download the code from Git:
 * (for more information see: mw:Extension:VisualEditor)

You may use add ?debug=1 to the url to get non compressed - this is a bad idea for VE since loading may take several minutes
 * Open an article, and edit it with visual editor. Open Web Developer tools ( in most browsers), and go to the Sources or Debugger tab. You should look at "load.php....ext.visualEditor...". Since MediaWiki gives you the compressed you should use a tool to "Pretty print" or "Beautify" the code (such options exist in Chrome and Firefox).
 * If you don't see the it may come from local cache - run in console localStorage.clear and reload the page

Debug diving
A good debugger is the most useful thing that you can have as a gadget writer. Since there is no good documentation yet for, to understand how everything works you will have to dive into debugging.

Assume we want to understand how transclusion of templates work inside :
 * To access VE object:  for the active  surface on the page.
 * Since we know (as users) that there is a dialog to insert templates, we should find this dialog in the code (search with ctrl+F). You should find a function called "ve.ui.MWTransclusionDialog.prototype.onAddTemplateButtonClick" - place a breakpoint there
 * As user, open the dialog, select a template, fill some parameters, and then add the template to the page - you will hit the break point.
 * Inspecting the transclusion object we can see what it looks like under the hood:

Now that we understand how templates are represented, let's take a look on an example of UI class - toolbar. There is a configuration object for the main toolbar:
 * Now that we know how template code is represented - we can go on with the debugger, step by step and see how it is added to the document:

Where * includes all the registered tools. (What are those tools? you can take a look/debug the function OO.ui.ToolGroup.prototype.populate to understand how it works - it loads all the registered commands, removed already used, remove the exclude and order using demote/promote).

Deployment
The above describes how to code a script for. Once your script is ready, you would like to publish it so other editors can use it. As other scripts, this can be done in one of the following options:
 * Gadget - turn it as a gadget that user can select it in their preferences (requires sysop rights). This is preferred method since it allows users to to install the gadget without code editing.
 * User script - users can install your script by adding code snippet to Special:Mypage/common.js

Gadget - Registering VE plugin
Registering your script in MediaWiki:Gadgets-definition allows other editors to turn your use using Special:Preferences (in Gadgets tab). The following section describes shortly how to do it, and details the specific requirements for a gadget. A more detailed explanation for general gadget can be found in Extension:Gadgets#Usage.

Since VE is heavy module, you must not create a gadget that dependent on VE internals. Instead you should create 2 gadgets:
 * A real gadget - that may be dependent on VE internals, but users shouldn't be able to turn it on (use hidden). The gadget code could be derived from #Code snippets below.
 * Create a "gadget loader" - a small gadget that tells VE to load your real gadget once VE is activated by the user

For example:

User script
If you don't have admin rights, or your script hasn't been tested enough or the target audience for your script is small, you can let users install the script by editing their personal (Special:Mypage/common.js). Afterwards you can publish it as a user script in pages such as en:Wikipedia:User scripts.

Here we use client side API for to do the same as the above section, e.g. to add our script to be loaded when user open VE.

Example for a URL for user script:
 * //meta.wikimedia.org/w/index.php?title=User:Jimbo_Wales/MyGadget.js&action=raw&ctype=text/javascript
 * Assuming the gadget code is located in meta:User:Jimbo_Wales/MyGadget.js, and contains code such as derived code from #Code snippets below.

Running code after VisualEditor is activated
To run code once VisualEditor is activated and ready to use:

To run code before the target starts to initialise, you can register a plugin module:

If you just want to run your code on the source editor, you can listen to the 've.wikitextInteractive' hook, like so:

itor is in regular 'visual' mode or 'source' mode
NB: This is currently a beta feature so the APIs may not yet be finalised

Checking whether VisualEditor is currently open
If you have a button that should act differently depending on whether the wikitext or the visual editor is in use:i

Adding templates
The following code adds Template:cite web as an example for adding template to page:

Adding/modifying/removing a link
Links in are implemented as "annotations" (additional information that can be applied to a part of text) of type  or. Text styling like bold and italics are also annotations.

To convert selected text to a link to page "", section "Status":

To remove internal links in selected text:

To convert selected text to an external link:

To make selected text bold:

Implementing a custom command
Things that the user can do in the editor are represented by commands. They can be associated with toolbar tools, keyboard shortcuts (triggers) or text sequences to allow them to be used (see below). A single command can be associated with multiple tools/triggers/sequences (e.g.  command is used by the trigger for Ctrl+B and by the Bold tool).

See also complete documented example scripts:
 * How to add a custom tool that inserts a template with default parameters
 * How to create a custom command to modify page content (in visual and source mode)

Most commands execute built-in actions: for example, the command below inserts a newline at cursor position.

However, commands can execute arbitrary code. For example, the command below displays a warning popup.

Triggering a command using a toolbar tool
This adds a new tool to the toolbar (under the "Insert" menu) to insert a line break at cursor position, using the command we defined above.

Use a wiki Message instead of a fixed title
If you want to get the title of you toolbar button from MediaWiki:my-message, you can use :

But you have to load the messages (here the syntax to load several messages) :

Triggering a command using a keyboard shortcut
This adds a new keyboard shortcut Ctrl+Shift+Y (or Cmd+Shift+Y on Mac) to insert a line break at cursor position, using the command we defined above.

Triggering a command using a text sequence
This adds a new text sequence 'kitten'. When the user types that, a warning message pops up using the command we defined above.

Add 'Center' to the Format list
This script adds an option 'Center' in the Format dropdown menu : mw.loader.using( [ 'ext.visualEditor.core', 'ext.visualEditor.mwtransclusion' ] ).then(function {

// - (start of ve.ui.CenterAction definition) --- // This is based on [lib/ve/src/ui/actions/ve.ui.BlockquoteAction.js] from Extension:VisualEditor.

ve.ui.CenterAction = function { ve.ui.CenterAction.super.apply( this, arguments ); };	OO.inheritClass( ve.ui.CenterAction, ve.ui.Action );

ve.ui.CenterAction.static.name = 'center'; ve.ui.CenterAction.static.methods = [ 'wrap', 'unwrap', 'toggle' ];

ve.ui.CenterAction.prototype.isWrapped = function { var fragment = this.surface.getModel.; return fragment.hasMatchingAncestor( 'center' ); };	ve.ui.CenterAction.prototype.toggle = function { return this[ this.isWrapped ? 'unwrap' : 'wrap' ]; };	ve.ui.CenterAction.prototype.wrap = function { var = this.surface.getModel, selection = surfaceModel.getSelection, fragment = surfaceModel.getFragment( null, true ), leaves, ;

if ( !( selection instanceof ve.dm.LinearSelection ) ) { return false; }

leaves = fragment.getSelectedLeafNodes; = new ve.Range(			leaves[ 0 ]..start,			leaves[ leaves.length - 1 ]..end		); fragment = surfaceModel.getLinearFragment(, true );

fragment = fragment.expandLinearSelection( 'siblings' );

while (			fragment.getCoveredNodes.some( function ( nodeInfo ) { return !nodeInfo.node.isAllowedParentNodeType( 'center' ) || nodeInfo.node.isContent; } )		) {			fragment = fragment.expandLinearSelection( 'parent' ); }

// Wrap everything in a tag fragment.wrapAllNodes( { type: 'center' } );

return true; };	ve.ui.CenterAction.prototype.unwrap = function { var = this.surface.getModel, selection = surfaceModel.getSelection, fragment = surfaceModel.getFragment( null, true ), leaves, ;

if ( !( selection instanceof ve.dm.LinearSelection ) ) { return false; }

if ( !this.isWrapped ) { return false; }

leaves = fragment.getSelectedLeafNodes; = new ve.Range(			leaves[ 0 ]..start,			leaves[ leaves.length - 1 ]..end		); fragment = surfaceModel.getLinearFragment(, true );

fragment // Expand to cover entire tag .( 'closest', ve.dm.CenterNode ) // Unwrap it			.( 0, 1 );

return true; };	ve.ui.actionFactory.register( ve.ui.CenterAction );

// - (end of ve.ui.CenterAction definition) -

ve.ui.CenterFormatTool = function { ve.ui.CenterFormatTool.super.apply( this, arguments ); };	OO.inheritClass( ve.ui.CenterFormatTool, ve.ui.FormatTool );

ve.ui.CenterFormatTool.static.name = 'center'; ve.ui.CenterFormatTool.static.group = 'format'; ve.ui.CenterFormatTool.static.title = 'Center'; ve.ui.CenterFormatTool.static.format = { type: 'center' }; ve.ui.CenterFormatTool.static.commandName = 'center'; ve.ui.toolFactory.register( ve.ui.CenterFormatTool );

ve.ui.commandRegistry.register(		new ve.ui.Command( ', 'center', 'toggle', { : [ 'linear' ] } )	); } ); 

Add a 'Reference list' when the first reference is added and there is no Reference list yet
Unfortunately this feature that could be useful has been refused in core VE, so you can use this script : function { // This function is based on gerrit:149117, original author: Alex Monk var = this.getFragment., = this.referenceGroupInput.$input.val, ;

this.referenceModel.setGroup;

// : This is probably the wrong way to do this. existingRefLists = $.grep( surfaceModel.getDocument., function ( element ) {			return element.type === '' && element.attributes.refGroup === ;		} );

if ( !existingRefLists.length ) { .( null, true ) .( 'root' ) .				.( [					{						type: '',						attributes: {							: '/' + ,							: 						}					},					{ type: '/' }				]			); }	}

mw.loader.using( 'ext.cite.visualEditor' ).then( function {		//  is what is normally called when you click "Insert"		// in the Reference dialog (Cite+).		// We wrap around this function, calling first the original function (which adds ),		// and then, which adds .		var = ve.ui.MWReferenceDialog.prototype.getActionProcess;		ve.ui.MWReferenceDialog.prototype.getActionProcess = function ( action ) {			var result = origFunc.apply( this, arguments );

if ( action === 'insert' || action === 'done' ) { result = result.next( addReferencesIfMissing.bind( this ) ); }

return result; }; } ); 

Real examples for gadgets/scripts that interact with VE
Here are some real world gadgets/scripts for VE. You can use them as is or use them as example for building your own gadgets!
 * en:MediaWiki:Gadget-defaultsummaries.js – Adds two new dropdown boxes below the edit summary box with some useful default summaries.
 * pl:MediaWiki:Gadget-edit-summaries.js – edit summary buttons for both VE and standard editor.
 * he:MediaWiki:Gadget-VeDirectionMarkTool.js, he:MediaWiki:Gadget-VeExtendedBar.js – Adds a button for inserting a common template (this is also an example of how to use ).
 * en:User:Eran/refToolbarVe.js, en:User:Eran/refToolbarVeLoader.js – Adds a button for cite dialog, in which user can select a cite template to be included in article.
 * en:User:ערן/veReplace.js – Search and replace. Demonstration of how to interact with the underlying model and create dialogs.
 * meta:User:Matma Rex/visualeditor-signature.js – A tool to insert a signature (<>~) that is correctly rendered and formatted in the editor.
 * de:Benutzer:Schnark/js/veAutocorrect.js – User script that implements an autocorrect feature, mostly for typographical replacements.
 * de:Benutzer:Schnark/js/veSummary.js — "Very hackish" user script for providing access to previous edit summaries.
 * zh:MediaWiki:Gadget-EditorAPIs.js — A library that presents a common interface for wikitext editing. Useful for 2017 source editor.
 * pl:MediaWiki:Gadget-ref-klawiatura.js — A gadget that inserts <>  in any code editor (including 2017 VE Editor)