Skip to content

mcecode/gemtext-parser

Repository files navigation

Gemtext Parser

A library for parsing, transforming, generating, and converting gemtext.

If you're unfamiliar with gemtext, you can read the quick introduction or the specification.

For the full documentation, go to https://pkg.go.dev/github.com/mcecode/gemtext-parser.

Installation

go get github.com/mcecode/gemtext-parser

Usage

Convert gemtext to HTML

Input (testdata/example.gmi)

# Some Heading
Some text...
=> gemini://example.org Some link

main.go

package main

import (
	"fmt"

	p "github.com/mcecode/gemtext-parser"
)

func main() {
	asl, _ := p.ParseFile("testdata/example.gmi")
	html := p.ToHTML(asl)
	fmt.Print(html)
}

Output

<h1>Some Heading</h1>
<p>Some text...</p>
<p><a href="gemini://example.org">Some link</a></p>

Transform gemtext

Input (testdata/example.gmi)

# Some Heading
Some text...
=> gemini://example.org Some link

main.go

package main

import (
	"fmt"
	"strings"

	p "github.com/mcecode/gemtext-parser"
)

func main() {
	asl, _ := p.ParseFile("testdata/example.gmi")

	asl.DeleteAll(func(e p.Element) bool {
		if e.Type() == p.ElementTypes.Text() {
			return true
		}

		return false
	})
	asl.InsertAfter(
		[]p.Element{p.NewHeading("Some Subheading", p.HeadingLevels.SubHeading())},
		func(e p.Element) bool {
			if e.Type() == p.ElementTypes.Heading() &&
				e.Level() == p.HeadingLevels.Heading() {
				return true
			}

			return false
		},
	)
	asl.Replace(
		[]p.Element{p.NewLink("Some other link", "gemini://example.com")},
		func(e p.Element) bool {
			if e.Type() == p.ElementTypes.Link() &&
				strings.HasSuffix(e.URL(), ".org") {
				return true
			}

			return false
		},
	)

	gemtext := p.ToGemtext(asl)
	fmt.Print(gemtext)
}

Output

# Some Heading
## Some Subheading
=> gemini://example.com Some other link

Programmatically generate gemtext

main.go

package main

import (
	"fmt"

	p "github.com/mcecode/gemtext-parser"
)

func main() {
	asl := p.NewASL(
		p.NewHeading("Main Heading", p.HeadingLevels.Heading()),
		p.NewText("Lorem ipsum..."),
		p.NewHeading("Subheading", p.HeadingLevels.Heading()),
		p.NewText("Lorem ipsum..."),
		p.NewLink("Sample link", "gemini://example.org"),
	)
	gemtext := p.ToGemtext(asl)
	fmt.Print(gemtext)
}

Output

# Main Heading
Lorem ipsum...
# Subheading
Lorem ipsum...
=> gemini://example.org Sample link

License

Copyright 2025-present Matthew Espino

This project is licensed under the Apache 2.0 license.

About

A library for parsing, transforming, generating, and converting gemtext.

Topics

Resources

License

Stars

Watchers

Forks

Languages