Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// ==UserScript==
// @name Save Indent - Better Copy for Github, Gist, google-code-prettify
// @namespace https://gist.github.com/7cc
// @description save indent/whitespace when copy source code / コピーした際のインデントを正常化する
// @include *
// @exclued https://www.google*
// @exclued https://www.youtube.com/*
// @version 2.03
// @grant none
// ==/UserScript==
// works on
// github
// gist, gist-embed
// google-code-prettify wih line-break
// NOT works if the selection starts from an *un*highlighted element. (= before code)
;(function(){
var syntaxType = ""
if (location.host === "gist.github.com" || document.querySelector(".lines.highlight")) {
syntaxType = "gist"
}else if (location.host === "github.com") {
syntaxType = "github"
}else if (document.querySelector(".prettyprint.linenums")) {
syntaxType = "google"
}else {
return
}
var query = ({
'gist': {
body: ".blob-wrapper",
line: '.line'
},
'github': {
body: ".blob-wrapper",
line:'.blob-line-code'
},
'google': {
body: ".prettyprint *",
line: 'li'
}
}) [syntaxType]
document.addEventListener("copy", copySyntax, false)
function copySyntax(e) {
var selectedNode = getSelection().anchorNode.nodetype === 1 ? getSelection().anchorNode : getSelection().anchorNode.parentNode
var isSelectCode = selectedNode.matches(query.body + "," + query.body + " *")
// disable if MarkDown
if( selectedNode.matches(".markdown-body *") ) {
return
}
if (isSelectCode) {
var df = getSelection().getRangeAt(0).cloneContents()
, td = df.querySelectorAll(query.line) // *
, isOneLine = td.length
, copyTarget = isOneLine ? td : df.childNodes
, joinStr = isOneLine ? "\n" : ""
, copyDate
copyDate = Array.map(copyTarget, function(e){
return e.textContent.replace(/\n|^\u00A0$/gm, "")
}).join(joinStr)
//console.log(copyDate)
e.clipboardData.setData("text/plain", copyDate)
e.preventDefault()
}
}
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.