GitHub Code Show Whitespace

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

当前为 2020-03-28 提交的版本,查看 最新版本

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