tinymce.ui.Factory.add( 'WPLinkPreview', tinymce.ui.Control.extend( {
'<div id="' + this._id + '" class="wp-link-preview">' +
'<a href="' + this.url + '" target="_blank" tabindex="-1">' + this.url + '</a>' +
setURL: function( url ) {
if ( this.url !== url ) {
url = window.decodeURIComponent( url );
url = url.replace( /^(?:https?:)?\/\/(?:www\.)?/, '' );
if ( ( index = url.indexOf( '?' ) ) !== -1 ) {
url = url.slice( 0, index );
if ( ( index = url.indexOf( '#' ) ) !== -1 ) {
url = url.slice( 0, index );
url = url.replace( /(?:index)?\.html$/, '' );
if ( url.charAt( url.length - 1 ) === '/' ) {
url = url.slice( 0, -1 );
// If nothing's left (maybe the URL was just a fragment), use the whole URL.
// If the URL is longer that 40 chars, concatenate the beginning (after the domain) and ending with '...'.
if ( url.length > 40 && ( index = url.indexOf( '/' ) ) !== -1 && ( lastIndex = url.lastIndexOf( '/' ) ) !== -1 && lastIndex !== index ) {
// If the beginning + ending are shorter that 40 chars, show more of the ending.
if ( index + url.length - lastIndex < 40 ) {
lastIndex = -( 40 - ( index + 1 ) );
url = url.slice( 0, index + 1 ) + '\u2026' + url.slice( lastIndex );
tinymce.$( this.getEl().firstChild ).attr( 'href', this.url ).text( url );
tinymce.ui.Factory.add( 'WPLinkInput', tinymce.ui.Control.extend( {
'<div id="' + this._id + '" class="wp-link-input">' +
'<label for="' + this._id + '_label">' + tinymce.translate( 'Paste URL or type to search' ) + '</label><input id="' + this._id + '_label" type="text" value="" />' +
'<input type="text" style="display:none" value="" />' +
setURL: function( url ) {
this.getEl().firstChild.nextSibling.value = url;
return tinymce.trim( this.getEl().firstChild.nextSibling.value );
getLinkText: function() {
var text = this.getEl().firstChild.nextSibling.nextSibling.value;
if ( ! tinymce.trim( text ) ) {
return text.replace( /[\r\n\t ]+/g, ' ' );
var urlInput = this.getEl().firstChild.nextSibling;
urlInput.nextSibling.value = '';
tinymce.PluginManager.add( 'wplink', function( editor ) {
var emailRegex = /^(mailto:)?[a-z0-9._%+-]+@[a-z0-9][a-z0-9.-]*\.[a-z]{2,63}$/i;
var urlRegex1 = /^https?:\/\/([^\s/?.#-][^\s\/?.#]*\.?)+(\/[^\s"]*)?$/i;
var urlRegex2 = /^https?:\/\/[^\/]+\.[^\/]+($|\/)/i;
var speak = ( typeof window.wp !== 'undefined' && window.wp.a11y && window.wp.a11y.speak ) ? window.wp.a11y.speak : function() {};
var hasLinkError = false;
var __ = window.wp.i18n.__;
var _n = window.wp.i18n._n;
var sprintf = window.wp.i18n.sprintf;
function getSelectedLink() {
node = editor.selection.getStart(),
link = editor.dom.getParent( node, 'a[href]' );
html = editor.selection.getContent({ format: 'raw' });
if ( html && html.indexOf( '</a>' ) !== -1 ) {
href = html.match( /href="([^">]+)"/ );
link = editor.$( 'a[href="' + href[1] + '"]', node )[0];
editor.selection.select( link );
function removePlaceholders() {
editor.$( 'a' ).each( function( i, element ) {
var $element = editor.$( element );
if ( $element.attr( 'href' ) === '_wp_link_placeholder' ) {
editor.dom.remove( element, true );
} else if ( $element.attr( 'data-wplink-edit' ) ) {
$element.attr( 'data-wplink-edit', null );
function removePlaceholderStrings( content, dataAttr ) {
return content.replace( /(<a [^>]+>)([\s\S]*?)<\/a>/g, function( all, tag, text ) {
if ( tag.indexOf( ' href="_wp_link_placeholder"' ) > -1 ) {
tag = tag.replace( / data-wplink-edit="true"/g, '' );
tag = tag.replace( / data-wplink-url-error="true"/g, '' );
return tag + text + '</a>';
function checkLink( node ) {
var $link = editor.$( node );
var href = $link.attr( 'href' );
if ( ! href || typeof $ === 'undefined' ) {
if ( /^http/i.test( href ) && ( ! urlRegex1.test( href ) || ! urlRegex2.test( href ) ) ) {
$link.attr( 'data-wplink-url-error', 'true' );
speak( editor.translate( 'Warning: the link has been inserted but may have errors. Please test it.' ), 'assertive' );
$link.removeAttr( 'data-wplink-url-error' );
editor.on( 'preinit', function() {
if ( editor.wp && editor.wp._createToolbar ) {
toolbar = editor.wp._createToolbar( [
if ( typeof window.wpLink !== 'undefined' ) {
editButtons.push( 'wp_link_advanced' );
editToolbar = editor.wp._createToolbar( editButtons, true );
editToolbar.on( 'show', function() {
if ( typeof window.wpLink === 'undefined' || ! window.wpLink.modalOpen ) {
window.setTimeout( function() {
var element = editToolbar.$el.find( 'input.ui-autocomplete-input' )[0],
selection = linkNode && ( linkNode.textContent || linkNode.innerText );
if ( ! element.value && selection && typeof window.wpLink !== 'undefined' ) {
element.value = window.wpLink.getUrlFromSelection( selection );
editToolbar.on( 'hide', function() {
if ( ! editToolbar.scrolling ) {
editor.execCommand( 'wp_link_cancel' );
editor.addCommand( 'WP_Link', function() {
if ( tinymce.Env.ie && tinymce.Env.ie < 10 && typeof window.wpLink !== 'undefined' ) {
window.wpLink.open( editor.id );
linkNode = getSelectedLink();
editToolbar.tempHide = false;
editor.execCommand( 'mceInsertLink', false, { href: '_wp_link_placeholder' } );
linkNode = editor.$( 'a[href="_wp_link_placeholder"]' )[0];
editor.dom.setAttribs( linkNode, { 'data-wplink-edit': true } );
editor.addCommand( 'wp_link_apply', function() {
if ( editToolbar.scrolling ) {
href = inputInstance.getURL();
text = inputInstance.getLinkText();
var parser = document.createElement( 'a' );
if ( 'javascript:' === parser.protocol || 'data:' === parser.protocol ) { // jshint ignore:line
editor.dom.remove( linkNode, true );
if ( ! /^(?:[a-z]+:|#|\?|\.|\/)/.test( href ) && ! emailRegex.test( href ) ) {
editor.dom.setAttribs( linkNode, { href: href, 'data-wplink-edit': null } );
if ( ! tinymce.trim( linkNode.innerHTML ) ) {
editor.$( linkNode ).text( text || href );
// Audible confirmation message when a link has been inserted in the Editor.
if ( typeof window.wpLinkL10n !== 'undefined' && ! hasLinkError ) {
speak( window.wpLinkL10n.linkInserted );
editor.addCommand( 'wp_link_cancel', function() {
if ( ! editToolbar.tempHide ) {
editor.addCommand( 'wp_unlink', function() {
editor.execCommand( 'unlink' );
editToolbar.tempHide = false;
editor.execCommand( 'wp_link_cancel' );
editor.addShortcut( 'access+a', '', 'WP_Link' );
editor.addShortcut( 'access+s', '', 'wp_unlink' );
// The "de-facto standard" shortcut, see #27305.
editor.addShortcut( 'meta+k', '', 'WP_Link' );
editor.addButton( 'link', {
tooltip: 'Insert/edit link',
editor.addButton( 'unlink', {
editor.addMenuItem( 'link', {
text: 'Insert/edit link',
stateSelector: 'a[href]',
editor.on( 'pastepreprocess', function( event ) {
var pastedStr = event.content,
regExp = /^(?:https?:)?\/\/\S+$/i;
if ( ! editor.selection.isCollapsed() && ! regExp.test( editor.selection.getContent() ) ) {
pastedStr = pastedStr.replace( /<[^>]+>/g, '' );
pastedStr = tinymce.trim( pastedStr );
if ( regExp.test( pastedStr ) ) {
editor.execCommand( 'mceInsertLink', false, {
href: editor.dom.decode( pastedStr )
// Remove any remaining placeholders on saving.
editor.on( 'savecontent', function( event ) {
event.content = removePlaceholderStrings( event.content, true );
// Prevent adding undo levels on inserting link placeholder.
editor.on( 'BeforeAddUndo', function( event ) {
if ( event.lastLevel && event.lastLevel.content && event.level.content &&
event.lastLevel.content === removePlaceholderStrings( event.level.content ) ) {
// When doing undo and redo with keyboard shortcuts (Ctrl|Cmd+Z, Ctrl|Cmd+Shift+Z, Ctrl|Cmd+Y),
// set a flag to not focus the inline dialog. The editor has to remain focused so the users can do consecutive undo/redo.
editor.on( 'keydown', function( event ) {
if ( event.keyCode === 27 ) { // Esc
editor.execCommand( 'wp_link_cancel' );
if ( event.altKey || ( tinymce.Env.mac && ( ! event.metaKey || event.ctrlKey ) ) ||
( ! tinymce.Env.mac && ! event.ctrlKey ) ) {
if ( event.keyCode === 89 || event.keyCode === 90 ) { // Y or Z
window.clearTimeout( doingUndoRedoTimer );
doingUndoRedoTimer = window.setTimeout( function() {
editor.addButton( 'wp_link_preview', {
onPostRender: function() {
editor.addButton( 'wp_link_input', {
onPostRender: function() {
var element = this.getEl(),
input = element.firstChild.nextSibling,
if ( $ && $.ui && $.ui.autocomplete ) {
$input.on( 'keydown', function() {
$input.removeAttr( 'aria-activedescendant' );
source: function( request, response ) {
if ( last === request.term ) {
if ( /^https?:/.test( request.term ) || request.term.indexOf( '.' ) !== -1 ) {
$.post( window.ajaxurl, {
_ajax_linking_nonce: $( '#_ajax_linking_nonce' ).val()
focus: function( event, ui ) {
$input.attr( 'aria-activedescendant', 'mce-wp-autocomplete-' + ui.item.ID );
* Don't empty the URL input field, when using the arrow keys to
* highlight items. See api.jqueryui.com/autocomplete/#event-focus
select: function( event, ui ) {
$input.val( ui.item.permalink );
$( element.firstChild.nextSibling.nextSibling ).val( ui.item.title );
if ( 9 === event.keyCode && typeof window.wpLinkL10n !== 'undefined' ) {
// Audible confirmation message when a link has been selected.
speak( window.wpLinkL10n.linkSelected );
$input.attr( 'aria-expanded', 'true' );
editToolbar.blockHide = true;
$input.attr( 'aria-expanded', 'false' );
editToolbar.blockHide = false;
noResults: __( 'No results found.' ) ,
results: function( number ) {
/* translators: %d: Number of search results found. */
'%d result found. Use up and down arrow keys to navigate.',
'%d results found. Use up and down arrow keys to navigate.',
} ).autocomplete( 'instance' )._renderItem = function( ul, item ) {
var fallbackTitle = ( typeof window.wpLinkL10n !== 'undefined' ) ? window.wpLinkL10n.noTitle : '',
title = item.title ? item.title : fallbackTitle;
return $( '<li role="option" id="mce-wp-autocomplete-' + item.ID + '">' )
.append( '<span>' + title + '</span> <span class="wp-editor-float-right">' + item.info + '</span>' )
'aria-autocomplete': 'list',
'aria-expanded': 'false',
'aria-owns': $input.autocomplete( 'widget' ).attr( 'id' )
.on( 'focus', function() {
var inputValue = $input.val();
* Don't trigger a search if the URL field already has a link or is empty.
* Also, avoids screen readers announce `No search results`.
if ( inputValue && ! /^https?:/.test( inputValue ) ) {
$input.autocomplete( 'search' );