Skip to content

Instantly share code, notes, and snippets.

@shu8
Last active May 17, 2022 07:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shu8/9203772dd22c4bc04aafebd4fc4f8ca1 to your computer and use it in GitHub Desktop.
Save shu8/9203772dd22c4bc04aafebd4fc4f8ca1 to your computer and use it in GitHub Desktop.
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.3
// @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://unpkg.com/turndown/dist/turndown.js
// @grant none
// ==/UserScript==
const turndownService = new TurndownService();
turndownService.addRule('div', {
filter: ['div'],
replacement: function(html, node) {
return '\n ' + html;
}
});
turndownService.addRule('script', {
filter: ['script'],
replacement: function(html, node) {
return $(node).text();
}
});
function getSelectionHtml() { //http://stackoverflow.com/a/6668159/3541881
if (typeof window.getSelection != "undefined") {
const sel = window.getSelection();
if (sel.rangeCount) {
const container = document.createElement("div");
for (let i = 0, len = sel.rangeCount; i < len; ++i) {
container.appendChild(sel.getRangeAt(i).cloneContents());
}
return container.innerHTML;
}
} else if (typeof document.selection != "undefined" && document.selection.type == "Text") {
return document.selection.createRange().htmlText;
}
}
$(document).on('keyup', function(e) {
if (e.ctrlKey && e.altKey && e.which == 77) {
const parsed = $.parseHTML(getSelectionHtml());
const c = $('<div/>');
$.each(parsed, function(i, v) {
c.append(v);
});
c.find('*').filter(function() {
return $(this).text().trim() === '';
}).remove();
const markdown = turndownService.turndown(c.html());
console.log(markdown);
prompt('Press Ctrl+C to copy markdown', markdown);
}
});
@vbrozik
Copy link

vbrozik commented May 16, 2022

@shu8
Copy link
Author

shu8 commented May 17, 2022

@vbrozik Thanks for letting me know -- it should be fixed now! :)

@vbrozik
Copy link

vbrozik commented May 17, 2022

Thanks, it works again!

Installation URL of this script for Tampermonkey:
https://gist.github.com/shu8/9203772dd22c4bc04aafebd4fc4f8ca1/raw/markdownCopier.user.js

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment