Class XMLFormatterDocument
Produces a list of TextEdit that transform the document's whitespace
(indentation, line breaks, trailing spaces) without altering content.
Architecture
This class owns the document state and delegates node-specific formatting to specialized formatters:
DOMElementFormatter— elements (start tag, attributes, end tag)DOMAttributeFormatter— individual attributesDOMTextFormatter— text nodesDOMCommentFormatter— commentsDOMCDATAFormatter— CDATA sectionsDOMDocTypeFormatter— DOCTYPE declarationsDOMProcessingInstructionFormatter— processing instructions
Formatting flow
- Determine the DOM node(s) covered by the requested range.
- Walk siblings left-to-right, dispatching each node to its formatter.
- Each formatter adjusts whitespace and tracks
availableLineWidthviaXMLFormattingConstraintsto enforcemaxLineWidth. - After all nodes, handle
trimFinalNewlines,insertFinalNewline, andtrimTrailingWhitespace.
Shared utilities
Provides indentation helpers (getIndentSpaces(int, boolean),
replaceLeftSpacesWithIndentation(int, int, int, boolean, java.util.List<org.eclipse.lsp4j.TextEdit>)), whitespace scanning
(adjustOffsetWithLeftWhitespaces(int, int), hasLineBreak(int, int)), and
text edit creation (createTextEditIfNeeded(int, int, java.lang.String, java.util.List<org.eclipse.lsp4j.TextEdit>)) used by all formatters.
@formatter:off/on
Comments containing @formatter:off disable formatting until a
matching @formatter:on comment is found (see issue #1648).
- Author:
- Angelo ZERR
- See Also:
-
Constructor Summary
ConstructorsConstructorDescriptionXMLFormatterDocument(DOMDocument xmlDocument, org.eclipse.lsp4j.Range range, SharedSettings sharedSettings, Collection<IFormatterParticipant> formatterParticipants) Creates a formatter for the given XML document. -
Method Summary
Modifier and TypeMethodDescriptionintadjustOffsetWithLeftWhitespaces(int leftLimit, int to) Scans leftward fromtoand returns the offset where contiguous whitespace begins, bounded byleftLimit.List<? extends org.eclipse.lsp4j.TextEdit> format()Returns a List containing multiple TextEdit, containing the newly formatted changes of an XML document.List<? extends org.eclipse.lsp4j.TextEdit> format(DOMDocument document, int start, int end) Formats a portion of the document, returning text edits.voidformat(DOMNode child, XMLFormattingConstraints parentConstraints, int start, int end, List<org.eclipse.lsp4j.TextEdit> edits) Dispatches a single DOM node to the appropriate formatter based on its type.voidformatAttributeValue(DOMAttr attr, XMLFormattingConstraints parentConstraints, List<org.eclipse.lsp4j.TextEdit> edits) Delegates attribute value formatting to registeredIFormatterParticipants.voidformatChildren(DOMNode currentDOMNode, XMLFormattingConstraints parentConstraints, int start, int end, List<org.eclipse.lsp4j.TextEdit> edits) Formats all child nodes of the given parent node.static intgetExistingNewLineCount(CharSequence text, int offset, String delimiter) Return the number of new lines in the whitespaces to the left of the given offset.getFormatElementCategory(DOMElement element, XMLFormattingConstraints parentConstraints) Returns the format element category of the given DOM element.intgetLineAtOffset(int offset) Returns the line start offset for the line containing the given offset.intgetLineBreakOffset(int startAttr, int start) Returns the offset of the first line break betweenstartAttrandstart, or -1 if none exists.intReturns the configured maximum line width, or 0 if disabled.intgetNewLineAvailableWidth(int indentLevel) Returns the available line width at the start of a new line at the given indent level:maxLineWidth - indentLevel * tabSize.intgetNormalizedLength(int from, int to) Returns the normalized length of text in [from,to), collapsing runs of whitespace to a single space.intgetOffsetWithPreserveLineBreaks(int from, int to, int tabSize, boolean isInsertSpaces) Adjusts an offset to account for existing line breaks and indentation when preserving the original line structure.voidinsertIndentation(int indentLevel, int offset, List<org.eclipse.lsp4j.TextEdit> edits) Inserts a line separator followed by indentation at the given offset (no existing whitespace is replaced — this is a pure insertion).booleanisBlockElement(DOMElement element) Returnstrueif the given element is an inline element in mixed content.booleanReturns true if formatting is currently turned off by a<!-- @formatter:off -->comment.booleanReturns true ifmaxLineWidthis set (non-zero).booleanbooleanReturnstruewhenmixedContentisrefloworexpand.voidremoveLeftSpaces(int leftLimit, int to, List<org.eclipse.lsp4j.TextEdit> edits) Removes all whitespace to the left ofto, bounded byleftLimit.intreplaceLeftSpacesWithIndentation(int indentLevel, int leftLimit, int to, boolean addLineSeparator, boolean removeConflictingEdits, List<org.eclipse.lsp4j.TextEdit> edits) Replaces whitespace to the left oftowith proper indentation, optionally removing conflicting edits that overlap the same range.intreplaceLeftSpacesWithIndentation(int indentLevel, int leftLimit, int to, boolean addLineSeparator, List<org.eclipse.lsp4j.TextEdit> edits) Replaces whitespace to the left oftowith proper indentation.voidreplaceLeftSpacesWithIndentationPreservedNewLines(int spaceStart, int spaceEnd, int indentLevel, List<org.eclipse.lsp4j.TextEdit> edits) Replaces whitespace at [spaceStart,spaceEnd) with indentation while preserving existing blank lines up to thepreservedNewlinessetting.intreplaceLeftSpacesWithIndentationWithMultiNewLines(int indentLevel, int leftLimit, int offset, int newLineCount, List<org.eclipse.lsp4j.TextEdit> edits) Replaces whitespace to the left ofoffsetwith indentation preceded by the specified number of new lines.intreplaceLeftSpacesWithIndentationWithOffsetSpaces(int indentSpace, int leftLimit, int to, boolean addLineSeparator, List<org.eclipse.lsp4j.TextEdit> edits) Replaces whitespace to the left oftowith indentation computed from a raw space count rather than an indent level.voidreplaceLeftSpacesWithOneSpace(int leftLimit, int to, List<org.eclipse.lsp4j.TextEdit> edits) Replaces all whitespace to the left oftowith a single space.voidresetLineWidth(XMLFormattingConstraints constraints, int indentLevel) Resets the available line width in the given constraints for a new line at the specified indent level.booleanshouldCollapseEmptyElement(DOMElement element, SharedSettings sharedSettings) Returns true if the given empty element should be collapsed to self-closing form (<foo></foo>→<foo />).
-
Constructor Details
-
Method Details
-
isFormatterOff
public boolean isFormatterOff()Returns true if formatting is currently turned off by a<!-- @formatter:off -->comment.- Returns:
- true if formatting is off.
-
format
Returns a List containing multiple TextEdit, containing the newly formatted changes of an XML document.- Returns:
- List containing multiple TextEdit of an XML document.
- Throws:
BadLocationException
-
format
Formats a portion of the document, returning text edits.Steps:
- Find the DOM node(s) covering [
start,end]. - Initialize
availableLineWidthfrom the node's column position. - Walk siblings, dispatching each to its node-type formatter.
- Apply end-of-document rules (trim trailing whitespace, final newline).
- Parameters:
document- the DOM document.start- start offset of the range to format (-1 for beginning).end- end offset of the range to format (-1 for end).- Returns:
- the list of text edits.
- Find the DOM node(s) covering [
-
format
public void format(DOMNode child, XMLFormattingConstraints parentConstraints, int start, int end, List<org.eclipse.lsp4j.TextEdit> edits) Dispatches a single DOM node to the appropriate formatter based on its type.Handles
@formatter:off/ontoggling: when a comment containing@formatter:offis encountered, subsequent nodes are skipped (onlyavailableLineWidthis updated) until@formatter:on.Node type dispatch:
ELEMENT_NODE→DOMElementFormatter.formatElement(org.eclipse.lemminx.dom.DOMElement, org.eclipse.lemminx.services.format.XMLFormattingConstraints, int, int, java.util.List<org.eclipse.lsp4j.TextEdit>)TEXT_NODE→DOMTextFormatter.formatText(org.eclipse.lemminx.dom.DOMText, org.eclipse.lemminx.services.format.XMLFormattingConstraints, int, int, java.util.List<org.eclipse.lsp4j.TextEdit>)COMMENT_NODE→DOMCommentFormatter.formatComment(org.eclipse.lemminx.dom.DOMComment, org.eclipse.lemminx.services.format.XMLFormattingConstraints, int, int, java.util.List<org.eclipse.lsp4j.TextEdit>)CDATA_SECTION_NODE→DOMCDATAFormatter.formatCDATASection(org.eclipse.lemminx.dom.DOMCDATASection, org.eclipse.lemminx.services.format.XMLFormattingConstraints, java.util.List<org.eclipse.lsp4j.TextEdit>)DOCUMENT_TYPE_NODE→DOMDocTypeFormatter.formatDocType(org.eclipse.lemminx.dom.DOMDocumentType, org.eclipse.lemminx.services.format.XMLFormattingConstraints, int, int, java.util.List<org.eclipse.lsp4j.TextEdit>)PROCESSING_INSTRUCTION_NODE→DOMProcessingInstructionFormatterDOCUMENT_NODE→ recurse into children
- Parameters:
child- the DOM node to format.parentConstraints- the parent's formatting constraints (modified in place).start- start offset of the formatting range.end- end offset of the formatting range.edits- the list of text edits to populate.
-
formatChildren
public void formatChildren(DOMNode currentDOMNode, XMLFormattingConstraints parentConstraints, int start, int end, List<org.eclipse.lsp4j.TextEdit> edits) Formats all child nodes of the given parent node.- Parameters:
currentDOMNode- the parent whose children to format.parentConstraints- the parent's formatting constraints.start- start offset of the formatting range.end- end offset of the formatting range.edits- the list of text edits to populate.
-
formatAttributeValue
public void formatAttributeValue(DOMAttr attr, XMLFormattingConstraints parentConstraints, List<org.eclipse.lsp4j.TextEdit> edits) Delegates attribute value formatting to registeredIFormatterParticipants.Use case: XSD/DTD-aware participants may reformat enumerated attribute values or enforce quoting conventions specific to the schema.
- Parameters:
attr- the attribute whose value to format.parentConstraints- the parent element's formatting constraints.edits- the list of text edits to populate.
-
removeLeftSpaces
Removes all whitespace to the left ofto, bounded byleftLimit.- Parameters:
leftLimit- the leftmost offset to scan for whitespace.to- the offset where whitespace ends.edits- the list of text edits to populate.
-
replaceLeftSpacesWithOneSpace
public void replaceLeftSpacesWithOneSpace(int leftLimit, int to, List<org.eclipse.lsp4j.TextEdit> edits) Replaces all whitespace to the left oftowith a single space.- Parameters:
leftLimit- the leftmost offset to scan for whitespace.to- the offset where whitespace ends.edits- the list of text edits to populate.
-
adjustOffsetWithLeftWhitespaces
public int adjustOffsetWithLeftWhitespaces(int leftLimit, int to) Scans leftward fromtoand returns the offset where contiguous whitespace begins, bounded byleftLimit.Returns
-1if no whitespace is found immediately beforeto, ortoitself if no whitespace exists at that position.- Parameters:
leftLimit- the leftmost offset to scan.to- the offset to scan leftward from.- Returns:
- the start offset of the whitespace, or -1 if none.
-
replaceLeftSpacesWithIndentation
public int replaceLeftSpacesWithIndentation(int indentLevel, int leftLimit, int to, boolean addLineSeparator, List<org.eclipse.lsp4j.TextEdit> edits) Replaces whitespace to the left oftowith proper indentation.- Parameters:
indentLevel- the indent level (each level = tabSize spaces or 1 tab).leftLimit- the leftmost offset to scan for whitespace.to- the offset where the indented content starts.addLineSeparator- true to prepend a line separator before the indent.edits- the list of text edits to populate.- Returns:
- the length of the replacement string, or 0 if no edit was needed.
-
replaceLeftSpacesWithIndentation
public int replaceLeftSpacesWithIndentation(int indentLevel, int leftLimit, int to, boolean addLineSeparator, boolean removeConflictingEdits, List<org.eclipse.lsp4j.TextEdit> edits) Replaces whitespace to the left oftowith proper indentation, optionally removing conflicting edits that overlap the same range.Use case: in MixedContent overflow handling, when an element is moved to a new line, a prior edit for the same whitespace region may already exist and must be replaced.
- Parameters:
indentLevel- the indent level.leftLimit- the leftmost offset to scan for whitespace.to- the offset where the indented content starts.addLineSeparator- true to prepend a line separator.removeConflictingEdits- true to remove existing edits covering the same range.edits- the list of text edits to populate.- Returns:
- the length of the replacement string, or 0 if no edit was needed.
-
replaceLeftSpacesWithIndentationWithMultiNewLines
public int replaceLeftSpacesWithIndentationWithMultiNewLines(int indentLevel, int leftLimit, int offset, int newLineCount, List<org.eclipse.lsp4j.TextEdit> edits) Replaces whitespace to the left ofoffsetwith indentation preceded by the specified number of new lines.Use case: PreservedNewlines — when the user has blank lines between elements, this keeps up to
preservedNewlinesblank lines.- Parameters:
indentLevel- the indent level.leftLimit- the leftmost offset to scan for whitespace.offset- the offset where the indented content starts.newLineCount- the number of line separators to insert.edits- the list of text edits to populate.- Returns:
- the length of the replacement string, or 0 if no edit was needed.
-
replaceLeftSpacesWithIndentationWithOffsetSpaces
public int replaceLeftSpacesWithIndentationWithOffsetSpaces(int indentSpace, int leftLimit, int to, boolean addLineSeparator, List<org.eclipse.lsp4j.TextEdit> edits) Replaces whitespace to the left oftowith indentation computed from a raw space count rather than an indent level.Use case: aligning continuation content (e.g., multi-line attribute values or DOCTYPE internal subsets) to a specific column.
- Parameters:
indentSpace- the number of spaces to indent.leftLimit- the leftmost offset to scan for whitespace.to- the offset where the indented content starts.addLineSeparator- true to prepend a line separator.edits- the list of text edits to populate.- Returns:
- the length of the replacement string, or 0 if no edit was needed.
-
replaceLeftSpacesWithIndentationPreservedNewLines
public void replaceLeftSpacesWithIndentationPreservedNewLines(int spaceStart, int spaceEnd, int indentLevel, List<org.eclipse.lsp4j.TextEdit> edits) Replaces whitespace at [spaceStart,spaceEnd) with indentation while preserving existing blank lines up to thepreservedNewlinessetting.Use case: MixedContent indentation normalization — when multi-line whitespace exists before an element, the line breaks are kept (up to the limit) but the indentation on the last line is corrected.
- Parameters:
spaceStart- the start offset of the whitespace region.spaceEnd- the end offset of the whitespace region.indentLevel- the indent level.edits- the list of text edits to populate.
-
getNormalizedLength
public int getNormalizedLength(int from, int to) Returns the normalized length of text in [from,to), collapsing runs of whitespace to a single space.Use case: NormalizeSpace text nodes — computes the effective width after whitespace normalization to track
availableLineWidth.- Parameters:
from- the start offset (inclusive).to- the end offset (exclusive).- Returns:
- the normalized character count.
-
getOffsetWithPreserveLineBreaks
public int getOffsetWithPreserveLineBreaks(int from, int to, int tabSize, boolean isInsertSpaces) Adjusts an offset to account for existing line breaks and indentation when preserving the original line structure.Use case: attribute formatting with
preserveAttributeLineBreaks— computes the effective column position after existing whitespace, accounting for tab width.- Parameters:
from- the start offset to scan from.to- the current offset to adjust.tabSize- the tab size (number of spaces per tab).isInsertSpaces- true if spaces are used instead of tabs.- Returns:
- the adjusted offset.
-
getLineBreakOffset
public int getLineBreakOffset(int startAttr, int start) Returns the offset of the first line break betweenstartAttrandstart, or -1 if none exists.Use case: attribute formatting — detects whether existing content already has a line break to decide split strategy.
- Parameters:
startAttr- the start offset to scan from.start- the end offset to scan to (exclusive).- Returns:
- the offset of the first line break, or -1 if none.
-
getFormatElementCategory
public FormatElementCategory getFormatElementCategory(DOMElement element, XMLFormattingConstraints parentConstraints) Returns the format element category of the given DOM element.- Parameters:
element- the DOM element.parentConstraints- the parent constraints.- Returns:
- the format element category of the given DOM element.
-
insertIndentation
Inserts a line separator followed by indentation at the given offset (no existing whitespace is replaced — this is a pure insertion).Use case: MixedContent adjacent elements — when
</a><b>has no whitespace between elements and<b>overflows, indentation is inserted before<b>.- Parameters:
indentLevel- the indent level.offset- the offset at which to insert.edits- the list of text edits to populate.
-
getExistingNewLineCount
Return the number of new lines in the whitespaces to the left of the given offset.- Parameters:
text- the xml text.offset- the offset to begin the count from.delimiter- the delimiter.- Returns:
- the number of new lines in the whitespaces to the left of the given offset.
-
isBlockElement
Returnstrueif the given element is an inline element in mixed content.Use case: in
<p>text <b>bold</b> <div>block</div></p>withblockElements=["div"],<div>gets block treatment (own line) while<b>stays inline with text.- Parameters:
element- the element to check.- Returns:
trueif the element is block.
-
isMixedContentReflow
public boolean isMixedContentReflow()ReturnstruewhenmixedContentisrefloworexpand. Whenfalse(defaultnormalize), newlines within text nodes are collapsed to spaces (but line breaks in whitespace-only gaps between sibling elements are still preserved).blockElementsis ignored innormalizemode.Use cases:
normalize(default) →false: newlines in text nodes joined to spaces, line breaks between elements preserved.<p>text\n<b>bold</b></p>→<p>text <b>bold</b></p>.reflow→true: newlines in text nodes preserved, block/inline distinction viablockElements, soft-wrap atmaxLineWidth.expand→true: all children on own lines.
-
isMixedContentExpand
public boolean isMixedContentExpand() -
isMaxLineWidthSupported
public boolean isMaxLineWidthSupported()Returns true ifmaxLineWidthis set (non-zero). -
getNewLineAvailableWidth
public int getNewLineAvailableWidth(int indentLevel) Returns the available line width at the start of a new line at the given indent level:maxLineWidth - indentLevel * tabSize.Single source of truth for this calculation, used by
resetLineWidth(org.eclipse.lemminx.services.format.XMLFormattingConstraints, int)and text formatters that track width locally.- Parameters:
indentLevel- the indent level of the new line.- Returns:
- the available width after indentation.
-
resetLineWidth
Resets the available line width in the given constraints for a new line at the specified indent level.Call this after inserting a line break (via
replaceLeftSpacesWithIndentation(int, int, int, boolean, java.util.List<org.eclipse.lsp4j.TextEdit>)orreplaceLeftSpacesWithIndentationPreservedNewLines(int, int, int, java.util.List<org.eclipse.lsp4j.TextEdit>)) instead of manually callingsetAvailableLineWidth(getMaxLineWidth())and addingindentLevel * tabSizeto the width accumulator.- Parameters:
constraints- the constraints to reset.indentLevel- the indent level of the new line.
-
getMaxLineWidth
public int getMaxLineWidth()Returns the configured maximum line width, or 0 if disabled. -
getLineAtOffset
public int getLineAtOffset(int offset) Returns the line start offset for the line containing the given offset.- Parameters:
offset- the document offset.- Returns:
- the line start offset, or -1 on error.
-