GitHub Code Show Whitespace

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

目前為 2018-07-31 提交的版本,檢視 最新版本

  1. // ==UserScript==
  2. // @name GitHub Code Show Whitespace
  3. // @version 1.2.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_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. `);
  89.  
  90. function addToggle() {
  91. $$(".file-actions").forEach(el => {
  92. if (!$(".ghcw-toggle", el)) {
  93. el.insertBefore(toggleButton.cloneNode(true), el.childNodes[0]);
  94. }
  95. if (showWhiteSpace === "true") {
  96. // Let the page render a bit before going nuts
  97. setTimeout(show(el, true), 200);
  98. }
  99. });
  100. }
  101.  
  102. function getNodes(line) {
  103. const nodeIterator = document.createNodeIterator(
  104. line,
  105. NodeFilter.SHOW_TEXT,
  106. () => NodeFilter.FILTER_ACCEPT
  107. );
  108. let currentNode,
  109. nodes = [];
  110. while ((currentNode = nodeIterator.nextNode())) {
  111. nodes.push(currentNode);
  112. }
  113. return nodes;
  114. }
  115.  
  116. function escapeHTML(html) {
  117. return html.replace(/[<>"'&]/g, m => ({
  118. "<": "&lt;",
  119. ">": "&gt;",
  120. "&": "&amp;",
  121. "'": "&#39;",
  122. "\"": "&quot;"
  123. }[m]));
  124. }
  125.  
  126. function replaceWhitespace(html) {
  127. return escapeHTML(html).replace(regexWS, s => {
  128. let idx = 0,
  129. ln = s.length,
  130. result = "";
  131. for (idx = 0; idx < ln; idx++) {
  132. result += whitespace[encodeURI(s[idx])] || s[idx] || "";
  133. }
  134. return result;
  135. });
  136. }
  137.  
  138. function replaceTextNode(nodes) {
  139. let node, indx, el,
  140. ln = nodes.length;
  141. for (indx = 0; indx < ln; indx++) {
  142. node = nodes[indx];
  143. if (
  144. node &&
  145. node.nodeType === 3 &&
  146. node.textContent &&
  147. node.textContent.search(regexWS) > -1
  148. ) {
  149. el = span.cloneNode();
  150. el.innerHTML = replaceWhitespace(node.textContent.replace(regexCR, ""));
  151. node.parentNode.insertBefore(el, node);
  152. node.parentNode.removeChild(node);
  153. }
  154. }
  155. }
  156.  
  157. function* modifyLine(lines) {
  158. while (lines.length) {
  159. const line = lines.shift();
  160. // first node is a syntax string and may have leading whitespace
  161. replaceTextNode(getNodes(line));
  162. // remove end CRLF if it exists; then add a line ending
  163. const html = line.innerHTML;
  164. const update = html.replace(regexCR, "") + whitespace.CRLF;
  165. if (update !== html) {
  166. line.innerHTML = update;
  167. }
  168. }
  169. yield lines;
  170. }
  171.  
  172. function addWhitespace(block) {
  173. if (block && !block.classList.contains("ghcw-processed")) {
  174. block.classList.add("ghcw-processed");
  175. let status;
  176.  
  177. // class name of each code row
  178. const lines = $$(".blob-code-inner:not(.blob-code-hunk)", block);
  179. const iter = modifyLine(lines);
  180.  
  181. // loop with delay to allow user interaction
  182. const loop = () => {
  183. for (let i = 0; i < 40; i++) {
  184. status = iter.next();
  185. }
  186. if (!status.done) {
  187. requestAnimationFrame(loop);
  188. }
  189. };
  190. loop();
  191. }
  192. }
  193.  
  194. function detectDiff(wrap) {
  195. const header = $(".file-header", wrap);
  196. if ($(".diff-table", wrap) && header) {
  197. const file = header.getAttribute("data-path");
  198. if (
  199. // File Exceptions that need tweaking (e.g. ".md")
  200. regexExceptions.test(file) ||
  201. // files with no extension (e.g. LICENSE)
  202. file.indexOf(".") === -1
  203. ) {
  204. // This class is added to adjust the position of the whitespace
  205. // markers for specific files; See issue #27
  206. wrap.classList.add("ghcw-adjust");
  207. }
  208. }
  209. }
  210.  
  211. function showAll() {
  212. $$(".file .highlight").forEach(target => {
  213. show(target, true);
  214. });
  215. }
  216.  
  217. function show(target, state) {
  218. const wrap = target.closest(".file");
  219. const block = $(".highlight", wrap);
  220. if (block) {
  221. wrap.querySelector(".ghcw-toggle").classList.toggle("selected", state);
  222. block.classList.toggle("ghcw-active", state);
  223. detectDiff(wrap);
  224. addWhitespace(block);
  225. }
  226. }
  227.  
  228. function $(selector, el) {
  229. return (el || document).querySelector(selector);
  230. }
  231.  
  232. function $$(selector, el) {
  233. return [...(el || document).querySelectorAll(selector)];
  234. }
  235.  
  236. // bind whitespace toggle button
  237. document.addEventListener("click", event => {
  238. const target = event.target;
  239. if (
  240. target.nodeName === "DIV" &&
  241. target.classList.contains("ghcw-toggle")
  242. ) {
  243. show(target);
  244. }
  245. });
  246.  
  247. GM.registerMenuCommand("Set GitHub Code White Space", async () => {
  248. let val = prompt("Always show on page load (true/false)?", showWhiteSpace);
  249. if (val !== null) {
  250. val = (val || "").toLowerCase();
  251. await GM.setValue("show-whitespace", val);
  252. showWhiteSpace = val;
  253. showAll();
  254. }
  255. });
  256.  
  257. document.addEventListener("ghmo:container", addToggle);
  258. document.addEventListener("ghmo:diff", addToggle);
  259. // toggle added to diff & file view
  260. addToggle();
  261.  
  262. })();