Code samples

This page explains how to format code samples. For more information about formatting code that appears in text, command-line syntax, and placeholders, see the following links:

Basic guidelines

Follow these guidelines when formatting code samples:

  • Don't use tabs to indent code; use spaces only.
  • Follow the indentation guidelines in the relevant coding-style guide. For most programming languages, that means indent by two spaces per indentation level. However, some contexts, such as Python and the Android Open Source Project, use four spaces.

    This guidance applies to formatting code samples, not to formatting commands.

  • Wrap lines at 80 characters.

    If you expect readers to have a relatively narrow browser window or to print out your document, consider wrapping at a smaller number of characters for readability.

  • Mark code blocks as preformatted text. In HTML, use a <pre> element; in Markdown, indent every line of the code block by four spaces.

Recommended:

<pre class="prettyprint">
function helloWorld() {
  alert('Hello, world! This sentence is so long that it wraps onto a second
    line.');
}
</pre>

This renders a code block with syntax highlighting:

function helloWorld() {
  alert('Hello, world! This sentence is so long that it wraps onto a second
    line.');
}

Introductory statements

In most cases, precede a code sample with an introductory sentence or paragraph. The introduction can end with a colon or a period; usually a colon if it immediately precedes the sample, usually a period if there's more material (such as a note paragraph) between the introduction and the sample, or if the introduction paragraph ends in a sentence that isn't directly related to the sample.

Recommended (ending with a period): The following code sample shows how to use the get method. For information about other methods, see [link]. [sample]

Also recommended: The following code sample shows how to use the get method: [sample] For information about other methods, see [link].

Not recommended (ending with a colon): The following code sample shows how to use the get method. For information about other methods, see [link]: [sample]