XSLT and XPath

for Visual Studio Code

143K Installs:

Editing XSLT/XPath

With DeltaXignia's XSLT/XPath extension, Visual Studio Code is a fully featured XSLT 3.0 editor, with support for the XSLT 4.0 and XPath 4.0 features implemented in Saxon 13. Standalone XPath 3.1 and XPath 4.0 files are also fully supported. Visual Studio Code's rich ecosystem is now available to XSLT and XPath developers.

Comprehensive, but language-neutral, descriptions of Visual Studio Code can be found in Microsoft's Visual Studio Code User Guide. Links to key sections are below:

The documentation here focuses on XSLT and XPath language features. More general XML features are covered on the Editing XML page. Help on navigating code in the editor is provided in the Code Navigation page.

Syntax Highlighting

Eva Dark Theme

For improved performance and precision, this extension avoids using the default but problematic TM Grammar. Instead we use Visual Studio Code's Semantic Highlighting introduced in 2020. For color theme extensions you should explicitly enable Semantic Highlighting. See the Settings page for more information.

Github Light Theme

The extension provides syntax highlighting for XSLT instructions, XML Literal Result Elements, XML attributes, XML character references, CDATA sections and all tokens within XPath expressions. XPath expressions within Attribute Value Templates (AVTs) and Text Value Templates are syntax highlighted also.

XSLT/XPath Dark Color Themes

The plethora of VS Code themes will highlight XSLT/XPath very well using Semantic Highlighting fallbacks for language-specific tokens. There is however a XSLT Dark Themes extension that enhances a set of popular dark themes specifically for XSLT and XPath:

  1. Darcula From IntelliJ
  2. Gruvbox Material Dark
  3. Iceberg
  4. Nord
  5. Tokyo Night Storm
  6. Zen

Formatting

Two commands are provided for formatting XML, XSLT or XPath expressions:

  • Format Document (⇧⌥F) - Format the entire active file.
  • Format Selection (⌘K ⌘F) - Format the selected content.

As well as explicitly invoking commands, formatting can be triggered as you type, when you save a file, or when you paste content from the clipboard. The following settings control this:

  • editor.formatOnType - indents a new line as you press Enter, and indents and completes an end tag as you type </.
  • editor.formatOnSave - formats the file when it is saved.
  • editor.formatOnPaste - formats the pasted content.
  • editor.formatOnSaveMode - with the modifications setting, only the changed code is formatted on save.

The XPath formatter indents code blocks within {}, [] and () bracket-pairs. Indentation is also adjusted for if/else blocks and range-variable blocks.

Folding

Folding with this extension uses indentation to determine fold regions. To set a region code-folding block, surround it with <?region?> and <?endregion?> processing instructions. You may optionally include a label for the processing instructions, for example:

<?region modeA?> ... <?endregion modeA?>

For more detail and a full list of Folding-related actions see the Folding section in Visual Studio Code's User Guide.

Imports and Top-Level Stylesheets

The functions, templates, variables and other global declarations of a stylesheet's imported and included modules are used throughout the editor: by auto-completion, hover and signature help, go to definition, find references, symbol renaming and the linter.

A 'non-standalone' module - one that's imported by a parent stylesheet - often relies on declarations that only the parent imports. Without knowing the parent, those references can't be resolved: they're missing from auto-completion and hover help, and the linter reports spurious problems that may obscure real ones.

With inferred imports, the top-level ('parent') stylesheet that imports or includes the active module, directly or indirectly, is found and imported along with the module's own imports, so those references can be resolved.

A parent stylesheet opened recently in Visual Studio Code is used first. Otherwise, the parent is found from the workspace's XSLT files, which are scanned in the background the first time they're needed, so the parent doesn't have to be opened first. The scan only reads the href attributes of xsl:import and xsl:include instructions, and is kept up to date as files change. Where a module is imported by more than one stylesheet, the one in the nearest folder is used. The workspace scan can be turned off with the XSLT.resources.inferParentFromWorkspace setting.

To use a different top-level stylesheet - for example, one of two that import the same modules - run XSLT: Choose Top-Level Stylesheet... from the Command Palette, or the button in the title bar of the XSLT Imports view. The list shows the top-level stylesheets that import or include the active module, directly or indirectly: the one chosen is used for all the modules of its tree. Automatic goes back to the nearest folder, and Browse... picks any stylesheet, for the active module alone. The choices are saved for the workspace, and XSLT: Reset Top-Level Stylesheet Choices clears them all. The XSLT Imports view marks a chosen stylesheet chosen, rather than inferred.

The XSLT Imports view

The XSLT Imports view in the Explorer shows, for the XSLT module in the active editor, its top-level stylesheet - marked inferred when it was found from the workspace - with its tree of imports and includes. The tree is expanded down to the active module, which is marked current, and clicking a module opens it. The tooltip for a module lists any other stylesheets that import or include it.

The ▶ button on the top-level stylesheet runs it with Quick Run, using the current XML context file - whichever module of its tree is being edited.

The XSLT Imports view in the Explorer, with the ▶ Quick Run button for the top-level stylesheet.

IntelliSense (Auto Complete)

IntelliSense suggestions include all in-scope XSLT and XPath symbols from xsl:accumulator names to xsl:variable names, to anonymous XPath function parameters. There is IntelliSense also for XSLT and XPath functions - help for built-in functions is shown alongside the suggestions list. Symbols from included/imported files are included in the suggestions list.

Hover Help and Signature Help

Hovering over a function call shows the function's signature and description. This works for built-in functions, with a link to the function's definition in the W3C specification, and for user-defined xsl:functions, including those in included and imported stylesheets. Hovering over the name of an xsl:call-template shows the named template's parameters. Hovering over a mode name, in an xsl:mode, xsl:template or xsl:apply-templates, shows where the mode is applied from across the stylesheet's modules: the template rules of other modes, named templates and functions with an xsl:apply-templates for it - see also Checks on modes.

While typing the arguments of a function call, signature help (parameter hints) shows the function's parameters, with the current parameter highlighted. Signature help is also shown for the xsl:with-param children of an xsl:call-template. Signature help can be triggered manually with ⇧⌘Space.

In an XSLT 4.0 stylesheet, a documentation note on a function or template is included in its hover help and signature help.

IntelliSense for XPath Locations

An XML source file is used for context to provide XML node-names when editing XPath location steps. This is initially the first non-XSLT file opened in Visual Studio Code. When the context file is set, the status-bar for the XSLT file editor will show the context filename. The label [XML context file] is shown if the context file has not been set, and [no XML context] if 'none' was picked. The same file is the XML source for Quick Run.

Locking the context file

To lock the auto-completion context file to a specific file, click on the status-bar item for the context file. You can then select from the list of recently opened XML files or pick a different file using the system's file explorer dialog. The file you pick is for the stylesheet you're editing (and the modules it imports or includes) - each stylesheet keeps its own, see Each stylesheet has its own XML context file.

Variables and XPath Locations

XPath is evaluated as you type so node-names in the auto-completion list are filtered to be just those that are possible given previous XPath steps such as axes and node-name tests. If an XPath location expression starts with a variable that also contains an XPath location, that context from that variable is also used to limit the node-names shown in the auto-completion list.

Triggering the auto-complete list

For XSLT IntelliSense, the < character triggers suggestions. XSLT instruction suggestions fit the context of the cursor location. On accepting a suggestion a Code Snippet is inserted which will include common attributes for the selected instruction.

IntelliSense is manually triggered with ⌃Space, with Tab or Enter used to accept suggestions. These key bindings are fully customizable.

XPath Expressions and Operators

At the start of an XPath expression, the suggestions include snippets for the expressions with several parts: for, let, some, every, if, map and array - for example, let $x := … return …, with placeholders for each part.

After an operand, such as a variable or a closing bracket, only the keyword operators that can follow are suggested, such as cast as, instance of and union - and return or satisfies within a for, let, some or every expression. Short operators such as and, eq and div are quicker to type, so aren't included.

Parameters for xsl:call-template

Typing < within an xsl:call-template suggests an xsl:with-param for each of the called template's parameters that isn't passed yet, for example xsl:with-param colour, which inserts the parameter name. The same applies to the parameters of the enclosing xsl:iterate within an xsl:next-iteration. The name attribute of an xsl:with-param also offers the parameter names.

XSLT Instruction Snippets

In an empty file, the xsl:stylesheet and xsl:package suggestions insert a boilerplate stylesheet complete with namespace declarations, including one for your own functions - an 'identity transform', or one starting from xsl:initial-template. Each is available for XSLT 3.0 and XSLT 4.0, shown on the right of the suggestion.

The xsl:message suggestions include snippets that use the xdm:debug() function to show the names and values of in-scope variables and parameters - see Print Debugging.

More Snippets

You can define your own snippets in Visual Studio Code in a declarative way, without writing an extension. See the Visual Studio Code documentation: Create your own snippets.

Emmet Snippets provide a useful shorthand for inserting literal result elements. They can be enabled for XSLT in Visual Studio Code Settings.

Bracket Matching

Matching brackets in XPath expressions are highlighted when the cursor is near one of them. You can jump to the matching bracket with ⇧⌘\

Symbol Renaming

The Rename Symbol command F2 (available in the context-menu) updates all in-scope usages of the symbol - across all imported stylesheet modules. Press ⇧Enter to preview the updates or Enter to perform updates immediately.

Code Refactoring

Code refactoring features are provided via VS Code's Quick Fix (⌘.) feature and the Refactor command:

  • xsl:function - full refactor and xsl:function - partial refactor - extract an xsl:function from selected XSLT instructions
  • xsl:function (XPath) - full refactor and xsl:function (XPath) - partial refactor - extract an xsl:function from a selected XPath expression
  • xsl:template - extract an xsl:template from selected XSLT instructions
  • xsl:variable - extract an xsl:variable from a selected XPath expression
  • Wrap with... (⌥⇧W) - wraps the selected instructions, or the element whose start tag is at the cursor, in an instruction such as xsl:if, xsl:choose or xsl:for-each, or a literal result element - chosen from a list of the instructions allowed at that point, with the recently used ones first. The selected lines are indented within the new instruction, and the cursor is placed in its first attribute, such as test or select
  • Extract record type and Use record type - XSLT 4.0, for a map constructor or xsl:map, see Records and Enums
  • Add documentation note - XSLT 4.0, with the cursor on the start tag of an xsl:function or xsl:template, see Code Documentation
  • Override Package Components... - with the cursor in an xsl:use-package, adds declarations to its xsl:override for the package components you pick, see Overriding package components

An available refactoring for a selection is indicated by a light-bulb💡 adjacent to the selection. Clicking on the 💡 will display the available refactorings. The light-bulb is only shown when the code selection is a valid expression or a set of XSLT instructions that would be valid inside the new component. If you don't see the light-bulb when you expect to, check that the code selection completely encloses the XSLT instruction or XPath expression.

The name of an extracted new component should be changed with the Rename Symbol feature, this is automatically triggered when the new component is added.

After refactoring, the XSLT is updated to fix any context problems introduced when code is moved. The new component has xsl:param instructions added to provide context-properties required. For extract to xsl:function two modes are available (fully documented here):

  • full refactoring - fixes 'missing-context' problems by updating XSLT to reference the context-property parameters.
  • partial refactoring - highlights 'missing context' problems in the XSLT.

Refactoring with 'Extract to xsl:function' in full mode, referencing context-parameters $c.x, $c.p and $c.l

Quick Fixes

Some problems reported by the linter have a Quick Fix, shown with the 💡 light-bulb when the cursor is on the problem:

  • include XSLT module for xdm:debug and xdm:trace and copy xdm-view library into workspace - for the xdm:debug() or xdm:trace() function when the xdm-view library isn't included, see Print Debugging
  • Don't report unknown 'prefix:' functions in this workspace - for a call of a function with a prefix, such as an extension function, that isn't found; the prefix is added to the XSLT.validation.externalFunctionPrefixes setting (in user settings when no folder is open), see Java extension functions
  • Set 'htmlParserJar' in User Settings... - for the parse-html() function, which needs the XSLT.tasks.htmlParserJar setting
  • Convert all Saxon type aliases in the workspace to xsl:item-type... - for a saxon:type-alias, see Converting Saxon type aliases
  • Add missing record fields - for a map constructor or xsl:map without all the required fields of its record type, see Records and Enums
  • Change to 'name' - for an unknown field of a record type, one for each field name that could replace it
  • Add missing xsl:when cases with select and Add missing xsl:when cases with content - for an xsl:switch on an enumeration type that doesn't test all its values, see xsl:switch on an enumeration
  • Remove duplicate enum value - for an enumeration type with a duplicate value
  • Add missing @param, Add missing @field and Add missing @variable - for a documentation note without an @param for each parameter, an @field for each record field, or (in a module note) an @variable for each global variable, see Code Documentation
  • Exclude with use-when="false()" - for an xsl:note in an XSLT 3.0 stylesheet, see Notes in XSLT 3.0
  • Add mode="#current" (preferred) and Add mode="#default" - for an xsl:apply-templates without a mode in a template rule with a mode, see Checks on modes
  • XSLT packages - for an xsl:use-package whose package isn't found, abstract components that aren't overridden, problems with xsl:accept and xsl:override, and modes a package doesn't declare, see a package that isn't found, abstract components, problems with xsl:accept and xsl:override and declared modes

XSLT Linter

The XSLT/XPath linter performs checks on your code as you type, performing symbol reference tests across all included modules. Any problems are shown in the Problems view and also highlighted inline with a squiggly underline for the specific token at issue.

A module that relies on its parent stylesheet's imports is checked with those imports too - see Imports and Top-Level Stylesheets.

Checks made by the linter
  1. XML Syntax
  2. XSLT/XPath Variable name references
  3. XSLT/XPath Parameter name references
  4. All other symbol name references (xsl:accumulator xsl:key etc.)
  5. Function name and arity (number of params)
  6. xsl:with-param names
  7. File locations in xsl:import xsl:include xsl:use-package
  8. Order of operators/operands in XPath
  9. Matching of brackets in XPath
  10. Presence of the context-item for expressions where it is required
  11. XSLT instructions and their attributes, and their structure - for example an xsl:choose without an xsl:when, or two xsl:with-param elements with the same name
  12. Duplicate global symbol names
  13. Attribute Value Template Syntax
  14. Text Value Template Syntax
  15. Item types on as attributes of XSLT instructions
  16. Accumulator names in use-accumulators attributes, and accumulators not used by any use-accumulators attribute
  17. Operators in patterns - or, and, eq or , outside a predicate or function call, for example match="a or b" instead of match="a | b"
  18. Duplicate keys in map constructors and in the xsl:map-entry children of an xsl:map
  19. Braced URI literals, for example Q{http://example.com}name
  20. The order of xsl:param, xsl:on-completion and xsl:next-iteration within xsl:iterate
  21. Modes - see Checks on modes
  22. XSLT 4.0: record and enumeration types, see Records and Enums
  23. XSLT 4.0: the @param tags of documentation notes, see Code Documentation

The linter follows the XSLT rules that affect which code is valid:

  • Names of functions, templates, modes and variables are matched by namespace across modules, so modules may use different prefixes for the same namespace.
  • A module may use a prefix other than xsl for XSLT instructions, for example xslt:template.
  • Forwards compatible mode: for an element with a higher version, an unknown XSLT element with an xsl:fallback child, and an unknown attribute, aren't reported.
  • Simplified stylesheets: a literal result element with xsl:version as the outermost element.
  • A call of a function that isn't known is not reported when it's guarded by use-when="function-available('name')".

Checks on modes

A large transform may run in many modes, and a template rule applied in the wrong mode fails silently. The linter warns about:

  • An unknown mode - an xsl:apply-templates whose mode isn't declared by an xsl:mode or used by any template rule, in all the stylesheet's modules - often a typo in the mode name.
  • An xsl:apply-templates without a mode in a template rule with a mode - it applies the default mode, not the template rule's mode. This commonly happens when a template rule is added for a new mode and mode="#current" is forgotten. The quick fixes add mode="#current", or mode="#default" to show that the default mode is intended. There's no warning when the template rule's modes include the default mode - the unnamed mode, or the mode named by the innermost [xsl:]default-mode attribute - or #all, nor for a template rule within an XSLT 4.0 xsl:mode, where the enclosing mode is the default.
  • XSLT 4.0: an xsl:mode with enclosed template rules but no name, and an enclosed template rule with a mode or name attribute, or without a match.

Union patterns and XSLT 4.0

The linter warns about a template rule without a priority attribute whose match is a union with branches of different default priorities, e.g. match="@d:* | @other" (-0.25 and 0). XSLT 3.0 makes a rule for each branch, with its own priority, but XSLT 4.0 makes one rule, with the highest - as Saxon reports with its warning SXWN9052. So another template rule may be chosen: here, match="@d:keep" would no longer win over the union. The warning lists each branch's priority. Give the template a priority, or split it into a template for each branch, so it runs the same either way.

It's shown where XSLT 4.0's rule applies:

  • in an XSLT 4.0 stylesheet
  • in a stylesheet before 4.0 that's run with Saxon's syntax extensions, as it - or a module of its stylesheet - uses item types or notes: Saxon 13 then uses 4.0's rule
  • in any stylesheet before 4.0, with the setting XSLT.validation.xslt40UnionPriorities - e.g. to prepare for XSLT 4.0

Other stylesheets before 4.0 are run without the syntax extensions by default, so they keep XSLT 3.0's rule.

Unused Variables

The linter detects unused variables and parameters declared in either XSLT or XPath expressions. These are highlighted by being 'grayed out' in the editor. Global variables are shown as unused if they are not referenced in the current file, the 'unused' state is not affected by imported stylesheets they may reference the same variable.

Compile-time and Run-time problems

The linter is designed to find most basic code problems due to typos or changes to referenced symbols. When XSLT is run, an attempt is made to parse error messages from the Saxon XSLT processor (shown in the Task tab of the Terminal View) so that the problem token is highlighted, and the error message is shown in the Problems view.

You can quickly create a new XSLT file when adding a xsl:import, xsl:use-package or xsl:include XSLT instruction. Simply enter the file path in the href, press ⌘+click and then, in the 'Unable to Open...' dialog press the Create File button.

On this page