MediaWiki:Gadget-JavascriptHeadings.js

From Wiktionary, the free dictionary
Jump to navigation Jump to search

Note – after saving, you may have to bypass your browser’s cache to see the changes.

  • Mozilla / Firefox / Safari: hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (Command-R on a Macintosh);
  • Konqueror and Chrome: click Reload or press F5;
  • Opera: clear the cache in Tools → Preferences;
  • Internet Explorer: hold Ctrl while clicking Refresh, or press Ctrl-F5.

See also: Special:Gadgets.


// {{documentation}}
// This transforms text surrounded by equals signs in JavaScript comments into HTML headers.
// comments should be on one line(!) and begin and end with two equals signs; it's space-friendly

// == Start ==
$ (function(){
	if (['view', 'submit'].indexOf(mw.config.get('wgAction')) == -1)
		return; // not just viewing the page
	if (['css', 'javascript'].indexOf(mw.config.get('wgPageContentModel')) == -1)
		return; // not on a JavaScript or CSS page
/* === Find comments and make headings out of them === */
	$("#bodyContent pre span").filter(".c1,.cm,.c").each(function(i, elem) { //c1=js oneliner, cm=js multiline, c=css comment
		var twoSlashes = $(elem).text().match(/^\s*\/\/\s*(==+)\s*(.+?)\s*(==+)\s*$/)
		var slashAsterisk = $(elem).text().match(/^\s*\/\*\s*(==+)\s*(.+?)\s*(==+)\s*\*\/\s*$/);
		var txt = (twoSlashes && twoSlashes[2]) || (slashAsterisk && slashAsterisk[2]); // if matched then length = 2
		if (txt && (!elem.previousSibling || /\s*\n+\s*/.test(elem.previousSibling.textContent))) { // means comment starts on a new line
			var tagLevel = ((twoSlashes && twoSlashes[1]) || (slashAsterisk && slashAsterisk[1])).length;
			var tagName = "<h" + tagLevel  + ">";
			$(tagName).addClass("mw-headline").css("margin-top", "0").text(txt).replaceAll(elem); //maybe even negative margins?
		}
	});
});