Skip to content

Instantly share code, notes, and snippets.

@graemephi
Last active December 30, 2021 14:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save graemephi/7c60093f342b6dabf00d976492b6c91f to your computer and use it in GitHub Desktop.
Save graemephi/7c60093f342b6dabf00d976492b6c91f to your computer and use it in GitHub Desktop.
const katex = require('katex');
const assert = require('assert').ok;
let inline = {
throwOnError: false,
displayMode: false,
output: 'html'
};
let display = {
throwOnError: false,
displayMode: true,
output: 'html'
};
function detex(block) {
if (block.t === 'Math') {
assert(block.c.length === 2);
assert((block.c[0].t === 'InlineMath') || (block.c[0].t === 'DisplayMath'));
assert(typeof(block.c[1]) === 'string');
block.t = 'RawInline';
block.c = ['html', katex.renderToString(block.c[1], block.c[0].t === 'InlineMath' ? inline : display)];
} else if (Array.isArray(block.c)) {
block.c.forEach(detex);
}
}
let json = '';
process.stdin.setEncoding('utf-8');
process.stdin.on('readable', () => {
for (let chunk = process.stdin.read(); chunk; chunk = process.stdin.read()) {
json += chunk;
}
});
process.stdin.on('end', () => {
let data = JSON.parse(json);
data.blocks.forEach(detex);
process.stdout.write(JSON.stringify(data));
});
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <io.h>
#include <fcntl.h>
#define EAGAIN 11
/*
* NOTE: While this looks POSIX-y, it is _not_ Linux compatible!
*
* An apparently undocumented feature of Windows pipes opened
* with _popen is that they are bidirectional--you can read
* from and write to the same pipe. Linux does not allow this.
*
* The weird way of checking for eof is due to
* http://cbloomrants.blogspot.com/2018/04/race-in-eof-on-windows-pipes.html
* which I never encountered, but, hell.
*/
int main(int argc, char **argv)
{
(void)(argc, argv);
#if 1
FILE *pandoc = _popen("/path/to/pandoc --katex --filter=katex", "wb");
#else
FILE *pandoc = _popen("path/to/node pandoc\\katex.js", "wb");
#endif
if (pandoc == 0) {
exit(1);
}
int in = _fileno(stdin);
int out = _fileno(stdout);
int pan = _fileno(pandoc);
_setmode(in, O_BINARY);
_setmode(out, O_BINARY);
char buf[BUFSIZ];
for (;;) {
int n = _read(in, buf, sizeof(buf));
if (n > 0) {
_write(pan, buf, n);
} else if (n == 0) {
if (_eof(in)) {
break;
}
} else {
if (errno == EAGAIN) {
continue;
}
if (_eof(in)) {
break;
}
}
}
for (;;) {
int n = _read(pan, buf, sizeof(buf));
if (n > 0) {
_write(out, buf, n);
} else if (n == 0) {
if (_eof(in)) {
break;
}
} else {
if (errno == EAGAIN) {
continue;
}
if (_eof(in)) {
break;
}
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment