Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save z3nth10n/d3d38347e94fd5f0af2a8543b88bd306 to your computer and use it in GitHub Desktop.
Save z3nth10n/d3d38347e94fd5f0af2a8543b88bd306 to your computer and use it in GitHub Desktop.
// ==UserScript==
// @name SO_like_keyboards_shortcuts
// @namespace sputnick
// @include https://github.com/*
// @include https://gist.github.com/*
// @include https://*.slack.com/*
// @version 1
// @grant none
// ==/UserScript==
var id, name;
if (document.location.href.search(/github\.com/) > 0 ) {
id = 'new_comment_field';
name = 'github';
}
else if (document.location.href.search(/slack\.com/) > 0 ) {
id = 'message-input';
name = 'slack';
}
(function() {
document.addEventListener('keydown', function(e){
//window.alert(e.which);
// ctrl+b: bold
if (e.ctrlKey && e.which == 66) {
override(e);
if (name === 'slack') { wrapText(id, '*', '*'); }
else if (name === 'github') { wrapText(id, '**', '**'); }
return false;
}
// ctrl+i: emphasis
if (e.ctrlKey && e.which == 73) {
override(e);
wrapText(id, '_', '_');
return false;
}
// ctrl+k: code
if (e.ctrlKey && e.which == 75) {
override(e);
wrapText(id, '`', '`');
return false;
}
// ctrl+l: link
if (name === 'github' && e.ctrlKey && e.which == 76) {
override(e);
var p = window.prompt("Link paste bellow");
wrapText(id, '[', ']('+p+')');
return false;
}
}, true);
})();
function wrapText(elementID, openTag, closeTag) {
var textArea = $('#' + elementID);
var len = textArea.val().length;
var start = textArea[0].selectionStart;
var end = textArea[0].selectionEnd;
var selectedText = textArea.val().substring(start, end);
if (openTag == '`' && selectedText.search(/\n/) > 0 ) {
openTag = '```\n';
closeTag = '\n```';
}
var replacement = openTag + selectedText + closeTag;
textArea.val(textArea.val().substring(0, start) + replacement + textArea.val().substring(end, len));
}
function override(e) {
if (document.activeElement.tagName == "TEXTAREA") {
e.stopImmediatePropagation();
e.cancelBubble = true;
e.preventDefault();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment