Skip to content

Instantly share code, notes, and snippets.

@okaits
Created May 24, 2025 16:55
Show Gist options
  • Select an option

  • Save okaits/a901235fcb1ca78c405c564cf5052e1b to your computer and use it in GitHub Desktop.

Select an option

Save okaits/a901235fcb1ca78c405c564cf5052e1b to your computer and use it in GitHub Desktop.
HTMLで<pre><code>の中にコードを書く時、先頭の改行を削除し、インデントを合わせる。
// Warn: ページ内の<code><pre>がすべてこのような形式になっていないと正常に動きません。
// <pre><code>
// import sys
// if True:
// pass
// </code></pre>
//
// 「<pre><code>」の後、「</code></pre>」の前のそれぞれに改行がある必要があります。
// MIT License
// Author: okaits#7534
for (const elem of document.querySelectorAll("pre code")) {
let shortest_indent = Infinity;
const lines = elem.innerHTML.split("\n");
lines.pop()
for (const line of lines) {
if (line.length === 0) {continue;};
let indent_num = 0;
for (char of line) {
if (char === " ") {
indent_num++;
} else {
break;
};
};
if (indent_num < shortest_indent) {
shortest_indent = indent_num;
};
};
let result = lines.shift();
for (const line of lines) {
result = result + line.slice(shortest_indent) + "\n";
};
elem.innerHTML = result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment