Code samples

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

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.
  • Indicate omitted code using three dots and no spaces (...). Do not use the ellipsis character (). If the omission is one or more lines long, place the three dots on their own line. Do not format a sample with omitted code as a click-to-copy code block.

Recommended:

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

This renders the following code block:

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

Recommended:

apiVersion: serving.knative.dev/v1
kind: Service
...
spec:
  template:
    spec:
      containers:
      - image: IMAGE_URL
        ports:
        - name: h2c
          containerPort: 8080

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]

For more information about how to introduce code samples, see Document command-line syntax.