GitHub Code Show Whitespace

A userscript that shows whitespace (space, tabs and carriage returns) in code blocks

目前為 2017-10-11 提交的版本,檢視 最新版本

  1. // ==UserScript==
  2. // @name GitHub Code Show Whitespace
  3. // @version 1.1.1
  4. // @description A userscript that shows whitespace (space, tabs and carriage returns) in code blocks
  5. // @license MIT
  6. // @author Rob Garrison
  7. // @namespace https://github.com/Mottie
  8. // @include https://github.com/*
  9. // @include https://gist.github.com/*
  10. // @run-at document-idle
  11. // @grant GM_addStyle
  12. // @require https://greasyfork.org/scripts/28721-mutations/code/mutations.js?version=198500
  13. // @icon https://github.com/fluidicon.png
  14. // ==/UserScript==
  15. (() => {
  16. "use strict";
  17.  
  18. // include em-space & en-space?
  19. const whitespace = {
  20. // Applies \xb7 (·) to every space
  21. "%20" : "<span class='pl-space ghcw-whitespace'> </span>",
  22. // Applies \xb7 (·) to every non-breaking space (alternative: \u2423 (␣))
  23. "%A0" : "<span class='pl-nbsp ghcw-whitespace'>&nbsp;</span>",
  24. // Applies \xbb (») to every tab
  25. "%09" : "<span class='pl-tab ghcw-whitespace'>\x09</span>",
  26. // non-matching key; applied manually
  27. // Applies \u231d (⌝) to the end of every line
  28. // (alternatives: \u21b5 (↵) or \u2938 (⤸))
  29. "CRLF" : "<span class='pl-crlf ghcw-whitespace'></span>\n"
  30. },
  31. span = document.createElement("span"),
  32. // ignore +/- in diff code blocks
  33. regexWS = /(\x20|&nbsp;|\x09)/g,
  34. regexCR = /\r*\n$/,
  35. regexExceptions = /(\.md)$/i,
  36.  
  37. toggleButton = document.createElement("div");
  38. toggleButton.className = "ghcw-toggle btn btn-sm tooltipped tooltipped-n";
  39. toggleButton.setAttribute("aria-label", "Toggle Whitespace");
  40. toggleButton.innerHTML = "<span class='pl-tab'></span>";
  41.  
  42. GM_addStyle(`
  43. .ghcw-active .ghcw-whitespace,
  44. .gist-content-wrapper .file-actions .btn-group {
  45. position: relative;
  46. display: inline;
  47. }
  48. .ghcw-active .ghcw-whitespace:before {
  49. position: absolute;
  50. opacity: .5;
  51. user-select: none;
  52. font-weight: bold;
  53. color: #777 !important;
  54. top: -.25em;
  55. left: 0;
  56. }
  57. .ghcw-toggle .pl-tab {
  58. pointer-events: none;
  59. }
  60. .ghcw-active .pl-space:before {
  61. content: "\\b7";
  62. }
  63. .ghcw-active .pl-nbsp:before {
  64. content: "\\b7";
  65. }
  66. .ghcw-active .pl-tab:before,
  67. .ghcw-toggle .pl-tab:before {
  68. content: "\\bb";
  69. }
  70. .ghcw-active .pl-crlf:before {
  71. content: "\\231d";
  72. top: .1em;
  73. }
  74. /* weird tweak for diff markdown files - see #27 */
  75. .ghcw-adjust .ghcw-active .ghcw-whitespace:before {
  76. left: .6em;
  77. }
  78. /* hide extra leading space added to diffs - see #27 */
  79. .diff-table .blob-code-inner .pl-space:first-child {
  80. opacity: 0;
  81. }
  82. `);
  83.  
  84. function addToggle() {
  85. $$(".file-actions").forEach(el => {
  86. if (!$(".ghcw-toggle", el)) {
  87. el.insertBefore(toggleButton.cloneNode(true), el.childNodes[0]);
  88. }
  89. });
  90. }
  91.  
  92. function getNodes(line) {
  93. const nodeIterator = document.createNodeIterator(
  94. line,
  95. NodeFilter.SHOW_TEXT,
  96. () => NodeFilter.FILTER_ACCEPT
  97. );
  98. let currentNode,
  99. nodes = [];
  100. while ((currentNode = nodeIterator.nextNode())) {
  101. nodes.push(currentNode);
  102. }
  103. return nodes;
  104. }
  105.  
  106. function escapeHTML(html) {
  107. return html.replace(/[<>"'&]/g, m => ({
  108. "<": "&lt;",
  109. ">": "&gt;",
  110. "&": "&amp;",
  111. "'": "&#39;",
  112. "\"": "&quot;"
  113. }[m]));
  114. }
  115.  
  116. function replaceWhitespace(html) {
  117. return escapeHTML(html).replace(regexWS, s => {
  118. let idx = 0,
  119. ln = s.length,
  120. result = "";
  121. for (idx = 0; idx < ln; idx++) {
  122. result += whitespace[encodeURI(s[idx])] || s[idx] || "";
  123. }
  124. return result;
  125. });
  126. }
  127.  
  128. function replaceTextNode(nodes) {
  129. let node, indx, el,
  130. ln = nodes.length;
  131. for (indx = 0; indx < ln; indx++) {
  132. node = nodes[indx];
  133. if (
  134. node &&
  135. node.nodeType === 3 &&
  136. node.textContent &&
  137. node.textContent.search(regexWS) > -1
  138. ) {
  139. el = span.cloneNode();
  140. el.innerHTML = replaceWhitespace(node.textContent.replace(regexCR, ""));
  141. node.parentNode.insertBefore(el, node);
  142. node.parentNode.removeChild(node);
  143. }
  144. }
  145. }
  146.  
  147. function addWhitespace(block) {
  148. let lines, indx, len;
  149. if (block && !block.classList.contains("ghcw-processed")) {
  150. block.classList.add("ghcw-processed");
  151. indx = 0;
  152.  
  153. // class name of each code row
  154. lines = $$(".blob-code-inner:not(.blob-code-hunk)", block);
  155. len = lines.length;
  156.  
  157. // loop with delay to allow user interaction
  158. const loop = () => {
  159. let line, nodes,
  160. // max number of DOM insertions per loop
  161. max = 0;
  162. while (max < 50 && indx < len) {
  163. if (indx >= len) {
  164. return;
  165. }
  166. line = lines[indx];
  167. // first node is a syntax string and may have leading whitespace
  168. nodes = getNodes(line);
  169. replaceTextNode(nodes);
  170. // remove end CRLF if it exists; then add a line ending
  171. line.innerHTML = line.innerHTML.replace(regexCR, "") + whitespace.CRLF;
  172. max++;
  173. indx++;
  174. }
  175. if (indx < len) {
  176. setTimeout(() => {
  177. loop();
  178. }, 100);
  179. }
  180. };
  181. loop();
  182. }
  183. }
  184.  
  185. function detectDiff(wrap) {
  186. const header = $(".file-header", wrap);
  187. if ($(".diff-table", wrap) && header) {
  188. const file = header.getAttribute("data-path");
  189. if (
  190. // File Exceptions that need tweaking (e.g. ".md")
  191. regexExceptions.test(file) ||
  192. // files with no extension (e.g. LICENSE)
  193. file.indexOf(".") === -1
  194. ) {
  195. // This class is added to adjust the position of the whitespace
  196. // markers for specific files; See issue #27
  197. wrap.classList.add("ghcw-adjust");
  198. }
  199. }
  200. }
  201.  
  202. function $(selector, el) {
  203. return (el || document).querySelector(selector);
  204. }
  205.  
  206. function $$(selector, el) {
  207. return [...(el || document).querySelectorAll(selector)];
  208. }
  209.  
  210. function closest(selector, el) {
  211. while (el && el.nodeType === 1) {
  212. if (el.matches(selector)) {
  213. return el;
  214. }
  215. el = el.parentNode;
  216. }
  217. return null;
  218. }
  219.  
  220. // bind whitespace toggle button
  221. document.addEventListener("click", event => {
  222. const target = event.target;
  223. if (
  224. target.nodeName === "DIV" &&
  225. target.classList.contains("ghcw-toggle")
  226. ) {
  227. const wrap = closest(".file", target);
  228. const block = $(".highlight", wrap);
  229. if (block) {
  230. target.classList.toggle("selected");
  231. block.classList.toggle("ghcw-active");
  232. detectDiff(wrap);
  233. addWhitespace(block);
  234. }
  235. }
  236. });
  237.  
  238. document.addEventListener("ghmo:container", addToggle);
  239. document.addEventListener("ghmo:diff", addToggle);
  240. // toggle added to diff & file view
  241. addToggle();
  242.  
  243. })();