User:Guywan/Scripts/InsertShortcuts.js

This is an old revision of this page, as edited by Guywan (talk | contribs) at 21:11, 20 March 2020 (grr python). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
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>
if(typeof(window.us_InsertShortcuts) == 'undefined')
{
	window.us_InsertShortcuts =
	{
		DEBUG: true,
		
		inserts: [],
		
		setup: function()
		{
			// Setup key handler.
			window.addEventListener("keyup", e =>
			{
				if(e.altKey && e.key.match(/\d/g))
				{
					this.insert(parseInt(e.key));
				}
			});
			
			// Load user's settings.
			$.ajax(
            {
                url : mw.util.getUrl(`User:${mw.config.get("wgUserName")}/InsertShortcutsSettings.js`) + "?action=raw", dataType : "text"
            })
            .fail(result => { mw.notify("Failed to load your settings: " + result, "error"); })
            .done(text =>
            {
            	text = text.split("\n");
            	for(var i = 0; i < text.length && i < 10; i++)
            	{
            		this.inserts.push(text[i].split(" "));
            	}
            	
            	if(this.DEBUG) console.log("Finished loading user settings." + inserts);
            });
		},
		
		insert: function(number)
		{
			const txtarea = document.getElementById("wpTextbox1");
			var start = txtarea.selectionStart;
			var end = txtarea.selectionEnd;
			
			if(start == end)  // Expand to select nearest 'word'.
			{
				while(txtarea.value.charAt(end).match(/\w/g)) end++;
				while(txtarea.value.charAt(start - 1).match(/\w/g)) start--;
				
				if(this.DEBUG) console.log(txtarea.value.substring(start, end));
			}
			
			// Enclose selected text.
			var result = this.inserts[number][0] + txtarea.value.substring(start, end) + this.inserts[number][1];
			
			// Update txtarea.
			txtarea.value = txtarea.value.substring(0, start) + result + txtarea.value.substr(end + 1);
			
			if(this.DEBUG) console.log("Inserted.");
		}
	};
}

$(() =>
{
	if(mw.config.get("wgAction") != "edit") return;
	
	us_InsertShortcuts.setup();
});
// </nowiki>