GitHub Code Show Whitespace

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

当前为 2018-08-03 提交的版本,查看 最新版本

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