Introduction: Include Code in an Instructable

About: The only thing I enjoy more than building things is taking things apart. You don't truly own something until you've voided the warranty. Profile image by Achim Grochowski (via wikimedia project)

Many Instructables require the author to include some amount of computer source code in their description, anything from a few console commands to a short, complete program. As an author, you have several different ways to handle source code. This Instructable (meta-Instructable?) will provide an overview and short tutorial for each of these different methods, plus discuss their pros and cons. The same code snippet will be used for each example so that they are easier to compare.

I created this Instructable because the official documentation for the Instructables editor doesn't mention anything about source code. Existing Instructables use a variety of different techniques, some giving better results than others. Everything here I learned through trial and error so if there's a technique I missed, please let me know about it.

It's perfectly fine - and often quite helpful - to use code snippets in an Instructable; however, remember that this site was not designed for storage and archival of source code. Your primary resource for storing source code should be a service that was built for that sort of thing. To keep things simple for the reader, an Instructable's description should only contain the code that is necessary to explain the project, plus a link to an external provider where the complete source code can be downloaded.

Step 1: Just Type It! (the Naïve Approach)

The absolute simplest approach is to simply type your source code into the page (or copy-paste it into the editor). Your code will be rendered just like the rest of the text on the page. Example:

/**

* Callback executed when a program opens a connection to a controller.

*/

static int pad_open(struct input_dev* dev)

{

// Start timer for polling controller state

mod_timer(&nes_timer, jiffies + SAMPLE_INTERVAL);

return 0;

}

The result is difficult to read, especially when you're alternating back and forth between code blocks and normal text. When using programming languages where whitespace is significant (like Python or GNU make), these formatting issues can actually change the behavior of your code, if not break it entirely.

Pros:

  • Easiest, fastest option for the author.
  • Can add code inline anywhere in the description.

Cons:

  • Hard for the reader to tell which parts are code and which parts are description.
  • Little control over spacing due to the variable-width font and the browser consolidating multiple spaces into a single space.
  • Inserting manual linebreaks between code lines causes the site to make a new paragraph, adding awkward vertical space to the code.
  • Code is typically harder to read in a variable-width font.

Step 2: Use Built-In Code Formatting Feature

The Instructables editor has a built-in feature for code formatting, although it's normally hidden. On the far left end of the toolbar above the editor window (near the buttons for bold and italics) is a button with the paragraph symbol on it. This is the "formatting" menu. Clicking on it will display a drop-down menu of formatting options. Click on the 'code' option to apply basic formatting for source code. Example:

/**
 * Callback executed when a program opens a connection to a controller.
 */
static int pad_open(struct input_dev* dev)
{
    // Start timer for polling controller state
    mod_timer(&nes_timer, jiffies + SAMPLE_INTERVAL);
    return 0;
}

Your code will be rendered in a fixed-width font inside a shaded box. This clearly sets your code apart from the rest of your text and makes it easier to read.

For short, one- or two-line code snippets, you can change the formatting to "code" and then type directly into the shaded box. You cannot copy-paste content into the shaded box, however. The pasted content will be inserted after the box, which is generally not what you want. Instead, you will need to copy-paste the code into the editor, highlight it, and then select "code" from the formatting menu. Pasting code into the editor usually messes with the formatting, so you'll almost certainly need to do some manual clean-up work.

Pros:

  • Only requires one or two more clicks vs. the "just type it" approach.
  • Code is more readable and is clearly separated from the rest of the text.
  • Author has control over spacing.
  • Can include code blocks inline with content anywhere in the description.

Cons:

  • No syntax highlighting.
  • Copy-pasting larger code sections requires additional steps.
  • Code pasted from external sources can result in extraneous spaces and line breaks that have to be manually cleaned up.
  • Tabs can be manually added to code, but pasting in code with tabs causes them to be auto-converted to four spaces. If your code uses a different tab size or mixes tabs with spaces, this can throw off your code alignment.

Step 3: Use a Screenshot

An author can also take a screenshot of the code in their editor. This lets you take advantage of editor features like syntax highlighting that the Instructables editor doesn't support. You can even add tags to the image to make notes about particular parts of the code.

This approach has a number of drawbacks, though. A screenshot includes visual elements that aren't useful in a still image (such as the "current line" highlight and code collapse/expand buttons shown above). Text can also be hard to read in a screenshot. If the reader's browser attempts to scale the screenshot at all, the text will quickly become illegible. Perhaps most importantly, a reader can't copy/paste the code from a screenshot to reuse it.

Pros:

  • Enables the author to use most of the visual styling features of their favorite editor or IDE.
  • Author can add image tags to the screenshot to comment on important code snippets.

Cons:

  • Screenshots appear in a pre-defined location.
  • Reader must manually re-type the code, increasing the risk of error.
  • Image scaling and compression can make text hard to read, especially on mobile devices.
  • Longer code samples can require multiple screenshots, requiring the reader to piece them together in the correct order.

Step 4: Attach It

Want to make sure that your readers don't make any mistakes copying your code? Upload your source code as a file and attach it to your Instructable. Readers can then simply download the file and use it as-is.

The main drawback of this method is that it makes it difficult to talk about the code in your Instructable. The reader would need to download the file, open it in a separate editor (assuming they even have one installed), and switch back and forth between the editor and the Instructable in order to follow along. This is awkward and annoying on a desktop computer, but on a mobile device it's unreasonably complicated.

This method is inappropriate for short one- or two-line code snippets, or for documenting commands that the reader should enter into a console. It works best for executable scripts or complete source files.

Pros:

  • Provide complex, reusable sections of code without risking reader typos or copy/paste errors.
  • Very little work for the author, just upload and attach.

Cons:

  • Code isn't displayed inline with the description.
  • Viewing on a mobile device can be tricky.
  • Readers get an inconsistent view of the code (it will depend on their editor).
  • Impractical for small code samples.

Step 5: Link to It

Another method that's relatively easy for the author is to simply provide a link to an external location where the source code can be found. The reader will view or download the source code through the link and use the code to follow along with the Instructable.

Every Instructable that uses a non-trivial amount of source code should archive that code somewhere and include a link in the description to the "official" copy. If you don't need to discuss the source code in your description, then this may be all that you need.

If you do need to talk about code in your description, then you will also want to use one of the other methods in your Instructable. This method (by itself) doesn't provide a way to include code in your description, and it has all of the drawbacks of the "attach it" method.

If you are going to link to a third-party site for code hosting, make sure that it will allow readers to freely view and download your code. Your readers will not appreciate being sent to a site that requires registration in order to get access, much less a site that requires a paid subscription. Try to use a relatively well-known hosting service; security-conscious users will be hesitant to click on a link to a domain that they've never heard of.

Pros:

  • User can always get the latest code without needing to modify the Instructable.
  • Easy to distribute codebases that contain multiple files.
  • A link to a code hosting service (e.g., github) also gives readers a place to file bug reports.

Cons:

  • Code isn't displayed inline with the description.
  • Viewing on a mobile device can be tricky.
  • Readers get an inconsistent view of the code (it will depend on their editor).
  • Impractical for small code samples.

Step 6: Embed Content From Github

Github is a very popular service that programmers use for hosting their source code. One interesting feature of the site is the ability to create and share "gists" (snippets of text or code). If you create a gist containing your code, you will get a URL that others can use to view it. You can also use that same URL to embed the gist directly into your Instructable, all while keeping the syntax highlighting and other nifty visual flair that Github uses.

To create a gist, go to gist.github.com. Paste your code into the large box in the middle of the page. The fields at the top allow you to add an optional title and filename. The programming language is inferred from the filename so if you want syntax highlighting, make sure to enter a file name with the appropriate extension. When you're done, click the "Create public gist" button (since you will be embedding the code into a publicly-viewable Instructable, there's no point in making a "secret gist"). Once your gist has been created, find a button above the code listing labeled "Embed" with a down arrow. Clicking this button will give you a menu of options for sharing the gist. Click on the option that says "Share" and a URL will appear in the box next to the menu. This is the URL that you need for embedding.

To embed the gist into your Instructable, edit the step where you want the code to appear. Click the "Add" menu and select "Video" (this option should actually be titled "Videos or External Content"). There will be a text field at the bottom that says "Insert URL". Copy the sharable URL from Github and paste it here. Click the "Preview" button to see what the end result will look like and if everything looks good, click "Done". Your code snippet will be added to the current step in your Instructable.

Pros:

  • Provides nice formatting for code.
  • If you are a Github user, you can track and manage your gists just like the rest of your source code.
  • Code can be copy-pasted by readers, and a link is automatically provided back to the original.

Cons:

  • Relies on a third-party service.
  • Embedding process not intuitive.
  • Code snippet appears at a pre-defined location.
  • There is currently a bug that can mangle the whitespace in an embedded gist; hopefully this can be fixed.

Some Sample Code

/**
* Callback executed when a program opens a connection to a controller.
*/
staticintpad_open(struct input_dev* dev)
{
// Start timer for polling controller state
mod_timer(&nes_timer, jiffies + SAMPLE_INTERVAL);
return0;
}
view rawsample_code.c hosted with ❤ by GitHub

Step 7: Use Inline HTML

You can manually control the way that your code displays by pasting the code into the editor and formatting it using raw HTML (such as <span>). This will allow you to specify things like text color so that you can draw the reader's attention to certain aspects of the code. To switch the editor into HTML mode, click on the "</>" icon on the left-hand side of the toolbar.

I attempted to generate a formatted code block using inline HTML, but gave up after about an hour. There are online tools to generate HTML for a code snippet, but the results still require heavy manual tweaking before they will display correctly from within Instructables. You're fighting against the site's existing CSS styles, plus the editor will "sanitize" your HTML before publishing (making some significant changes). Attempting to do something as complex as a multi-line code block with syntax highlighting seems to be more trouble than its worth, but styling smaller, inline code snippets is reasonably doable. If you want to explore this feature on your own, here are a few tips based on my experiences.

  • For simple inline text in a fixed-width font, use <code> (this is what the examples on this page use).
  • Don't use <pre>, it's heavily styled already and will likely cause lots of display problems.
  • Using <span style="..."> to apply visual effects (colors, bold, etc) works well, but nested spans can behave strangely.
  • A <div> will get converted to a <p> when you publish, which can completely change the appearance.
  • Don't use !important to override styles, it will get stripped from the code once you publish.
  • Publish initially as a private Instructable. This will let you see what the final published version will look like (and tweak it) before releasing it to the public.

The ability to use the HTML view is restricted to those with Pro memberships. Basic members won't have that button as an option, and attempting to paste HTML into the editor's normal view can lead to some strange formatting abnormalities that can be difficult to fix.

Pros:

  • Extremely flexible. Can apply styles and effects not otherwise possible.
  • Can place code at any point in the description, as a separate block or inline.
  • Can create inline links (e.g., clicking on a function name links to the official documentation for that function).

Cons:

  • Requires Pro membership.
  • Time consuming, especially for novice web programmers.
  • Changes to the website's internal formatting/styles can suddenly cause display problems for your code.
  • What looks good in the editor and previewer can look very different after publishing.
  • Publishing an Instructable and editing it afterwards can cause steps with custom HTML to have their formatting mangled.

Step 8: Conclusion

There is not a single standard way to include source code in your Instructable so it helps to be aware of all of your options. The most common approach seems to be the "just type the code" method, which is unfortunately the least readable of the options. The most readable (in my opinion) appears to be embedding from Github, but the optimal balance of readability and flexibility appears to be the "code" formatting style in the editor. If your code is hosted on another site/service, make sure you also include a link so that users can locate the latest version.

Whatever method you decide to use, your readers will certainly appreciate you taking the extra time and effort to make a nice-looking Instructable!