Skip to content

Instantly share code, notes, and snippets.

@joakim
Last active December 6, 2021 20:32
Show Gist options
  • Save joakim/73f7b4cd39fd06d743326f4d07062769 to your computer and use it in GitHub Desktop.
Save joakim/73f7b4cd39fd06d743326f4d07062769 to your computer and use it in GitHub Desktop.
Lagrange MIME hook for formatting of inline Markdown style emphasis in Gemini's GemText
import { readLines } from 'https://deno.land/std/io/buffer.ts'
import { copy } from 'https://deno.land/std/streams/conversion.ts'
const print = console.log
type type = [search: RegExp, replace: string]
// Pass-through the header
print(`20 ${ Deno.args.join(';') }\r`)
// Check for type=inline parameter
const inline = Deno.args.find(
(arg) =>
arg.trim().startsWith('type=') &&
arg.split('=')[1].split(',').includes('inline')
)
// Pass-through the body if no type=inline
if (!inline) {
await copy(Deno.stdin, Deno.stdout)
Deno.exit()
}
const types: type[] = [
[/_([^_]+)_/g, '\x1b[3m$1\x1b[0m'], // italic
[/\*\*([^*]+)\*\*/g, '\x1b[1m$1\x1b[0m'], // bold
]
const replace = (text: string, type: type): string =>
text.replaceAll(...type)
const format = (text: string): string =>
types.reduce(replace, text)
let preformatting = false
for await (const line of readLines(Deno.stdin)) {
// Toggle preformatting lines
if (line.startsWith('```')) {
preformatting = !preformatting
print(line)
}
// Skip preformatted, header and link lines
else if (preformatting || line.startsWith('#') || line.startsWith('=>')) {
print(line)
}
// Format list item lines
else if (line.startsWith('* ')) {
print(`* ${ format(line.slice(2)) }`)
}
// Format text and quote lines
else {
print(format(line))
}
}
@joakim
Copy link
Author

joakim commented Dec 5, 2021

A simple shell script is needed to make it run it from Lagrange.

#!/bin/sh
/usr/local/bin/deno run /(…)/lagrange-inline-formatting.ts "$@"

And this in mimehooks.txt:

Inline formatting
text/gemini
path-to-shell-script

I first tried #!/usr/bin/env deno run at the top of the TypeScript file, but Deno didn't like that for some reason.

@joakim
Copy link
Author

joakim commented Dec 5, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment