Skip to content

Instantly share code, notes, and snippets.

@jdinkla jdinkla/lhs2hs.groovy
Last active Nov 23, 2016

Embed
What would you like to do?
Convert literate Haskell (*.lhs) files to normal Haskell files (*.hs)
// (c) 2016 Jörn Dinkla, www.dinkla.net
// usage groovy lhs2hs.groovy FILENAMES.lhs
// warning: existing files with .hs extension are overwritten
void transformBeginEndCode(StringBuilder sb, File f) {
boolean inCode = false
sb << "{-\n"
f.text.eachLine { line ->
if (line =~ /^\\begin\{code\}/) {
sb << "-}\n\n"
inCode = true
} else if (line =~ /^\\end\{code\}/) {
inCode = false
sb << "\n{-\n"
} else {
def line2 = line.replaceAll(/\t/, ' ')
sb << line2 << "\n"
}
}
sb << "-}"
}
void transformTaggedCode(StringBuilder sb, File f) {
boolean inCode = false
sb << "{-\n"
f.text.eachLine { line ->
if (line =~ /^>/) {
if (!inCode) {
sb << "-}\n\n"
inCode = true
}
def line2 = line.substring(1).replaceAll(/\t/, ' ')
sb << line2 << "\n"
} else {
if (inCode) {
inCode = false
sb << "\n{-\n"
}
def line2 = line.replaceAll(/\t/, ' ')
sb << line2 << "\n"
}
}
sb << "-}"
}
void writeFile(String newFilename, StringBuilder sb) {
def out = new File(newFilename)
out.delete()
out << sb.toString()
}
for (filename in args) {
def newFilename = filename.replace('.lhs', '.hs')
def f = new File(filename)
def sb = new StringBuilder()
// quick test to determine the format
boolean hasBeginEndCode = false
boolean hasTaggedCode = false
f.text.eachLine { line ->
if (line =~/^\\begin\{code\}/) {
hasBeginEndCode = true
}
if (line =~/^>/) {
hasTaggedCode = true
}
}
if (hasBeginEndCode && hasTaggedCode) {
println("Sorry, both formats simultaneously is not supported.")
exit(1)
} else if (hasBeginEndCode) {
println("File $filename has begin..end code")
transformBeginEndCode(sb, f)
writeFile(newFilename, sb)
} else if (hasTaggedCode) {
println("File $filename has >-tagged code")
transformTaggedCode(sb, f)
writeFile(newFilename, sb)
} else {
println("The code in file $filename is in an unknown format");
exit(2)
}
}
@jdinkla

This comment has been minimized.

Copy link
Owner Author

commented Nov 23, 2016

Today i converted my GeomAlgLib with this script.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.