Skip to content

Instantly share code, notes, and snippets.

@k3kaimu
Created September 11, 2015 17:11
Show Gist options
  • Save k3kaimu/6695540935047fd63677 to your computer and use it in GitHub Desktop.
Save k3kaimu/6695540935047fd63677 to your computer and use it in GitHub Desktop.
TeXのDSL的ななにか
import std.array;
import std.ascii;
import std.format;
import std.stdio;
import std.string;
void main()
{
auto fig =
TeX.Figure(["!t"], TeX.Center(TeX
.includegraphics(["width=65mm"], "fig/foo.pdf").br
.caption("なんかの図")
.label("fig:foo")
));
writeln(fig);
}
struct TeX
{
static:
TeXValue opDispatch(string name)(string arg) { return opDispatch!name(null, arg); }
TeXValue opDispatch(string name)(string[] opt, string arg)
{
auto app = appender!string();
auto sub = appender!string();
if(opt.length)
sub.formattedWrite(`[%-(%s, %)]`, opt);
if(name[0].isUpper)
{
app.formattedWrite(`\begin%1$s{%2$s}%3$s\end{%2$s}`, sub.data, name.toLower, arg);
}
else
{
app.formattedWrite(`\%1$s%2$s{%3$s}`, name, sub.data, arg);
}
return TeXValue(app.data);
}
}
struct TeXValue
{
this(string str)
{
_str = str;
}
string toString() const pure nothrow @safe @nogc @property { return _str; }
alias toString this;
const:
TeXValue opDispatch(string name)(string arg) { return opDispatch!name(null, arg); }
TeXValue opDispatch(string name)(string[] opt, string arg)
if(isLower(name[0]))
{
auto app = appender!string();
auto sub = appender!string();
if(opt.length)
sub.formattedWrite(`[%-(%s, %)]`, opt);
app.put(_str);
app.put(`\n`);
switch(name)
{
default:
app.formattedWrite(`\%1$s%2$s{%3$s}`, name, sub.data, arg);
}
return TeXValue(app.data);
}
TeXValue opDispatch(string name)() @property
{
auto app = appender!string();
app.put(_str);
switch(name)
{
case "br":
app.put(`\\ `);
default:
app.formattedWrite(`\%1$s`, name);
}
return TeXValue(app.data);
}
private:
string _str;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment