代码片段高亮

选择代码片段后点击图标弹出新窗口显示语法高亮美化与格式化后的代码与字数统计

当前为 2022-01-09 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Highlight Every Code
  3. // @name:zh-CN 代码片段高亮
  4. // @name:zh-TW 程式碼片斷高亮
  5. // @namespace hoothin
  6. // @version 2.2
  7. // @description Add a icon to popup a window that allows syntax highlighting and beautify and word count of source code snippets on current page
  8. // @description:zh-CN 选择代码片段后点击图标弹出新窗口显示语法高亮美化与格式化后的代码与字数统计
  9. // @description:zh-TW 選擇程式碼片段後點選圖示彈出新視窗顯示語法高亮美化與格式化後的程式碼與字數統計
  10. // @author Hoothin
  11. // @grant GM_registerMenuCommand
  12. // @grant GM.registerMenuCommand
  13. // @grant GM_setValue
  14. // @grant GM.setValue
  15. // @grant GM_getValue
  16. // @grant GM.getValue
  17. // @grant unsafeWindow
  18. // @compatible chrome
  19. // @compatible firefox
  20. // @license MIT License
  21. // @contributionURL https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=rixixi@sina.com&item_name=Greasy+Fork+donation
  22. // @contributionAmount 1
  23. // @include *
  24. // ==/UserScript==
  25.  
  26. (function() {
  27. 'use strict';
  28. var codeIcon=document.createElement("img");
  29. var codes, selStr, scrollX, scrollY, customInput=false,altKey=true,ctrlKey=true,shiftKey=true,metaKey=true;
  30. var _unsafeWindow=(typeof unsafeWindow=='undefined'? window : unsafeWindow);
  31. codeIcon.style.cssText="position:fixed;z-index:99999;cursor:pointer;transition:opacity 0.5s ease-in-out 0s;opacity:0;border:5px solid rgba(0, 0, 0, 0.2);border-radius:10px;";
  32. codeIcon.title="Show this code snippet";
  33. codeIcon.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABYAAAAYAgMAAACD0OXYAAAACVBMVEX7+/swMDBTU1MLxgsCAAAAJElEQVQI12MIBYEAGLUKBBbAqAUMQICgAoAqoBQ95JaCnASjAAgXMdk3d5HTAAAAAElFTkSuQmCC";
  34. codeIcon.onmousedown=highlight;
  35.  
  36. document.addEventListener('DOMMouseScroll', function(o) {
  37. hideIcon();
  38. });
  39. document.addEventListener('wheel', function(o) {
  40. hideIcon();
  41. });
  42. document.addEventListener('mousewheel', function(o) {
  43. hideIcon();
  44. });
  45. document.addEventListener('mouseover', function(o) {
  46. if(o.target.nodeName!="PRE" && o.target.nodeName!="CODE")return;
  47. if(o.target.offsetWidth && o.target.offsetWidth<110)return;
  48. selStr=o.target.innerText;
  49. if(!selStr)return;
  50. codes=selStr.replace(/&/g, "&amp;").replace(/\</g,"&lt;").replace(/\>/g,"&gt;");
  51. document.body.appendChild(codeIcon);
  52. let pos=getMousePos(o);
  53. scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
  54. scrollY = document.documentElement.scrollTop || document.body.scrollTop;
  55. let top=o.target.offsetTop-scrollY;
  56. let left=o.target.offsetLeft-scrollX;
  57. codeIcon.style.opacity=0.9;
  58. codeIcon.style.top=top+"px";
  59. codeIcon.style.left=left+"px";
  60. });
  61. document.addEventListener('mousedown', function(o) {
  62. hideIcon();
  63. });
  64. document.addEventListener('mouseup', function(o) {
  65. if (o.button === 0 && ((!ctrlKey && !altKey && !metaKey && !shiftKey) || (ctrlKey && o.ctrlKey) || (altKey && o.altKey) || (metaKey && o.metaKey) || (shiftKey && o.shiftKey))) {
  66. //var customInputKey=(o.ctrlKey && o.shiftKey);
  67. setTimeout(function(){
  68. selStr=document.getSelection().toString();
  69. codes=selStr.replace(/&/g, "&amp;").replace(/\</g,"&lt;").replace(/\>/g,"&gt;");
  70. if(!codes){
  71. return;
  72. }
  73. document.body.appendChild(codeIcon);
  74. let pos=getMousePos(o);
  75. let clientH=(document.documentElement && document.documentElement.clientHeight) || 0;
  76. let clientW=(document.documentElement && document.documentElement.clientWidth) || 0;
  77. let top=pos.y>clientH-50?(pos.y-30):(pos.y+20);
  78. let left=pos.x>clientW-50?(pos.x-30):(pos.x+20);
  79. codeIcon.style.opacity=0.9;
  80. codeIcon.style.top=top+"px";
  81. codeIcon.style.left=left+"px";
  82. },1);
  83. }
  84. },false);
  85.  
  86. function highlight(){
  87. if(customInput){
  88. selStr=prompt("Input code here","");
  89. if(!selStr)return;
  90. codes=selStr.replace(/&/g, "&amp;").replace(/\</g,"&lt;").replace(/\>/g,"&gt;");
  91. }
  92. let html='<title>Code Snippet</title>'+
  93. '<link rel="stylesheet" href="https://cdn.rawgit.com/google/code-prettify/master/styles/sons-of-obsidian.css"/>'+
  94. '<script>var code,codeStr;window.onload=function(){code=document.querySelector("#code");codeStr=code.innerHTML.replace(/&amp;/g, "&").replace(/&(nbsp;|amp;|#39;|quot;)/g, "&amp;$1");prettyPrint();'+
  95. 'document.querySelector("body>a:nth-child(1)").onclick=function(){'+
  96. 'code.innerHTML=js_beautify('+
  97. 'codeStr.replace(/&gt;/g, \'>\').replace(/&lt;/g, \'<\').replace(/\'(\\\\\'|[^\'])*?\'/g, function(word){'+
  98. 'return word.replace(/>/g, \'&gt;\').replace(/</g, \'&lt;\');}'+
  99. ').replace(/\"(\\\\\"|[^\"])*?\"/g, function(word){'+
  100. 'return word.replace(/>/g, \'&gt;\').replace(/</g, \'&lt;\');}'+
  101. '));code.className=\'prettyprint linenums\';prettyPrint();return false;'+
  102. '};}</script>'+
  103. '<script src="https://cdnjs.cloudflare.com/ajax/libs/prettify/r298/prettify.min.js?skin=sons-of-obsidian"></script>'+
  104. '<script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.6.4/beautify.min.js"></script>'+
  105. '<script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.6.4/beautify-html.min.js"></script>'+
  106. '<script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.6.4/beautify-css.min.js"></script>'+
  107. 'Code formatting: <a href="#">Javaspcript</a> '+
  108. '<a href="#" onclick="code.innerHTML=html_beautify(codeStr);code.className=\'prettyprint linenums\';prettyPrint();return false;">Html</a> '+
  109. '<a href="#" onclick="code.innerHTML=css_beautify(codeStr);code.className=\'prettyprint linenums\';prettyPrint();return false;">Css</a> '+
  110. '<a href="#" onclick="code.innerHTML=codeStr;code.className=\'prettyprint linenums\';prettyPrint();return false;">Raw</a> <b style="color:red">('+selStr.replace(/\s/g,"").length+' words)</b>'+
  111. '<pre id="code" class="prettyprint linenums" style="word-wrap: break-word; white-space: pre-wrap;border: 1px solid rgb(136, 136, 204);border-radius: 8px;">' + codes + "</pre>";
  112.  
  113. let c = _unsafeWindow.open("", "_blank", "width=750, height=400, location=0, resizable=1, menubar=0, scrollbars=0");
  114. c.document.write(html);
  115. c.document.close();
  116. }
  117. function hideIcon(){
  118. codeIcon.style.opacity=0;
  119. customInput=false;
  120. if(codeIcon.parentNode)codeIcon.parentNode.removeChild(codeIcon);
  121. }
  122. function getMousePos(event) {
  123. var e = event || window.event;
  124. scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
  125. scrollY = document.documentElement.scrollTop || document.body.scrollTop;
  126. var x = (e.pageX || e.clientX) - scrollX;
  127. var y = (e.pageY || e.clientY) - scrollY;
  128. return { 'x': x, 'y': y };
  129. }
  130.  
  131. var _GM_registerMenuCommand;
  132. if(typeof GM_registerMenuCommand!='undefined'){
  133. _GM_registerMenuCommand=GM_registerMenuCommand;
  134. }else if(typeof GM!='undefined' && typeof GM.registerMenuCommand!='undefined'){
  135. _GM_registerMenuCommand=GM.registerMenuCommand;
  136. }
  137. if(typeof _GM_registerMenuCommand=='undefined')_GM_registerMenuCommand=(s,f)=>{};
  138. var storage={
  139. supportGM: typeof GM_getValue=='function' && typeof GM_getValue('a','b')!='undefined',
  140. supportGMPromise: typeof GM!='undefined' && typeof GM.getValue=='function' && typeof GM.getValue('a','b')!='undefined',
  141. mxAppStorage:(function(){
  142. try{
  143. return window.external.mxGetRuntime().storage;
  144. }catch(e){
  145. };
  146. })(),
  147. operaUJSStorage:(function(){
  148. try{
  149. return window.opera.scriptStorage;
  150. }catch(e){
  151. };
  152. })(),
  153. setItem:function(key,value){
  154. if(this.operaUJSStorage){
  155. this.operaUJSStorage.setItem(key,value);
  156. }else if(this.mxAppStorage){
  157. this.mxAppStorage.setConfig(key,value);
  158. }else if(this.supportGM){
  159. GM_setValue(key,value);
  160. }else if(this.supportGMPromise){
  161. GM.setValue(key,value);
  162. }else if(window.localStorage){
  163. window.localStorage.setItem(key,value);
  164. };
  165. },
  166. getItem:function(key,cb){
  167. var value;
  168. if(this.operaUJSStorage){
  169. value=this.operaUJSStorage.getItem(key);
  170. }else if(this.mxAppStorage){
  171. value=this.mxAppStorage.getConfig(key);
  172. }else if(this.supportGM){
  173. value=GM_getValue(key);
  174. }else if(this.supportGMPromise){
  175. value=GM.getValue(key).then(v=>{cb(v)});
  176. return;
  177. }else if(window.localStorage){
  178. value=window.localStorage.getItem(key);
  179. };
  180. cb(value);
  181. },
  182. };
  183. storage.getItem("keyConfig",v=>{
  184. if(v){
  185. var keys=v.split("");
  186. altKey=keys[0]!="0";
  187. ctrlKey=keys[1]!="0";
  188. shiftKey=keys[2]!="0";
  189. metaKey=keys[3]!="0";
  190. }
  191. if(/greasyfork\.org\/.*\/scripts\/24150[^\/]*$/.test(location.href)){
  192. var saveConfig=()=>{
  193. var conStr="";
  194. conStr+=altKey?"1":"0";
  195. conStr+=ctrlKey?"1":"0";
  196. conStr+=shiftKey?"1":"0";
  197. conStr+=metaKey?"1":"0";
  198. storage.setItem("keyConfig",conStr);
  199. };
  200. var keyEles=document.querySelectorAll("h1>em>code");
  201. keyEles[0].style.userSelect="none";
  202. keyEles[1].style.userSelect="none";
  203. keyEles[2].style.userSelect="none";
  204. keyEles[3].style.userSelect="none";
  205. keyEles[0].style.opacity=altKey?"":"0.3";
  206. keyEles[1].style.opacity=ctrlKey?"":"0.3";
  207. keyEles[2].style.opacity=shiftKey?"":"0.3";
  208. keyEles[3].style.opacity=metaKey?"":"0.3";
  209.  
  210. keyEles[0].onclick=e=>{
  211. altKey=!altKey;
  212. keyEles[0].style.opacity=altKey?"":"0.3";
  213. saveConfig();
  214. };
  215. keyEles[1].onclick=e=>{
  216. ctrlKey=!ctrlKey;
  217. keyEles[1].style.opacity=ctrlKey?"":"0.3";
  218. saveConfig();
  219. };
  220. keyEles[2].onclick=e=>{
  221. shiftKey=!shiftKey;
  222. keyEles[2].style.opacity=shiftKey?"":"0.3";
  223. saveConfig();
  224. };
  225. keyEles[3].onclick=e=>{
  226. metaKey=!metaKey;
  227. keyEles[3].style.opacity=metaKey?"":"0.3";
  228. saveConfig();
  229. };
  230. }
  231. });
  232.  
  233. _GM_registerMenuCommand("Custom input to highlight", ()=>{
  234. selStr=document.getSelection().toString();
  235. codes=selStr.replace(/&/g, "&amp;").replace(/\</g,"&lt;").replace(/\>/g,"&gt;");
  236. if(!codes){
  237. customInput=true;
  238. }
  239. highlight();
  240. });
  241. })();