vfile-location

5.0.3 · active · verified Sun Apr 19

vfile-location is a utility package within the unified ecosystem, currently at stable version 5.0.3, designed to convert between positional (line and column-based) and offset (character index-based) locations within a vfile instance. It provides `toOffset` and `toPoint` methods for accurate translation. The package sees active development and frequent, minor releases, with major versions typically introducing breaking changes like the move to ESM-only and Node.js 16+ requirement in v5. A key differentiator is its tight integration with `vfile`, making it ideal for tasks like generating precise linting reports or manipulating text based on raw file content where traditional AST node locations might be insufficient for location tracking.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a location index for a `VFile`, convert a line/column point to a character offset, and convert an offset back to a point, including how out-of-bounds values are handled since v5.

import { VFile } from 'vfile';
import { location } from 'vfile-location';

// Create a VFile instance with some content
const fileContent = 'foo\nbar\nbaz';
const file = new VFile(fileContent);

// Create a location index for the file
const place = location(file);

// Convert a line/column point to an offset
const point = { line: 3, column: 3 };
const offset = place.toOffset(point); // Should be 10 (0-indexed)
console.log(`Offset for point {line: ${point.line}, column: ${point.column}} is: ${offset}`);

// Convert an offset back to a line/column point
const targetOffset = 10;
const retrievedPoint = place.toPoint(targetOffset);
console.log(`Point for offset ${targetOffset} is: {line: ${retrievedPoint?.line}, column: ${retrievedPoint?.column}, offset: ${retrievedPoint?.offset}}`);

// Demonstrate out-of-bounds handling (v5 change)
const outOfBoundsOffset = 100;
const invalidPoint = place.toPoint(outOfBoundsOffset);
console.log(`Point for out-of-bounds offset ${outOfBoundsOffset} is: ${invalidPoint}`); // Should be undefined

const outOfBoundsPoint = { line: 10, column: 1 };
const invalidOffset = place.toOffset(outOfBoundsPoint);
console.log(`Offset for out-of-bounds point {line: ${outOfBoundsPoint.line}, column: ${outOfBoundsPoint.column}} is: ${invalidOffset}`); // Should be undefined

view raw JSON →