Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A userscript that lets you quickly copy content on SE as markdown. Just select and pres Ctrl+Alt+M
// ==UserScript==
// @name Copy as markdown
// @namespace http://stackexchange.com/users/4337810/
// @version 1.2
// @description A userscript that lets you quickly copy content on SE as markdown. Just select and pres Ctrl+Alt+M
// @author ᔕᖺᘎᕊ (http://stackexchange.com/users/4337810/)
// @match *://*.stackexchange.com/*
// @match *://*.stackoverflow.com/*
// @match *://*.superuser.com/*
// @match *://*.serverfault.com/*
// @match *://*.askubuntu.com/*
// @match *://*.stackapps.com/*
// @match *://*.mathoverflow.net/*
// @require https://cdn.rawgit.com/domchristie/to-markdown/master/dist/to-markdown.js
// @grant none
// ==/UserScript==
function getSelectionHtml() { //http://stackoverflow.com/a/6668159/3541881
if (typeof window.getSelection != "undefined") {
var sel = window.getSelection();
if (sel.rangeCount) {
var container = document.createElement("div");
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
container.appendChild(sel.getRangeAt(i).cloneContents());
}
return container.innerHTML;
}
} else if (typeof document.selection != "undefined") {
if (document.selection.type == "Text") {
return document.selection.createRange().htmlText;
}
}
}
$(document).on('keyup', function(e) {
if (e.ctrlKey && e.altKey && e.which == 77) {
var parsed = $.parseHTML(getSelectionHtml()),
c = $('<div/>');
$.each(parsed, function(i, v) {
c.append(v);
});
c.find('*').filter(function() {
return $(this).text().trim() === '';
}).remove();
var newhtml = c.html(),
markdown = toMarkdown(newhtml, {
converters: [{
filter: 'div',
replacement: function(html, node) {
return '\n ' + html;
}
}, {
filter: 'span',
replacement: function(html, node) {
return '';
}
}, {
filter: 'script',
replacement: function(html, node) {
return $(node).text();
}
}]
});
console.log(markdown);
prompt('Press Ctrl+C to copy markdown', markdown);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment