GitHub Code Show Whitespace

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

当前为 2019-04-28 提交的版本,查看 最新版本

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