An open API service indexing awesome lists of open source software.

https://github.com/joeltg/hast-util-from-lezer

Render styled Lezer syntax trees to hast
https://github.com/joeltg/hast-util-from-lezer

abstract-syntax-tree ast hast hast-util lezer

Last synced: 5 months ago
JSON representation

Render styled Lezer syntax trees to hast

Awesome Lists containing this project

README

          

# hast-util-from-lezer

[![standard-readme compliant](https://img.shields.io/badge/readme%20style-standard-brightgreen.svg)](https://github.com/RichardLitt/standard-readme) [![license](https://img.shields.io/github/license/joeltg/hast-util-from-lezer)](https://opensource.org/licenses/MIT) [![NPM version](https://img.shields.io/npm/v/hast-util-from-lezer)](https://www.npmjs.com/package/hast-util-from-lezer) ![TypeScript types](https://img.shields.io/npm/types/hast-util-from-lezer)

Render styled [Lezer syntax trees](https://github.com/lezer-parser/common) to [hast](https://github.com/syntax-tree/hast).

## Table of contents

- [Install](#install)
- [Usage](#usage)
- [API](#api)
- [Contributing](#contributing)
- [License](#license)

## Install

```
npm i hast-util-from-lezer
```

## Usage

```typescript
import { fromLezer } from "hast-util-from-lezer"
import { parser as javascriptParser } from "@lezer/javascript"
import { toHtml } from "hast-util-to-html"

const source = `function norm(a: number, b: number): number {
return Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2))
}`

const tree = javascriptParser.parse(source)
const element = fromLezer(source, tree)
console.log(toHtml(element))
```

yields the following HTML:

```
function norm(a: number, b: number): number {
return Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2))
}
```

## API

```typescript
import type { Tree } from "@lezer/common"
import type { Root } from "hast"

declare function fromLezer(source: string, tree: Tree): Root
```

`tree` must already be styled if you want highlighting classnames in the resulting hast. This means the Lezer grammar you're using has to support highlight style props, typically included with a `highlight.js` file and a `@external propSource` directive in the grammar source. All the Lezer grammars maintained by the Lezer project do; you shouldn't have to worry about it.

## Contributing

hast-util-from-lezer is meant to be a minimal utility library - it's unlikely that I'll want to add new features to it, but if you find bugs, have interface or API suggestions, or general feedback, feel free to open an issue to discuss it!

## License

MIT (c) 2024 Joel Gustafson