Home
💻

Formatting code for blog posts

I'm writing a lot of code on this website, especially for my Advent of Code solutions, and thought it would be helpful to write down something simple that's saved me a lot of headache.
In particular, we want articles which contain source code to have that source code be legible on all devices (I tweet out a lot of my articles, and people frequently read twitter on their phones).

Disable text wrap

Things can quickly go awry when your code is substantially indented. Replace it with a horizontal scrollbar so it doesn't wrap.
pre code {
  padding: 1em 0 !important;
  overflow: auto;
  display: block;
}

Leveraging Prettier

Scrollbars are good, but they're a crutch. When possible, we should keep line lengths to a minimum. For my blog I've noticed that anything over 45 characters creates a scrollbar at my font size and my screen dimensions.
For instance, the following code block has a fair bit of necessary scrolling to see it all on a mobile device.
async function getChildren(notion, id) {
  const req = await notion.blocks.children.list({ block_id: id });
  const blocks = req.results;
  return Promise.all(
    blocks.map(async (block) => {
      if (block.has_children) {
        block.children = await getChildren(notion, block.id);
      } else {
        block.children = [];
      }
      return block;
    })
  );
}
Thanks to Prettier, this is trivial. (Make sure you install it and the corresponding VSCode extension). Then we create a .prettierrc.json in project's directory with these rules:
{
  "printWidth": 45,
  "tabWidth": 2
}
Upon formatting (or saving with "editor.formatOnSave": true), our code transforms to the following:
async function getChildren(notion, id) {
  const req =
    await notion.blocks.children.list({
      block_id: id,
    });
  const blocks = req.results;
  return Promise.all(
    blocks.map(async (block) => {
      if (block.has_children) {
        block.children = await getChildren(
          notion,
          block.id
        );
      } else {
        block.children = [];
      }
      return block;
    })
  );
}
Which comfortably fits on the screen 😊 Maybe we could even render both the before and after and display the right with a @media query.