User:Thedewster/monobook.js

Source: Wikipedia, the free encyclopedia.
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
/* <nowiki> */

/* ========== AddLink Function ========== */
//A helper function to add a button to one of the toolbars in the interface.
//An improved(I hope) version of [[Wikipedia:WikiProject User scripts/Scripts/Add Link|addlilink]].
//[[User:JesseW/sig|JesseW, the juggling janitor]] 05:33, 8 November *2005 (UTC)

function addLink(where, url, name, id, title, key, after){
    //* where is the id of the toolbar where the button should be added;
    //   i.e. one of "p-cactions", "p-personal", "p-navigation", or "p-tb".
    //
    //* url is the URL which will be called when the button is clicked.
    //   javascript: urls can be used to do more complex things.
    //
    //* name is what will appear as the name of the button.
    //
    //* id is the id of the button; it's best to define one.  
    //   Use a prefix to make sure its unique. Optional.
    //
    //* title is the tooltip title that gives a longer description 
    //   of the button; if you define a accesskey, mention it here. Optional.
    //
    //* key is the char you want for the accesskey. Optional.
    //
    //* after is the id or DOM node of the button you want to follow this one. Optional.
    //
    var na = document.createElement('a');
    na.href = url;
    na.appendChild(document.createTextNode(name));
    var li = document.createElement('li');
    if(id) li.id = id;
    li.appendChild(na);
    var tabs = document.getElementById(where).getElementsByTagName('ul')[0];
    if (!after) {
        tabs.appendChild(li);
    } else if (after.cloneNode) {  // looks like a DOM node
        tabs.insertBefore(li,after);
    } else {  // assume this is an ID string
        tabs.insertBefore(li,document.getElementById(after));
    }
    if(id) {
        if(key && title) { ta[id] = [key, title]; }
        else if(key) { ta[id] = [key, '']; }
        else if(title) { ta[id] = ['', title];} 
    }
    // re-render the title and accesskeys from existing code in wikibits.js
    akeytt();
    return li;
}

/*Returns the name of the page. For example, if you were browsing the "[[foo]]" WP page, getPname() would return "foo".*/
function getPname() {
  return wgPageName.replace(/_/g, ' ');
}

/* ========== Assessment script ========== */
// [[User:Outriggr/metadatatest.js]]
importScript('User:Outriggr/metadatatest.js'); 
assessmentMyTemplateCode = ["{{WikiProject College football|class=}}", "{{WikiProject Oklahoma|class=|importance=}}", "{{WikiProject University of Oklahoma|class=}}", "{{WPBiography|class=|importance=}}", "{{College-baseball-WikiProject|class=|importance=}}", "{{WikiProject College basketball|class=|importance=}}"];
assessmentDefaultProject = "WikiProject College football";
assessmentOverrideWatchPref = true;

/* ========== Formatter ========== */
//Begin formatter
function format() {
    var txt = document.editform.wpTextbox1;
    txt.value = catFixer(txt.value);
    txt.value = entities(txt.value);
    txt.value = fixheadings(txt.value);
    txt.value = fixsyntax(txt.value);
    txt.value = linkfixer(txt.value, false);
    //txt.value = imagefixer(txt.value);
    txt.value = whitespace(txt.value);
    txt.value = linksimplifyer(txt.value);
    txt.value = trim(txt.value);
}

function whitespace(str){
    str = str.replace(/\t/g, " ");

    str = str.replace(/^ ? ? \n/gm, "\n");
    str = str.replace(/(\n\n)\n+/g, "$1");
    str = str.replace(/== ? ?\n\n==/g, "==\n==");
    str = str.replace(/\n\n(\* ?\[?http)/g, "\n$1");

    str = str.replace(/^ ? ? \n/gm, "\n");
    str = str.replace(/\n\n\*/g, "\n*");
    str = str.replace(/[ \t][ \t]+/g, " ");
    str = str.replace(/([=\n]\n)\n+/g, "$1");
    str = str.replace(/ \n/g, "\n");

    //* bullet points
    str = str.replace(/^([\*#]+) /gm, "$1");
    str = str.replace(/^([\*#]+)/gm, "$1 ");

    //==Headings==
    str = str.replace(/^(={1,4}) ?(.*?) ?(={1,4})$/gm, "$1$2$3");

    //dash — spacing
    str = str.replace(/ ?(–|–|–|–|–) ?/g, "$1");
    str = str.replace(/ ?(—|—|—|—|—) ?/g, "$1");
    str = str.replace(/(—|—|—|—|—|–|–|–|–|–)/g, " $1 ");

    return trim(str);
}

function entities(str){
    //str = str.replace(//g, "");
    str = str.replace(/–|–|–/g, "–");
    str = str.replace(/—|—|—/g, "—");
   // str = str.replace(/(cm| m|km|mi)<sup>2</sup>/g, "$1²");
    str = str.replace(/²/g, "²");
    str = str.replace(/°/g, "°");

    return trim(str);
}

//Fix ==See also== and similar section common errors.
function fixheadings(str)
{
  if( !str.match(/= ?See also ?=/) )
    str = str.replace(/(== ?)(see also:?|related topics:?|related articles:?|internal links:?|also see:?)( ?==)/gi, "$1See also$3");

  str = str.replace(/(== ?)(external links:?|outside links|web ?links:?|exterior links:?)( ?==)/gi, "$1External links$3");
  str = str.replace(/(== ?)(external link:?|web ?link:?|exterior link:?)( ?==)/gi, "$1External link$3");
  str = str.replace(/(== ?)(reference:?)(s? ?==)/gi, "$1Reference$3");
  str = str.replace(/(== ?)(source:?)(s? ?==)/gi, "$1Source$3");
  str = str.replace(/(== ?)(further readings?:?)( ?==)/gi, "$1Further reading$3");

  return str;
}

function catFixer(str){
    str = str.replace(/\[\[ ?[Cc]ategory ?: ?/g, "[[Category:");

    return trim(str);
}

//fixes many common syntax problems
function fixsyntax(str)
{
  //replace html with wiki syntax
  if( !str.match(/'<\/?[ib]>|<\/?[ib]>'/gi) )
  {
    str = str.replace(/<i>(.*?)<\/i>/gi, "''$1''");
    str = str.replace(/<b>(.*?)<\/b>/gi, "'''$1'''");
  }
  str = str.replace(/<br\/>/gi, "<br />");
                      
  return trim(str);
}

//formats links in standard fashion
function linkfixer(str, checkImages)
{ 
  str = str.replace(/\]\[/g, "] [");
  var m = str.match(/\[?\[[^\]]*?\]\]?/g);
  if (m)
  {
    for (var i = 0; i < m.length; i++)
    {
      var x = m[i].toString();
      var y = x;

      //internal links only
      if ( !y.match(/^\[?\[http:\/\//i) && !y.match(/^\[?\[image:/i) )
      {
        if (y.indexOf(":") == -1 && y.substr(0,3) != "[[_" && y.indexOf("|_") == -1)
        {
          if (y.indexOf("|") == -1)
            y = y.replace(/_/g, " ");
          else
            y = y.replace( y.substr(0, y.indexOf("|")), y.substr(0, y.indexOf("|")).replace(/_/g, " "));
        }  
      
        y = y.replace(/ ?\| ?/, "|").replace("|]]", "| ]]");
        
      }

      str = str.replace(x, y);
    }
  }

  //repair bad internal links
  str = str.replace(/([^\[]|^)\[?\[([^\]]*?)\]\]?([^\]]|$)/gm, "$1[[$2]]$3");
  str = str.replace(/\[\[ ?([^\]]*?) ?\]\]/g, "[[$1]]");
  str = str.replace(/\[\[([^\]]*?)( |_)#([^\]]*?)\]\]/g, "[[$1#$3]]");

  //repair bad external links
  str = str.replace(/\[?\[http:\/\/([^\]]*?)\]\]?/gi, "[http://$1]");
  str = str.replace(/\[http:\/\/([^\]]*?)\|([^\]]*?)\]/gi, "[http://$1 $2]");

  return trim(str);
}

//fixes images
function imagefixer(str)
{

  //remove external images
  str = str.replace(/\[?\[image:http:\/\/([^\]]*?)\]\]?/gi, "[http://$1]");

  //fix links within internal images
  var m = str.match(/\[?\[image:[^\[\]]*?(\[?\[[^\]]*?\]*?[^\[\]]*?)*?\]+/gi);
  if (m)
  {
    for (var i = 0; i < m.length; i++)
    {
      var x = m[i].toString();
      var y = x;

      y = y.replace(/^\[\[i/i, "I").replace(/\]\]$/, "");
      y = y.replace(/(\[[^\]]*?)$/, "$1]");
      y = linkfixer(y, true);
      y = "[[" + y + "]]";

      str = str.replace(x, y);
    }
  }

  return trim(str);
}

//simplifies some links e.g. [[Dog|dog]] to [[dog]] and [[Dog|dogs]] to [[dog]]s
function linksimplifyer(str){
  var m = str.match(/\[\[([^[]*?)\|([^[]*?)\]\]/g);
  if (m)
  {
    for (var i = 0; i < m.length; i++)
    {
      var n_arr = m[i].toString().match(/\[\[([^[]*?)\|([^[]*?)\]\]/);
      var n = n_arr[0];
      var a = n_arr[1];
      var b = n_arr[2];

      if (b.indexOf(a) == 0 || b.indexOf(TurnFirstToLower(a)) == 0)
      {
        var k = n.replace(/\[\[([^\]\|]*?)\|(\1)([\w]*?)\]\]/i, "[[$2]]$3");
        str = str.replace(n, k);
      }
    }
  }

  str = str.replace(/\[\[([^\]\|]+)\|([^\]\|]+)\]\]([A-Za-z\'][A-Za-z]*)([\.\,\;\:\"\!\?\s\n])/g, "[[$1|$2$3]]$4");

  return str;
}

//trim start and end, trim spaces from the end of lines
function trim(str) {
   str = str.replace(/ $/gm, "");
   return str.replace(/^\s*|\s*$/g, "");
}

//turns first character to lowercase
function TurnFirstToLower(input) {
  if (input != "")
  {
    var input = trim(input);
    var temp = input.substr(0, 1);
    return temp.toLowerCase() + input.substr(1, input.length);
  }
  else
    return "";
}


//entities that should never be unicoded
function noUnicodify(str) {
  str = str.replace(" & ", " & ");
  str = str.replace("&", "&amp;").replace("&lt;", "&amp;lt;").replace("&gt;", "&amp;gt;").replace("&quot;", "&amp;quot;").replace("&apos;", "&amp;apos;");
  str = str.replace("−", "&minus;").replace("×", "&times;");

  str = str.replace(" ", "&nbsp;").replace(" ", "&thinsp;").replace("­", "&shy;");
  str = str.replace("′", "&prime;");
  str = str.replace(/&(#0?9[13];)/, "&$1");
  str = str.replace(/&(#0?12[345];)/, "&$1");

  return str;
}

$(function () {
  if(document.forms.editform) {
    addLink('p-cactions', 'javascript:format()', 'format', 'ca-format', 'Format article', '', 'ca-history');
  }
});
//End formatter

/* ========== Quick Image Delete ========== */
mw.loader.load('https://en.wikipedia.org/w/index.php?title=User:Howcheng/quickimgdelete.js' +
  '&action=raw&ctype=text/javascript');
/* This is to keep track of who is using this extension: [[User:Howcheng/quickimgdelete.js]] */

/* ========== AFD Helper ========== */
document.write('<script type="text/javascript"' +
  'src="http://en.wikipedia.org/w/index.php?title=User:Jnothman/afd_helper/' +
  'script.js&action=raw&ctype=text/javascript&dontcountme=s"></script>');
/* This is to keep track of who is using this extension: [[User:Jnothman/afd_helper/script.js]] */

/* ========== AutoCopyVio Tool ==========*/
mw.loader.load('https://en.wikipedia.org/w/index.php?title=Wikipedia:WikiProject User scripts/Scripts/Autocopyvio.js' +
  '&action=raw&ctype=text/javascript');

/* ========== MECU's ImageCopyVio ========== */
mw.loader.load('https://en.wikipedia.org/w/index.php?title=User:Mecu/imagevio.js'
             + '&action=raw&ctype=text/javascript');
/* This is to keep track of who is using this extension: [[User:Mecu/imagevio.js]] */

/* ========== Personal links & Clock ========== */
// change personal links and add a clock
mw.loader.load('https://en.wikipedia.org/w/index.php?title=User:Nmajdan/personallinks.js' 
             + '&action=raw&ctype=text/javascript');

/* ========== PopUps ========== */
// [[User:Lupin/popups.js]]
importScript('User:Lupin/popups.js');
popupFixDabs=true;

/* ========== Interiot's Javascript Edit Counter ========== */
if (document.title.indexOf('User:Interiot/Tool2/code.js') != -1) {
  mw.loader.load('https://en.wikipedia.org/w/index.php?title=User:Interiot/Tool2/code.js&action=raw&ctype=text/javascript'); }

/* ========== winc ========== */
//Create 'winc' function:
function winc(s) {
document.write('<script type="text/javascript" src="' 
             + 'http://en.wikipedia.org/w/index.php?title=' + s
             + '&action=raw&ctype=text/javascript&dontcountme=s"></script>');
}
//function to handle dates:
winc('User:Bobblewik/monobook.js/dates.js');
//function to handle units:
winc('User:Bobblewik/monobook.js/unitformatter.js');

/* ========== UTC Clock========== */
//UTC clock
mw.loader.load('https://en.wikipedia.org/w/index.php?title=User:Voice_of_All/UTCclock.js' 
             + '&action=raw&ctype=text/javascript');
//[[Category:Wikipedians who use VoA script |{{PAGENAME}}]]

/* ========== Welcome New User script========== */
function welcome() {
 
    // Find the edit box
    var txt = document.editform.wpTextbox1;
 
    //The welcome template you are wanting to use
    var welcome_msg = 'W-basic'
 
    // The code to be added to the page
    var tag = '{{'+'subst'+':'+ welcome_msg +'}}';
 
    // If the edit box doesn't already have this tag...
    if (txt.value.indexOf(tag) == -1) {
 
        // Append the tag
        txt.value += tag;
 
        // Add an edit summary
        document.editform.wpSummary.value = 'Welcome to Wikipedia!';    
 
        // Press the Save page button
        document.editform.submit();
    } 
 
    // If the tag was already there, turn the tab background red to indicate 
    // that the script is functioning properly, but that there is no action 
    // to do.  This doesn't interrupt the user's work like an alert() would.
    else {
        document.getElementById('ca-unverified').firstChild.style.backgroundColor = "#ff4444";
        document.getElementById('ca-unverified').style.backgroundColor = "#ff4444";
    }
}
 
// Create a tab that calls this function when pressed
$(function () {
    if(document.title.indexOf("Editing User talk:") == 0) {
        mw.util.addPortletLink('p-cactions', 'javascript:welcome()', 'welcome', 'ca-welcome', 'Adds a welcome note to a new user', '', '');
    }
});
 
/* This is to keep track of who is using this extension: [[User:Nmajdan/welcome_newuser.js]] */


/* ========== ISBN linker ========== */
//This code will change ISBN links to point to the url of your choice,
//instead of Special:Book_sources. 
//
//How to use it:
//
//First, you must copy this code to your user javascript page. This is 
//at User:<your username>/monobook.js . My username is Lunchboxhero so
//my javascript page is User:Lunchboxhero/monobook.js . You must be logged
//in to edit your javascript page.
//
//Once you have copied the code and saved the page, you need to refresh your
//browser's cache. For Mozilla/Safari/Konqueror: hold down Shift while clicking 
//Reload (or press Ctrl-Shift-R), IE: press Ctrl-F5, Opera: press F5.
//
//The code should now work, as long as you are logged in.
//
//You can change the destination url by simply modifying the quoted url that
//follows document.links[i].href=
//
//Good luck, and if you have any questions, leave me a comment on the discussion
//page of User:Lunchboxhero/monobook.js .
//
//(Every line that starts with "//" is a comment and can be discarded.)

function externISBN() {
  for (var i = 0; i < document.links.length; i++) 
    {       
         var ln = document.links[i].href.match(/isbn=(.*)/);
         if (ln) {
           document.links[i].href='http://www.amazon.com/exec/obidos/ASIN/'+RegExp.$1;
         }
    }

}
$(externISBN);

/* ========== Peer Review ========== */
// Script from [[User:AndyZ/peerreviewer.js]]
mw.loader.load('https://en.wikipedia.org/w/index.php?title=User:AndyZ/peerreviewer.js' 
             + '&action=raw&ctype=text/javascript');

/* ========== Helper tools ========== */
mw.loader.load(
             'https://en.wikipedia.org/w/index.php?title=User:Voice_of_All/Addtabs/monobook.js'
             + '&action=raw&ctype=text/javascript&dontcountme=s');

/* ========== AfD/PfD/Copyvio tabs========== */
// AfD/PfD/Copyvio and tagging tabs
mw.loader.load('https://en.wikipedia.org/w/index.php?title=User:Voice_of_All/Deletion/monobook.js' 
             + '&action=raw&ctype=text/javascript');

/* ========== DEFAULTSORT script ========== */
// [[User:DStoykov/defaultsort.js]]

function defaultsort() {
//var apiurl = mw.config.get('wgServer')+mw.config.get('wgScriptPath')+'/api.php?action=query&meta=siteinfo&siprop=namespaces&format=xml';
//var xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : null;
//xmlhttp.open('GET',apiurl, false);
//xmlhttp.send(null);
//alert(xmlhttp.responseXML.getElementById('14'));

    var txt = document.editform.wpTextbox1.value;
    var sortkey = '';
    // Create an array of all category links
    if (txt.match(/\{\{\s*defaultsort/i)) {
        alert('There\'s already a defaultsort statement!');
        return;
    } 
    var catlinks = txt.match(/\[\[\s*((C|K)at(e|e)gor(y|i|ie|ia|ia|ija|io)|Кат(е|э)гор(ия|ија|ія|ыя)|Luokka|Flokkur)\s*:.*\]\]/ig);
    if (!catlinks) {
        alert('There are no category links!');
        return;
    } 
    for (i=0; i< catlinks.length; i++) {
        // Extract the name of the category
        var catname = catlinks[i].replace(/.+\s*:\s*([^|]*[^|\s])\s*(\|.*)?\]\]/,"$1");
        // Extract the sort key 
        var match = /\|[^\]]+/.exec(catlinks[i]);
        if (match == null) {
	          alert('Category '+catname+' doesn\'t include a sort key!'); 
            return;
        }
        // Strip the '|' and any trailing spaces
        var sk = match[0].replace(/\|(.+)/, "$1").replace(/(\S) +$/,"$1");
        if (i == 0) {
            sortkey = sk;
        } else {
            if (sortkey != sk) {
                alert('Not all sort keys are identical!\nThe sort key for category '+catname+' is different.');
                return;
            }
        }
    }
    // Now that we know that everything is OK, we can proceed with modifying the content of the editbox
    txt = txt.replace(catlinks[0], "{{DEFAULTSORT:"+sortkey+"}}\n"+catlinks[0]);
    for (i=0; i< catlinks.length; i++) {
        subst = catlinks[i].replace(/\|[^\]]+/,"");
        txt = txt.replace(catlinks[i], subst);
    }
    document.editform.wpTextbox1.value=txt;
}

$(function () {
  if(document.forms.editform) {
    mw.util.addPortletLink('p-cactions', 'javascript:defaultsort()', 'defaultsort', 'ca-defaultsort', '', '', document.getElementById('ca-purge'));
  }
});

// install [[User:Cacycle/wikEd]] in-browser text editor
document.write('<script type="text/javascript" src="'
+ 'http://en.wikipedia.org/w/index.php?title=User:Cacycle/wikEd.js'
+ '&action=raw&ctype=text/javascript"></' + 'script>');

//
 
function inc (file) {
  var lt = String.fromCharCode(60);
  var gt = String.fromCharCode(62);
  if (file.indexOf(".js") > -1) {
    document.writeln(lt+'script type="text/javascript" src="/w/index.php?title='+file+'&action=raw&ctype=text/javascript&dontcountme=s"'+gt+lt+'/script'+gt);
  } else if (file.indexOf(".css") > -1) {
    document.writeln(lt+'link rel="stylesheet" type="text/css" href="/w/index.php?title='+file+'&action=raw&ctype=text/css" /'+gt);
  }
}
 
inc("User:Topaz/init.js");
inc("User:Topaz/util.js");
inc("User:Topaz/comm.js");
inc("User:Topaz/wputil.js");
inc("Special:Mypage/statuschanger.js");

//
importScript('User:VoA/monobook.js');

/* Watchlist notifier ([[User:Ais523/watchlistnotifier.js]]); displays a message every time a watched page changes. */

var wmwpajax;
// From [[WP:US]] mainpage (wpajax renamed to wmwpajax)
wmwpajax={
        download:function(bundle) {
                // mandatory: bundle.url
                // optional:  bundle.onSuccess (xmlhttprequest, bundle)
                // optional:  bundle.onFailure (xmlhttprequest, bundle)
                // optional:  bundle.otherStuff OK too, passed to onSuccess and onFailure
                
                var x = window.XMLHttpRequest ? new XMLHttpRequest()
                : window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP")
                : false;
                
                if (x) {
                        x.onreadystatechange=function() {
                                x.readyState==4 && wmwpajax.downloadComplete(x,bundle);
                        };
                        x.open("GET",bundle.url,true);
                        x.send(null); 
                }
                return x;
        },

        downloadComplete:function(x,bundle) {
                x.status==200 && ( bundle.onSuccess && bundle.onSuccess(x,bundle) || true )
                || ( bundle.onFailure && bundle.onFailure(x,bundle) || alert(x.statusText+': '+bundle.url));
        }
};

// Example:
// function dlComplete(xmlreq, data) {
//      alert(data.message + xmlreq.responseText);
// }
//  wmwpajax.download({url:'http://en.wikipedia.org/w/index.php?title=Thresher&action=raw', 
//                   onSuccess: dlComplete, message: "Here's what we got:\n\n" });

// End of [[WP:US]] quote

function wmWatchEditFound(xmlreq, data) {
  var watchrev, watchsum, watchrevold, watchpage, junk;
  if(xmlreq.responseText.indexOf('revid=')==-1)
  {
    document.getElementById('contentSub').innerHTML+=
      "<div class='watchlistnotify'>(<i>watchlistnotifier can't determine whether a "+
      "watched page has changed<i>)</div>";
    return;
  }
  watchrev=xmlreq.responseText.split('revid="')[1].split('"')[0];
  try
  {
    watchrevold=document.cookie.split('ais523wmwatchrev=')[1].split('.')[0];
  }
  catch(junk) {watchrevold=0;}
  if(wgPageName == "Special:Watchlist")
  {
    document.cookie="ais523wmwatchrev="+watchrev+".; path=/";
    var aas=document.getElementById('bodyContent').getElementsByTagName('a');
    var i=aas.length;
    while(i--)
    {
      if(aas[i].href.indexOf('diff=')!=-1&&watchrevold)
        if(+(aas[i].href.split('diff=')[1].split('&')[0])>watchrevold)
          aas[i].parentNode.style.fontWeight='bold';
    }
  }
  else
  {
    watchsum=xmlreq.responseText.split('comment="')[1].split('"')[0];
    watchpage=xmlreq.responseText.split('title="')[1].split('"')[0];
    watchsum=watchsum.split('<').join('&lt;').split('>').join('&gt;');
    watchpage=watchpage.split('<').join('&lt;').split('>').join('&gt;');
    if(watchrev!=watchrevold)
      document.getElementById('contentSub').innerHTML+=
        "<div class='watchlistnotify'>\""+watchpage+'" changed: "'+watchsum+
        '". (<a href="/wiki/Special:Watchlist">watchlist</a>)</div>';
  }
}

$(function() {
  /* Find the top item in the watchlist, and its edit summary. We only need one item, so
     set the limit to 1 to ease the load on the server. */
    wmwpajax.download({url:'http://en.wikipedia.org/w/api.php?action=query&list=watchlist&wllimit=1&'+
      'wldir=older&format=xml&wlprop=comment|ids|title', onSuccess: wmWatchEditFound});
});

//[[Category:Wikipedians who use RC script]]

/* </nowiki> */