[TxMt] LaTeX Tidy command

Eric Hsu erichsu at math.sfsu.edu
Thu Jan 6 05:46:03 UTC 2005


Here is a little command I've written (as usual, a wrapper around a 
Perl script), which naively tries to indent your LaTeX file 
intelligently. If it succeeds, there are two good side effects. 
First, your file looks nicer. Second, your file foldings work 
correctly, as TM is cued by the indentation.

Good luck. Check the file, if you use it. It works for me, your 
mileage may vary.

I've appended the one-liner version. Since it is a blob of line 
noise, I also have a link to the latest version of the uncompressed 
Perl, which is at 
<http://anon:anon@macromates.com/svn/Bundles/trunk/Latex.tmbundle/LaTeXTidy.pl> 
You can put that somewhere and write a command to call it instead.

I suspect anyone with issues with the folding could customize this 
script for their language if necessary. I know PerlTidy and HTMLTidy 
exist. I couldn't find a TeXTidy, so I wrote this last year...

- Eric

--

Before: Nothing
STDIN: Entire
STDOUT: Replace doc

Command:

perl -e 'my$in;while(<STDIN>){$in.=$_;}my at keywords=qw(  appendix 
author  bibliography  bigskip  chapter  date  def  document 
evensidemargin  font  headheight  headsep  include  index  make  new 
noindent  oddsidemargin  page  paragraph  part  ragged  renew 
section  subsection  subsubsection  subsubsubsection  table 
textheight  textwidth  title  topmargin  use 
vfil);$in=~s/\%(.*?)\n/\n\n\%$1\n\n/g;my at pieces=split(/\n\s*\n/,$in);my$string,$keyword;foreach(@pieces){if(/^\s*\%/){$string.=$_."\n";next;}s/\s+/ 
/g;foreach$keyword(@keywords){s/(\\$keyword)/\n$1/g;}s/([^\\]\%)/\n$1/g;s/(\\begin\{)(.*?)(\})/\n$1$2$3\n/g;s/(\\end\{)(.*?)(\})/\n$1$2$3\n/g;s/(\\item)(.*?)(\\item)/$1$2\n$3/g;s/(\\item)/\n$1/g;s/[^\\](\\\[)/\n$1/g;s/(\\\])/$1\n/g;s/(\\\\)\s/$1\n/g;s/(\\\\\[)(.*?)(\])\s/$1$2$3\n/g;s/\n\s*\n/\n/g;s/^\n//;chomp;$string.=$_."\n\n";}$string=~s/\n\s+\n/\n\n/g;$string=~s/(\%[^\n]*)(\\)(end)/$1$2\{\n\n\n\}$3/g;$string=~s/(\%[^\n]*)(\\)(begin)/$1$2\{\n\n\n\}$3/g;$string=~s/(\\end)/\[\n\n\n\]$1/g;$string=~s/(\\begin)/\[\n\n\n\]$1/g;@pieces=split(/\[\n\n\n\]/,$string);my$indent=1;my at lines;my$piece,$i;$string="";foreach$piece(@pieces){$piece=~s/\{\n\n\n\}//g;$piece=~/^\\(.*?)\{/;if(lc($1)eq"begin"){$indent++;}else{$indent--;}@lines=split(/\n/,$piece);foreach(@lines){s/^\s+//;if(/^\\begin/i){for($i=1;$i<=$indent-1;$i++){$string.="\t";}}else{for($i=1;$i<=$indent;$i++){$string.="\t";}}$string.=$_."\n";}}print$string;'



More information about the textmate mailing list