Jump to content

User:Decltype/autoeval.js

From 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.
function autoevalTab()
{
 // mw.util.addPortletLink("p-cactions", "javascript:subster( getSelectedText() )", "subster", "substtab-link", "subst");
  if(mw.config.get('wgAction') == "edit")
    $(window).load(function() { $("body").mouseup(autoeval); } );
}
$(autoevalTab);

function autoeval()
{
  var textarea = document.getElementById("wpTextbox1");
  if(!textarea)
    return;
  var start = textarea.selectionStart;
  var end = textarea.selectionEnd;
  var text = textarea.value.substring(start, end); //alert(text);
  var template = /{{([^]+)}}/.exec(text);
  if(!template)
    return;
  var qtext = "{{subst:" + template[1] + "}}";
  
  $.post(mw.config.get('wgServer') + mw.config.get('wgScript') + "?title=" + mw.config.get('wgPageName') + "&action=submit&wpPreview=true&live=true&wpTextbox1=" + qtext,
    function(data) 
    { var textarea = document.getElementById("wpTextbox1");
      var pre = $("preview", data).text(); alert(pre);
      var repl = /<div class='previewnote'>[^]*<\/div>[^]*<p>([^]+)<\/p>/.exec(pre)[1]; 

//      alert (text + " " + repl);
      textarea.value = textarea.value.replace(text, repl);
      textarea.setSelectionRange(start, end + repl.length - text.length);
    }
  );
}