Skip to content

Instantly share code, notes, and snippets.

@bermudalocket
Last active May 14, 2020 23:51
Show Gist options
  • Save bermudalocket/336805b75aa749a938aa7240deda0ff2 to your computer and use it in GitHub Desktop.
Save bermudalocket/336805b75aa749a938aa7240deda0ff2 to your computer and use it in GitHub Desktop.
Reddit Code-ifier Script
// ==UserScript==
// @name Reddit Code-ifier
// @namespace https://*.reddit.com/*
// @version 1.0
// @description Fix up messy code formatting on Reddit.
// @author u/thebermudalocket
// @match https://*.reddit.com/*
// @grant none
// @run-at document-end
// ==/UserScript==
(function() {
'use strict';
$(".comment, .usertext").each(function() {
var linesOfCode = new Array();
let codeTags = $(this).find("code");
let firstCodeTag = codeTags.first();
let firstDepth = firstCodeTag.parents().length;
codeTags.each(function() {
if ($(this).parents().length != firstDepth) {
return;
}
var line = $(this).html();
if (line.length > 100) {
return;
}
linesOfCode.push(line);
});
if (linesOfCode.length <= 1) {
return;
}
codeTags.each(function() {
$(this).hide();
$(this).next("br").hide(); // hide <br>s
});
var numberOfOpenSquareBrackets = 0;
var nestedLevel = 0;
for (var i = 0; i < linesOfCode.length; i++) {
let thisLine = linesOfCode[i];
let thisLineStartsWithCurlyBrace = thisLine[0] === "}";
if (thisLineStartsWithCurlyBrace) {
nestedLevel--;
}
let thisLineEndsWithCurlyBrace = thisLine[thisLine.length - 1] === "{";
linesOfCode[i] = ' '.repeat(4 * (nestedLevel + numberOfOpenSquareBrackets)) + thisLine;
if (thisLineEndsWithCurlyBrace) {
nestedLevel++;
}
for (var j = 0; j < thisLine.length - 1; j++) {
let char = thisLine[j];
if (char === "[") {
numberOfOpenSquareBrackets++;
} else if (char === "]") {
numberOfOpenSquareBrackets--;
}
}
}
firstCodeTag.before("<pre><code style='overflow-x: scroll'>" + linesOfCode.join("\n") + "</code></pre>");
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment