Class XMLFormatterDocument

java.lang.Object
org.eclipse.lemminx.services.format.XMLFormatterDocument

public class XMLFormatterDocument extends Object
Central coordinator for XML document formatting.

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:

Formatting flow

  1. Determine the DOM node(s) covered by the requested range.
  2. Walk siblings left-to-right, dispatching each node to its formatter.
  3. Each formatter adjusts whitespace and tracks availableLineWidth via XMLFormattingConstraints to enforce maxLineWidth.
  4. After all nodes, handle trimFinalNewlines, insertFinalNewline, and trimTrailingWhitespace.

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 Details

    • XMLFormatterDocument

      public XMLFormatterDocument(DOMDocument xmlDocument, org.eclipse.lsp4j.Range range, SharedSettings sharedSettings, Collection<IFormatterParticipant> formatterParticipants)
      Creates a formatter for the given XML document.
      Parameters:
      xmlDocument - the parsed DOM document to format.
      range - the range to format, or null to format the entire document.
      sharedSettings - formatting options (indent size, max line width, etc.).
      formatterParticipants - extension-point participants that can override formatting behavior (e.g., XSD/DTD-aware formatting).
  • 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

      public List<? extends org.eclipse.lsp4j.TextEdit> format() throws BadLocationException
      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

      public List<? extends org.eclipse.lsp4j.TextEdit> format(DOMDocument document, int start, int end)
      Formats a portion of the document, returning text edits.

      Steps:

      1. Find the DOM node(s) covering [start, end].
      2. Initialize availableLineWidth from the node's column position.
      3. Walk siblings, dispatching each to its node-type formatter.
      4. 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.
    • format

      public void format(DOMNode child, XMLFormattingConstraints parentConstraints, int start, int end, List<org.eclipse.lsp4j.TextEdit> edits)
      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 registered IFormatterParticipants.

      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

      public void removeLeftSpaces(int leftLimit, int to, List<org.eclipse.lsp4j.TextEdit> edits)
      Removes all whitespace to the left of to, bounded by leftLimit.
      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 of to with 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 from to and returns the offset where contiguous whitespace begins, bounded by leftLimit.

      Returns -1 if no whitespace is found immediately before to, or to itself 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 of to with 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 of to with 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 of offset with indentation preceded by the specified number of new lines.

      Use case: PreservedNewlines — when the user has blank lines between elements, this keeps up to preservedNewlines blank 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 of to with 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 the preservedNewlines setting.

      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 between startAttr and start, 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.
    • shouldCollapseEmptyElement

      public boolean shouldCollapseEmptyElement(DOMElement element, SharedSettings sharedSettings)
      Returns true if the given empty element should be collapsed to self-closing form (<foo></foo> → <foo />).

      Delegates to IFormatterParticipants — any participant can veto collapsing (e.g., HTML-aware formatters for void elements).

      Parameters:
      element - the empty element to check.
      sharedSettings - the shared settings.
      Returns:
      true if the element should be collapsed to self-closing.
    • insertIndentation

      public void insertIndentation(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).

      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

      public static int getExistingNewLineCount(CharSequence text, int offset, String delimiter)
      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

      public boolean isBlockElement(DOMElement element)
      Returns true if the given element is an inline element in mixed content.

      Use case: in <p>text <b>bold</b> <div>block</div></p> with blockElements=["div"], <div> gets block treatment (own line) while <b> stays inline with text.

      Parameters:
      element - the element to check.
      Returns:
      true if the element is block.
    • isMixedContentReflow

      public boolean isMixedContentReflow()
      Returns true when mixedContent is reflow or expand. When false (default normalize), newlines within text nodes are collapsed to spaces (but line breaks in whitespace-only gaps between sibling elements are still preserved). blockElements is ignored in normalize mode.

      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 via blockElements, soft-wrap at maxLineWidth.
      • expand → true: all children on own lines.
    • isMixedContentExpand

      public boolean isMixedContentExpand()
    • isMaxLineWidthSupported

      public boolean isMaxLineWidthSupported()
      Returns true if maxLineWidth is 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

      public void resetLineWidth(XMLFormattingConstraints constraints, int indentLevel)
      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>) or replaceLeftSpacesWithIndentationPreservedNewLines(int, int, int, java.util.List<org.eclipse.lsp4j.TextEdit>)) instead of manually calling setAvailableLineWidth(getMaxLineWidth()) and adding indentLevel * tabSize to 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.