In This Article

Text Formatting

The text framework includes an interface for formatting regions of text. Text that has been formatted can be more readable because whitespace and symbols such as braces are uniformly placed.

Formatting Logic

Text formatters implement the ITextFormatter interface. This interface defines one method, the Format method, which has one parameter that indicates the TextSnapshotRange to examine and update.

The TextSnapshotOffset.Snapshot property gives access to its ITextSnapshot. Likewise, the ITextSnapshot.Document provides access to its owner ITextDocument. The ITextDocument.TabSize property tells how many spaces are in a tab, in case that information is useful while formatting.

If the ITextDocument is an ICodeDocument, the ICodeDocument.ParseData property may also contain AST or other language-specific information that can be useful when formatting.

When formatting, it is likely that multiple changes will be made. These updates can be batched up into a single undoable text change. For information on text changes, see the Text Changes and Operations topic.

Formatters are free to implement any custom logic to perform the formatting. However, there are most likely going to be similarities in the technique that most formatters use. Here are some common steps that a formatter might follow in the process of formatting a document:

  1. Find the next token that allows whitespace between itself and the following non-whitespace token.

  2. Replace all whitespace between these two tokens with the new whitespace, which can either be no whitespace at all, or a combination of any number of line breaks, tabs and spaces.

  3. Repeat from the first step until the entire range is formatted.

Registering a Text Formatter with a Syntax Language

An ITextFormatter can be associated with an ISyntaxLanguage by registering it with the language:

language.RegisterService<ITextFormatter>(myTextFormatter);

Registering a text formatter with a language is optional but recommended.

Formatting a Range of Text

This code uses an ICodeDocument's current language's text formatter to format a range of text from offsets 0 to 10:

ITextFormatter textFormatter = document.Language.GetService<ITextFormatter>();
if (textFormatter != null) {
	TextSnapshotRange range = new TextSnapshotRange(document.CurrentSnapshot, 0, 10);
	textFormatter.Format(range.Snapshot, TextPositionRange.CreateCollection(range.PositionRange, false), TextFormatMode.Ranges);
}

This code uses an ICodeDocument's current language's text formatter to format the entire document:

ITextFormatter textFormatter = document.Language.GetService<ITextFormatter>();
if (textFormatter != null)
	textFormatter.Format(document.CurrentSnapshot, TextPositionRange.CreateCollection(document.CurrentSnapshot.SnapshotRange.PositionRange, false), TextFormatMode.All);