Created
September 2, 2011 06:15
-
-
Save Benjol/1188013 to your computer and use it in GitHub Desktop.
Non-break-space userscript for StackExchange
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ==UserScript== | |
// @name NonBreakSpaces+ | |
// @namespace benjol | |
// @description Make Ctrl-space add a non-break-space in textareas | |
// @include http://french.stackexchange.com/questions/* | |
// @include http://meta.french.stackexchange.com/questions/* | |
// @include http://chat.stackexchange.com/rooms/1098/* | |
// ==/UserScript== | |
function inject(f) { | |
var script = document.createElement("script"); | |
script.type = "text/javascript"; | |
script.textContent = "(" + f.toString() + ")()"; | |
document.body.appendChild(script); | |
}; | |
//Note that if you copy in Firefox, you'll get the impression that the nbsp isn't there, but it is! | |
// (https://bugzilla.mozilla.org/show_bug.cgi?id=359303) | |
inject(function () { | |
var nbsp = String.fromCharCode(160), | |
left = "«" + nbsp, //171 | |
right = nbsp + "»", //187 | |
next = left; | |
function insert(field, val) { | |
if(field.selectionStart || field.selectionStart == '0') { | |
var cursorAfter = field.selectionStart + val.length; | |
var first = field.value.slice(0, field.selectionStart); | |
var second = field.value.slice(field.selectionEnd); | |
field.value = first + val + second; | |
field.setSelectionRange(cursorAfter, cursorAfter); | |
} | |
else //won't work in IE, sorry! | |
field.value += val; | |
} | |
$(document).keypress(function(event) { | |
var field = event.target; | |
if(event.ctrlKey && event.charCode == 32) { | |
insert(field, nbsp); | |
event.preventDefault(); | |
} else if (event.charCode == 34) { | |
insert(field, next); | |
next = (next == left) ? right : left; | |
event.preventDefault(); | |
}; | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment