Code snippets

OPS supports inline code snippets, coloring, language selectors, and external code snippets.

To see the content of this article in Markdown, select the Edit link.

Internal code snippets

You can reference code snippets stored in your repo by using the specified code language. The content of the specified code path will be expanded and included in your file.

We don’t have restrictions on the folder structure of code snippets. You can manage the code snippets as normal source code.

Syntax:

[!code-<language>[<name>](<codepath><queryoption><queryoptionvalue> "<title>")]

Important

This syntax is a block Markdown extension. It must be used on its own line.

  • -<language> (optional)
    • Language of the code snippet. For the list of languages supported on docs.microsoft.com, see the Supported languages section in this article.
    • Do not forget the hyphen (-) before the language name.
  • <name> (optional)

    • Name for the code snippet. It doesn’t have any impact on the output HTML, but you can use it to improve the readability of your Markdown source. It is added to be compatible with normal Markdown link syntax, so it is still rendered as a link in a Markdown parser that doesn’t support OPS syntax (like GitHub).
  • <codepath> (mandatory)

    • Relative path in the file system that indicates the code snippet file to reference.
  • <queryoption> and <queryoptionvalue> (optional)

    • Used together to specify how the code should be retrieved from the file:

      • #: #L{startlinenumber}-L{endlinenumber} (line range) or #{tagname} (tag name)
      • ?: ?start={startlinenumber}&end={endlinenumber} (line range) or ?name={tagname} (tag name)
      • range: ?range=1,3-5 A range of lines. This example includes lines 1, 3, 4, and 5.
      • dedent: ?dedent=8 Dedents the lines by a number of spaces--in this case, 8. This can be combined with the range and other query options that select a subset of the lines of a file.
      • outdent: ?outdent=8 Reverses the indent of the lines by a number of spaces--in this case, 8. This can be combined with range and other query options that select a subset of the lines of a file.

      For details about tag name representation in code snippet source files by language, see the DocFX guidelines.

  • <title> (optional)
    • Title for the code snippet. It doesn’t have any impact on the output HTML, but you can use it to improve the readability of your Markdown source. It is added to be compatible with normal Markdown link syntax, so it is still rendered as a link in a Markdown parser that doesn’t support OPS syntax (like GitHub).

Code snippet example

[!code-csharp[Main](Program.cs)]

[!code[Main](Program.cs#L12-L16 "This is source file")]
[!code-vb[Main](../Application/Program.vb#testsnippet "This is source file")]

[!code[Main](index.xml?start=5&end=9)]
[!code-javascript[Main](../jquery.js?name=testsnippet)]

External code snippets

You can reference code snippets stored in an external repository--a repo different from that in which your article resides. You use a method similar to the one for an internal code snippet, with two additional requirements:

  • Add the external repo to the repo config file

    To reference an external repo, you must first add it to the dependent_repositories collection in your repo's .openpublishing.publish.config.json file found in the root of the repo. The format is as follows:

    {
      "path_to_root": "name-of-repo",
      "url": "https://github.com/path/to/repo.git",
      "branch": "master"
    }
    

    For example, if you want to include code found in azure-storage-net in an article in azure-docs-pr, add the following to the dependent_repositories section in azure-docs-pr's .openpublishing.publish.config.json:

    {
      "path_to_root": "azure-storage-net",
      "url": "https://github.com/Azure/azure-storage-net.git",
      "branch": "master"
    }
    
  • Prefix relative <codepath> with, for example, ../../

    You can now reference azure-storage-net in <codepath>. Use a relative path to include the code snippet based on the folder structure of both the content repo and the snippet repo.

Now that you've added the dependent repository to the config file, you can reference code snippets by using the following format:

[!code-language[name](../../repo-path-root/path/to/file.cs#TagName "Title")]

To continue with the preceding example for azure-storage-net, a reference might look like this:

[!code-csharp[tableinsert](../../azure-storage-net/Test/WindowsRuntime/Table/TableBatchOperationTest.cs#Insert "Table insert")]

Important

Updating an external code snippet won’t automatically trigger a content build. You need to trigger the build by either changing something in the doc repo or manually starting a build.

Tabbed code snippets

Important

This feature works only for non-Docs sites (MSDN, TechNet, and visualstudio.com).

You can group multiple code snippets so that readers can see them on different tabs. Tabbed code snippets work for both inline and external code snippets.

Note

If your code tabs aren't appearing as expected, ensure that the beginning and ending code tags (```) are flush left and not tabbed in.

Example:

> [!div class="tabbedCodeSnippets"]
```cs
  var outlookClient = await CreateOutlookClientAsync("Calendar");
  var events = await outlookClient.Me.Events
    .Take(10)
    .ExecuteAsync();
  foreach(var calendarEvent in events.CurrentPage)
  {
    System.Diagnostics.Debug.WriteLine("Event '{0}'.", calendarEvent.Subject);
  }
```
```javascript
  outlookClient.me.events.getEvents().fetch().then(function (result) {
      result.currentPage.forEach(function (event) {
  console.log('Event "' + event.subject + '"')
      });
  }, function(error) {
      console.log(error);
  });
```

This syntax will be rendered as tabbed code snippets in MSDN, TechNet, and visualstudio.com. It will not be rendered as tabbed code snippets in OPS documentation or docs.microsoft.com, because the template doesn't support that.

  var outlookClient = await CreateOutlookClientAsync("Calendar");
  var events = await outlookClient.Me.Events
    .Take(10)
    .ExecuteAsync();
  foreach(var calendarEvent in events.CurrentPage)
  {
    System.Diagnostics.Debug.WriteLine("Event '{0}'.", calendarEvent.Subject);
  }
  outlookClient.me.events.getEvents().fetch().then(function (result) {
      result.currentPage.forEach(function (event) {
  console.log('Event "' + event.subject + '"')
      });
  }, function(error) {
      console.log(error);
  });

Note that you can specify the tab name as cs='C#'. It's optional for known languages, such as C#, C++, and JavaScript. For any unknown language, the tab name can be shown only if the mapping is specified in the div element. The feature depends on the front-end implementation to show the tab names correctly.

> [!div class="tabbedCodeSnippets" cs='C#' javascript='Javascript']

Interactive code snippets

Note

This feature is available only on docs.microsoft.com.

Certain languages can be made interactive, allowing the code snippet to be executable from within the browser window.

We currently have the ability to enable interactive experiences for:

  • Azure Cloud Shell
  • Azure PowerShell Cloud Shell
  • C# REPL

Code samples for which this is enabled have a Try It button. Activating this button turns on the interactive experience for the sample. Here's an example:

az group create --name myResourceGroup --location westeurope

To turn on this feature for a particular code block, you must use a special language identifier. Above, we used azurecli-interactive to enable the Azure Cloud Shell. The available options are:

  • azurecli-interactive - Enables the Azure Cloud Shell
  • csharp-interactive - Enables the C# REPL
  • azurepowershell-interactive - Enable the Azure PowerShell Cloud Shell

For the Azure Cloud Shell and PowerShell Cloud Shell, we've built an experience that facilitates an authentication for customers so that they can run commands against only their own Azure account. This work is part of a collaboration with the Azure Cloud Shell team.

To turn on this feature for a particular code block, you must use the language azurecli-interactive instead of azurecli for that code block. Here's the Markup for the preceding example:

```azurecli-interactive
az group create --name myResourceGroup --location westeurope
```

You can alse enable interactive for include blocks. Here's what that would look like:

[!code-azurecli-interactive[main](../../../cli_scripts/virtual-machine/create-docker-host/create-docker-host.sh "Docker Host")

Supported languages

Inline code blocks

Name Markdown label
Azure CLI azurecli
AzCopy azcopy
C++ cpp
C# csharp
F# fsharp
Java java
JavaScript javascript
JSON json
NodeJS nodejs
Objective-C objc
PHP php
PowerShell powershell
Python python
Ruby ruby
SQL sql
Swift swift
VB vb
XAML xaml
XML xml

Code extensions

Name Markdown label File extension
C# csharp .cs
C++ cpp .cpp, .h
F# fsharp .fs
Java java .java
JavaScript javascript .js
Python python .py
SQL sql .sql
VB vb .vb
XAML xaml .xaml
XML xml .xml