YAML Language Server
The YAML Language Server provides comprehensive language support for YAML files, adhering to the Language Server Protocol (LSP). It offers features such as robust YAML validation against JSON Schema drafts (04, 07, 2019-09, and 2020-12), intelligent auto-completion, rich hover information, document outlining, and code formatting capabilities. Since version 1.0.0, it utilizes the `eemeli/yaml` parser for strict enforcement of the YAML specification (defaulting to YAML 1.2). Key differentiators include built-in Kubernetes syntax support, integration with the JSON Schema Store for automatic schema fetching, and the ability to parse Kubernetes Custom Resource Definitions (CRDs). The project maintains an active development cycle, with frequent releases often on a monthly or bi-monthly cadence, with version 1.22.0 being the current stable release.
Common errors
-
No errors are appearing in the LSP log... not seeing syntax highlighting, autocomplete, or suggestions in YAML files
cause The language server is not being correctly started, or the LSP client is failing to establish communication or send necessary requests (e.g., 'initialize', 'textDocument/didOpen').fixVerify that the `yaml-language-server` executable path is correct in your LSP client's configuration (e.g., Neovim's `lspconfig`, VSCode extension settings). Check client/server logs for any connection errors. Ensure Node.js is installed and accessible in the environment where the server runs. -
mapping values are not allowed in this context at line X column Y
cause This error typically indicates an indentation issue, a missing colon (`:`), or an attempt to use a non-scalar value (like a map or sequence) where a scalar is expected, violating YAML syntax rules.fixCarefully review the specified line and column for incorrect indentation, missing key-value separators, or misplaced complex structures. Online YAML validators (e.g., YAML Lint) can help pinpoint syntax errors. -
Incorrectly flagging 'Missing property "$ref"' for OpenAPI 3.0.X
cause The language server's schema validation might incorrectly interpret OpenAPI 3.0.X schemas, particularly regarding the `$ref` keyword, leading to false-positive validation errors.fixCheck for updates to the `yaml-language-server` and `vscode-yaml` extensions, as this was a known issue that might have been resolved in newer versions. Ensure your OpenAPI schema is valid and accessible, and potentially simplify `$ref` usage if possible.
Warnings
- breaking Starting from version 1.0.0, the YAML Language Server switched its internal parser to `eemeli/yaml`. This change results in stricter adherence to the specified YAML specification, which might cause previously tolerated, non-compliant YAML files to now trigger validation errors.
- gotcha When working with YAML files containing multiple documents (separated by `---`), Intellisense completion and sometimes other language features may break or behave unexpectedly, especially in certain LSP client integrations.
- gotcha Configuring schema associations using `yaml.schemas` with glob patterns can be complex, especially when using local schema files. Paths must be relative to the project root, and overlapping globs can lead to unexpected behavior or incorrect schema application.
Install
-
npm install yaml-language-server -
yarn add yaml-language-server -
pnpm add yaml-language-server
Imports
- Settings
import { Settings } from 'yaml-language-server'; - YAML_SCHEMA_ASSOCIATIONS
import { YAML_SCHEMA_ASSOCIATIONS } from 'yaml-language-server'; - ISchemaAssociations
import { ISchemaAssociations } from 'yaml-language-server';
Quickstart
import { spawn } from 'child_process';
import { createConnection, MessageConnection, InitializeParams, TextDocumentItem, DidOpenTextDocumentParams } from 'vscode-languageserver/node';
import { TextDocuments } from 'vscode-languageserver-textdocument';
const serverPath = require.resolve('yaml-language-server/bin/yaml-language-server');
async function startYamlLanguageServer() {
console.log(`Starting YAML Language Server from: ${serverPath}`);
const serverProcess = spawn('node', [serverPath, '--stdio']);
serverProcess.stdout.pipe(process.stdout);
serverProcess.stderr.pipe(process.stderr);
process.stdin.pipe(serverProcess.stdin);
const connection: MessageConnection = createConnection(
serverProcess.stdin,
serverProcess.stdout
);
connection.listen();
connection.onInitialize(async (params: InitializeParams) => {
console.log('LSP Client: Initializing...');
return {
capabilities: {
textDocumentSync: 1, // Full
completionProvider: { resolveProvider: false, triggerCharacters: ['-', ':'] },
hoverProvider: true,
documentFormattingProvider: true,
documentRangeFormattingProvider: true,
documentSymbolProvider: true,
workspace: { workspaceFolders: { supported: true } }
},
serverInfo: { name: 'yaml-language-client', version: '1.0' }
};
});
// Send initialize request after connection is established
connection.sendRequest('initialize', {
processId: process.pid,
rootUri: null,
capabilities: {},
workspaceFolders: null
} as InitializeParams).then(async () => {
console.log('LSP Client: Initialized. Sending didOpen notification...');
// Example: Open a dummy YAML document
const dummyYamlContent = `---
apiVersion: v1
kind: Pod
metadata:
name: my-pod
spec:
containers:
- name: my-container
image: busybox
command: ['sh', '-c', 'echo Hello Kubernetes! && sleep 3600']
`;
const textDocument: TextDocumentItem = {
uri: 'file:///tmp/test.yaml',
languageId: 'yaml',
version: 1,
text: dummyYamlContent
};
connection.sendNotification('textDocument/didOpen', { textDocument } as DidOpenTextDocumentParams);
console.log('LSP Client: Sent didOpen for test.yaml. Check server logs for activity.');
}).catch(error => {
console.error('LSP Client: Initialization failed:', error);
});
process.on('exit', () => {
serverProcess.kill();
});
}
startYamlLanguageServer().catch(console.error);