Last active
May 14, 2020 23:51
Reddit Code-ifier Script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ==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