Skip to content

Instantly share code, notes, and snippets.

@7cc
Last active December 28, 2015 09:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 7cc/7480799 to your computer and use it in GitHub Desktop.
Save 7cc/7480799 to your computer and use it in GitHub Desktop.
// ==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