GitHub Code Show Whitespace

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

当前为 2019-06-07 提交的版本,查看 最新版本

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