source: git/doc/doc2tex.pl @ 1edbcdd

spielwiese
Last change on this file since 1edbcdd was 012576, checked in by Hans Schönemann <hannes@…>, 14 years ago
support () in section names git-svn-id: file:///usr/local/Singular/svn/trunk@12698 2c84dea3-7e68-4137-9b89-c4e89433aadc
  • Property mode set to 100755
File size: 17.9 KB
Line 
1#!/usr/local/bin/perl
2# $Id$
3###################################################################
4#  Computer Algebra System SINGULAR
5#
6#  doc2tex: utility to generate the Singular manual
7#
8####
9# @c example [error] [no_comp] [unix_only]
10#    -> the text till the next @c example is feed into Singular,
11#       the text is then substituted by
12#       @c computed example $ex_prefix $doc_file:$line
13#       <text from the input>
14#       @expansion{} <corresponding output>
15#       ....
16#       @c end computed example $ex_prefix $doc_file:$line
17#       reuse computed examples if ($reuse && -r $ex_prefix.inc)
18#       cut absolute directory names from the loaded messages
19#       substituted @,{ and } by @@, @{ resp. @}
20#       wrap around output lines  longer than $ex_length = 73;
21#       Processing is aborted if error occures in Singular run,
22#       unless 'error' is specified
23#       if no_comp is given, then computation is not run
24#       if unix_only is given, then computation is only run
25#                              under unix
26#       
27#
28####
29# @c include file
30#    -> copy content of file into output file protecting texi special chars
31#
32####
33# @c ref
34# ....
35# @c ref
36#    -> scans intermediate lines for @ref{..} strings
37#    Creates menu of (sorted) refs for ifinfo
38#    Creates comma-separated (sorted) refs for iftex, prepended with
39#    the text before first @ref.
40#
41####
42# @c lib libname.lib[:proc] [no_ex, no_fun, Fun, (\w*)section]
43#   --> replaced by @include $texfile where
44#        $texfile = $subdir/libname_lib[_noFun,_noEx].tex
45#   --> if $make, calls "make $texfile"
46#   --> Error, if $tex_file does not exist
47#   --> if [:proc] is given, then includes only of respective
48#       proc body
49#   --> Fun overwrites global no_fun
50#   --> if (\w*)section is given, replaces @subsubsection by @$1section
51#       and pastes in content of tex file directly
52#
53#
54###################################################################
55
56use Config;
57$Win32 = 1 if ($Config{osname} =~ /win/i);
58
59#
60# default settings of command-line arguments
61#
62$Singular = "../Singular/Singular"; # should be overwritten
63$Singular_opts = " -teqr12345678 --no-rc";
64$clean = 0;
65$verbose = 1;
66$reuse = 1;
67$no_ex = 0;
68%exclude_ex = ();
69$no_fun = 0;
70$doc_subdir = "./d2t_singular";
71$ex_subdir = "./examples";
72@include_dirs = (".", "../Singular/LIB");
73$make = 0;
74$make_opts = " --no-print-directory";
75
76
77#
78# misc. defaults
79#
80$ex_length = 73;
81$ERROR = "\n**** Error:";
82$WARNING = "\n** Warning:";
83
84#
85# flush stdout and stderr after every write
86#
87select(STDERR);
88$| = 1;
89select(STDOUT);
90$| = 1;
91
92#
93# get file to convert
94#
95$doc_file = pop(@ARGV);
96if ($doc_file =~  /(.+)\..*$/)
97{
98  die "*** Error: Need .doc file as input\n" . &Usage 
99    unless ($doc_file =~ /(.+)\.doc$/);
100}
101else
102{
103  if ($doc_file =~ /^-h(elp)?$/) { print &Usage; exit;}
104  $doc_file .= ".doc";
105}
106
107#
108# parse command line options
109#
110$args = join(" ", @ARGV);
111while (@ARGV && $ARGV[0] =~ /^-/) 
112{
113  $_ = shift(@ARGV);
114  if (/^-S(ingular)?$/)  { $Singular = shift(@ARGV); next;}
115  if (/^-o(utput)?$/)    { $tex_file = shift(@ARGV); next;}
116  if (/^-no_r(euse)?$/)  { $reuse = 0; next;}
117  if (/^-c(lean)?$/)     { $clean = 1; next;}
118  if (/^-no_e(x)?$/)     { $no_ex = 1; next;}
119  if (/^-exclude$/)      { $exclude_ex{shift(@ARGV)} = 1;next;}
120  if (/^-no_fu(n)?$/)    { $no_fun = 1;next;}
121  if (/^-m(ake)?$/)      { $make =  shift(@ARGV);next;}
122  if (/^-d(ocdir)?$/)    { $doc_subdir = shift(@ARGV); next;}
123  if (/^-e(xdir)?$/)     { $ex_subdir = shift(@ARGV); next;}
124  if (/^-I$/)            { unshift(@include_dirs, shift(@ARGV)); next;}
125  if (/^-v(erbose)?$/)   { $verbose = shift(@ARGV); next;}
126  if (/^-h(elp)?$/)      { print &Usage; exit;}
127  Error("Unknown Option $_\n" .&Usage);
128}
129$verbose = ($verbose < 0 ? 0 : $verbose);
130$make_opts .= " -s" unless $verbose > 1;
131
132#
133# construct filenames
134#
135($doc_dir = $doc_file) =~ s/(.+)\.doc$/$1/;
136if ($doc_dir =~ /(.*)\//)
137{
138  $doc = $';
139  $doc_dir = $1;
140}
141else
142{
143  $doc = $doc_dir;
144  $doc_dir = ".";
145}
146unless ($tex_file)
147{
148  $tex_file = ($no_ex ? "$doc_dir/${doc}_noEx.tex" : "$doc_dir/$doc.tex");
149}
150
151#
152# open files
153#
154open(DOC, "<$doc_file") 
155  || Error("can't open $doc_file for reading: $!\n" . &Usage);
156open(TEX, ">$tex_file") || Error("can't open $tex_file for writing: $!\n");
157print "(d2t $doc_file==>$tex_file" if ($verbose);
158if (-d $doc_subdir)
159{
160  print "<docdir:$doc_subdir>"  if ($verbose > 1);
161}
162else
163{
164  mkdir($doc_subdir, oct(755)) 
165    || Error("can't create directory $doc_subdir: $!\n");
166  print "(docdir:$doc_subdir)"  if ($verbose > 1);
167}
168if (-d $ex_subdir)
169{
170  print "<exdir:$ex_subdir>"  if ($verbose > 1);
171}
172else
173{
174  mkdir($ex_subdir, oct(755)) 
175    || Error("can't create directory $ex_subdir: $!\n");
176  print "(exdir:$ex_subdir)"  if ($verbose > 1);
177}
178
179#######################################################################
180#
181# go !
182#
183while (<DOC>)
184{
185  $line++;
186  if (/^\@c\s*example/)     {&HandleExample; next;}
187  if (/^\@c\s*include\s+/)  {&HandleInclude; next;}
188  if (/^\@c\s*ref\s*$/)     {&HandleRef; next;}
189  if (/^\@c\s*lib\s+/)      {&HandleLib; next;}
190  if (/^\@setfilename/)     {print TEX "\@setfilename $doc.hlp\n"; next;}
191
192  if (/^\@\w*section\s*/ || /^\@\w*chapter\s*/ || /^\@\w*heading\s*/)
193  {
194    $section = $';
195    $section =~ s/^\s*(.*)\s*$/$1/;
196    if ($section =~ /\(/)
197    {
198      $section =~ s/\(/_/g
199    }
200    if ($section =~ /\)/)
201    {
202      $section =~ s/\)/_/g
203    }
204    if ($section =~ /\w/)
205    {
206      $section =~ s/\s/_/g
207    }
208    else
209    {
210      $section = "unknown";
211    }
212  }
213
214  # handle math
215  $in_info = 1 if /^\@ifinfo/;
216  $in_info = 0 if /^\@end\s*ifinfo/;
217  s[\@math\{(.*?)\}][&HandleMath($1)]eg unless $in_info;
218
219  print TEX $_;
220
221  if (! $printed_header && /^\@c/) 
222  {
223    $printed_header = 1;
224    print TEX <<EOT;
225\@comment This file was generated by doc2tex.pl from $doc_file
226\@comment DO NOT EDIT DIRECTLY, BUT EDIT $doc_file INSTEAD
227EOT
228  }
229
230  if (/^\@bye$/)            {last;}
231}
232
233#
234# wrap up
235#
236close(TEX);
237print "==>$tex_file)\n" if ($verbose);
238
239sub HandleMath
240{
241  my $what = shift;
242  return <<EOT;
243
244\@ifinfo
245\@math{$what}
246\@end ifinfo
247\@tex
248\$$what\$
249\@end tex
250EOT
251}
252
253######################################################################
254# @c example [error] [no_comp] [unix_only]
255#    -> the text till the next @c example is fed into Singular,
256#       the text is then substituted by
257#       @c computed example $ex_prefix $doc_file:$line
258#       <text from the input>
259#       @expansion{} <corresponding output>
260#       ....
261#       @c end computed example $ex_prefix $doc_file:$line
262#       reuse computed examples if ($reuse && -r $ex_prefix.inc)
263#       cut absolute directory names from the loaded messages
264#       substituted @,{ and } by @@, @{ resp. @}
265#       wrap around output lines  longer than $ex_length = 73;
266#       Processing is aborted if error occures in Singular run,
267#       unless 'error' is specified
268#       If [no_comp] is given, actual computation is not run
269#       if [unix_only] is given, then computation is only run
270#                                under unix
271
272sub HandleExample
273{
274  my($inc_file, $ex_file, $lline, $thisexample, $error_ok, $cache, $no_comp,
275     $unix_only, $tag);
276 
277  $lline = $line;
278  $section = 'unknown' unless $section;
279  $ex_prefix = $section;
280  $ex_prefix .= "_$examples{$section}" if $examples{$section};
281  $examples{$section}++;
282
283  if (/tag:(\w+)/)
284  {
285    $tag = $1;
286  }
287  else
288  {
289    $tag = 'NOTAG';
290  }
291 
292  if ($no_ex or $exclude_ex{$tag})
293  {
294    print "{$ex_prefix}" if ($verbose);
295    print TEX "\@c skipped computation of example $ex_prefix $doc_file:$lline \n";
296   
297  }
298  else
299  {
300    $inc_file = "$ex_subdir/$ex_prefix.inc";
301    $ex_file = "$ex_subdir/$ex_prefix.sing";
302    if (-r $inc_file && -r $ex_file && -s $inc_file && -s $ex_file)
303    {
304      $cache = 1;
305      open(SING, "<$ex_file") || ($cache = 0);
306    }
307  }
308
309  $thisexample = '';
310  $error_ok = 1 if /error/;
311  $no_comp = 1 if /no_comp/;
312  $unix_only = 1 if /unix_only/ && $Win32;
313 
314  # print content in example file till next @c example
315  print TEX "// only supported on Unix platforms\n"
316    if $unix_only;
317 
318  while (<DOC>)
319  {
320    $line++;
321    last if (/^\@c\s*example\s*$/);
322#    s/^\s*//; # remove preceeding white spaces
323    if ($no_ex || $exclude_ex{$tag} || $no_comp || $unix_only)
324    {
325      &protect_texi;
326      print TEX $_;
327    }
328    else
329    {
330      $thisexample .= $_;
331      if ($cache && $_ && $_ ne <SING>)
332      {
333        $cache = 0;
334        close(SING);
335      }
336    }
337  }
338  close(SING) if $cache;
339  Error("no matching '\@c example' found for $doc_file:$lline\n")
340    unless (/^\@c\s*example\s*$/);
341
342  # done, if no examples
343  return if ($no_ex || $exclude_ex{$tag} || $no_comp || $unix_only);
344
345  # check whether it can be reused
346  if ($reuse && $cache)
347  {
348    my $ok = 1;
349    print "<$ex_prefix>" if ($verbose);
350    print TEX "\@c reused example $ex_prefix $doc_file:$lline \n";
351    open(INC, "<$inc_file") || Error("can't open $inc_file for reading: $!\n");
352    while (<INC>)
353    {
354      if (/error occurred/ && $ok && !error_ok)
355      {
356        Warn("Result file $inc_file contains errors. Force re-computation by removing $inc_file");
357        $ok = 0;
358      }
359      print TEX $_;
360    }
361    close(INC);
362  }
363  else
364  {
365    print "($ex_prefix" if ($verbose == 1);
366    my ($res_file);
367    $res_file = "$ex_subdir/$ex_prefix.res";
368
369    print TEX "\@c computed example $ex_prefix $doc_file:$lline \n";
370
371    # run singular
372    open(EX, ">$ex_file") || Error("can't open $ex_file for writing: $!\n");
373    print EX "$thisexample";
374    close(EX);
375
376    unless ($Singular_OK)
377    {
378      if (system("echo '\$' | $Singular $Singular_opts > $res_file"))
379      {
380        $Singular .= '.exe' if ($Win32 && $Singular !~ /\.exe$/);
381        Error("CanŽt run '$Singular $Singular_opts': $@")
382          if (system("echo '\$' | $Singular $Singular_opts > $res_file"));
383      }
384      $Singular_OK = 1
385    }
386
387    &System("echo '\$' | $Singular $Singular_opts $ex_file > $res_file");
388    print ")" if ($verbose == 1);
389
390    open(RES, "<$res_file") || Error("can't open $res_file for reading: $!\n");
391    open(INC, ">$inc_file") || Error("can't open $inc_file for writing: $!\n");
392
393    # get result, manipulate it and put it into inc file
394    while (<RES>)
395    {
396      last if (/^STDIN\s*([0-9]+)..\$/);
397      # check for error
398      Error("while running example $ex_prefix from $doc_file:$lline.\nCall: '$Singular $Singular_opts $ex_file > $res_file'\n")
399        if (/error occurred/ && ! $error_ok);
400      # remove stuff from echo
401      if (/^$ex_file\s*([0-9]+)../)
402      {
403        $_ = $';
404        &protect_texi;
405      }
406      else
407      {
408        local($to_do, $done);
409        # remove absolute path names from laoded messages
410        s/^(\/\/ \*\* loaded )(.*)\/(.+).lib(.*)/$1$3.lib$4/;
411        # shorten error occurred in messages
412        s/\? error occurred in [^ ]* line/\? error occurred in line/;
413        # break after $ex_length characters
414        $to_do = $_;
415        while (length($to_do) > $ex_length && $to_do =~ /\w/ && 
416               substr($to_do, $ex_length) !~ /^\s*$/)
417        {
418         
419          $done .= substr($to_do, 0, $ex_length)."\\\n   ";
420          $to_do = substr($to_do, $ex_length);
421        }
422        $_ = $done.$to_do if($done);
423        &protect_texi;
424        $_ = "\@expansion{} ".$_;
425      }
426      print INC $_;
427      print TEX $_;
428    }
429    close(RES);
430    close(INC);
431    unlink $ex_file, $res_file, $inc_file if ($clean);
432  }
433  print TEX "\@c end example $ex_prefix $doc_file:$lline\n";
434}
435 
436######################################################################
437# @c include file
438#    -> copy content of file into output file protecting texi special chars
439sub HandleInclude
440{
441  s/^\@c\s*include\s+([^\s]+)\s/$1/;
442  s/\s*$//;
443  unless (&Open(*INC, "<$_"))
444  {
445    warn "$WARNING HandleInclude: can't open $_ for reading\n";
446    print TEX "\@c include file $_ not found\n";
447    return;
448  }
449  print "<$_>" if ($verbose);
450  print TEX "\@c begin included file $_ from $doc_file:$line\n";
451  while (<INC>)
452  {
453    &protect_texi;
454    print TEX $_;
455  }
456  print TEX "\@c end included file from $doc_file:$line\n";
457  close (INC);
458}
459
460######################################################################
461# @c ref
462# ....
463# @c ref
464#    -> scans intermediate lines for @ref{..} strings
465#    Creates menu of (sorted) refs for ifinfo
466#    Creates comma-separated (sorted) refs for iftex, prepended with
467#    the text before first @ref.
468
469sub HandleRef
470{
471  local(%refs, @refs, $header, $lline, $lref);
472 
473  print TEX "\@c inserted refs from $doc_file:$line\n";
474 
475  # scan lines use %ref to remove duplicates
476  $lline = $line;
477  while (<DOC>)
478  {
479    $line++;
480    last if (/^\@c\s*ref\s*$/);
481   
482    while (/\@ref{(.*?)}[;\.]/)
483    {
484      $refs{$1} = 1;
485      $_ = $';
486      unless ($header)
487      {
488        $header = $`;
489        $header = " " unless ($header);
490      }
491    }
492    $header = $_ unless ($header)
493  }
494  chomp $header;
495  die "$ERRROR no matching \@c ref found for $doc_file:$lline\n" 
496    unless (/^\@c\s*ref\s*$/);
497  # sort refs
498  @refs = sort(keys(%refs));
499  # put them out
500  print TEX "\@ifinfo\n";
501  print TEX "\@menu\n";
502  if ($header && $header ne " ")
503  {
504    print TEX "$header\n";
505  }
506  else
507  {
508    print TEX "See also:\n";
509  }
510  foreach $ref (@refs) {print TEX "* ".$ref."::\n";}
511  print TEX "\@end menu\n\@end ifinfo\n\@iftex\n";
512
513  if ($header ne " ")
514  {
515    print TEX "$header\n" unless ($header eq " ");
516  }
517  else
518  {
519    print TEX "\@strong{See also:}\n";
520  }
521  $lref = pop(@refs);
522  foreach $ref (@refs) {print TEX "\@ref{".$ref."};\n";}
523  print TEX "\@ref{".$lref."}.\n" if ($lref); 
524  print TEX "\@end iftex\n\@c end inserted refs from $doc_file:$lline\n";
525}
526
527###################################################################
528#
529# @c lib libname.lib[:proc] [no_ex, no_fun, Fun, (\w*)section]
530#   --> replaced by @include $texfile where
531#        $texfile = $subdir/libname_lib[_noFun,_noEx].tex
532#   --> if $make, calls "make $texfile"
533#   --> Error, if $tex_file does not exist
534#   --> if [:proc] is given, then includes only of respective
535#       proc body
536#   --> Fun overwrites global no_fun
537#   --> if (\w*)section is given, replaces @subsubsection by @$1section
538#       and pastes in content of tex file directly
539
540sub HandleLib
541{
542  my($lib, $proc, $n_fun, $n_ex, $section, $tex_file);
543
544  if (/^\@c\s*lib\s+([^\.]+)\.lib(.*)/)
545  {
546    $lib = $1;
547    $_ = $2;
548  }
549  else
550  {
551    warn "$WARNING need .lib file to process '$_'\n";
552    print TEX $_;
553    return;
554  }
555
556  $proc = $1 if (/^:(.*?) /);
557  $n_fun = 1 if ($no_fun || /no_fun/);
558  $n_fun = 0 if (/Fun/);
559  $n_ex = 1 if ($no_ex || /no_ex/ || (/unix_only/ && $Win32));
560  $section = $1 if /(\w*)section/;
561 
562  # contruct tex file name
563  $tex_file = "$doc_subdir/$lib"."_lib";
564  if ($n_fun)
565  {
566    $tex_file .= "_noFun";
567  }
568  elsif ($n_ex)
569  {
570    $tex_file .= "_noEx";
571  }
572  $tex_file .= ".tex";
573
574  if ($make)
575  {
576    print "<lib $lib " if ($verbose);
577    System("$make $make_opts VERBOSE=$verbose $tex_file"); 
578  }
579 
580  # make sure file exists
581  if (-r $tex_file)
582  {
583    if ($verbose)
584    {
585      print "<lib $lib " unless $make;
586      print "$proc>";
587    }
588  }
589  else
590  {
591    Error("Can't read $tex_file\n") unless -r $tex_file;
592  }
593
594  # see whether we have to paste something in
595  if ($proc || $section)
596  {
597    open(LTEX, "<$tex_file") 
598      || Error("Can't open $tex_file for reading: $!\n");
599
600    print TEX "\@c start include of docu for $lib.lib:$proc\n";
601    print TEX "\@c replaced \@subsubsection by \@$section\n" if ($section);
602    if ($proc)
603    {
604      my $found = 0;
605      while (<LTEX>)
606      {
607        $found = 1 if /c ---content $proc---/;
608        if ($found)
609        {
610          s/subsubsection/${section}section/ if $section;
611          print TEX $_; 
612        }
613        last if $found && /c ---end content $proc---/;
614      }
615      if ($found)
616      {
617        Error("no end content found for lib proc docu for $lib.lib:$proc $doc_file:$line in $tex_file\n")
618          unless (/c ---end content $proc---/);
619        print TEX "\@c generated lib proc docu for $lib.lib:$proc $doc_file:$line \n";
620      }
621      else
622      {
623        Error("did not find lib proc docu for $lib.lib:$proc $doc_file:$line in $tex_file\n");
624      }
625    }
626    else
627    {
628      while (<LTEX>)
629      {
630        s/subsubsection/${section}section/;
631        print TEX $_;
632      }
633    }
634    print TEX "\@c end include of docu for $lib.lib:$proc\n";
635    close(LTEX);
636  }
637  else
638  {
639    print TEX "\@c include of docu for $lib.lib\n";
640    print TEX "\@include $tex_file\n";
641  }
642}
643
644####################################################################
645# Auxillary routines
646#
647
648# protect texi special characters
649sub protect_texi
650{
651  s/\@/\@\@/g;
652  s/{/\@{/g;
653  s/}/\@}/g;
654}       
655
656# open w.r.t. include_dirs
657sub Open
658{
659  local(*FH, $file) = @_;
660  local($mode);
661  $file =~ s/^(.{1})(.*)/$2/;
662  $mode = $1;
663
664  foreach $dir (@include_dirs)
665  {
666    return $dir if(open(FH, $mode.$dir."/".$file));
667  }
668}
669   
670# system call with echo on verbose > 1 and die on fail
671sub System
672{
673  local($call) = @_;
674  print " d2t system:\n$call\n" if ($verbose > 1);
675  Error("non-zero exit status of system call: '$call': $!\n")
676    if (system($call));
677}
678
679sub Error
680{
681  print "$ERROR $_[0]";
682  close(TEX);
683  unlink $tex_file if $tex_file && -e $tex_file;
684  exit(1);
685}
686
687sub Warn
688{
689  print "$WARNING $_[0]\n";
690}
691#
692# leave this here --otherwise fontification in my emacs gets screwd up
693#
694sub Usage
695{
696  return <<EOT;
697This is doc2tex: a utility to generate Singular texinfo from doc file
698To convert a doc file to texinfo: $0 [options] input_file.doc
699where options can be (abbreviated to shortest possible prefix):
700  -Singular prog: use 'prog' as Singular program to generate ex output
701                          (default: '../Singular/Singular')
702  -output file  : use 'file' as output file
703                          (default: input_file.tex)
704  -clean        : delete intermediate files
705  -make  cmd    : use cmd as make command to generate tex files for libraries
706  -no_reuse     : don't reuse intermediate files
707  -no_ex        : skip computation of examples
708  -no_fun       : don't include help for library functions
709  -docdir  dir  : put intermediate doc/tex files into 'dir'
710                          (default: './d2t_singular')
711  -exdir   dir  : put example files into 'dir'
712                          (default: './examples')
713  -I dir        : look also into 'dir' for include  and lib files
714                          (default: ".", "../Singular/LIB")
715  -verbose  val : Set verbosity to 'val' (0=quiet, 1=prot, >1=all)
716  -help         : print help and exit
717EOT
718}
719
Note: See TracBrowser for help on using the repository browser.