GreasyFork Code: Syntax Highlight by PrismJS

To syntax highlight GreasyFork Code by PrismJS

As of 2025-06-04. See the latest version.

  1. // ==UserScript==
  2. // @name GreasyFork Code: Syntax Highlight by PrismJS
  3. // @namespace Violentmonkey Scripts
  4. // @grant none
  5. // @version 0.4.3
  6. // @author CY Fung
  7. // @description To syntax highlight GreasyFork Code by PrismJS
  8. // @run-at document-start
  9. // @inject-into page
  10. // @unwrap
  11. // @license MIT
  12. // @match https://greatest.deepsurf.us/*
  13. // @match https://sleazyfork.org/*
  14. //
  15. // ==/UserScript==
  16.  
  17. (() => {
  18.  
  19. const USE_SHADOW_MODE = true; // performance fix for long coding
  20.  
  21. const cdn = 'https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0';
  22. const resoruces = {
  23. 'prism-core.js': `${cdn}/components/prism-core.js`,
  24. 'prism-clike.js': `${cdn}/components/prism-clike.min.js`,
  25. 'prism-javascript.js': `${cdn}/components/prism-javascript.min.js`,
  26. 'prism-css.js': `${cdn}/components/prism-css.min.js`,
  27. 'prism-stylus.js': `${cdn}/components/prism-stylus.min.js`,
  28. 'prism.css': `${cdn}/themes/prism.min.css`,
  29. 'prism-dark.css': `${cdn}/themes/prism-dark.min.css`,
  30. }
  31.  
  32. const doActionCSS = () => `
  33.  
  34. .code-container, .code-container-shadow{
  35. height:100vh;
  36. }
  37. .code-container .CodeMirror, .code-container textarea{
  38. height:100%;
  39. }
  40. `;
  41.  
  42.  
  43. const global_css = () =>`
  44.  
  45. html {
  46. line-height: 1.5;
  47. -webkit-text-size-adjust: 100%;
  48. -moz-tab-size: 4;
  49. -o-tab-size: 4;
  50. tab-size: 4;
  51. font-family: ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;
  52. font-feature-settings: normal;
  53. font-variation-settings: normal
  54. }
  55.  
  56. .code-container code, .code-container kbd, .code-container pre, .code-container samp,
  57. .code-container-pre, .code-container-pre code, .code-container-pre pre {
  58. font-family: ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;
  59. font-size: 1em
  60. }
  61.  
  62. #script-content > .code-container[class] {
  63. width: 100%;
  64. }
  65.  
  66. .code-container[class], .code-container-shadow[class] {
  67. border-radius: 0;
  68. }
  69.  
  70. .code-container > pre:only-child, .code-container-pre{
  71. padding:0;
  72. }
  73.  
  74. pre.code-container-pre[class]{
  75.  
  76. padding: 0;
  77. border: 0;
  78. margin: 0;
  79. }
  80.  
  81. code.syntax-highlighted[class] {
  82. font-family: monospace;
  83. font-size: 13px;
  84. font-variant-ligatures: contextual;
  85. line-height: 1.15rem;
  86. text-shadow: none !important;
  87. }
  88.  
  89. .hljs-comment[class], .hljs-quote[class] {
  90. font-style: inherit;
  91. color: #259789;
  92. }
  93.  
  94. .hljs-add-marker-width .marker-fixed-width[class] {
  95. user-select: none !important;
  96. width: calc(var(--hljs-marker-width, 0em) + 16px);
  97. background: var(--marker-color-background, #f4f4f4);
  98. padding-right: 6px;
  99. margin-right: 4px;
  100. contain: paint style;
  101. color: var(--marker-color-text, inherit);
  102. }
  103.  
  104. .marker-fixed-width[marker-text]::before {
  105. content:attr(marker-text);
  106. }
  107.  
  108. `;
  109.  
  110.  
  111. const cssForCodePage = () => /\/scripts\/\d+[^\s\/\\]*\/code(\/|$)/.test(location.href) ? `
  112.  
  113. html:not([dkkfv]) div.code-container {
  114. display:none;
  115. }
  116.  
  117. .code-container,
  118. .code-container pre:only-child,
  119. .code-container pre:only-child code:only-child,
  120. .code-container-pre {
  121. max-height: calc(100vh + 4px);
  122. max-width: calc(100vw + 4px);
  123. }
  124. ` : '';
  125.  
  126.  
  127. const cssAdd = () =>`
  128.  
  129. ${global_css()}
  130.  
  131. ${cssForCodePage()}
  132.  
  133. .code-container, .code-container-shadow {
  134. max-width: 100%;
  135. display: inline-flex;
  136. flex-direction: column;
  137. overflow: auto;
  138. border-radius: 8px;
  139. max-height: 100%;
  140. overflow: visible;
  141. }
  142. .code-container > pre:only-child, .code-container-pre {
  143. max-width: 100%;
  144. display: inline-flex;
  145. flex-direction: column;
  146. flex-grow: 1;
  147. height: 0;
  148. }
  149. .code-container > pre:only-child > code:only-child, .code-container-pre > code:only-child{
  150. max-width: 100%;
  151. flex-grow: 1;
  152. height: 0;
  153. }
  154. .code-container pre code, .code-container-pre code {
  155. padding: 0;
  156. font-family: Consolas;
  157. cursor: text;
  158. overflow: auto;
  159. box-sizing: border-box;
  160. }
  161. .code-container pre code .marker, .code-container-pre code .marker {
  162. display: inline-block;
  163. color: #636d83;
  164. text-align: right;
  165. padding-right: 20px;
  166. user-select: none;
  167. cursor: auto;
  168. }
  169.  
  170. .code-container[contenteditable]{
  171. outline: 0 !important;
  172. contain: strict;
  173. box-sizing: border-box;
  174. }
  175.  
  176. .code-container[contenteditable]>pre[contenteditable="false"]{
  177. contain: strict;
  178. width: initial;
  179. box-sizing: border-box;
  180. }
  181.  
  182.  
  183.  
  184.  
  185. html {
  186.  
  187. --token-color-keyword: #07a;
  188. --token-color-punctuation: #1415ec;
  189. --token-color-comment: #259789;
  190. --token-color-function: #da204f;
  191. --token-color-atrule: #700d0d;
  192. --token-stylus-selector: #1373bb;
  193. }
  194.  
  195. [dark] {
  196.  
  197. --token-color-keyword: #898af2;
  198. --token-color-punctuation: #fadbdb;
  199. --token-color-comment:#59c6b9;
  200. --token-color-function: #e98aa2;
  201. --token-color-atrule: #cc66ce;
  202. --token-stylus-selector: #96c7ec;
  203.  
  204. --marker-color-background: #242424;
  205. --marker-color-text: #b6b2b2;
  206.  
  207. }
  208.  
  209.  
  210. code .token.comment {
  211. color: var(--token-color-comment);
  212. }
  213.  
  214. code .token.atrule, code .token.attr-value, code .token.keyword {
  215. color: #1415ec;
  216. color: var(--token-color-keyword);
  217. }
  218.  
  219. code .token.punctuation{
  220. color: var(--token-color-punctuation);
  221. }
  222.  
  223.  
  224. code .token.variable-declaration,
  225. code .token.variable {
  226. color: #0d10cd;
  227. }
  228.  
  229. code .token.selector{
  230. color: #1373bb;
  231. }
  232.  
  233.  
  234. code .token.function {
  235. color:var(--token-color-function);
  236. }
  237.  
  238.  
  239.  
  240. .language-stylus .token.variable-declaration,
  241. .language-stylus .token.variable {
  242. color: #0d10cd;
  243. }
  244.  
  245. .language-stylus .token.selector{
  246. color: #1373bb;
  247. color: var(--token-stylus-selector);
  248. }
  249.  
  250. .language-stylus .token.punctuation{
  251. color:#700d0d;
  252. }
  253.  
  254.  
  255. .language-stylus .token.function {
  256. color:#da204f
  257. }
  258.  
  259.  
  260. code.language-stylus .token.atrule,
  261. code.language-stylus .token.attr-value,
  262. code.language-stylus .token.keyword,
  263. code.language-stylus .token.punctuation,
  264. code.language-stylus .token.function {
  265. color: #700d0d;
  266. color: var(--token-color-atrule);
  267. }
  268.  
  269. code.language-stylus .token.punctuation {
  270. opacity: 1;
  271. }
  272.  
  273. code.language-stylus .property-declaration .operator {
  274. color: inherit;
  275. }
  276.  
  277. .token, span.marker {
  278. contain: content;
  279. }
  280.  
  281. .prettyprint.prettyprint {
  282. background-color: transparent;
  283. }
  284.  
  285. `;
  286.  
  287.  
  288. const Promise = (async function () { })().constructor;
  289.  
  290. const delayPn = delay => new Promise((fn => setTimeout(fn, delay)));
  291.  
  292. const PromiseExternal = ((resolve_, reject_) => {
  293. const h = (resolve, reject) => { resolve_ = resolve; reject_ = reject };
  294. return class PromiseExternal extends Promise {
  295. constructor(cb = h) {
  296. super(cb);
  297. if (cb === h) {
  298. /** @type {(value: any) => void} */
  299. this.resolve = resolve_;
  300. /** @type {(reason?: any) => void} */
  301. this.reject = reject_;
  302. }
  303. }
  304. };
  305. })();
  306.  
  307. // -------- fix requestIdleCallback issue for long coding --------
  308.  
  309. const pud = new PromiseExternal();
  310. if (typeof window.requestIdleCallback === 'function' && !window.requestIdleCallback842 && window.requestIdleCallback.length === 1) {
  311. window.requestIdleCallback842 = window.requestIdleCallback;
  312. window.requestIdleCallback = function (callback, ...args) {
  313. console.error(322)
  314. return (this || window).requestIdleCallback842(async function () {
  315. await pud.then();
  316. setTimeout(()=>{
  317. callback.apply(this, arguments);
  318. });
  319. }, ...args);
  320. }
  321. }
  322.  
  323. // -------- fix requestIdleCallback issue for long coding --------
  324.  
  325. const pScript = new PromiseExternal();
  326. const pElementQuery = new PromiseExternal();
  327.  
  328. HTMLElement.prototype.getElementsByTagName331 = HTMLElement.prototype.getElementsByTagName;
  329. Document.prototype.getElementsByTagName331 = Document.prototype.getElementsByTagName;
  330.  
  331. HTMLElement.prototype.getElementsByTagName = getElementsByTagName;
  332. Document.prototype.getElementsByTagName = getElementsByTagName;
  333.  
  334. let byPass = true;
  335.  
  336. const observablePromise = (proc, timeoutPromise) => {
  337. let promise = null;
  338. return {
  339. obtain() {
  340. if (!promise) {
  341. promise = new Promise(resolve => {
  342. let mo = null;
  343. const f = () => {
  344. let t = proc();
  345. if (t) {
  346. mo.disconnect();
  347. mo.takeRecords();
  348. mo = null;
  349. resolve(t);
  350. }
  351. }
  352. mo = new MutationObserver(f);
  353. mo.observe(document, { subtree: true, childList: true })
  354. f();
  355. timeoutPromise && timeoutPromise.then(() => {
  356. resolve(null)
  357. });
  358. });
  359. }
  360. return promise
  361. }
  362. }
  363. }
  364.  
  365. const documentReady = new Promise(resolve => {
  366. Promise.resolve().then(() => {
  367. if (document.readyState !== 'loading') {
  368. resolve();
  369. } else {
  370. window.addEventListener("DOMContentLoaded", resolve, false);
  371. }
  372. });
  373. });
  374.  
  375. documentReady.then(async () => {
  376. pud.resolve();
  377. });
  378.  
  379. function getElementsByTagName(tag) {
  380. if (byPass) {
  381. if (tag === 'pre' || tag === 'code' || tag === 'xmp') {
  382. if (location.pathname.endsWith('/code')) {
  383. pElementQuery.resolve();
  384. return [];
  385. }
  386. }
  387. }
  388. return this.getElementsByTagName331(tag);
  389. }
  390.  
  391. async function onBodyHeadReadyAsync() {
  392. await observablePromise(() => document.body && document.head).obtain();
  393. }
  394.  
  395.  
  396. // Load CSS
  397. function loadJS(href) {
  398.  
  399. return new Promise(resolve => {
  400.  
  401. const script = document.createElement('script');
  402. script.src = href;
  403. script.onload = () => {
  404. resolve(script);
  405. };
  406. document.head.appendChild(script);
  407.  
  408. });
  409.  
  410. }
  411.  
  412. // Load CSS
  413. function loadCSS(href) {
  414. const link = document.createElement('link');
  415. link.rel = 'stylesheet';
  416. link.href = href;
  417. document.head.appendChild(link);
  418. return link;
  419. }
  420.  
  421.  
  422.  
  423.  
  424.  
  425. function getLangClassName(pre, textContent){
  426.  
  427.  
  428.  
  429. let className = '';
  430. let preLang = '';
  431.  
  432. if (pre.classList.contains('lang-js')) {
  433. preLang = 'lang-js';
  434. } else if (pre.classList.contains('lang-css')) {
  435. preLang = 'lang-css';
  436. } else if (pre.classList.contains('uglyprint')){
  437. let m =/\/\/\s*={2,9}(\w+)={2,9}\s*[\r\n]/.exec(pre.textContent);
  438. if(m){
  439. m = m[1];
  440. if(m === 'UserScript') preLang = 'lang-js';
  441. if(m === 'UserStyle') preLang = 'lang-css';
  442. }
  443. }
  444.  
  445. if (preLang === 'lang-js') {
  446. className = 'language-javascript';
  447. } else if (preLang === 'lang-css') {
  448.  
  449. const text = textContent;
  450. let m = /\n@preprocessor\s+([-_a-zA-Z]{3,8})\s*\n/.exec(text);
  451. className = 'language-css'
  452. if (m) {
  453. const preprocessor = m[1];
  454. if (preprocessor === 'stylus') {
  455. className = 'language-stylus';
  456. } else if (preprocessor === 'uso') {
  457. className = 'language-stylus';
  458. } else if (preprocessor === 'less') {
  459. className = 'language-less';
  460. } else if (preprocessor === 'default') {
  461. className = 'language-stylus';
  462. } else {
  463. className = 'language-stylus';
  464. }
  465. }
  466.  
  467. }
  468.  
  469. return className;
  470.  
  471.  
  472. }
  473.  
  474. /** @param {HTMLElement} pre */
  475. function prepareCodeAreaAsync(pre) {
  476.  
  477. if (pre.isConnected === false) return;
  478. const preParentNode = pre.parentNode;
  479. const preNextNode = pre.nextSibling;
  480.  
  481. const codeContainer = pre.closest('.code-container');
  482. const doContentEditable = codeContainer && codeContainer.querySelector('.code-container>pre:only-child');
  483.  
  484. pre.remove();
  485.  
  486. for (const li of pre.querySelectorAll('li')) {
  487. li.append(document.createTextNode('\n'));
  488. }
  489.  
  490. const textContent = pre.textContent;
  491.  
  492. const className = getLangClassName(pre, textContent);
  493.  
  494. if (!className) return;
  495.  
  496. if (doContentEditable) {
  497. // avoid selection to the outside by mouse dragging
  498. codeContainer.setAttribute('contenteditable', '');
  499. pre.setAttribute('contenteditable', 'false');
  500. }
  501.  
  502. const code = document.createElement('code');
  503.  
  504. code.classList.add(className);
  505. code.classList.add('syntax-highlighted')
  506.  
  507. let htmlCode = '';
  508.  
  509. if (className === 'language-javascript') {
  510. htmlCode = Prism.highlight(textContent, Prism.languages.javascript, 'javascript');
  511. } else if (className === 'language-stylus') {
  512. htmlCode = Prism.highlight(textContent, Prism.languages.stylus, 'stylus');
  513. } else if (className === 'language-less') {
  514. htmlCode = Prism.highlight(textContent, Prism.languages.less, 'less');
  515. } else {
  516. htmlCode = Prism.highlight(textContent, Prism.languages.css, 'css');
  517. }
  518.  
  519. // Adding line numbers
  520. htmlCode = htmlCode || '';
  521. const htmlSplit = htmlCode ? htmlCode.split('\n') : [];
  522. const totalLines = htmlSplit.length;
  523.  
  524. let mwStyle = '';
  525.  
  526. if (totalLines >= 1) {
  527. code.classList.add('hljs-add-marker-width');
  528. const len = `${totalLines}`.length * 0.5;
  529. mwStyle = `${len}em`;
  530. htmlCode = htmlSplit.map((n, i) => `<span class="marker marker-fixed-width" marker-text="${i + 1}"></span>${n}`).join('\n') || '';
  531.  
  532. } else {
  533.  
  534. code.classList.remove('hljs-add-marker-width');
  535. }
  536.  
  537. code.innerHTML = htmlCode;
  538. code.style.setProperty('--hljs-marker-width', mwStyle);
  539.  
  540.  
  541.  
  542. if(pre.firstChild === pre.lastChild && pre.firstChild instanceof Node){
  543. pre.firstChild.replaceWith(code);
  544. }else{
  545. pre.innerHTML = '';
  546. pre.appendChild(code);
  547. }
  548. pre.classList.add('code-container-pre');
  549.  
  550.  
  551. if(USE_SHADOW_MODE){
  552.  
  553. const shadowDiv = document.createElement("div");
  554. shadowDiv.classList.add('code-container-shadow')
  555.  
  556. const shadow = shadowDiv.attachShadow({ mode: "open" });
  557.  
  558. const styles = document.querySelectorAll('link, style');
  559. for(style of styles) {
  560. if(style.classList.contains("stylus")) continue;
  561. if(style.nodeName === 'LINK' && style.rel !== 'stylesheet') continue;
  562. shadow.appendChild(style.cloneNode(true))
  563. }
  564.  
  565. shadow.appendChild(pre)
  566. preParentNode.insertBefore(shadowDiv, preNextNode);
  567. }else{
  568.  
  569. preParentNode.insertBefore(pre, preNextNode);
  570. }
  571.  
  572.  
  573.  
  574.  
  575. }
  576.  
  577. const documentBodyHeadReady = onBodyHeadReadyAsync();
  578.  
  579. documentBodyHeadReady.then(async () => {
  580.  
  581. if (!location.pathname.endsWith('/code')) {
  582. return;
  583. }
  584.  
  585. document.head.appendChild(document.createElement('style')).textContent = `${cssAdd()}`;
  586.  
  587. self.Prism = self.Prism || {};
  588. self.Prism.manual = true;
  589. await loadJS(resoruces['prism-core.js']);
  590. await loadJS(resoruces['prism-clike.js']);
  591. await loadJS(resoruces['prism-javascript.js']);
  592. await loadJS(resoruces['prism-css.js']);
  593. await loadJS(resoruces['prism-stylus.js']);
  594.  
  595. if (document.documentElement.hasAttribute('dark')) {
  596.  
  597. loadCSS(resoruces['prism-dark.css']);
  598. } else {
  599.  
  600. loadCSS(resoruces['prism.css']);
  601. }
  602.  
  603. pScript.resolve();
  604.  
  605.  
  606.  
  607.  
  608. });
  609.  
  610. let keydownActive = false;
  611.  
  612. documentReady.then(async () => {
  613.  
  614. if (!location.pathname.endsWith('/code')) {
  615. byPass = false;
  616. return;
  617. }
  618. await pScript.then();
  619.  
  620. await Promise.race([pElementQuery, delayPn(800)]);
  621.  
  622. const targets = document.querySelectorAll('.code-container pre.lang-js, .code-container pre.lang-css, .code-container pre.uglyprint');
  623. // pre.uglyprint : too long code ; see https://greatest.deepsurf.us/zh-CN/scripts/24204-picviewer-ce/code
  624.  
  625. if (targets.length === 0) return;
  626.  
  627. await delayPn(40);
  628.  
  629. document.head.appendChild(document.createElement('style')).textContent = doActionCSS();
  630.  
  631. await delayPn(40);
  632.  
  633. byPass = false;
  634.  
  635. // Code highlighting
  636. const promises = [...targets].map(prepareCodeAreaAsync)
  637. await Promise.all(promises);
  638.  
  639. await delayPn(40);
  640. document.documentElement.setAttribute('dkkfv', '');
  641. keydownActive = true;
  642.  
  643. });
  644.  
  645. function selectAllWithinElement(element) {
  646. window.getSelection().removeAllRanges();
  647. let range = document.createRange();
  648. if (element) {
  649. range.selectNodeContents(element);
  650. window.getSelection().addRange(range);
  651. } else {
  652. console.error('Element not found with ID:', element);
  653. }
  654. }
  655. document.addEventListener('keydown', (e) => {
  656. if (keydownActive && e && e.code === 'KeyA' && e.isTrusted && (e.metaKey || e.ctrlKey) && !e.shiftKey && !e.altKey) {
  657.  
  658. const target = e.target;
  659. const container = target ? target.closest('div.code-container') : null;
  660. const code = container ? container.querySelector('code') : null;
  661.  
  662. if (container && code) {
  663.  
  664. e.preventDefault();
  665. e.stopPropagation();
  666. e.stopImmediatePropagation();
  667.  
  668. setTimeout(() => {
  669. selectAllWithinElement(code);
  670. }, 1)
  671.  
  672. }
  673.  
  674. }
  675. }, true);
  676.  
  677.  
  678. })();