VisualEditor/Gadgets/Creating a custom command

This is an example for how to create a custom command. It will show up in the “Page options” menu and unlink all years (i.e. remove all links to pages with a numeric title, keeping the label). Currently it only works in the 2017 wikitext editor and only when text is selected.

Function to modify wikitext
First of all, we define our function to modify wikitext. This is not specific to VisualEditor, if you're reading this because you want to adapt your scripts to VisualEditor, you should already have this function.

Just as a minor note: In the early days of Wikipedia linking every year in a text was very popular. After some time editors realized that these links didn't really help anyone in most cases, so they tried to eliminate all those links. During that time scripts to do so automatically were very popular. Nowadays the remaining links to years are sensible in most cases, so scripts to remove them should no longer be needed, but it's still a nice example.

Create and register command
Next, we create a command to unlink all years. Most commands work by invoking a method from an  (documentation, see this example about how to create a command this way), but here it's easier to provide our own execution method instead.

So we inherit from  (documentation), and override two methods:

In, we check whether we are in source code mode or not. As the command currently only works with wikitext, we return  if we are in visual mode.

The  method is the place where we do the actual work: First, we check again the mode. This shouldn't be necessary, as no code should try to execute a command that isn't executable. But just in case we return  to indicate that nothing has been executed.

Next, we get the current selection. If it is collapsed (i.e. nothing is selected) we select the whole document. From this selection we get the wikitext. The result from the  method is almost what we want, but we have to fix the newline characters: In source mode, every line is wrapped in   tags, and the method returns   for both the opening and closing tags. So we have to strip the first one and replace two consecutive linebreaks with just one.

Now we can apply our function to change the wikitext. Before we can insert the new text, we have to transform it back to the format VisualEditor uses, so we replace every linebreak with a closing and an opening paragraph tag.

If we worked on the whole text, we collapse the selection, i.e. we set the cursor to the start of the text. Note that if we started with a selection it is automatically adapted to the changed text (in our case: it is made shorter for the removed links).