unist-util-lsp Conversion Utility

2.1.0 · active · verified Sun Apr 19

The `unist-util-lsp` library provides a focused set of utility functions to accurately convert positional information between unist (Universal Syntax Tree) nodes and the Language Server Protocol (LSP) format. This is crucial for developers building sophisticated tooling, such as IDE extensions or linters, that operate on both ASTs and interact with LSP-compliant language servers. The current stable version is 2.1.0, with an active release cadence demonstrating ongoing maintenance and feature additions. Key differentiators include its tight integration with the unist ecosystem and its precise mapping to LSP’s `Range` and `Position` types, making it an essential bridge for creating robust language-aware applications. It primarily targets environments supporting ECMAScript Modules (ESM) and requires Node.js version 16 or higher.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to use the core conversion utilities to map positional data between unist and LSP formats, including converting full positions and individual points, and showcasing the `fromPlace` utility.

import { fromMarkdown } from 'mdast-util-from-markdown';
import {
  fromPlace,
  fromPoint,
  fromPosition,
  toPoint,
  toPosition
} from 'unist-util-lsp';

const markdown = '## Hello **World**!\n';
const mdast = fromMarkdown(markdown);

console.log('Unist Position:', mdast.position);

// Convert unist position to LSP range
const lspRange = fromPosition(mdast.position);
console.log('LSP Range from Unist Position:', lspRange);

// Convert LSP range back to unist position
const unistPosition = toPosition(lspRange);
console.log('Unist Position from LSP Range:', unistPosition);

// Convert unist point (start of the AST) to LSP position
const lspStartPosition = fromPoint(mdast.position.start);
console.log('LSP Position from Unist Start Point:', lspStartPosition);

// Convert LSP position back to unist point
const unistStartPoint = toPoint(lspStartPosition);
console.log('Unist Point from LSP Start Position:', unistStartPoint);

// Convert a unist place (point or position) to an LSP range (introduced in v2.1.0)
const fullRangeFromPlace = fromPlace(mdast.position);
console.log('LSP Range from Unist Position (via fromPlace):', fullRangeFromPlace);

const startRangeFromPlace = fromPlace(mdast.position.start);
console.log('LSP Range from Unist Start Point (via fromPlace):', startRangeFromPlace);

view raw JSON →