Skip to content

Instantly share code, notes, and snippets.

@jbedo
Created May 13, 2013 06:53
Show Gist options
  • Save jbedo/5566572 to your computer and use it in GitHub Desktop.
Save jbedo/5566572 to your computer and use it in GitHub Desktop.
LaTeX code beautifier. Wraps text chunks at 70c, indents between begin/end, and puts a hard line break after every sentence. Does not wrap math.
#!/usr/bin/awk -f
BEGIN{
linelen=70
indent=0
braces=0
FS="\\.[\t ]+"
}
/\\end\{/{indent--}
/\\end\{.*(align|gather|equation)/{math=0}
/\\\]/{indent--; math=0}
/^[ \t]*$/ {printf("\n")}
function mkindent(i){
for(i = 1; i <= indent; i++)
printf("\t")
for(i = 1; i <= braces; i++)
printf(" ")
}
function printline(line, i, j){
clen = 0
mkindent()
n = split(line, fields, " ")
for(j = 1; j <= n; j++){
if(!math && clen > 0 && clen + length(fields[j]) > linelen){
printf("\n")
mkindent()
clen = 0
}
printf("%s%s", fields[j], j == n?"":" ")
clen += length(fields[j])
}
}
{
gsub (/^[ \t]+/,"")
gsub (/[ \t]+$/,"")
gsub (/[ \t]+/," ")
for(j = 1; j <= NF; j++){
printline($j)
printf("%s", j == NF?"\n":".\n")
}
}
/\\begin\{/{indent++}
/\\begin\{.*(align|gather|equation)/{math=1}
/\\end\{.*(align|gather|equation)/{math=0}
/\\\[/{indent++; math=1}
/\\\]/{math=0}
/\{/{
split($0, chars, "")
for (i=1; i <= length(chars); i++){
if(chars[i] == "{")
braces++
if(chars[i] == "\\")
i++
}
}
/\}/{
split($0, chars, "")
for (i=1; i <= length(chars); i++){
if(chars[i] == "}")
braces--
if(chars[i] == "\\")
i++
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment