summaryrefslogtreecommitdiff
path: root/scripts
diff options
context:
space:
mode:
authorHans Hagen <pragma@wxs.nl>2004-06-10 00:00:00 +0200
committerHans Hagen <pragma@wxs.nl>2004-06-10 00:00:00 +0200
commit51d573f4c0e8d3b8499bff7a3c6fba3dcd71d725 (patch)
treea902c3c67fe2272ee9e2325d6a6f28f0fd15d9d8 /scripts
parentab3f887feadf929129087cd2cbc3783064507565 (diff)
downloadcontext-51d573f4c0e8d3b8499bff7a3c6fba3dcd71d725.tar.gz
stable 2004.06.10
Diffstat (limited to 'scripts')
-rw-r--r--scripts/context/perl/cont_set.pm498
-rw-r--r--scripts/context/perl/mptopdf.pl94
-rw-r--r--scripts/context/perl/texexec.pl638
-rw-r--r--scripts/context/perl/texexec.rme28
-rw-r--r--scripts/context/perl/texfont.pl120
-rw-r--r--scripts/context/perl/texshow.pl2
-rw-r--r--scripts/context/perl/texutil.pl22
-rw-r--r--scripts/context/ruby/concheck.rb459
-rw-r--r--scripts/context/ruby/exa/logger.rb104
-rw-r--r--scripts/context/ruby/texmfstart.rb483
-rw-r--r--scripts/context/ruby/texsync.rb200
-rw-r--r--scripts/context/ruby/textools.rb666
-rw-r--r--scripts/context/ruby/xmltools.rb346
-rw-r--r--scripts/context/ruby/xmpl/switch.rb473
14 files changed, 3608 insertions, 525 deletions
diff --git a/scripts/context/perl/cont_set.pm b/scripts/context/perl/cont_set.pm
index 9c6d2cbcd..c14cc679c 100644
--- a/scripts/context/perl/cont_set.pm
+++ b/scripts/context/perl/cont_set.pm
@@ -1,7 +1,7 @@
#D \module
#D [ file=cont\_set.pm,
#D version=1999.04.01,
-#D title=General modules,
+#D title=General modules,
#D subtitle=showing \CONTEXT\ commands,
#D author=Hans Hagen,
#D date=\currentdate,
@@ -9,187 +9,187 @@
#D suggestions={Tobias Burnus \& Taco Hoekater}]
#C
#C This module is part of the \CONTEXT\ macro||package and is
-#C therefore copyrighted by \PRAGMA. See licen-en.pdf for
-#C details.
+#C therefore copyrighted by \PRAGMA. See licen-en.pdf for
+#C details.
-# todo: tacos speed patch
+# todo: tacos speed patch
-#D As always: thanks to Taco and Tobias for testing this
-#D module and providing suggestions and code snippets as
-#D well as haunting bugs.
+#D As always: thanks to Taco and Tobias for testing this
+#D module and providing suggestions and code snippets as
+#D well as haunting bugs.
-package cont_set ;
+package cont_set ;
#D This module (package) deals with providing help information
#D about the \CONTEXT\ commands. The data needed is derived
#D from the setup files by \CONTEXT\ itself. The data is
-#D stored in files with suffix \type {tws} (tex work setup).
-#D This module introduces some subroutines:
-#D
+#D stored in files with suffix \type {tws} (tex work setup).
+#D This module introduces some subroutines:
+#D
#D \starttabulatie[|Tl|p|]
-#D \NC \type {set\_setup\_interface} \NC sets the primary interface
-#D to search in \NC \NR
-#D \NC \type {set\_setup\_title} \NC sets the title of the main
-#D window title \NC \NR
-#D \NC \type {setups\_found} \NC locate the \type {tws} files
-#D using the \type {kpsewhich}
-#D program \NC \NR
-#D \NC \type {show\_setups} \NC allocate the radio buttons
-#D that can be used to select a
-#D command set \NC \NR
-#D \NC \type {load\_setup(filename)} \NC load the names \type {tws}
-#D file \NC \NR
-#D \NC \type {load\_setups} \NC all found command files can
-#D be loaded at once \NC \NR
-#D \NC \type {setup\_found(filename)} \NC this routine returns~1 when
-#D the file is loaded \NC \NR
-#D \NC \type {update\_setup} \NC when we browse the list with
-#D commands, this routine takes care
-#D of updating the text area \NC \NR
-#D \NC \type {change\_setup} \NC we can manually set the
-#D command set we want to browse,
-#D and this routine takes care of
-#D this \NC \NR
-#D \NC \type {show\_setup(command)} \NC context sensitive help can be
+#D \NC \type {set\_setup\_interface} \NC sets the primary interface
+#D to search in \NC \NR
+#D \NC \type {set\_setup\_title} \NC sets the title of the main
+#D window title \NC \NR
+#D \NC \type {setups\_found} \NC locate the \type {tws} files
+#D using the \type {kpsewhich}
+#D program \NC \NR
+#D \NC \type {show\_setups} \NC allocate the radio buttons
+#D that can be used to select a
+#D command set \NC \NR
+#D \NC \type {load\_setup(filename)} \NC load the names \type {tws}
+#D file \NC \NR
+#D \NC \type {load\_setups} \NC all found command files can
+#D be loaded at once \NC \NR
+#D \NC \type {setup\_found(filename)} \NC this routine returns~1 when
+#D the file is loaded \NC \NR
+#D \NC \type {update\_setup} \NC when we browse the list with
+#D commands, this routine takes care
+#D of updating the text area \NC \NR
+#D \NC \type {change\_setup} \NC we can manually set the
+#D command set we want to browse,
+#D and this routine takes care of
+#D this \NC \NR
+#D \NC \type {show\_setup(command)} \NC context sensitive help can be
#D provided by calling this sub \NC \NR
#D \stoptabulatie
-#D
-#D First we load some packages and set some constants.
+#D
+#D First we load some packages and set some constants.
use Tk ;
use Tk::ROText ;
-use Config ;
+use Config ;
use strict;
use subs qw/ update_setup / ;
my $dosish = ($Config{'osname'} =~ /dos|win/i) ;
-my $default_size = $dosish ? 9 : 12 ;
+my $default_size = $dosish ? 9 : 12 ;
my $textfont = "Courier $default_size " ;
my $userfont = "Courier $default_size italic" ;
my $buttonfont = "Helvetica $default_size bold " ;
-unless ($dosish)
+unless ($dosish)
{ $textfont = "-adobe-courier-bold-r-normal--$default_size-120-75-75-m-70-iso8859-1" ;
$userfont = "-adobe-courier-bold-o-normal--$default_size-120-75-75-m-70-iso8859-1" ;
$buttonfont = "-adobe-helvetica-bold-r-normal--$default_size-120-75-75-p-69-iso8859-1" }
-
-my $s_vertical = 30 ;
-my $s_horizontal = 72 ;
-my $c_horizontal = 24 ;
-#D The main window is not resizable, but the text area and
-#D command list will have scrollbars.
+my $s_vertical = 30 ;
+my $s_horizontal = 72 ;
+my $c_horizontal = 24 ;
+
+#D The main window is not resizable, but the text area and
+#D command list will have scrollbars.
-my %lw ; # stack of lists
+my %lw ; # stack of lists
my $mw = MainWindow -> new ( -title => 'ConTeXt commands' ) ;
-$mw -> withdraw() ; $mw -> resizable ('y', 'y') ;
+$mw -> withdraw() ; $mw -> resizable ('y', 'y') ;
-sub SetupWindow { return $mw } ;
+sub SetupWindow { return $mw } ;
-my $bw = $mw -> Frame () ; # buttons
-my $tw = $mw -> Frame () ; # sw + fw
-my $fw = $tw -> Frame () ; # string + list
+my $bw = $mw -> Frame () ; # buttons
+my $tw = $mw -> Frame () ; # sw + fw
+my $fw = $tw -> Frame () ; # string + list
-my $request = $fw -> Entry ( -font => $textfont ,
+my $request = $fw -> Entry ( -font => $textfont ,
-background => 'ivory1' ,
- -width => $c_horizontal ) ;
+ -width => $c_horizontal ) ;
my $cw = $fw -> Scrolled ( 'Listbox' ,
-scrollbars => 'e' ,
-font => $textfont ,
- -width => $c_horizontal ,
+ -width => $c_horizontal ,
-selectbackground => 'gray' ,
-background => 'ivory1' ,
-selectmode => 'browse' ) ;
$cw -> pack ( -side => 'bottom' , -fill => 'both' , -expand => 1 ) ;
-$request -> pack ( -side => 'top' , -fill => 'x' ) ;
+$request -> pack ( -side => 'top' , -fill => 'x' ) ;
my $sw = $tw -> Scrolled ( 'ROText' ,
-scrollbars => 'se' ,
- -height => $s_vertical ,
- -width => $s_horizontal ,
+ -height => $s_vertical ,
+ -width => $s_horizontal ,
-wrap => 'none' ,
-background => 'ivory1' ,
-font => $textfont ) ;
-#D And the whole bunch of widgets are packed in the main
-#D window.
+#D And the whole bunch of widgets are packed in the main
+#D window.
-sub pack_them_all
+sub pack_them_all
{ $sw -> pack ( -side => 'left' , -fill => 'both' , -expand => 1 ) ;
- $fw -> pack ( -side => 'right' , -fill => 'y' , -expand => 0 ) ;
+ $fw -> pack ( -side => 'right' , -fill => 'y' , -expand => 0 ) ;
$bw -> pack ( -side => 'top' , -fill => 'x' , -anchor => 'w' , -expand => 1 ) ;
$tw -> pack ( -side => 'bottom', -fill => 'both' , -expand => 1 ) }
-sub unpack_them_all
+sub unpack_them_all
{ }
-pack_them_all ;
+pack_them_all ;
#D We scan for available setup files, with suffix \type {tws}.
#D These should be somewhere on the system, grouped in one
#D directory. At least the english file \type {cont-en.tws}
-#D should be found.
+#D should be found.
-my $tws_path = '' ;
-my @setup_files = ('cont-en.tws') ;
-my $setup_file = $setup_files[0] ;
-my $setup_interface = 'en' ;
+my $tws_path = '' ;
+my @setup_files = ('cont-en.tws') ;
+my $setup_file = $setup_files[0] ;
+my $setup_interface = 'en' ;
my $old_setup_file = '' ;
-sub set_setup_interface
- { $setup_interface = shift }
+sub set_setup_interface
+ { $setup_interface = shift }
-sub set_setup_title
+sub set_setup_title
{ $mw -> configure ( -title => shift ) }
-sub setups_found
- { $tws_path = `kpsewhich --format="other text files" --progname=context cont-en.tws` ;
- $tws_path =~ s/cont-en\.tws.*// ;
- chop $tws_path ;
- @setup_files = glob ("$tws_path*.tws") ;
- if (@setup_files)
- { foreach (@setup_files) { s/\.tws// ; s/.*\/// }
+sub setups_found
+ { $tws_path = `kpsewhich --format="other text files" --progname=context cont-en.tws` ;
+ $tws_path =~ s/cont-en\.tws.*// ;
+ chop $tws_path ;
+ @setup_files = glob ("$tws_path*.tws") ;
+ if (@setup_files)
+ { foreach (@setup_files) { s/\.tws// ; s/.*\/// }
$setup_file = $setup_files[0] ;
- return 1 }
- else
- { return 0 } }
+ return 1 }
+ else
+ { return 0 } }
-#D A hide button
+#D A hide button
sub show_hide_button
{ my $hb = $bw -> Button ( -text => "hide" ,
- -font => $buttonfont ,
- command => \&hide_widget ) ;
- $hb -> pack ( -padx => '2p',
- -pady => '2p',
- -side => 'right' ) }
+ -font => $buttonfont ,
+ -command => \&hide_widget ) ;
+ $hb -> pack ( -padx => '2p',
+ -pady => '2p',
+ -side => 'right' ) }
-sub hide_widget
- { $mw -> withdraw() }
+sub hide_widget
+ { $mw -> withdraw() }
-#D The setup files can be shown and chosen.
+#D The setup files can be shown and chosen.
-sub show_setups
- { unpack_them_all ;
+sub show_setups
+ { unpack_them_all ;
foreach (@setup_files)
- { $lw{$_} = $bw -> Radiobutton ( -text => lc $_ ,
- -value => $_ ,
- -font => $buttonfont ,
+ { $lw{$_} = $bw -> Radiobutton ( -text => lc $_ ,
+ -value => $_ ,
+ -font => $buttonfont ,
-selectcolor => 'ivory1' ,
- -indicatoron => 0 ,
+ -indicatoron => 0 ,
command => \&change_setup ,
-variable => \$setup_file ) ;
- $lw{$_} -> pack ( -padx => '2p',
- -pady => '2p',
- -side => 'left' ) }
+ $lw{$_} -> pack ( -padx => '2p',
+ -pady => '2p',
+ -side => 'left' ) }
pack_them_all }
$cw -> bind ('<B1-Motion>', \&update_setup ) ;
@@ -207,36 +207,36 @@ $sw -> tag ('configure', 'par' , -lmargin1 => '4m' ,
-lmargin2 => '6m' ) ;
my %setups ;
-my %commands ;
-my %loadedsetups ;
-my %positions ;
-my %crosslinks ;
+my %commands ;
+my %loadedsetups ;
+my %positions ;
+my %crosslinks ;
-my $current_setup = '' ;
+my $current_setup = '' ;
#D Setups are organized in files called \type {*.tws} and
#D alike. Several files can be loaded simultaneously. When
#D loading, we grab whole paragraphs. The variables and values
#D belonging to a command, are stored in the hash table \type
#D {setups}, one per language. The command templates are
-#D stored in \type {commands}.
-#D
+#D stored in \type {commands}.
+#D
#D A \type {tws} file is generated by \CONTEXT\ from the setup
#D definition files. Only \CONTEXT\ knows the current meaning
#D of commands and keywords. The files are generating by
-#D simply saying something like:
-#D
+#D simply saying something like:
+#D
+#D \starttypen
+#D texexec --interface=en setupd
+#D texexec --interface=de setupd
+#D texexec --interface=nl setupd
+#D texexec --interface=cz setupd
+#D texexec --interface=it setupd
+#D \stoptypen
+#D
+#D This results in files formatted as:
+#D
#D \starttypen
-#D texexec --interface=en setupd
-#D texexec --interface=de setupd
-#D texexec --interface=nl setupd
-#D texexec --interface=cz setupd
-#D texexec --interface=it setupd
-#D \stoptypen
-#D
-#D This results in files formatted as:
-#D
-#D \starttypen
#D startsetup
#D com:setupcolors
#D typ:vars/
@@ -249,22 +249,22 @@ my $current_setup = '' ;
#D \stoptypen
#D
#D This format can be stored rather efficient and parsed rather
-#D fast. What more do we need.
+#D fast. What more do we need.
-sub load_setup
- { my $filename = shift ;
+sub load_setup
+ { my $filename = shift ;
unless (keys %{$commands{$filename}})
{ local $/ = 'stopsetup' ; # in plaats van '' ivm unix ; (taco)
- $current_setup = '' ;
+ $current_setup = '' ;
if (open(SETUP, "$tws_path$filename.tws" ))
- { my $position = 0 ;
+ { my $position = 0 ;
while (<SETUP>)
{ chomp ;
s/startsetup//mso ;
- s/stopsetup//mso ; # redundant geworden
+ s/stopsetup//mso ; # redundant geworden
s/\r\n //gms ; # in plaats van s/ //gms ; (taco)
s/com\:(.*?)\:\s(.*)//mso ;
- my $string = $1 ;
+ my $string = $1 ;
my $command = $1 ;
my $setup = $2 ;
++$position ;
@@ -280,20 +280,20 @@ sub load_setup
$cw -> selectionSet ('0.0', '0.0') ;
$cw -> activate ('0.0') ;
$setup_file = $filename ;
- update_setup }
+ update_setup }
-sub load_setups
+sub load_setups
{ foreach my $setup (@setup_files) { load_setup ($setup) } ;
$mw -> deiconify() }
-#D The core of this module deals with transforming the
-#D definitions like shown earlier. Details on the format
-#D can be found in the file \type {setupd.tex}. We use the
-#D \type {Tk::Text} automatic hanging identation features.
-#D The next subs are examples of the kind you write once
+#D The core of this module deals with transforming the
+#D definitions like shown earlier. Details on the format
+#D can be found in the file \type {setupd.tex}. We use the
+#D \type {Tk::Text} automatic hanging identation features.
+#D The next subs are examples of the kind you write once
#D and never look at again.
-my @arguments = () ;
+my @arguments = () ;
my $nested_setup = 0 ;
my $continue_setup = 0 ;
my $argument = 0 ;
@@ -344,23 +344,23 @@ sub show_command
$stopsuffix = $2 } }
sub show_left_argument
- { local $_ = shift ;
+ { local $_ = shift ;
my @thearg = split (/\//, $arg{$arguments[$_]}) ;
$sw -> insert ('end', $thearg[1], ['par',$thearg[0]] ) }
sub show_middle_argument
- { local $_ = shift ;
+ { local $_ = shift ;
my @thearg = split (/\//, $arg{$arguments[$_]}) ;
if ($thearg[1])
- { $sw -> insert ('end', $thearg[2], 'par' ) }
+ { $sw -> insert ('end', $thearg[2], 'par' ) }
else
{ $sw -> insert ('end', $thearg[2], ['par',$thearg[0]] ) } }
sub show_right_argument
- { local $_ = shift ;
+ { local $_ = shift ;
my @thearg = split (/\//, $arg{$arguments[$_]}) ;
$sw -> insert ('end', $thearg[3], ['par',$thearg[0]] ) ;
- ++$argument }
+ ++$argument }
sub show_reference
{ if (($nested_setup<=1)&&(defined($arguments[$argument])))
@@ -371,7 +371,7 @@ sub show_reference
show_right_argument ($argument) } } }
sub show_stop_command
- { my $before_stop = shift ;
+ { my $before_stop = shift ;
if ($stopcommand)
{ if ($stopsuffix)
{ $sw -> insert ('end', '\\stop', 'command' ) ;
@@ -380,23 +380,23 @@ sub show_stop_command
{ $sw -> insert ('end', $stopcommand, 'command' ) } } }
sub show_whatever_left
- { while ($argument<@arguments)
+ { while ($argument<@arguments)
{ $sw -> insert ('end', "\n" ) ;
show_left_argument ($argument) ;
show_middle_argument ($argument) ;
- show_right_argument ($argument) ;
- ++$argument }
+ show_right_argument ($argument) ;
+ ++$argument }
if ($stopcommand)
{ $sw -> insert ('end', "\n...\n...\n...\n", 'par') ;
show_stop_command } }
-sub do_update_setup # type: 0=all 1=vars 2=vals
- { my ($command, $type) = @_ ;
+sub do_update_setup # type: 0=all 1=vars 2=vals
+ { my ($command, $type) = @_ ;
my $setup = $setups{$setup_file}{$command} ;
- my $default = '' ;
- my $key = '' ;
- my $meaning = '' ;
- my @values = () ;
+ my $default = '' ;
+ my $key = '' ;
+ my $meaning = '' ;
+ my @values = () ;
local $_ ;
++$nested_setup ;
while ($setup=~/(typ|var|val|ivr|ivl)\:(.*?)\:\s/mgo)
@@ -405,9 +405,9 @@ sub do_update_setup # type: 0=all 1=vars 2=vals
if (($key=~/var/o)&&($type!=2))
{ $_ = $meaning ; s/(.*?)\:(.*?)\:(.*)//o ;
if (($nested_setup>1)&&(!$2)) { next }
- $key = $1 ;
+ $key = $1 ;
if ($3) { $default = $3 } else { $default = '' }
- $_= $2 ; s/\s//go ; @values = split (/,/,$_) ;
+ $_= $2 ; s/\s//go ; @values = split (/,/,$_) ;
if ($continue_setup)
{ $sw -> insert ('end', ",\n ", 'par') }
else
@@ -419,8 +419,8 @@ sub do_update_setup # type: 0=all 1=vars 2=vals
#while (1)
while (@values)
{ my $value = shift @values ;
- if ($value =~ /^\*/o)
- { $value =~ s/^\*//o ;
+ if ($value =~ /^\*/o)
+ { $value =~ s/^\*//o ;
$sw -> insert ('end', lc $value, ['variable','par'] ) }
elsif ($value eq $default)
{ $sw -> insert ('end', $value, ['default','par'] ) }
@@ -442,10 +442,10 @@ sub do_update_setup # type: 0=all 1=vars 2=vals
show_left_argument($argument) ;
#while (1)
while (@values)
- { unless (@values) { last }
+ { unless (@values) { last }
my $value = shift (@values) ;
if ($value =~ /^\*/o)
- { $value =~ s/^\*//o ;
+ { $value =~ s/^\*//o ;
$sw -> insert ('end', lc $value, ['variable','par'] ) }
elsif ($value eq $default)
{ $sw -> insert ('end', $value, ['default','par'] ) }
@@ -467,13 +467,13 @@ sub do_update_setup # type: 0=all 1=vars 2=vals
$arguments =~ s/stp//go }
@arguments = split (/\//,$arguments) ;
if (@arguments)
- { for (my $i=0;$i<@arguments;$i++)
+ { for (my $i=0;$i<@arguments;$i++)
{ show_left_argument ($i) ;
show_middle_argument ($i) ;
show_right_argument ($i) }
- if ($stopcommand)
+ if ($stopcommand)
{ $sw -> insert ('end', ' ... ') ;
- show_stop_command }
+ show_stop_command }
$sw -> insert ('end', "\n\n") ;
show_command ($command) }
$argument = 0 ;
@@ -486,23 +486,23 @@ sub do_update_setup # type: 0=all 1=vars 2=vals
do_update_setup ($1,2) }
show_reference }
--$nested_setup ;
- if (($continue_setup)&&(!$nested_setup))
+ if (($continue_setup)&&(!$nested_setup))
{ show_right_argument ;
show_whatever_left } }
#D Now the real work is done, we only have to define a few
-#D housekeeping routines. The next sub adapts the text area
-#D to the current selected command and normally is bound to
-#D the list browsing commands.
+#D housekeeping routines. The next sub adapts the text area
+#D to the current selected command and normally is bound to
+#D the list browsing commands.
-sub update_setup
+sub update_setup
{ $old_setup_file = $setup_file ;
if (keys %{$commands{$setup_file}})
- { my $key ;
+ { my $key ;
unless ($cw->curselection)
- { $cw -> selectionSet('0.0','0.0') }
+ { $cw -> selectionSet('0.0','0.0') }
$key = $cw -> get($cw->curselection) ;
- if ($current_setup ne $key)
+ if ($current_setup ne $key)
{ $current_setup = $key ;
$sw -> delete ('1.0', 'end' ) ;
$nested_setup = 0 ;
@@ -510,58 +510,58 @@ sub update_setup
$stopcommand = '' ;
$stopsuffix = '' ;
do_update_setup ($key,0) ;
- $mw -> raise ;
+ $mw -> raise ;
$mw -> focus } } }
#D In editors we want to provide context sensitive help
#D information. The next sub first tries to locate the
#D commands asked for in the setup data currently selected,
-#D and when not found takes a look at all the loaded files.
-
-sub show_setup
+#D and when not found takes a look at all the loaded files.
+
+sub show_setup
{ my $asked_for = shift ;
- unless ($asked_for) { return }
- my $found = 0 ;
- $asked_for =~ s/^\\// ;
- if ($setup_interface)
- { $found = 0 ;
- foreach my $name (@setup_files)
- { if (($name=~/\-$setup_interface/)&&(exists($commands{$name}{$asked_for})))
- { $found = 1 ;
- $setup_file = $name ;
- last } } }
- if (!($found)&&(exists($commands{$setup_file}{$asked_for})))
- { $found = 1 }
- else
- { $found = 0 ;
- foreach my $name (@setup_files)
- { if (exists($commands{$name}{$asked_for}))
- { $found = 1 ;
- $setup_file = $name ;
- last } } }
- if ($found)
+ unless ($asked_for) { return }
+ my $found = 0 ;
+ $asked_for =~ s/^\\// ;
+ if ($setup_interface)
+ { $found = 0 ;
+ foreach my $name (@setup_files)
+ { if (($name=~/\-$setup_interface/)&&(exists($commands{$name}{$asked_for})))
+ { $found = 1 ;
+ $setup_file = $name ;
+ last } } }
+ if (!($found)&&(exists($commands{$setup_file}{$asked_for})))
+ { $found = 1 }
+ else
+ { $found = 0 ;
+ foreach my $name (@setup_files)
+ { if (exists($commands{$name}{$asked_for}))
+ { $found = 1 ;
+ $setup_file = $name ;
+ last } } }
+ if ($found)
{ my @list = sort {lc $a cmp lc $b} keys %{$commands{$setup_file}} ;
$cw -> delete ('0.0', 'end') ;
$cw -> insert ('end', @list) ;
- $found = 0 ;
- foreach (@list) { if ($_ eq $asked_for) { last } ++$found }
- my $index = "$found.0" ;
+ $found = 0 ;
+ foreach (@list) { if ($_ eq $asked_for) { last } ++$found }
+ my $index = "$found.0" ;
$cw -> selectionSet ($index, $index) ;
$cw -> activate ($index) ;
$cw -> see ($index) ;
update_setup ;
- $mw -> raise ;
- $mw -> focus } }
+ $mw -> raise ;
+ $mw -> focus } }
#D Whenever a new set of commands is selected (by means of the
#D buttons on top the screen) the list and text are to be
-#D updated.
+#D updated.
-sub change_setup
- { my $command = '' ;
+sub change_setup
+ { my $command = '' ;
if ($old_setup_file)
{ unless ($cw->curselection)
- { $cw -> selectionSet('0.0','0.0') }
+ { $cw -> selectionSet('0.0','0.0') }
$command = $cw -> get($cw->curselection) ;
my $position = $positions{$old_setup_file}{$command} ;
$command = $crosslinks{$setup_file}[$position] }
@@ -569,102 +569,102 @@ sub change_setup
my @list = sort {lc $a cmp lc $b} keys %{$commands{$setup_file}} ;
$cw -> delete ('0.0', 'end') ;
$cw -> insert ('end', @list) ;
- if ($command)
- { show_setup($command) }
- else
- { $cw -> selectionClear ('0.0','end') ;
+ if ($command)
+ { show_setup($command) }
+ else
+ { $cw -> selectionClear ('0.0','end') ;
$cw -> selectionSet ('0.0', '0.0') ;
$cw -> see ('0.0') ;
$cw -> activate ('0.0') }
update_setup ;
- $mw -> raise ;
+ $mw -> raise ;
$mw -> focus }
#D Sometimes we want to make sure the dat is loaded indeed:
sub setup_found
- { my $filename = shift ;
- if (-e "$tws_path$filename.tws")
- { $setup_file = $filename ;
- return 1 }
- else
+ { my $filename = shift ;
+ if (-e "$tws_path$filename.tws")
+ { $setup_file = $filename ;
+ return 1 }
+ else
{ return 0 } }
-#D The next feature is dedicated to Tobias, who suggested
-#D it, and Taco, who saw it as yet another proof of the
-#D speed of \PERL. It's also dedicated to Ton, who needs it
-#D for translating the big manual.
+#D The next feature is dedicated to Tobias, who suggested
+#D it, and Taco, who saw it as yet another proof of the
+#D speed of \PERL. It's also dedicated to Ton, who needs it
+#D for translating the big manual.
-sub handle_request
+sub handle_request
{ my $index = $cw -> index('end') ;
- unless ($index) { return }
- my $req = $request -> get ;
- unless ($req) { return }
- $req =~ s/\\//o ;
- $req =~ s/\s//go ;
- $request -> delete('0','end') ;
- $request -> insert('0',$req) ;
- unless ($req) { return }
- my ($l,$c) = split (/\./,$index) ;
+ unless ($index) { return }
+ my $req = $request -> get ;
+ unless ($req) { return }
+ $req =~ s/\\//o ;
+ $req =~ s/\s//go ;
+ $request -> delete('0','end') ;
+ $request -> insert('0',$req) ;
+ unless ($req) { return }
+ my ($l,$c) = split (/\./,$index) ;
for (my $i=0;$i<=$l;$i++)
- { $index = "$i.0" ;
- my $str = $cw -> get ($index, $index) ;
- if ($str =~ /^$req/)
- { $cw -> selectionClear ('0.0','end') ;
- $cw -> selectionSet ($index, $index) ;
+ { $index = "$i.0" ;
+ my $str = $cw -> get ($index, $index) ;
+ if ($str =~ /^$req/)
+ { $cw -> selectionClear ('0.0','end') ;
+ $cw -> selectionSet ($index, $index) ;
$cw -> activate ($index) ;
$cw -> see ($index) ;
- update_setup ;
- $mw -> raise ;
+ update_setup ;
+ $mw -> raise ;
$mw -> focus ;
- return } } }
+ return } } }
$request -> bind ('<Return>', sub { handle_request } ) ;
-sub insert_request
+sub insert_request
{ my ($self, $chr) = @_ ;
- if ($self ne $request)
+ if ($self ne $request)
{ $request -> insert ('end', $chr) }
- handle_request }
+ handle_request }
foreach my $chr ('a'..'z','A'..'Z')
- { $mw -> bind ( "<KeyPress-$chr>", sub { insert_request(shift, $chr) } ) }
+ { $mw -> bind ( "<KeyPress-$chr>", sub { insert_request(shift, $chr) } ) }
$mw -> bind ( "<backslash>", sub { insert_request(shift, "\\") } ) ;
sub delete_request
{ my $self = shift ;
- if ($self ne $request)
- { my $to = $request -> index ('end') ;
+ if ($self ne $request)
+ { my $to = $request -> index ('end') ;
my $from = $to - 1 ;
if ($from<0) { $from = 0 }
$request -> delete ($from,$to) }
- handle_request }
+ handle_request }
$mw -> bind ( "<BackSpace>", sub { delete_request } ) ;
-sub new_request
+sub new_request
{ $request -> delete (0,'end') ;
handle_request }
$mw -> bind ( "<space>", sub { new_request } ) ;
-#D Just in case:
+#D Just in case:
-sub raise_setup
+sub raise_setup
{ $mw -> raise }
-sub dont_exit
- { $mw -> protocol( 'WM_DELETE_WINDOW' => sub { } ) }
+sub dont_exit
+ { $mw -> protocol( 'WM_DELETE_WINDOW' => sub { } ) }
-#D An example use is:
+#D An example use is:
#D
-#D \starttypen
-#D load_setup ("cont-$nl") ;
-#D show_setup ('omlijnd') ;
+#D \starttypen
+#D load_setup ("cont-$nl") ;
+#D show_setup ('omlijnd') ;
#D MainLoop () ;
-#D \stoptypen
+#D \stoptypen
#D
-#D Now everything is done, we return 1:
+#D Now everything is done, we return 1:
1 ;
diff --git a/scripts/context/perl/mptopdf.pl b/scripts/context/perl/mptopdf.pl
index 337869519..0528a4010 100644
--- a/scripts/context/perl/mptopdf.pl
+++ b/scripts/context/perl/mptopdf.pl
@@ -1,7 +1,7 @@
eval '(exit $?0)' && eval 'exec perl -S $0 ${1+"$@"}' && eval 'exec perl -S $0 $argv:q'
if 0;
-# MikTeX users can set environment variable TEXSYSTEM to "miktex".
+# MikTeX users can set environment variable TEXSYSTEM to "miktex".
#D \module
#D [ file=mptopdf.pl,
@@ -17,68 +17,70 @@ eval '(exit $?0)' && eval 'exec perl -S $0 ${1+"$@"}' && eval 'exec perl -S $0 $
#C therefore copyrighted by \PRAGMA. See licen-en.pdf for
#C details.
-# use File::Copy ; # not in every perl
+# use File::Copy ; # not in every perl
use Config ;
use Getopt::Long ;
-use strict ;
+use strict ;
$Getopt::Long::passthrough = 1 ; # no error message
$Getopt::Long::autoabbrev = 1 ; # partial switch accepted
-my $Help = my $Latex = my $RawMP = 0 ;
-my $PassOn = '' ;
+my $Help = my $Latex = my $RawMP = 0 ;
+my $PassOn = '' ;
&GetOptions
( "help" => \$Help ,
- "rawmp" => \$RawMP,
+ "rawmp" => \$RawMP,
"passon" => \$PassOn,
"latex" => \$Latex ) ;
-
-my $program = "MPtoPDF 1.2" ;
+
+my $program = "MPtoPDF 1.3" ;
my $pattern = $ARGV[0] ;
my $done = 0 ;
my $report = '' ;
-my $latexswitch = " --tex=latex --format=latex " ;
-
-## $dosish = ($Config{'osname'} =~ /dos|mswin/i) ;
-my $dosish = ($Config{'osname'} =~ /^(ms)?dos|^os\/2|^(ms|cyg)win/i) ;
+my $texlatexswitch = " --tex=latex --format=latex " ;
+my $mplatexswitch = " --tex=latex " ;
-my $miktex = ($ENV{"TEXSYSTEM"} =~ /miktex/io);
+my $dosish = ($Config{'osname'} =~ /^(ms)?dos|^os\/2|^(ms|cyg)win/i) ;
+my $miktex = ($ENV{"TEXSYSTEM"} =~ /miktex/io);
+my $escapeshell = ( ($ENV{'SHELL'}) && ($ENV{'SHELL'} =~ m/sh/i ));
-my @files ;
-my $command = my $mpbin = '' ;
+my @files ;
+my $command = my $mpbin = '' ;
-sub CopyFile # agressive copy, works for open files like in gs
- { my ($From,$To) = @_ ;
- return unless open(INP,"<$From") ; binmode INP ;
- return unless open(OUT,">$To") ; binmode OUT ;
- while (<INP>) { print OUT $_ }
- close (INP) ;
+sub CopyFile # agressive copy, works for open files like in gs
+ { my ($From,$To) = @_ ;
+ return unless open(INP,"<$From") ; binmode INP ;
+ return unless open(OUT,">$To") ; binmode OUT ;
+ while (<INP>) { print OUT $_ }
+ close (INP) ;
close (OUT) }
if (($pattern eq '')||($Help))
{ print "\n$program : provide MP output file (or pattern)\n" ;
exit }
-elsif ($pattern =~ /\.mp$/io)
- { shift @ARGV ; my $rest = join(" ", @ARGV) ;
+elsif ($pattern =~ /\.mp$/io)
+ { shift @ARGV ; my $rest = join(" ", @ARGV) ;
if (open(INP,$pattern))
- { while (<INP>)
- { if (/(documentstyle|documentclass|begin\{document\})/io)
- { $Latex = 1 ; last } }
- close (INP) }
- if ($Latex)
- { $rest .= " $latexswitch" }
+ { while (<INP>)
+ { if (/(documentstyle|documentclass|begin\{document\})/io)
+ { $Latex = 1 ; last } }
+ close (INP) }
if ($RawMP)
- { $mpbin = 'mpost' }
+ { if ($Latex)
+ { $rest .= " $mplatexswitch" }
+ $mpbin = 'mpost' }
else
- { $mpbin = 'texexec --mptex $PassOn' }
+ { if ($Latex)
+ { $rest .= " $texlatexswitch" }
+ $mpbin = 'texexec --mptex $PassOn' }
my $error = system ("$mpbin $rest $pattern") ;
- if ($error)
- { print "\n$program : error while processing mp file\n" ; exit }
- else
- { $pattern =~ s/\.mp$//io ;
- @files = glob "$pattern.*" } }
+ if ($error)
+ { print "\n$program : error while processing mp file\n" ; exit }
+ else
+ { $pattern =~ s/\.mp$//io ;
+ @files = glob "$pattern.*" } }
elsif (-e $pattern)
{ @files = ($pattern) }
elsif ($pattern =~ /.\../o)
@@ -90,15 +92,17 @@ else
foreach my $file (@files)
{ $_ = $file ;
if (s/\.(\d+|mps)$// && -e $file)
- { if ($miktex)
- { if ($dosish)
- { $command = "pdfetex &mptopdf" }
+ { if ($miktex)
+ { if ($dosish)
+ { $command = "pdfetex &mptopdf" }
else
{ $command = "pdfetex \\&mptopdf" } }
- else
-# { $command = "pdfetex -progname=pdfetex -efmt=mptopdf" }
- { $command = "pdfetex -progname=context -efmt=mptopdf" }
- if ($dosish)
+ else
+ { if ($dosish)
+ { $command = "pdfetex -progname=context &mptopdf" }
+ else
+ { $command = "pdfetex -progname=context \\&mptopdf" } }
+ if ($dosish)
{ system ("$command \\relax $file") }
else
{ system ("$command \\\\relax $file") }
@@ -108,8 +112,8 @@ foreach my $file (@files)
$report .= " $_-$1.pdf" ;
++$done } }
-if ($report eq '')
- { $report = '*' }
+if ($report eq '')
+ { $report = '*' }
if ($done)
{ print "\n$program : $pattern is converted to$report\n" }
diff --git a/scripts/context/perl/texexec.pl b/scripts/context/perl/texexec.pl
index e3bf969ec..9a1d31bdc 100644
--- a/scripts/context/perl/texexec.pl
+++ b/scripts/context/perl/texexec.pl
@@ -3,7 +3,7 @@ eval '(exit $?0)' && eval 'exec perl -w -S $0 ${1+"$@"}' && eval 'exec perl -w -
#D \module
#D [ file=texexec.pl,
-#D version=2003.09.16,
+#D version=2004.08.29,
#D title=running \ConTeXt,
#D subtitle=\TEXEXEC,
#D author=Hans Hagen,
@@ -26,7 +26,14 @@ eval '(exit $?0)' && eval 'exec perl -w -S $0 ${1+"$@"}' && eval 'exec perl -w -
#D expression replaces the unix specific line \type
#D {#!/usr/bin/perl}.
+#D History has learned that writing wrappers like this is quite painful
+#D because of differences between platforms, changes in the tex command
+#D line flags (fmt), default behaviour (e.g. 8 bit), and the assumption
+#D that everyone runs the same tex and that distributers take care of
+#D everything. Well, the result is a messy script like this ... Sorry.
+
use strict ;
+#~ use warnings ; # strange warnings, todo
# todo: second run of checksum of mp file with --nomprun changes
# todo: warning if no args
@@ -84,12 +91,8 @@ my $escapeshell = ( ($ENV{'SHELL'}) && ($ENV{'SHELL'} =~ m/sh/i ));
my $TeXUtil = 'texutil';
my $TeXExec = 'texexec';
-my $DVIspec = 'dvispec';
-my $SGMLtoTeX = 'sgml2tex';
-my $FDFtoTeX = 'fdf2tex';
-
-my $MetaFun = 'metafun';
-my $MpToPdf = 'mptopdf';
+my $MetaFun = 'metafun';
+my $MpToPdf = 'mptopdf';
$Getopt::Long::passthrough = 1; # no error message
$Getopt::Long::autoabbrev = 1; # partial switch accepted
@@ -115,6 +118,7 @@ my $FinalMode = 0;
my $Format = '';
my $MpDoFormat = '';
my $HelpAsked = 0;
+my $Version = 0;
my $MainBodyFont = 'standard';
my $MainLanguage = 'standard';
my $MainResponse = 'standard';
@@ -123,7 +127,7 @@ my $Markings = 0;
my $Mode = '';
my $NoArrange = 0;
my $NoDuplex = 0;
-my $NOfRuns = 7;
+my $NOfRuns = 8;
my $NoMPMode = 0;
my $NoMPRun = 0;
my $NoBanner = 0;
@@ -166,6 +170,7 @@ my $PdfCopy = 0;
my $LogFile = "";
my $MpyForce = 0;
my $InpPath = "";
+my $AutoPath = 0;
my $RunPath = "";
my $Arguments = "";
my $Pretty = 0;
@@ -180,7 +185,14 @@ my $AllPatterns = 0;
my $ForceXML = 0;
my $Random = 0;
my $Filters = '';
-my $NoMapFiles = 0;
+my $NoMapFiles = 0 ;
+my $Foxet = 0 ;
+my $TheEnginePath = 0 ;
+
+my $StartLine = 0 ;
+my $StartColumn = 0 ;
+my $EndLine = 0 ;
+my $EndColumn = 0 ;
# makempy :
@@ -202,6 +214,7 @@ my $MakeMpy = '';
"format=s" => \$Format,
"mpformat=s" => \$MpDoFormat,
"help" => \$HelpAsked,
+ "version" => \$Version,
"interface=s" => \$ConTeXtInterface,
"language=s" => \$MainLanguage,
"bodyfont=s" => \$MainBodyFont,
@@ -227,6 +240,7 @@ my $MakeMpy = '';
"paper=s" => \$PaperFormat,
"passon=s" => \$PassOn,
"path=s" => \$InpPath,
+ "autopath" => \$AutoPath,
"pdf" => \$ProducePdfT,
"pdm" => \$ProducePdfM,
"pdx" => \$ProducePdfX,
@@ -259,7 +273,7 @@ my $MakeMpy = '';
"input=s" => \$Input,
"arguments=s" => \$Arguments,
"pretty" => \$Pretty,
- "setfile=s" => \$SetFile,
+ "setfile=s" => \$SetFile, # obsolete
"purge" => \$Purge,
#### yet undocumented #################
"runpath=s" => \$RunPath,
@@ -275,9 +289,22 @@ my $MakeMpy = '';
"autopdf" => \$AutoPdf,
"modefile=s" => \$ModeFile, # additional modes file
"globalfile" => \$GlobalFile,
- "nomapfiles" => \$NoMapFiles
+ "nomapfiles" => \$NoMapFiles,
+ "foxet" => \$Foxet,
+ "engine" => \$TheEnginePath,
+ #### exxperiment
+ "startline=s" => \$StartLine,
+ "startcolumn=s" => \$StartColumn,
+ "endline=s" => \$EndLine,
+ "endcolumn=s" => \$EndColumn
); # don't check name
+if ($Foxet) {
+ $ProducePdfT = 1 ;
+ $ForceXML = 1 ;
+ $Modules = "foxet" ;
+}
+
# a set file (like blabla.bat) can set paths now
if ( $SetFile ne "" ) { load_set_file( $SetFile, $Verbose ); $SetFile = "" }
@@ -327,7 +354,7 @@ if ( ( $LogFile ne '' ) && ( $LogFile =~ /\w+\.log$/io ) ) {
*STDERR = *LOGFILE;
}
-my $Program = " TeXExec 4.3 - ConTeXt / PRAGMA ADE 1997-2004";
+my $Program = " TeXExec 5.0 - ConTeXt / PRAGMA ADE 1997-2004";
print "\n$Program\n\n";
@@ -400,8 +427,14 @@ my $kpsewhich = '';
sub found_ini_file {
my $suffix = shift ;
+ #~ $IniPath = $0 ;
+ #~ $IniPath ~= s/\.pl$//io ;
+ #~ $IniPath = $InPath . ".'" + $suffix ;
+ #~ if (-e $IniPath) {
+ #~ }
+ # not really needed to check on texmfscripts, better on own path
print " locating ini file : kpsewhiching texexec.$suffix on scripts\n" if $Verbose ;
- my $IniPath = `$kpsewhich --format="scripts" -progname=context texexec.$suffix` ;
+ my $IniPath = `$kpsewhich --format="texmfscripts" -progname=context texexec.$suffix` ;
chomp($IniPath) ;
if ($IniPath eq '') {
print " locating ini file : kpsewhiching texexec.$suffix elsewhere\n" if $Verbose ;
@@ -564,12 +597,11 @@ if ( open( INI, $IniPath ) ) {
my $two = $2;
my $three = $3;
if ( $one ne $Done{"TeXShell"} ) {
- $three =~ s/^[\'\"]//;
- $three =~ s/[\'\"]$//;
- $three =~ s/\s*$//;
+ $three =~ s/^[\'\"]//o;
+ $three =~ s/[\'\"]$//o;
+ $three =~ s/\s*$//o;
if ($Verbose) {
- print
-" setting : '$two' to '$three' except for '$one'\n";
+ print " setting : '$two' to '$three' except for '$one'\n";
}
$Done{"$two"} = $three;
CheckPath( $two, $three );
@@ -578,10 +610,10 @@ if ( open( INI, $IniPath ) ) {
my $one = $1;
my $two = $2;
my $three = $3;
- $three =~ s/\s*$//;
+ $three =~ s/\s*$//o;
if ( $one eq $Done{"TeXShell"} ) {
- $three =~ s/^[\'\"]//;
- $three =~ s/[\'\"]$//;
+ $three =~ s/^[\'\"]//o;
+ $three =~ s/[\'\"]$//o;
if ($Verbose) {
print
" setting : '$two' to '$three' for '$one'\n";
@@ -593,9 +625,9 @@ if ( open( INI, $IniPath ) ) {
my $one = $1;
my $two = $2;
unless ( defined( $Done{"$one"} ) ) {
- $two =~ s/^[\'\"]//;
- $two =~ s/[\'\"]$//;
- $two =~ s/\s*$//;
+ $two =~ s/^[\'\"]//o;
+ $two =~ s/[\'\"]$//o;
+ $two =~ s/\s*$//o;
if ($Verbose) {
print
" setting : '$one' to '$two' for 'all'\n";
@@ -620,6 +652,11 @@ if ( open( INI, $IniPath ) ) {
sub IniValue {
my ( $Key, $Default ) = @_;
if ( defined( $Done{$Key} ) ) { $Default = $Done{$Key} }
+ if ($Default =~ /^(true|yes|on)$/io) {
+ $Default = 1 ;
+ } elsif ($Default =~ /^(false|no|off)$/io) {
+ $Default = 0 ;
+ }
if ($Verbose) { print " used setting : $Key = $Default\n" }
return $Default;
}
@@ -639,10 +676,10 @@ my $TeXScriptsPath = IniValue( 'TeXScriptsPath', '' );
my $TeXHashExecutable = IniValue( 'TeXHashExecutable', '' );
my $TeXExecutable = IniValue( 'TeXExecutable', 'tex' );
my $TeXVirginFlag = IniValue( 'TeXVirginFlag', '-ini' );
-my $TeXBatchFlag = IniValue( 'TeXBatchFlag', '-int=batchmode' );
-my $TeXNonStopFlag = IniValue( 'TeXNonStopFlag', '-int=nonstopmode' );
-my $MpBatchFlag = IniValue( 'MpBatchFlag', '-int=batchmode' );
-my $MpNonStopFlag = IniValue( 'MpNonStopFlag', '-int=nonstopmode' );
+my $TeXBatchFlag = IniValue( 'TeXBatchFlag', '-interaction=batchmode' );
+my $TeXNonStopFlag = IniValue( 'TeXNonStopFlag', '-interaction=nonstopmode' );
+my $MpBatchFlag = IniValue( 'MpBatchFlag', '-interaction=batchmode' );
+my $MpNonStopFlag = IniValue( 'MpNonStopFlag', '-interaction=nonstopmode' );
my $TeXPassString = IniValue( 'TeXPassString', '' );
my $TeXFormatFlag = IniValue( 'TeXFormatFlag', '' );
my $MpFormatFlag = IniValue( 'MpFormatFlag', '' );
@@ -650,12 +687,14 @@ my $MpVirginFlag = IniValue( 'MpVirginFlag', '-ini' );
my $MpPassString = IniValue( 'MpPassString', '' );
my $MpFormat = IniValue( 'MpFormat', $MetaFun );
my $MpFormatPath = IniValue( 'MpFormatPath', $TeXFormatPath );
+my $UseEnginePath = IniValue( 'UseEnginePath', $TheEnginePath);
my $FmtLanguage = IniValue( 'FmtLanguage', '' );
my $FmtBodyFont = IniValue( 'FmtBodyFont', '' );
my $FmtResponse = IniValue( 'FmtResponse', '' );
my $TcXPath = IniValue( 'TcXPath', '' );
+
$SetFile = IniValue( 'SetFile', $SetFile );
if ( ($Verbose) && ( $kpsewhich ne '' ) ) {
@@ -675,9 +714,31 @@ if ( ($FmtResponse) && ( $MainResponse eq 'standard' ) ) {
$MainResponse = $FmtResponse;
}
-if ( $TeXFormatFlag eq "" ) { $TeXFormatFlag = "&" }
+# new versions, > 2004 will have -fmt as switch
+
+if ( $TeXFormatFlag eq "" ) {
+ if ($TeXProgram =~ /(etex|pdfetex)/) {
+ $TeXFormatFlag = "-efmt=" ; # >=2004 -fmt=
+ } elsif ($TeXProgram =~ /(eomega)/) {
+ $TeXFormatFlag = "-eoft=" ; # >=2004 obsolete
+ } elsif ($TeXProgram =~ /(aleph)/) {
+ $TeXFormatFlag = "-fmt=" ;
+ } else {
+ $TeXFormatFlag = "-fmt=" ;
+ }
+}
+
+if ( $MpFormatFlag eq "" ) {
+ $MpFormatFlag = "-mem=" ;
+}
+
+if ($UseEnginePath && (! $MakeFormats)) {
+ $MpFormatFlag .= $MpExecutable . '/' ;
+ $TeXFormatFlag .= $TeXExecutable . '/' ;
+}
-if ( $MpFormatFlag eq "" ) { $MpFormatFlag = "&" }
+#~ if ( $TeXFormatFlag eq "" ) { $TeXFormatFlag = "&" }
+#~ if ( $MpFormatFlag eq "" ) { $MpFormatFlag = "&" }
unless ( $dosish && !$escapeshell ) {
if ( $TeXFormatFlag eq "&" ) { $TeXFormatFlag = "\\&" }
@@ -688,8 +749,12 @@ if ($TeXProgram) { $TeXExecutable = $TeXProgram }
my $fmtutil = '';
+# for the moment forget about fmtutil, since it does not support $engine subpaths
+
+$Alone = 1 ;
+
if ( $MakeFormats || $Verbose ) {
- if ($Alone) {
+ if ($Alone || $UseEnginePath) {
if ($Verbose) { print " generating format : not using fmtutil\n" }
} elsif ( $TeXShell =~ /tetex|fptex/i ) {
foreach (@paths) {
@@ -697,7 +762,7 @@ if ( $MakeFormats || $Verbose ) {
if ( -e $p ) { $fmtutil = $p; last }
elsif ( -e $p . '.exe' ) { $fmtutil = $p . '.exe'; last }
}
- $fmtutil = ($fmtutil =~ m/^[^\"].* / ? "\"$fmtutil\"" : "$fmtutil") ;
+ $fmtutil = ($fmtutil =~ m/^[^\"].* / ? "\"$fmtutil\"" : "$fmtutil") ;
if ($Verbose) {
if ( $fmtutil eq '' ) {
print " locating fmtutil : not found in path\n";
@@ -879,11 +944,14 @@ sub print_opt {
sub show_help_options {
print # "\n" .
- " --help overview of all options and their values\n"
+ " --help overview of all options and their values\n"
. " --help all all about all options\n"
. " --help short just the main options\n"
. " --help mode ... pdf all about a few options\n"
- . " --help '*.pdf' all about options containing 'pdf'\n";
+ . " --help '*.pdf' all about options containing 'pdf'\n"
+ . "\n"
+ . " more info http://www.pragma-ade.com/general/manuals/mtexexec.pdf\n"
+ . " http://www.ntg.nl/mailman/listinfo/ntg-context\n";
}
# determine what user wants to see
@@ -953,17 +1021,10 @@ sub RunPerlScript {
} else {
$cmd = "$ScriptName $Options";
}
- unless ( $cmd eq "" ) { system($cmd) }
-}
-
-sub ConvertXMLFile {
- my $FileName = shift;
- RunPerlScript( $SGMLtoTeX, "$FileName.xml" );
-}
-
-sub ConvertSGMLFile {
- my $FileName = shift;
- RunPerlScript( $SGMLtoTeX, "$FileName.sgm" );
+ unless ( $cmd eq "" ) {
+ print $cmd if ($Verbose) ;
+ system($cmd) ;
+ }
}
my $FullFormat = '';
@@ -985,7 +1046,7 @@ sub CheckOutputFormat {
if ( !$Ok ) {
print $Help{'output'};
} elsif ($FullFormat) {
- print OPT "\\setupoutput[$FullFormat]\n";
+ # print OPT "\\setupoutput[$FullFormat]\n";
}
}
unless ($FullFormat) { $FullFormat = $OutputFormat }
@@ -996,6 +1057,8 @@ sub MakeOptionFile {
open( OPT, ">$JobName.top" );
print OPT "\% $JobName.top\n";
print OPT "\\unprotect\n";
+ $ModeFile =~ s/\\/\//gio ; # do this at top of file
+ $Result =~ s/\\/\//gio ; # do this at top of file
if ( $ModeFile ne '' ) { print OPT "\\readlocfile{$ModeFile}{}{}" }
if ( $Result ne '' ) { print OPT "\\setupsystem[file=$Result]\n" }
elsif ($Suffix) { print OPT "\\setupsystem[file=$JobName$Suffix]\n" }
@@ -1020,16 +1083,16 @@ sub MakeOptionFile {
}
if ($EnterBatchMode) { print OPT "\\batchmode\n" }
if ($EnterNonStopMode) { print OPT "\\nonstopmode\n" }
- if ($UseColor) { print OPT "\\setupcolors[\\c!status=\\v!start]\n" }
+ if ($UseColor) { print OPT "\\setupcolors[\\c!state=\\v!start]\n" }
if ( $NoMPMode || $NoMPRun || $AutoMPRun ) {
print OPT "\\runMPgraphicsfalse\n";
}
if ( ($FastMode) && ( !$FastDisabled ) ) { print OPT "\\fastmode\n" }
if ($SilentMode) { print OPT "\\silentmode\n" }
if ( $Separation ne "" ) {
- print OPT "\\setupcolors[\\c!splitsen=$Separation]\n";
+ print OPT "\\setupcolors[\\c!split=$Separation]\n";
}
- if ($SetupPath) { print OPT "\\setupsystem[\\c!gebied=\{$SetupPath\}]\n" }
+ if ($SetupPath) { print OPT "\\setupsystem[\\c!directory=\{$SetupPath\}]\n" }
print OPT "\\setupsystem[\\c!n=$KindOfRun]\n";
$_ = $PaperFormat;
#unless (($PdfArrange)||($PdfSelect)||($PdfCombine)||($PdfCopy))
@@ -1049,41 +1112,41 @@ sub MakeOptionFile {
{
print " background graphic : $Background\n";
print OPT "\\defineoverlay[whatever][{\\externalfigure[$Background][\\c!factor=\\v!max]}]\n";
- print OPT "\\setupbackgrounds[\\v!pagina][\\c!achtergrond=whatever]\n";
+ print OPT "\\setupbackgrounds[\\v!page][\\c!background=whatever]\n";
}
if ($CenterPage) {
print OPT
- "\\setuplayout[\\c!plaats=\\v!midden,\\c!markering=\\v!aan]\n";
+ "\\setuplayout[\\c!location=\\v!middle,\\c!marking=\\v!on]\n";
}
if ($NoMapFiles) {
print OPT "\\disablemapfiles\n";
}
- if ($NoArrange) { print OPT "\\setuparranging[\\v!blokkeer]\n" }
+ if ($NoArrange) { print OPT "\\setuparranging[\\v!disable]\n" }
elsif ( $Arrange || $PdfArrange ) {
$FinalRunNeeded = 1;
if ($FinalRun) {
my $DupStr;
if ($NoDuplex) { $DupStr = "" }
- else { $DupStr = ",\\v!dubbelzijdig" }
+ else { $DupStr = ",\\v!doublesided" }
if ( $PrintFormat eq '' ) {
- print OPT "\\setuparranging[\\v!normaal]\n";
+ print OPT "\\setuparranging[\\v!normal]\n";
} elsif ( $PrintFormat =~ /.*up/goi ) {
- print OPT "\\setuparranging[2UP,\\v!geroteerd$DupStr]\n";
+ print OPT "\\setuparranging[2UP,\\v!rotated$DupStr]\n";
} elsif ( $PrintFormat =~ /.*down/goi ) {
- print OPT "\\setuparranging[2DOWN,\\v!geroteerd$DupStr]\n";
+ print OPT "\\setuparranging[2DOWN,\\v!rotated$DupStr]\n";
} elsif ( $PrintFormat =~ /.*side/goi ) {
- print OPT "\\setuparranging[2SIDE,\\v!geroteerd$DupStr]\n";
+ print OPT "\\setuparranging[2SIDE,\\v!rotated$DupStr]\n";
} else {
print OPT "\\setuparranging[$PrintFormat]\n";
}
} else {
- print OPT "\\setuparranging[\\v!blokkeer]\n";
+ print OPT "\\setuparranging[\\v!disable]\n";
}
}
if ($Arguments) { print OPT "\\setupenv[$Arguments]\n" }
if ($Input) { print OPT "\\setupsystem[inputfile=$Input]\n" }
else { print OPT "\\setupsystem[inputfile=$JobName.$JobSuffix]\n" }
- if ($Random) { print OPT "\\setupsystem[\\c!willekeur=$RandomSeed]\n" }
+ if ($Random) { print OPT "\\setupsystem[\\c!random=$RandomSeed]\n" }
if ($Mode) { print OPT "\\enablemode[$Mode]\n" }
if ($Pages) {
if ( lc $Pages eq "odd" ) {
@@ -1146,7 +1209,7 @@ sub MakeUserFile {
if ( $MainLanguage ne 'standard' ) {
@MainLanguages = split( /\,/, $MainLanguage );
foreach (@MainLanguages) {
- print USR "\\installlanguage[\\s!$_][\\c!status=\\v!start]\n";
+ print USR "\\installlanguage[\\s!$_][\\c!state=\\v!start]\n";
}
$MainLanguage = $MainLanguages[0];
print USR "\\setupcurrentlanguage[\\s!$MainLanguage]\n";
@@ -1203,7 +1266,7 @@ sub CheckPositions { }
my $ConTeXtVersion = "unknown";
my $ConTeXtModes = '';
-sub ScanPreamble {
+sub ScanTeXPreamble {
my ($FileName) = @_;
open( TEX, $FileName );
while (<TEX>) {
@@ -1231,12 +1294,19 @@ sub ScanPreamble {
}
}
close(TEX);
+
+ # handy later on
+
+ $ProducePdfT = ($OutputFormat eq "pdftex") ;
+ $ProducePdfM = ($OutputFormat eq "dvipdfm") ;
+ $ProducePdfX = ($OutputFormat eq "dvipdfmx") ;
}
sub ScanContent {
my ($ConTeXtInput) = @_;
open( TEX, $ConTeXtInput );
while (<TEX>) {
+ next if (/^\%/) ;
if (
/\\(starttekst|stoptekst|startonderdeel|startdocument|startoverzicht)/
)
@@ -1279,9 +1349,65 @@ if ( $ConTeXtInterfaces{$ConTeXtInterface} ) {
my $Problems = my $Ok = 0;
-sub RunTeX {
- my ( $JobName, $JobSuffix ) = @_;
- my $StartTime = time;
+#~ sub RunTeX {
+ #~ my ( $JobName, $JobSuffix ) = @_;
+ #~ my $StartTime = time;
+ #~ my $cmd;
+ #~ my $TeXProgNameFlag = '';
+ #~ if ( !$dosish ) # we assume tetex on linux
+ #~ {
+ #~ $TeXProgramPath = '';
+ #~ $TeXFormatPath = '';
+ #~ if ( !$TeXProgNameFlag
+ #~ && ( $Format =~ /^cont/ )
+ #~ && ( $TeXPassString !~ /progname/io ) )
+ #~ {
+ #~ $TeXProgNameFlag = "-progname=context";
+ #~ }
+ #~ }
+ #~ $own_quote = ($TeXProgramPath =~ m/^[^\"].* / ? "\"" : "") ;
+ #~ $cmd = join( ' ',
+ #~ "$own_quote$TeXProgramPath$TeXExecutable$own_quote",
+ #~ $TeXProgNameFlag, $TeXPassString, $PassOn, "" );
+ #~ if ($EnterBatchMode) { $cmd .= "$TeXBatchFlag " }
+ #~ if ($EnterNonStopMode) { $cmd .= "$TeXNonStopFlag " }
+ #~ if ( $TeXTranslation ne '' ) { $cmd .= "-translate-file=$TeXTranslation " }
+ #~ $cmd .= "$TeXFormatFlag$TeXFormatPath$Format $JobName.$JobSuffix";
+ #~ if ($Verbose) { print "\n$cmd\n\n" }
+ #~ if ($EnterBatchMode) {
+ #~ $Problems = system("$cmd");
+ #~ } else {
+ #~ $Problems = system("$cmd");
+ #~ }
+ #~ # generate formats if needed and retry
+ #~ #
+ #~ # well, this used to work ok, until a engines started to use the same suffix
+ #~ # and no robust check was possible any more
+ #~ #
+ #~ # if ($Problems) {
+ #~ # my $efmt = `$kpsewhich cont-en.efmt` ;
+ #~ # chomp $efmt ;
+ #~ # if ($efmt eq "") {
+ #~ # print "\n";
+ #~ # print " emergency action : generate all formats\n";
+ #~ # system("texexec --make --alone --all") ;
+ #~ # print "\n";
+ #~ # print " emergency action : retry processing file\n";
+ #~ # if ($EnterBatchMode) {
+ #~ # $Problems = system("$cmd");
+ #~ # } else {
+ #~ # $Problems = system("$cmd");
+ #~ # }
+ #~ # }
+ #~ # }
+ #~ my $StopTime = time - $StartTime;
+ #~ print "\n return code : $Problems";
+ #~ print "\n run time : $StopTime seconds\n";
+ #~ return $Problems;
+#~ }
+
+sub PrepRunTeX {
+ my ( $JobName, $JobSuffix, $PipeString ) = @_;
my $cmd;
my $TeXProgNameFlag = '';
if ( !$dosish ) # we assume tetex on linux
@@ -1302,32 +1428,42 @@ sub RunTeX {
if ($EnterBatchMode) { $cmd .= "$TeXBatchFlag " }
if ($EnterNonStopMode) { $cmd .= "$TeXNonStopFlag " }
if ( $TeXTranslation ne '' ) { $cmd .= "-translate-file=$TeXTranslation " }
- $cmd .= "$TeXFormatFlag$TeXFormatPath$Format $JobName.$JobSuffix";
+ $cmd .= "$TeXFormatFlag$TeXFormatPath$Format $JobName.$JobSuffix $PipeString";
if ($Verbose) { print "\n$cmd\n\n" }
+ return $cmd;
+}
+
+sub RunTeX {
+ my ( $JobName, $JobSuffix ) = @_;
+ my $StartTime = time;
+ my $cmd = PrepRunTeX($JobName, $JobSuffix, '');
if ($EnterBatchMode) {
$Problems = system("$cmd");
} else {
$Problems = system("$cmd");
}
# generate formats if needed and retry
- if ($Problems) {
- my $efmt = `$kpsewhich cont-en.efmt` ;
- chomp $efmt ;
- if ($efmt eq "") {
- # generate formats
- print "\n";
- print " emergency action : generate all formats\n";
- system("texexec --make --alone --all") ;
- # try again
- print "\n";
- print " emergency action : retry processing file\n";
- if ($EnterBatchMode) {
- $Problems = system("$cmd");
- } else {
- $Problems = system("$cmd");
- }
- }
- }
+ #
+ # well, this used to work ok, until a engines started to use the same suffix
+ # and no robust check was possible any more
+ #
+ # if ($Problems) {
+ # my $efmt = `$kpsewhich cont-en.efmt` ;
+ # chomp $efmt ;
+ # if ($efmt eq "") {
+ # print "\n";
+ # print " emergency action : generate all formats\n";
+ # system("texexec --make --alone --all") ;
+ # print "\n";
+ # print " emergency action : retry processing file\n";
+ # if ($EnterBatchMode) {
+ # $Problems = system("$cmd");
+ # } else {
+ # $Problems = system("$cmd");
+ # }
+ # }
+ # }
+
my $StopTime = time - $StartTime;
print "\n return code : $Problems";
print "\n run time : $StopTime seconds\n";
@@ -1498,7 +1634,7 @@ my $DummyFile = 0;
sub isXMLfile {
my $Name = shift;
- if ( ($ForceXML) || ( $Name =~ /\.xml$/io ) ) { return 1 }
+ if ( ($ForceXML) || ( $Name =~ /\.(xml|fo|fox)$/io ) ) { return 1 }
else {
open( XML, $Name );
my $str = <XML>;
@@ -1509,9 +1645,23 @@ sub isXMLfile {
sub RunConTeXtFile {
my ( $JobName, $JobSuffix ) = @_;
+if ($AutoPath) {
+ if ($JobName =~ /^(.*)[\/\\](.*?)$/o) {
+ $InpPath = $1 ;
+ $JobName = $2 ;
+ }
+}
$JobName =~ s/\\/\//goi;
$InpPath =~ s/\\/\//goi;
my $OriSuffix = $JobSuffix;
+if ($JobSuffix =~ /\_fo$/i) {
+ if (! -f $JobName) {
+ print "stripping funny suffix : _fo\n";
+ $JobName =~ s/\_fo$//io ;
+ $JobSuffix =~ s/\_fo$//io ;
+ $OriSuffix =~ s/\_fo$//io ;
+ }
+}
if (($dosish) && ($PdfClose)) {
my $ok = system("pdfclose --file $JobName.pdf") if -e "$JobName.pdf" ;
if (($Result ne '') && (-e "$Result.pdf")) {
@@ -1520,7 +1670,7 @@ sub RunConTeXtFile {
system("pdfclose --all") unless $ok ;
}
if ( -e "$JobName.$JobSuffix" ) {
- $DummyFile = ( ($ForceXML) || ( $JobSuffix =~ /xml/io ) );
+ $DummyFile = ( ($ForceXML) || ( $JobSuffix =~ /(xml|fo|fox)/io ) );
}
# to be considered :
# { $DummyFile = isXMLfile("$JobName.$JobSuffix") }
@@ -1532,7 +1682,26 @@ sub RunConTeXtFile {
}
if ($DummyFile) {
open( TMP, ">$JobName.run" );
- if ( ( $JobSuffix =~ /xml/io ) || $ForceXML ) {
+ if ( ( $JobSuffix =~ /(xml|fo|fox)/io ) || $ForceXML ) {
+ # scan xml preamble
+ open(XML,"<$JobName.$JobSuffix") ;
+ while (<XML>) {
+ if (/\<[a-z]+/io) {
+ last ;
+ } elsif (/\<\?context\-directive\s+(.+?)\s+(.+?)\s+(.+?)\s*\?\>/o) {
+ my ($class, $key, $value) = ($1, $2, $3) ;
+ if ($class eq 'job') {
+ if ($key eq 'stylefile') {
+ print TMP "\\environment $value\n" ;
+ } elsif ($key eq 'module') {
+ print TMP "\\usemodule[$value]\n" ;
+ } elsif ($key eq 'interface') {
+ $ConTeXtInterface = $value ;
+ }
+ }
+ }
+ }
+ close(XML) ;
if ( $Filters ne "" ) {
print " using xml filters : $Filters\n";
}
@@ -1548,9 +1717,8 @@ sub RunConTeXtFile {
$JobSuffix = "run";
}
if ( ( -e "$JobName.$JobSuffix" ) || ($GlobalFile) ) {
- unless ($DummyFile) # we don't need this for xml
- {
- ScanPreamble("$JobName.$JobSuffix");
+ unless ($DummyFile) { # we don't need this for xml
+ ScanTeXPreamble("$JobName.$JobSuffix");
if ( $ConTeXtInterface eq "unknown" ) {
ScanContent("$JobName.$JobSuffix");
}
@@ -1655,6 +1823,11 @@ sub RunConTeXtFile {
CopyFile( "$JobName.top", "$JobName.tmp" );
unlink "$JobName.tup"; # previous tuo file
unlink "$JobName.top"; # runtime option file
+ if ($ProducePdfX) {
+ system("dvipdfmx -f dvipdfmx.map -d 4 $JobName") ;
+ } elsif ($ProducePdfM) {
+ system("dvipdfm $JobName") ;
+ }
PopResult($JobName);
}
if ($Purge) { PurgeFiles($JobName) }
@@ -1694,15 +1867,19 @@ my $CombineFile = "texexec";
sub RunModule {
my @FileNames = sort @_;
- unless ( -e $FileNames[0] ) {
- my $Name = $FileNames[0];
- @FileNames = ( "$Name.tex", "$Name.mp", "$Name.pl", "$Name.pm" );
- }
- foreach my $FileName (@FileNames) {
- next unless -e $FileName;
- my ( $Name, $Suffix ) = split( /\./, $FileName );
- next unless $Suffix =~ /(tex|mp|pl|pm)/io;
- DoRunModule( $Name, $Suffix );
+ if ($FileNames[0]) {
+ unless ( -e $FileNames[0] ) {
+ my $Name = $FileNames[0];
+ @FileNames = ( "$Name.tex", "$Name.mp", "$Name.pl", "$Name.pm" );
+ }
+ foreach my $FileName (@FileNames) {
+ next unless -e $FileName;
+ my ( $Name, $Suffix ) = split( /\./, $FileName );
+ next unless $Suffix =~ /(tex|mp|pl|pm)/io;
+ DoRunModule( $Name, $Suffix );
+ }
+ } else {
+ print " module : no modules found\n\n";
}
}
@@ -1718,14 +1895,17 @@ sub DoRunModule {
open( TED, "$FileName.ted" );
my $firstline = <TED>;
close(TED);
- if ( $firstline =~ /interface=en/ ) { print MOD $firstline }
- else { print MOD "% interface=nl\n" }
+ if ( $firstline =~ /interface=/ ) {
+ print MOD $firstline ;
+ } else {
+ print MOD "% interface=en\n" ;
+ }
# so far
print MOD "\\usemodule[abr-01,mod-01]\n";
print MOD "\\def\\ModuleNumber{1}\n";
- print MOD "\\starttekst\n";
+ print MOD "\\starttext\n";
print MOD "\\readlocfile{$FileName.ted}{}{}\n";
- print MOD "\\stoptekst\n";
+ print MOD "\\stoptext\n";
close(MOD);
RunConTeXtFile( $ModuleFile, "tex" );
@@ -1996,6 +2176,7 @@ sub RunCombine {
sub LocatedFormatPath {
my $FormatPath = shift;
+ my $EnginePath = shift;
if ( ( $FormatPath eq '' ) && ( $kpsewhich ne '' ) ) {
$FormatPath = `$kpsewhich --show-path=fmt`;
chomp $FormatPath;
@@ -2011,6 +2192,14 @@ sub LocatedFormatPath {
print " located formatpath : $FormatPath\n";
}
}
+
+ if ($UseEnginePath && ($FormatPath ne '' && ($FormatPath !~ /$EnginePath\/$/))) {
+ $FormatPath .= $EnginePath . '/' ;
+ unless (-d $FormatPath) {
+ mkdir $FormatPath ;
+ }
+ }
+
return $FormatPath;
}
@@ -2019,6 +2208,7 @@ sub RunOneFormat {
my @TeXFormatPath;
my $TeXPrefix = "";
if ( ( $fmtutil ne "" ) && ( $FormatName !~ /metafun|mptopdf/io ) ) {
+# could not happen, not supported any more
my $cmd = "$fmtutil --byfmt $FormatName";
if ($Verbose) { print "\n$cmd\n\n" }
MakeUserFile; # this works only when the path is kept
@@ -2031,15 +2221,15 @@ sub RunOneFormat {
}
if ($Problems) {
$Problems = 0;
- if ( $TeXExecutable =~ /etex|eetex|pdfetex|pdfeetex|pdfxtex|xpdfetex|eomega|aleph/io ) {
+ if ( $TeXExecutable =~ /etex|eetex|pdfetex|pdfeetex|pdfxtex|xpdfetex|eomega|aleph|xetex/io ) {
$TeXPrefix = "*";
}
my $CurrentPath = cwd();
- $TeXFormatPath = LocatedFormatPath($TeXFormatPath);
- if ( $TeXFormatPath ne '' ) { chdir $TeXFormatPath }
+ my $TheTeXFormatPath = LocatedFormatPath($TeXFormatPath, $TeXExecutable);
+ if ( $TheTeXFormatPath ne '' ) { chdir $TheTeXFormatPath }
MakeUserFile;
MakeResponseFile;
- $own_quote = ($TeXProgramPath =~ m/^[^\"].* / ? "\"" : "") ;
+ $own_quote = ($TeXProgramPath =~ m/^[^\"].* / ? "\"" : "") ;
my $cmd =
"$own_quote$TeXProgramPath$TeXExecutable$own_quote $TeXVirginFlag "
. "$TeXPassString $PassOn ${TeXPrefix}$FormatName";
@@ -2048,7 +2238,7 @@ sub RunOneFormat {
RemoveResponseFile;
RestoreUserFile;
- if ( ( $TeXFormatPath ne '' ) && ( $CurrentPath ne '' ) ) {
+ if ( ( $TheTeXFormatPath ne '' ) && ( $CurrentPath ne '' ) ) {
chdir $CurrentPath;
}
}
@@ -2064,13 +2254,15 @@ sub RunFormats {
if ($Format) { @ConTeXtFormats = $Format; $ConTeXtFormatsPrefix = ''; }
else { $ConTeXtFormatsPrefix = "cont-"; }
if ( $TeXHashExecutable ne '' ) {
- $own_quote = ($TeXProgramPath =~ m/^[^\"].* / ? "\"" : "") ;
- my $cmd = "$own_quote$TeXProgramPath$TeXHashExecutable$own_quote";
- print "\n";
- print " TeX hash binary : $TeXProgramPath$TeXHashExecutable\n";
- print " comment : hashing may take a while ...\n";
- if ($Verbose) { print "\n$cmd\n\n" }
- system($cmd);
+ unless ($FastMode) {
+ $own_quote = ($TeXProgramPath =~ m/^[^\"].* / ? "\"" : "") ;
+ my $cmd = "$own_quote$TeXProgramPath$TeXHashExecutable$own_quote";
+ print "\n";
+ print " TeX hash binary : $TeXProgramPath$TeXHashExecutable\n";
+ print " comment : hashing may take a while ...\n";
+ if ($Verbose) { print "\n$cmd\n\n" }
+ system($cmd);
+ }
}
foreach my $Interface (@ConTeXtFormats) {
if ( $Interface eq $MetaFun ) {
@@ -2091,37 +2283,37 @@ sub RunMpFormat {
my $MpFormat = shift;
return if ( $MpFormat eq '' );
my $CurrentPath = cwd();
- $MpFormatPath = LocatedFormatPath($MpFormatPath);
- if ( $MpFormatPath ne '' ) { chdir "$MpFormatPath" }
+ my $TheMpFormatPath = LocatedFormatPath($MpFormatPath, $MpExecutable);
+ if ( $TheMpFormatPath ne '' ) { chdir $TheMpFormatPath }
$own_quote = ($MpExecutable =~ m/^[^\"].* / ? "\"" : "") ;
my $cmd =
"$own_quote$MpExecutable$own_quote $MpVirginFlag $MpPassString $MpFormat";
if ($Verbose) { print "\n$cmd\n\n" }
system($cmd ) ;
- if ( ( $MpFormatPath ne '' ) && ( $CurrentPath ne '' ) ) {
+ if ( ( $TheMpFormatPath ne '' ) && ( $CurrentPath ne '' ) ) {
chdir $CurrentPath;
}
}
sub RunFiles {
-my $currentpath = cwd() ;
-# test if current path is writable
-if (! -w $currentpath) {
- print " current path readonly : $currentpath\n";
- if ($ENV["TEMP"] && -e $ENV["TEMP"]) {
- $RunPath = $ENV["TEMP"] ;
- } elsif ($ENV["TMP"] && -e $ENV["TMP"]) {
- $RunPath = $ENV["TMP"] ;
- }
-}
-# test if we need to change paths
-if (($RunPath ne "") && (! -w $RunPath)) {
- print " changing to path : $RunPath\n";
- $InpPath = $currentpath ;
- chdir ($RunPath) ;
-}
-# start working
+ my $currentpath = cwd() ;
+ # test if current path is writable
+ if (! -w "$currentpath") {
+ print " current path readonly : $currentpath\n";
+ if ($ENV{"TEMP"} && -e $ENV{"TEMP"}) {
+ $RunPath = $ENV{"TEMP"} ;
+ } elsif ($ENV{"TMP"} && -e $ENV{"TMP"}) {
+ $RunPath = $ENV{"TMP"} ;
+ }
+ }
+ # test if we need to change paths
+ if (($RunPath ne "") && (-w "$RunPath")) {
+ print " changing to path : $RunPath\n";
+ $InpPath = $currentpath ;
+ chdir ($RunPath) ;
+ }
+ # start working
if ($PdfArrange) {
my @arrangedfiles = ();
foreach my $JobName (@ARGV) {
@@ -2154,6 +2346,38 @@ if (($RunPath ne "") && (! -w $RunPath)) {
} else {
my $JobSuffix = "tex";
foreach my $JobName (@ARGV) {
+ # start experiment - full name spec including suffix is prerequisite
+ if (($StartLine>0) && ($EndLine>=$StartLine) && (-e $JobName)) {
+ if (open(INP,$JobName) && open(OUT,'>texexec.tex')) {
+ print " writing partial file : $JobName\n";
+ my $Line = 1 ;
+ my $Preamble = 1 ;
+ while (my $str = <INP>) {
+ if ($Preamble) {
+ if ($str =~ /\\start(text|tekst|product|project|component)/io) {
+ $Preamble = 0 ;
+ } else {
+ print OUT $str;
+ }
+ } elsif ($Line==$StartLine) {
+ print OUT "\\starttext\n" ; # todo: multilingual
+ print OUT $str ;
+ } elsif ($Line==$EndLine) {
+ print OUT $str ;
+ print OUT "\\stoptext\n" ; # todo: multilingual
+ last ;
+ } elsif (($Line>$StartLine) && ($Line<$EndLine)) {
+ print OUT $str ;
+ }
+ $Line += 1 ;
+ }
+ close(INP) ;
+ close(OUT) ;
+ $JobName = 'texexec.tex' ;
+ print " using job name : $JobName\n";
+ }
+ }
+ # end experiment
if ( $JobName =~ s/\.(\w+)$//io ) { $JobSuffix = $1 }
if ( ( $Format eq '' ) || ( $Format =~ /^cont.*/io ) ) {
RunConTeXtFile( $JobName, $JobSuffix );
@@ -2224,17 +2448,40 @@ sub checkMPgraphics { # also see makempy
sub checkMPlabels {
my $MpName = shift;
- return 0 unless ( -s "$MpName.mpt" > 10 );
+ return 0 unless ((-f "$MpName.mpt") && ((-s "$MpName.mpt")>10) );
return 0 unless open( MP, "$MpName.mpt" );
my $n = 0;
+ my $t = "" ;
while (<MP>) {
- if (/% figure (\d+) : (.*)/o) { $mpbetex{$1} .= "$2\n"; ++$n }
+ if (/% setup : (.*)/o) {
+ $t = $1 ;
+ } else {
+ $t = "" ;
+ }
+ if (/% figure (\d+) : (.*)/o) {
+ if ($t ne "") {
+ $mpbetex{$1} .= "$t\n" ;
+ $t = "" ;
+ }
+ $mpbetex{$1} .= "$2\n";
+ ++$n ;
+ }
}
close(MP);
print " second MP run needed : $n tex labels found\n" if $n;
return $n;
}
+sub doMergeMP {
+ # make sure that the verbatimtex ends up before btex etc
+ my ($n,$str) = @_ ;
+ if ($str =~ /(.*?)(verbatimtex.*?etex)\s*\;(.*)/mois) {
+ return "beginfig($n)\;\n$1$2\;\n$mpbetex{$n}\n$3\;endfig\;\n" ;
+ } else {
+ return "beginfig($n)\;\n$mpbetex{$n}\n$str\;endfig\;\n" ;
+ }
+}
+
sub doRunMP { ###########
my ( $MpName, $MergeBE ) = @_;
my $TexFound = 0;
@@ -2259,22 +2506,28 @@ sub doRunMP { ###########
unless ( -e $MpFile ) {
open( MP, ">$MpFile" );
s/(btex.*?)\;(.*?etex)/$1\@\@\@$2/gmois;
+ s/(\".*?)\;(.*?\")/$1\@\@\@$2/gmois; # added
s/\;/\;\n/gmois;
s/\n\n/\n/gmois;
s/(btex.*?)\@\@\@(.*?etex)/$1\;$2/gmois;
+ s/(\".*?)\@\@\@(.*?\")/$1\;$2/gmois; # added
# merge labels
if ($MergeBE) {
-s/beginfig\s*\((\d+)\)\s*\;/beginfig($1)\;\n$mpbetex{$1}\n/goims;
+ # i hate this indirect (sub regexp) mess
+ s/beginfig\s*\((\d+)\)\s*\;(.*?)endfig\s*\;/doMergeMP($1,$2)/gems ;
+ }
+ unless (/beginfig\s*\(\s*0\s*\)/gmois) {
+ if (defined($mpbetex{0})) { # test added, warning
+ print MP $mpbetex{0} ;
+ }
}
- # flush
- unless (/beginfig\s*\(\s*0\s*\)/gmois) { print MP $mpbetex{0} }
print MP $_;
print MP "\n" . "end" . "\n";
close(MP);
}
if ($TexFound) {
print " metapost to tex : $MpName\n";
- $own_quote = ($MpToTeXExecutable =~ m/^[^\"].* / ? "\"" : "") ;
+ $own_quote = ($MpToTeXExecutable =~ m/^[^\"].* / ? "\"" : "") ;
$Problems =
system("$own_quote$MpToTeXExecutable$own_quote $MpFile > $MpTex");
if ( -e $MpTex && !$Problems ) {
@@ -2289,7 +2542,7 @@ s/beginfig\s*\((\d+)\)\s*\;/beginfig($1)\;\n$mpbetex{$1}\n/goims;
}
if ( -e $MpDvi && !$Problems ) {
print " dvi to metapost : $MpName\n";
- $own_quote = ($DviToMpExecutable =~ m/^[^\"].* / ? "\"" : "") ;
+ $own_quote = ($DviToMpExecutable =~ m/^[^\"].* / ? "\"" : "") ;
$Problems = system("$own_quote$DviToMpExecutable$own_quote $MpDvi $MpName.mpx");
}
unlink $MpBck;
@@ -2298,7 +2551,7 @@ s/beginfig\s*\((\d+)\)\s*\;/beginfig($1)\;\n$mpbetex{$1}\n/goims;
}
}
print " metapost : $MpName\n";
- $own_quote = ($MpExecutable =~ m/^[^\"].* / ? "\"" : "") ;
+ $own_quote = ($MpExecutable =~ m/^[^\"].* / ? "\"" : "") ;
my $cmd = "$own_quote$MpExecutable$own_quote";
if ($EnterBatchMode) { $cmd .= " $MpBatchFlag " }
if ($EnterNonStopMode) { $cmd .= " $MpNonStopFlag " }
@@ -2316,6 +2569,7 @@ s/beginfig\s*\((\d+)\)\s*\;/beginfig($1)\;\n$mpbetex{$1}\n/goims;
print " error in metapost run : $MpName.mp:$1\n";
}
}
+ close(MPL) ;
unlink "mptrace.tmp";
rename( $MpFile, "mptrace.tmp" );
if ( -e $MpKep ) {
@@ -2338,7 +2592,7 @@ sub RunMPX {
local $/ = "\0777";
$_ = <MP>;
close(MP);
- if (/(btex|etex|verbatimtex)/o) {
+ if (/(btex|etex|verbatimtex)/mos) {
print " generating mpx file : $MpName\n";
$own_quote = ($MpToTeXExecutable =~ m/^[^\"].* / ? "\"" : "") ;
$Problems =
@@ -2441,10 +2695,92 @@ if ( $SetFile ne "" ) { load_set_file( $SetFile, $Verbose ) }
sub check_texmf_root { }
sub check_texmf_tree { }
+#~ sub AnalyzeVersion
+ #~ { my ($texengine,$type);
+ #~ open (LOG, "<texvers.log") ;
+ #~ while (<LOG>)
+ #~ { /^\s*This is (.*pdf(|e)TeX.*?) \(format.*$/o and $texengine = $1 ;
+ #~ /^\s*ConTeXt (.*int: ([a-z]+).*?)\s*$/o and $type = $1; }
+ #~ $type =~ s/ int: ([a-z]+)//;
+ #~ $texengine =~ s/ Version//;
+ #~ close (LOG);
+ #~ return ($texengine,$type) }
+
+#~ sub AnalyzeVersion
+ #~ { my $str = join("\n", @_) ;
+ #~ my ($texengine,$type);
+ #~ if ($str =~ /^\s*This is (.*pdf(|e)TeX.*?) \(format.*$/mos) {
+ #~ $texengine = $1 ;
+ #~ }
+ #~ if ($str =~ /^\s*ConTeXt (.*int: ([a-z]+).*?)\s*$/mos) {
+ #~ $type = $1 ;
+ #~ }
+ #~ $type =~ s/ int: ([a-z]+)//;
+ #~ $texengine =~ s/ Version//;
+ #~ return ($texengine,$type) }
+
+
+sub AnalyzeVersion
+ { my $str = join("\n", @_) ;
+ my ($texengine,$type) = ('unknown', 'unknown');
+ open (LOG, "<texvers.log") ;
+ while (<LOG>)
+ { /^\s*This is (.*pdf(|e)TeX.*?)$/o and $texengine = $1 ;
+ /^\s*ConTeXt (.*int: ([a-z]+).*?)\s*$/o and $type = $1; }
+ $type =~ s/ int: ([a-z]+)//;
+ $texengine =~ s/ Version//;
+ $texengine =~ s/ \(format.*$//;
+ close (LOG);
+ return ($texengine,$type) }
+
+sub show_version_info {
+ my ($texengine,$type);
+ open (TEX,">texvers.tex") ;
+ print TEX "\\bye " ;
+ close (TEX) ;
+ my $texutil = `$TeXUtil --help`;
+ $texutil =~ s/.*(TeXUtil[^\n]+)\n.*?$/$1/s;
+ print " texexec :$Program\n" ;
+ print " texutil : $texutil" ;
+ my $contexttext = `$kpsewhich context.tex`;
+ my $contextversion = "<not found>";
+ if ($contexttext) {
+ chop $contexttext;
+ { local $/;
+ open (IN,"<$contexttext");
+ $contextversion = <IN>;
+ close IN;
+ }
+ $contextversion =~ s/.*contextversion\{([0-9.]+)\}.*/$1/s;
+ }
+ $EnterBatchMode = 1;
+ $Format = 'cont-en';
+ my $cmd = PrepRunTeX("texvers","tex",'') ;
+ #~ my $ok = system("$cmd");
+ ($texengine,$type) = AnalyzeVersion(`$cmd`) ;
+ print " tex : $texengine\n" ;
+ print " context : ver: $contextversion\n" ;
+ print " cont-en : $type\n" ;
+ foreach my $a (qw(cz de it nl ro uk)) {
+ my $test = `$kpsewhich -format='fmt' cont-$a`;
+ if (defined $test && $test) {
+ $Format = 'cont-' . $a;
+ $cmd = PrepRunTeX("texvers","tex",'');
+ #~ my $ok = system("$cmd");
+ ($texengine,$type) = AnalyzeVersion(`$cmd`) ;
+ print " cont-$a : $type\n" ;
+ }
+ }
+ unlink <texvers.*>;
+}
+
# the main thing
-if ($HelpAsked) { show_help_info }
-elsif ($TypesetListing) {
+if ($HelpAsked) {
+ show_help_info
+} elsif ($Version) {
+ show_version_info
+} elsif ($TypesetListing) {
check_texmf_root;
check_texmf_tree;
RunListing(@ARGV);
@@ -2463,8 +2799,12 @@ elsif ($TypesetListing) {
} elsif ($MakeFormats) {
check_texmf_root;
check_texmf_tree;
- if ( $MpDoFormat ne '' ) { RunMpFormat($MpDoFormat) }
- else { RunFormats }
+ if ( $MpDoFormat ne '' ) {
+ RunMpFormat($MpDoFormat) ;
+ }
+ else {
+ RunFormats ;
+ }
} elsif (@ARGV) {
check_texmf_root;
check_texmf_tree;
@@ -2662,4 +3002,6 @@ alone bypass utilities (e.g. fmtutil for non-standard fmt's)
-----------
texutil force TeXUtil run
-----------
-setfile load environment (batch) file \ No newline at end of file
+version display various version information
+-----------
+setfile load environment (batch) file
diff --git a/scripts/context/perl/texexec.rme b/scripts/context/perl/texexec.rme
index f544f5bbf..419d1faec 100644
--- a/scripts/context/perl/texexec.rme
+++ b/scripts/context/perl/texexec.rme
@@ -24,7 +24,7 @@
%
% == flags ==
%
-% TeXFormatFlag & the format introducer
+% TeXFormatFlag -fmt= the format introducer
% TeXVirginFlag -ini the format generation switch
%
% == paths ==
@@ -51,6 +51,8 @@ set TeXShell to tetex
%
% Here are some general defaults. They can be overruled later.
+set UseEnginePath to false
+
set UsedInterfaces to en nl metafun mptopdf
set UserInterface to en
@@ -66,10 +68,6 @@ set MpFormat to metafun
set TeXFormatFlag to &
set MpFormatFlag to &
-% This one is only for testing, you can leave it untouched.
-
-set TeXFontsPath to l:/tex/texmf;l:/tex/texmf-local;
-
% For teTeX the next settings will do.
% -default-translate-file=cp8bit -file-line-error-style
@@ -95,24 +93,36 @@ for fptex set TeXExecutable to pdfetex
for fptex set TeXVirginFlag to -ini
for fptex set TeXPassString to -progname=context
for fptex set TeXBatchFlag to -int=batchmode
-for tetex set TeXNonStopFlag to -int=nonstopmode
+for fptex set TeXNonStopFlag to -int=nonstopmode
for fptex set MpToTeXExecutable to mpto
for fptex set MpVirginFlag to -ini
for fptex set MpPassString to -progname=mpost
for fptex set MpBatchFlag to -int=batchmode
-for tetex set MpNonStopFlag to -int=nonstopmode
+for fptex set MpNonStopFlag to -int=nonstopmode
+
+% a downward compatibility test (<7.5.3), next year we will use -8bit
+
+for tetex set TeXVirginFlag to -ini -translate-file=natural.tcx
+for fptex set TeXVirginFlag to -ini -translate-file=natural.tcx
+for tetex set MpVirginFlag to -ini -translate-file=natural.tcx
+for fptex set MpVirginFlag to -ini -translate-file=natural.tcx
+
+for tetex set TeXPassString to -progname=context -translate-file=natural.tcx
+for fptex set TeXPassString to -progname=context -translate-file=natural.tcx
+for tetex set MpPassString to -progname=mpost -translate-file=natural.tcx
+for fptex set MpPassString to -progname=mpost -translate-file=natural.tcx
% MikTeX users probably have to set up some paths too.
for miktex set TeXHashExecutable to initexmf --update-fndb
for miktex set TeXExecutable to pdfetex
for miktex set TeXVirginFlag to --initialize
-for miktex set TeXPassString to --alias=context
+for miktex set TeXPassString to --alias=context --translate-file=natural.tcx
for miktex set TeXBatchFlag to --interaction=batchmode
for miktex set TeXNonStopFlag to --interaction=nonstopmode
for miktex set MpToTeXExecutable to mptotex
for miktex set MpVirginFlag to --initialize
-for miktex set MpPassString to --alias=mpost
+for miktex set MpPassString to --alias=mpost --translate-file=natural.tcx
for miktex set MpBatchFlag to --interaction=batchmode
for miktex set MpNonStopFlag to --interaction=nonstopmode
diff --git a/scripts/context/perl/texfont.pl b/scripts/context/perl/texfont.pl
index b762e928d..bebb636f5 100644
--- a/scripts/context/perl/texfont.pl
+++ b/scripts/context/perl/texfont.pl
@@ -57,7 +57,7 @@ BEGIN {
$IsWin32 = ($^O =~ /MSWin32/i) ;
$SpacyPath = 0 ;
if ($IsWin32) {
- my $str = `kpsewhich --expand-path=\$TEXMF` ;
+ my $str = `kpsewhich -expand-path=\$TEXMF` ;
$SpacyPath = ($str =~ / /) ;
if ($SpacyPath) {
require Win32::API; import Win32::API;
@@ -155,9 +155,6 @@ my $variant = "" ; # atl: encoding variant
my $extension = "pfb" ; # atl: default font extension
my $lcdf = "" ; # atl: trigger for lcdf otftotfm
-my $mappath = 'fonts/map' ; # will be set later
-my $encpath = 'fonts/enc' ; # will be set later
-
my @cleanup = () ; # atl: build list of generated files to delete
# todo: parse name for style, take face from command line
@@ -227,8 +224,6 @@ if (!$novirtual) {
$virtual = 1 ;
}
-# starting with 2004 tetex/fptex/texlive will combine pdftex and dvips paths
-
# A couple of routines.
sub report {
@@ -305,9 +300,9 @@ if (($listing||$remove)&&($sourcepath eq "."))
if ($fontroot eq "")
{ if ($dosish)
- { $fontroot = `kpsewhich --expand-path=\$$installpath` }
+ { $fontroot = `kpsewhich -expand-path=\$$installpath` }
else
- { $fontroot = `kpsewhich --expand-path=\\\$$installpath` }
+ { $fontroot = `kpsewhich -expand-path=\\\$$installpath` }
chomp $fontroot }
@@ -381,11 +376,8 @@ if (($batch)||(($ARGV[0]) && ($ARGV[0] =~ /.+\.dat$/io)))
{ if ($batchfile !~ /\.dat$/io) { $batchfile .= ".dat" } }
unless (-f $batchfile)
{ report ("trying to locate : $batchfile") ;
- $batchfile = `kpsewhich --format="scripts" -progname=context $batchfile` ;
- chomp $batchfile ;
- if ($batchfile eq '')
- { $batchfile = `kpsewhich --format="other text files" -progname=context $batchfile` ;
- chomp $batchfile } }
+ $batchfile = `kpsewhich -format="other text files" -progname=context $batchfile` ;
+ chomp $batchfile }
error ("unknown batch file $batchfile") unless -e $batchfile ;
report ("processing batch file : $batchfile") ;
my $select = (($vendor ne "")||($collection ne "")) ;
@@ -500,7 +492,7 @@ if ($sourcepath eq "auto") # todo uppercase root
else
{ $path = `kpsewhich -expand-path=\\\$$root` }
chomp $path ;
- $path = $ENV{$root} if (($path == '') && defined($ENV{$root})) ;
+ $path = $ENV{$root} if (($path eq '') && defined($ENV{$root})) ;
report ("checking root : $root") ;
if ($preproc)
{ $sourcepath = "$path/fonts/truetype/$vendor/$collection" }
@@ -560,7 +552,7 @@ if ($sourcepath eq "auto") # todo uppercase root
{ report ("removing : $nam") ;
unlink "$nam" }
my $mapfile = "$encoding$varlabel-$vendor-$collection" ;
- my $maproot = "$fontroot/fonts/map/";
+ my $maproot = "$fontroot/fonts/map/pdftex/context";
if (-e "$maproot$mapfile.map")
{ report ("renaming : $mapfile.map -> $mapfile.bak") ;
unlink "$maproot$mapfile.bak" ;
@@ -571,15 +563,15 @@ if ($sourcepath eq "auto") # todo uppercase root
error ("unknown subpath ../fonts/afm/$vendor/$collection") unless -d $sourcepath }
error ("unknown source path $sourcepath") unless -d $sourcepath ;
-error ("unknown option $ARGV[0]") if ($ARGV[0] =~ /\-\-/) ;
+error ("unknown option $ARGV[0]") if (($ARGV[0]||'') =~ /\-\-/) ;
my $afmpath = "$fontroot/fonts/afm/$vendor/$collection" ;
my $tfmpath = "$fontroot/fonts/tfm/$vendor/$collection" ;
my $vfpath = "$fontroot/fonts/vf/$vendor/$collection" ;
my $pfbpath = "$fontroot/fonts/type1/$vendor/$collection" ;
my $ttfpath = "$fontroot/fonts/truetype/$vendor/$collection" ;
-my $mappath = "$fontroot/fonts/map" ;
-my $encpath = "$fontroot/fonts/enc" ;
+my $mappath = "$fontroot/fonts/map/pdftex/context" ;
+my $encpath = "$fontroot/fonts/enc/dvips/context" ;
# are not on local path ! ! ! !
@@ -588,10 +580,14 @@ foreach my $path ($afmpath, $pfbpath)
foreach my $file (@gzipped)
{ print "file = $file\n";
system ("gzip -d $file") } }
+
system ("mktexlsr $fontroot"); # needed ?
sub do_make_path
- { my $str = shift ; mkdir $str, 0755 unless -d $str }
+ { my $str = shift ;
+ if ($str =~ /^(.*)\/.*?$/)
+ { do_make_path($1) }
+ mkdir $str, 0755 unless -d $str }
sub make_path
{ my $str = shift ;
@@ -607,10 +603,6 @@ do_make_path($mappath) ;
do_make_path($encpath) ;
# now fonts/map and fonts/enc
-#
-# if ($lcdf)
-# { do_make_path("$fontroot/dvips") ;
-# do_make_path("$fontroot/dvips/local") }
make_path ("vf") ;
make_path ("tfm") ;
@@ -699,7 +691,7 @@ sub globafmfiles
}
return @files }
-if ($ARGV[0] ne "")
+if ($ARGV[0])
{ $pattern = $ARGV[0] ;
report ("processing files : all in pattern $ARGV[0]") ;
@files = globafmfiles($runpath,$pattern) }
@@ -765,7 +757,7 @@ if ($map)
print MAP "%\n" ;
print MAP "% Alternatively in your TeX source you can say:\n" ;
print MAP "%\n" ;
- print MAP "% \\pdfmapfile\{+$mapfile\}\n" ;
+ print MAP "% \\pdf \{+$mapfile\}\n" ;
print MAP "%\n" ;
print MAP "% In ConTeXt you can best use:\n" ;
print MAP "%\n" ;
@@ -905,46 +897,46 @@ foreach my $file (@files)
print "$otfcommand\n" if $trace ;
system("$otfcommand") ;
$encfil = $encout }
- else
- { # generate tfm and vpl, $file is on afm path
- my $font = '' ;
- if ($afmpl)
- { report " generating pl : $cleanname$fontsuffix (from $cleanname)" ;
- $encstr = " -p $encfil" ;
- my $command = "afm2pl $shape $passon $encstr $file $cleanname$fontsuffix.vpl" ;
- print "$command\n" if $trace ;
- my $ok = `$command` ;
- if (open (TMP,"$cleanname$fontsuffix.map"))
- { $font = <TMP> ;
- close(TMP) ;
- UnLink "$cleanname$fontsuffix.map" } }
else
- { report "generating raw tfm/vpl : $raw$cleanname$fontsuffix (from $cleanname)" ;
- my $command = "afm2tfm $file $shape $passon $encstr $vfstr $raw$cleanname$fontsuffix" ;
- print "$command\n" if $trace ;
- $font = `$command` }
- # generate vf file if needed
- chomp $font ;
- if ($font =~ /.*?([\d\.]+)\s*ExtendFont/io) { $extend = $1 }
- if ($font =~ /.*?([\d\.]+)\s*SlantFont/io) { $slant = $1 }
- if ($extend ne "") { $option .= " $1 ExtendFont " }
- if ($slant ne "") { $option .= " $1 SlantFont " }
- if ($noligs) { removeligatures("$raw$cleanname$fontsuffix") }
- if ($afmpl)
- { report "generating new tfm : $use$cleanname$fontsuffix" ;
- my $command = "pltotf $cleanname$fontsuffix.vpl $use$cleanname$fontsuffix.tfm" ;
- print "$command\n" if $trace ;
- my $ok = `$command` }
- elsif ($virtual)
- { report "generating new vf : $use$cleanname$fontsuffix (from $raw$cleanname)" ;
- my $command = "vptovf $raw$cleanname$fontsuffix.vpl $use$cleanname$fontsuffix.vf $use$cleanname$fontsuffix.tfm" ;
- print "$command\n" if $trace ;
- my $ok = `$command` }
- else
- { report "generating new tfm : $use$cleanname$fontsuffix (from $raw$cleanname)" ;
- my $command = "pltotf $raw$cleanname$fontsuffix.vpl $use$cleanname$fontsuffix.tfm" ;
- print "$command\n" if $trace ;
- my $ok = `$command` } } }
+ { # generate tfm and vpl, $file is on afm path
+ my $font = '' ;
+ if ($afmpl)
+ { report " generating pl : $cleanname$fontsuffix (from $cleanname)" ;
+ $encstr = " -p $encfil" ;
+ my $command = "afm2pl -f afm2tfm $shape $passon $encstr $file $cleanname$fontsuffix.vpl" ;
+ print "$command\n" if $trace ;
+ my $ok = `$command` ;
+ if (open (TMP,"$cleanname$fontsuffix.map"))
+ { $font = <TMP> ;
+ close(TMP) ;
+ UnLink "$cleanname$fontsuffix.map" } }
+ else
+ { report "generating raw tfm/vpl : $raw$cleanname$fontsuffix (from $cleanname)" ;
+ my $command = "afm2tfm $file $shape $passon $encstr $vfstr $raw$cleanname$fontsuffix" ;
+ print "$command\n" if $trace ;
+ $font = `$command` }
+ # generate vf file if needed
+ chomp $font ;
+ if ($font =~ /.*?([\d\.]+)\s*ExtendFont/io) { $extend = $1 }
+ if ($font =~ /.*?([\d\.]+)\s*SlantFont/io) { $slant = $1 }
+ if ($extend ne "") { $option .= " $1 ExtendFont " }
+ if ($slant ne "") { $option .= " $1 SlantFont " }
+ if ($noligs) { removeligatures("$raw$cleanname$fontsuffix") }
+ if ($afmpl)
+ { report "generating new tfm : $use$cleanname$fontsuffix" ;
+ my $command = "pltotf $cleanname$fontsuffix.vpl $use$cleanname$fontsuffix.tfm" ;
+ print "$command\n" if $trace ;
+ my $ok = `$command` }
+ elsif ($virtual)
+ { report "generating new vf : $use$cleanname$fontsuffix (from $raw$cleanname)" ;
+ my $command = "vptovf $raw$cleanname$fontsuffix.vpl $use$cleanname$fontsuffix.vf $use$cleanname$fontsuffix.tfm" ;
+ print "$command\n" if $trace ;
+ my $ok = `$command` }
+ else
+ { report "generating new tfm : $use$cleanname$fontsuffix (from $raw$cleanname)" ;
+ my $command = "pltotf $raw$cleanname$fontsuffix.vpl $use$cleanname$fontsuffix.tfm" ;
+ print "$command\n" if $trace ;
+ my $ok = `$command` } } }
elsif (-e "$sourcepath/$cleanname.tfm" )
{ report "using existing tfm : $cleanname.tfm" }
elsif (($strange eq "expert")&&($expert))
diff --git a/scripts/context/perl/texshow.pl b/scripts/context/perl/texshow.pl
index 533d7ed89..cc56a78a1 100644
--- a/scripts/context/perl/texshow.pl
+++ b/scripts/context/perl/texshow.pl
@@ -26,7 +26,7 @@ eval '(exit $?0)' && eval 'exec perl -S $0 ${1+"$@"}' && eval 'exec perl -S $0 $
#D next few lines are more appropriate:
BEGIN {
- $cont_pm_path = `kpsewhich --format="scripts" --progname=context cont_mis.pm` ;
+ $cont_pm_path = `kpsewhich --format="texmfscripts" --progname=context cont_mis.pm` ;
chomp($cont_pm_path) ;
if ($cont_pm_path eq '') {
$cont_pm_path = `kpsewhich --format="other text files" --progname=context cont_mis.pm` ;
diff --git a/scripts/context/perl/texutil.pl b/scripts/context/perl/texutil.pl
index 14b2b3a4f..e7f13ee3e 100644
--- a/scripts/context/perl/texutil.pl
+++ b/scripts/context/perl/texutil.pl
@@ -40,7 +40,7 @@ eval '(exit $?0)' && eval 'exec perl -S $0 ${1+"$@"}' && eval 'exec perl -S $0 $
#D binary version, like scanning illustrations other than \EPS.
#D I would suggest to keep an eye on the version number:
-$Program = "TeXUtil 8.2 - ConTeXt / PRAGMA ADE 1992-2004" ;
+$Program = "TeXUtil 9.0 - ConTeXt / PRAGMA ADE 1992-2004" ;
#D By the way, this is my first \PERL\ script, which means
#D that it will be improved as soon as I find new and/or more
@@ -979,13 +979,15 @@ sub HandleCommand
$RestOfLine =~ s/^\\//go ;
if ($RestOfLine =~ /^pospxy/o)
{ ++$NOfPositionsFound }
- elsif ($RestOfLine =~ /^initializevariable\\totalnofpositions\{(.*)\}/i)
+ elsif ($RestOfLine =~ /^initializevariable\\totalnofpositions\{(.*)\}/o)
{ $TotalNOfPositions = $1 }
- elsif ($RestOfLine =~ /^initializevariable\\totalnofMPgraphics\{(.*)\}/i)
+ elsif ($RestOfLine =~ /^initializevariable\\totalnofMPgraphics\{(.*)\}/o)
{ $TotalNOfMPgraphics = $1 }
# todo: reg how to
# elsif ($RestOfLine =~ /^thisissectionseparator\{(.*)\}/o)
# { $SectionSeparator = $1 }
+ elsif ($RestOfLine =~ /^thisisbytesequence\{(.*)\}/o)
+ { $RestOfLine =~ s/\^//go }
print TUO "\\$RestOfLine\n" }
sub FlushCommands
@@ -2021,7 +2023,7 @@ sub SaveFigurePresets
{ ++$NOfFigures ;
$Figures[$NOfFigures] = "\\presetfigure[$FNam][e=$FTyp" ;
if ($FUni)
- { $Figures[$NOfFigures] .= (sprintf ",w=%5.3fcm,h=%5.3fcm\n", $FWid, $FHei) }
+ { $Figures[$NOfFigures] .= (sprintf ",w=%5.3fcm,h=%5.3fcm", $FWid, $FHei) }
else
{ $Figures[$NOfFigures] .= ",w=${FWid}bp,h=${FHei}bp" }
if (($FXof!=0)||($FYof!=0))
@@ -2129,7 +2131,7 @@ sub HandleEpsFigure
if (($BBoxFound) && ((substr $SomeLine,0,1) ne "%"))
{ last }
if ($BBoxFound<2)
- { if ($SomeLine =~ /^%%BoundingBox:/io)
+ { if ($SomeLine =~ /^%%BoundingBox:(?!\s+\(atend\))/io) # atend (th)
{ $EpsBBox = $SomeLine ; $BBoxFound = 1 ; next }
elsif ($SomeLine =~ /^%%HiResBoundingBox:/io)
{ $EpsBBox = $SomeLine ; $BBoxFound = 2 ; next }
@@ -2716,7 +2718,7 @@ if ($PurgeAllFiles)
{ push @forsuresuffixes, @texnonesuffixes ; @texnonesuffixes = [] }
sub PurgeFiles # no my in foreach
- { my $pattern = $ARGV[0] ; my $strippedname ;
+ { my $pattern = $ARGV[0] ; my $strippedname, $basename ;
my @files = () ;
if ($pattern eq '')
{ $pattern = "*.*" ;
@@ -2742,9 +2744,11 @@ sub PurgeFiles # no my in foreach
{ foreach (@files)
{ if (/\.$suffix$/i)
{ RemoveContextFile($_) } } }
- foreach (@files)
- { if (/\.\d*$/)
- { RemoveContextFile($_) } }
+ foreach $file (@files)
+ { if ($file =~ /(.*?)\.\d+$/)
+ { $basename = $1 ;
+ if (($file =~ /mp(graph|run)/) || (-e "$basename.mp"))
+ { RemoveContextFile($file) } } }
foreach $suffix (@texnonesuffixes)
{ foreach (@files)
{ if (/(.*)\.$suffix$/i)
diff --git a/scripts/context/ruby/concheck.rb b/scripts/context/ruby/concheck.rb
new file mode 100644
index 000000000..b15c9b3ae
--- /dev/null
+++ b/scripts/context/ruby/concheck.rb
@@ -0,0 +1,459 @@
+# Program : concheck (tex & context syntax checker)
+# Copyright : PRAGMA ADE / Hasselt NL / www.pragma-ade.com
+# Author : Hans Hagen
+# Version : 1.1 / 2003.08.18
+
+# remarks:
+#
+# - the error messages are formatted like tex's messages so that scite can see them
+# - begin and end tags are only tested on a per line basis because we assume clean sources
+# - maybe i'll add begin{something} ... end{something} checking
+
+# # example validation file
+#
+# begin interface en
+#
+# 1 text
+# 4 Question
+# 0 endinput
+# 0 setupsomething
+# 0 chapter
+#
+# end interface en
+
+# nicer
+
+# class Interface
+
+ # def initialize (language = 'unknown')
+ # @valid = Array.new
+ # @language = language
+ # end
+
+ # def register (left, right)
+ # @valid.push([left,right])
+ # end
+
+# end
+
+# $interfaces = Hash.new
+
+# $interfaces['en'] = Interface.new('english')
+# $interfaces['nl'] = Interface.new('dutch')
+
+# $interfaces['en'].add('\\\\start','\\\\stop')
+# $interfaces['en'].add('\\\\begin','\\\\end')
+# $interfaces['en'].add('\\\\Start','\\\\Stop')
+# $interfaces['en'].add('\\\\Begin','\\\\End')
+
+# $interfaces['nl'].add('\\\\start','\\\\stop')
+# $interfaces['nl'].add('\\\\beginvan','\\\\eindvan')
+# $interfaces['nl'].add('\\\\Start','\\\\Stop')
+# $interfaces['nl'].add('\\\\BeginVan','\\\\Eindvan')
+
+# rest todo
+
+$valid = Hash.new
+
+$valid['en'] = Array.new
+$valid['nl'] = Array.new
+
+#$valid['en'].push(['',''])
+$valid['en'].push(['\\\\start','\\\\stop'])
+$valid['en'].push(['\\\\begin','\\\\end'])
+$valid['en'].push(['\\\\Start','\\\\Stop'])
+$valid['en'].push(['\\\\Begin','\\\\End'])
+
+#$valid['nl'].push(['',''])
+$valid['nl'].push(['\\\\start','\\\\stop'])
+$valid['nl'].push(['\\\\beginvan','\\\\eindvan'])
+$valid['nl'].push(['\\\\Start','\\\\Stop'])
+$valid['nl'].push(['\\\\BeginVan','\\\\Eindvan'])
+
+$valid_tex = "\\\\end\(input|insert|csname|linechar|graf|buffer|strut\)"
+$valid_mp = "(enddef||end||endinput)"
+
+$start_verbatim = Hash.new
+$stop_verbatim = Hash.new
+
+$start_verbatim['en'] = '\\\\starttyping'
+$start_verbatim['nl'] = '\\\\starttypen'
+
+$stop_verbatim['en'] = '\\\\stoptyping'
+$stop_verbatim['nl'] = '\\\\stoptypen'
+
+def message(str, filename=nil, line=nil, column=nil)
+ if filename then
+ if line then
+ if column then
+ puts("error in file #{filename} at line #{line} in column #{column}: #{str}\n")
+ else
+ puts("error in file #{filename} at line #{line}: #{str}\n")
+ end
+ else
+ puts("file #{filename}: #{str}\n")
+ end
+ else
+ puts(str+"\n")
+ end
+end
+
+def load_file (filename='')
+ begin
+ data = IO.readlines(filename)
+ data.collect! do |d|
+ if d =~ /^\s*%/o then
+ ''
+ elsif d =~ /(.*?[^\\])%.*$/o then
+ $1
+ else
+ d
+ end
+ end
+ rescue
+ message("provide proper filename")
+ return nil
+ end
+ # print data.to_s + "\n"
+ return data
+end
+
+def guess_interface(data)
+ if data.first =~ /^%.*interface\=(.*)\s*/ then
+ return $1
+ else
+ data.each do |line|
+ case line
+ when /\\(starttekst|stoptekst|startonderdeel|startdocument|startoverzicht)/o then return 'nl'
+ when /\\(stelle|verwende|umgebung|benutze)/o then return 'de'
+ when /\\(stel|gebruik|omgeving)/ then return 'nl'
+ when /\\(use|setup|environment)/ then return 'en'
+ when /\\(usa|imposta|ambiente)/ then return 'it'
+ when /(height|width|style)=/ then return 'en'
+ when /(hoehe|breite|schrift)=/ then return 'de'
+ when /(hoogte|breedte|letter)=/ then return 'nl'
+ when /(altezza|ampiezza|stile)=/ then return 'it'
+ when /externfiguur/ then return 'nl'
+ when /externalfigure/ then return 'en'
+ when /externeabbildung/ then return 'de'
+ when /figuraesterna/ then return 'it'
+ end
+ end
+ return 'en'
+ end
+end
+
+def cleanup_data(data, interface='en')
+ verbatim = 0
+ re_start = /^\s*#{$start_verbatim[interface]}/
+ re_stop = /^\s*#{$stop_verbatim[interface]}/
+ data.collect! do |d|
+ if d =~ re_start then
+ verbatim += 1
+ if verbatim>1 then
+ ''
+ else
+ d
+ end
+ elsif d =~ re_stop then
+ verbatim -= 1
+ if verbatim>0 then
+ ''
+ else
+ d
+ end
+ elsif verbatim > 0 then
+ ''
+ else
+ d
+ end
+ end
+ return data
+end
+
+def load_valid(data, interface=nil)
+ if data && (data.first =~ /^%.*valid\=(.*)\s*/)
+ filename = $1
+ filename = '../' + filename unless test(?f,filename)
+ filename = '../' + filename unless test(?f,filename)
+ if test(?f,filename) then
+ interface = guess_interface(data) unless interface
+ if $valid.has_key?(interface) then
+ interface = $valid[interface]
+ else
+ interface = $valid['en']
+ end
+ begin
+ message("loading validation file",filename)
+ validkeys = Hash.new
+ line = 1
+ IO.readlines(filename).each do |l|
+ if l =~ /\s+[\#\%]/io then
+ # ignore line
+ elsif l =~ /^\s*(begin|end)\s+interface\s+([a-z][a-z])/o then
+ # not yet supported
+ elsif l =~ /^\s*(\d+)\s+([a-zA-Z]*)$/o then
+ type, key = $1.to_i, $2.strip
+ if interface[type] then
+ validkeys[interface[type].first+key] = true
+ validkeys[interface[type].last+key] = true
+ else
+ error_message(filename,line,nil,'wrong definition')
+ end
+ end
+ line += 1
+ end
+ if validkeys then
+ message("#{validkeys.length} validation keys loaded",filename)
+ end
+ return validkeys
+ rescue
+ message("invalid validation file",filename)
+ end
+ else
+ message("unknown validation file", filename)
+ end
+ else
+ message("no extra validation file specified")
+ end
+ return nil
+end
+
+def some_chr_error(data, filename, left, right)
+ levels = Array.new
+ for line in 0..data.length-1 do
+ str = data[line]
+ column = 0
+ while column<str.length do
+ case str[column].chr
+ when "\%" then
+ break
+ when "\\" then
+ column += 2
+ when left then
+ levels.push([line,column])
+ column += 1
+ when right then
+ if levels.pop
+ column += 1
+ else
+ message("missing #{left} for #{right}",filename,line+1,column+1)
+ return true
+ end
+ else
+ column += 1
+ end
+ end
+ end
+ if levels && levels.length>0 then
+ levels.each do |l|
+ column = l.pop
+ line = l.pop
+ message("missing #{right} for #{left}",filename,line+1,column+1)
+ end
+ return true
+ else
+ return false
+ end
+end
+
+def some_wrd_error(data, filename, start, stop, ignore)
+ levels = Array.new
+ len = 0
+ re_start = /[^\%]*(#{start})([a-zA-Z]*)/
+ re_stop = /[^\%]*(#{stop})([a-zA-Z]*)/
+ re_ignore = /#{ignore}.*/
+ str_start = start.gsub(/\\+/,'\\')
+ str_stop = stop.gsub(/\\+/,'\\')
+ line = 0
+ while line<data.length do
+ dataline = data[line].split(/[^\\A-Za-z]/)
+ if dataline.length>0 then
+ dataline.each do |dataword|
+ case dataword
+ when re_ignore then
+ # just go on
+ when re_start then
+ levels.push([line,$2])
+ # print ' '*levels.length + '>' + $2 + "\n"
+ when re_stop then
+ # print ' '*levels.length + '<' + $2 + "\n"
+ if levels && levels.last && (levels.last[1] == $2) then
+ levels.pop
+ elsif levels && levels.last then
+ message("#{str_stop}#{levels.last[1]} expected instead of #{str_stop}#{$2}",filename,line+1)
+ return true
+ else
+ message("missing #{str_start}#{$2} for #{str_stop}#{$2}",filename,line+1)
+ return true
+ end
+ else
+ # just go on
+ end
+ end
+ end
+ line += 1
+ end
+ if levels && levels.length>0 then
+ levels.each do |l|
+ text = l.pop
+ line = l.pop
+ message("missing #{str_stop}#{text} for #{str_start}#{text}",filename,line+1)
+ end
+ return true
+ else
+ return false
+ end
+end
+
+def some_sym_error (data, filename, symbol,template=false)
+ saved = Array.new
+ inside = false
+ level = 0
+ for line in 0..data.length-1 do
+ str = data[line]
+ column = 0
+ while column<str.length do
+ case str[column].chr
+ when "[" then
+ level += 1 if template
+ when "]" then
+ level -= 1 if template && level > 0
+ when "\%" then
+ break
+ when "\\" then
+ column += 1
+ when symbol then
+ if level == 0 then
+ inside = ! inside
+ saved = [line,column]
+ else
+ # we're in some kind of template or so
+ end
+ else
+ # go on
+ end
+ column += 1
+ end
+ end
+ if inside && saved && level == 0 then
+ column = saved.pop
+ line = saved.pop
+ message("missing #{symbol} for #{symbol}",filename,line+1)
+ return true
+ else
+ return false
+ end
+end
+
+def some_key_error(data, filename, valid)
+ return if (! valid) || (valid.length == 0)
+ error = false
+ for line in 0..data.length-1 do
+ data[line].scan(/\\([a-zA-Z]+)/io) do
+ unless valid.has_key?($1) then
+ message("unknown command \\#{$1}",filename,line+1)
+ error = true
+ end
+ end
+ end
+ return error
+end
+
+# todo : language dependent
+
+def check_file_tex (filename)
+ if data = load_file(filename) then
+ message("checking tex file", filename)
+ interface = guess_interface(data)
+ valid = load_valid(data,interface)
+ data = cleanup_data(data,interface)
+ # data.each do |d| print d end
+ $valid[interface].each do |v|
+ return false if some_wrd_error(data, filename, v[0], v[1] ,$valid_tex)
+ end
+ # return false if some_wrd_error(data, filename, '\\\\start' , '\\\\stop' , $valid_tex)
+ # return false if some_wrd_error(data, filename, '\\\\Start' , '\\\\Stop' , $valid_tex)
+ # return false if some_wrd_error(data, filename, '\\\\beginvan', '\\\\eindvan', $valid_tex)
+ # return false if some_wrd_error(data, filename, '\\\\begin' , '\\\\end|\\\\eind', $valid_tex)
+ return false if some_sym_error(data, filename, '$', false)
+ return false if some_sym_error(data, filename, '|', true)
+ return false if some_chr_error(data, filename, '{', '}')
+ return false if some_chr_error(data, filename, '[', ']')
+ return false if some_chr_error(data, filename, '(', ')')
+ return false if some_key_error(data, filename, valid)
+ message("no errors in tex code", filename)
+ return true
+ else
+ return false
+ end
+end
+
+def check_file_mp (filename)
+ if data = load_file(filename) then
+ message("checking metapost file", filename)
+ interface = guess_interface(data)
+ valid = load_valid(data,interface)
+ $valid[interface].each do |v|
+ return false if some_wrd_error(data, filename, v[0], v[1] ,$valid_tex)
+ end
+ # return false if some_wrd_error(data, filename, '', 'begin', 'end', $valid_mp)
+ return false if some_chr_error(data, filename, '{', '}')
+ return false if some_chr_error(data, filename, '[', ']')
+ return false if some_chr_error(data, filename, '(', ')')
+ return false if some_key_error(data, filename, valid)
+ message("no errors in metapost code", filename)
+ return true
+ else
+ return true
+ end
+end
+
+def check_file_text(filename='')
+ if data = load_file(filename) then
+ for line in 0..data.length-1 do
+ # case data[line]
+ # when /\s([\:\;\,\.\?\!])/ then
+ # message("space before #{$1}",filename,line+1)
+ # when /\D([\:\;\,\.\?\!])\S/ then
+ # message("no space after #{$1}",filename,line+1)
+ # end
+ if data[line] =~ /\s([\:\;\,\.\?\!])/ then
+ message("space before #{$1}",filename,line+1)
+ else
+ data[line].gsub!(/\[.*?\]/o, '')
+ data[line].gsub!(/\(.*?\)/o, '')
+ data[line].gsub!(/\[.*?$/o, '')
+ data[line].gsub!(/^.*?\]/o, '')
+ if data[line] =~ /\D([\:\;\,\.\?\!])\S/ then
+ message("no space after #{$1}",filename,line+1)
+ end
+ end
+ end
+ end
+end
+
+def check_file(filename='')
+ case filename
+ when '' then
+ message("provide filename")
+ return false
+ when /\.tex$/i then
+ return check_file_tex(filename) # && check_file_text(filename)
+ when /\.mp$/i then
+ return check_file_mp(filename)
+ else
+ message("only tex and metapost files are checked")
+ return false
+ end
+end
+
+if filename = ARGV[0] then
+ if check_file(filename) then
+ exit 0
+ else
+ exit 1
+ end
+else
+ exit 1
+end \ No newline at end of file
diff --git a/scripts/context/ruby/exa/logger.rb b/scripts/context/ruby/exa/logger.rb
new file mode 100644
index 000000000..fc5212fc0
--- /dev/null
+++ b/scripts/context/ruby/exa/logger.rb
@@ -0,0 +1,104 @@
+# module : exa/logger
+# copyright : PRAGMA Publishing On Demand
+# version : 1.01 - 2002/2003
+# author : Hans Hagen
+#
+# project : eXaMpLe
+# concept : Hans Hagen
+# info : j.hagen@xs4all.nl
+# www : www.pragma-pod.com / www.pragma-ade.com
+
+require 'thread'
+
+module EXA
+
+ # The next calls are valid:
+ #
+ # @log.report('a','b','c', 'd')
+ # @log.report('a','b',"c #{d}")
+ # @log.report("a b c #{d}")
+ #
+ # Keep in mind that "whatever #{something}" is two times faster than
+ # 'whatever ' + something or ['whatever',something].join and that
+ # when verbosity is not needed the following is much faster too:
+ #
+ # @log.report('a','b','c', 'd') if @log.verbose?
+ # @log.report('a','b',"c #{d}") if @log.verbose?
+ # @log.report("a b c #{d}") if @log.verbose?
+ #
+ # The last three cases are equally fast when verbosity is turned off.
+
+ # Under consideration: verbose per instance
+
+ class ExaLogger
+
+ @@length = 0
+ @@verbose = false
+
+ def initialize(tag=nil,length=0,verbose=false)
+ @tag = tag || ''
+ @@verbose = @@verbose || verbose
+ @@length = @tag.length if @tag.length > @@length
+ @@length = length if length > @@length
+ end
+
+ def report(*str)
+ begin
+ case str.length
+ when 0
+ print("\n")
+ return true
+ when 1
+ message = str.first
+ else
+ message = [str].flatten.collect{|s| s.to_s}.join(' ').chomp
+ end
+ if @tag.empty? then
+ print("#{message}\n")
+ else
+ # try to avoid too many adjustments
+ @tag = @tag.ljust(@@length) unless @tag.length == @@length
+ print("#{@tag} | #{message}\n")
+ end
+ rescue
+ end
+ return true
+ end
+
+ def reportlines(*str)
+ unless @tag.empty? then
+ @tag = @tag.ljust(@@length) unless @tag.length == @@length
+ end
+ report([str].flatten.collect{|s| s.gsub(/\n/,"\n#{@tag} | ")}.join(' '))
+ end
+
+ def debug(*str)
+ report(str) if @@verbose
+ end
+
+ def error(*str)
+ if ! $! || $!.to_s.empty? then
+ report(str)
+ else
+ report(str,$!)
+ end
+ end
+
+ def verbose
+ @@verbose = true
+ end
+
+ def verbose?
+ @@verbose
+ end
+
+ # attr_reader :tag
+
+ # alias fatal error
+ # alias info debug
+ # alias warn debug
+ # alias debug? :verbose?
+
+ end
+
+end \ No newline at end of file
diff --git a/scripts/context/ruby/texmfstart.rb b/scripts/context/ruby/texmfstart.rb
new file mode 100644
index 000000000..8d5175325
--- /dev/null
+++ b/scripts/context/ruby/texmfstart.rb
@@ -0,0 +1,483 @@
+#!/usr/bin/env ruby
+
+# program : texmfstart
+# copyright : PRAGMA Advanced Document Engineering
+# version : 1.04 - 2003/2004
+# author : Hans Hagen
+#
+# project : ConTeXt / eXaMpLe
+# info : j.hagen@xs4all.nl
+# www : www.pragma-pod.com / www.pragma-ade.com
+
+# texmfstart [switches] filename [optional arguments]
+#
+# ruby2exe texmfstart --help -> avoids stub test
+#
+# Of couse I can make this into a nice class, which i'll undoubtely will
+# do when I feel the need. In that case it will be part of a bigger game.
+
+# turning this into a service would be nice, so some day ...
+
+require "rbconfig"
+
+$mswindows = Config::CONFIG['host_os'] =~ /mswin/
+$separator = File::PATH_SEPARATOR
+
+if $mswindows then
+
+ require "win32ole"
+ require "Win32API"
+
+ GetShortPathName = Win32API.new('kernel32', 'GetShortPathName', ['P','P','N'], 'N')
+ GetLongPathName = Win32API.new('kernel32', 'GetLongPathName', ['P','P','N'], 'N')
+
+ def dowith_pathname (filename,filemethod)
+ filename.gsub!(/\\/o,'/')
+ case filename
+ when /\;/o then
+ # could be a path spec
+ return filename
+ when /\s+/o then
+ # danger lurking
+ buffer = ' ' * 260
+ length = filemethod.call(filename,buffer,buffer.size)
+ if length>0 then
+ return buffer.slice(0..length-1)
+ else
+ # when the path or file does not exist, nothing is returned
+ # so we try to handle the path separately from the basename
+ basename = File.basename(filename)
+ pathname = File.dirname(filename)
+ length = filemethod.call(pathname,buffer,260)
+ if length>0 then
+ return buffer.slice(0..length-1) + '/' + basename
+ else
+ return filename
+ end
+ end
+ else
+ # no danger
+ return filename
+ end
+ end
+
+ def shortpathname (filename)
+ dowith_pathname(filename,GetShortPathName)
+ end
+
+ def longpathname (filename)
+ dowith_pathname(filename,GetLongPathName)
+ end
+
+else
+
+ def shortpathname (filename)
+ filename
+ end
+
+ def longpathname (filename)
+ filename
+ end
+
+end
+
+$applications = Hash.new
+$suffixinputs = Hash.new
+
+$suffixinputs['pl'] = 'PERLINPUTS'
+$suffixinputs['rb'] = 'RUBYINPUTS'
+$suffixinputs['py'] = 'PYTHONINPUTS'
+$suffixinputs['jar'] = 'JAVAINPUTS'
+$suffixinputs['pdf'] = 'PDFINPUTS'
+
+$scriptlist = 'rb|pl|py|jar'
+$documentlist = 'pdf|ps|eps|htm|html'
+
+def hashed (arr=[])
+ arg = if arr.class == String then arr.split(' ') else arr.dup end
+ hsh = Hash.new
+ if arg.length > 0
+ hsh['arguments'] = ''
+ done = false
+ arg.each do |s|
+ if done then
+ hsh['arguments'] += ' ' + s
+ else
+ kvl = s.split('=')
+ if kvl[0].sub!(/^\-+/,'') then
+ hsh[kvl[0]] = if kvl.length > 1 then kvl[1] else true end
+ else
+ hsh['file'] = s
+ done = true
+ end
+ end
+ end
+ end
+ return hsh
+end
+
+def launch(filename)
+ if $browser && $mswindows then
+ filename.gsub!(/\.[\/\\]/) do
+ Dir.getwd + '/'
+ end
+ report("launching #{filename}")
+ ie = WIN32OLE.new("InternetExplorer.Application")
+ ie.visible = true
+ ie.navigate(filename)
+ return true
+ else
+ return false
+ end
+end
+
+def runoneof(application,fullname,browserpermitted)
+ if browserpermitted && launch(fullname) then
+ return true
+ else
+ report("starting #{$filename}") unless $report
+ print "\n" if $report && $verbose
+ applications = $applications[application]
+ if applications.class == Array then
+ if $report then
+ print [fullname,$arguments].join(' ')
+ return true
+ else
+ applications.each do |a|
+ if system([a,fullname,$arguments].join(' ')) then
+ return true
+ end
+ end
+ end
+ elsif applications.empty? then
+ if $report then
+ print [fullname,$arguments].join(' ')
+ return true
+ else
+ return system([fullname,$arguments].join(' '))
+ end
+ else
+ if $report then
+ print [applications,fullname,$arguments].join(' ')
+ return true
+ else
+ return system([applications,fullname,$arguments].join(' '))
+ end
+ end
+ return false
+ end
+end
+
+def report(str)
+ print str + "\n" if $verbose ;
+end
+
+def usage
+ print "version : 1.04 - 2003/2004 - www.pragma-ade.com\n"
+ print("\n")
+ print("usage : texmfstart [switches] filename [optional arguments]\n")
+ print("\n")
+ print("switches : --verbose --report --browser\n")
+ print(" --program --file --page --arguments\n")
+ print(" --make --lmake --wmake\n")
+ print("\n")
+ print("example : texmfstart pstopdf.rb cow.eps\n")
+ print(" texmfstart --browser examplap.pdf\n")
+ print(" texmfstart showcase.pdf\n")
+ print(" texmfstart --page=2 --file=showcase.pdf\n")
+ print(" texmfstart --program=yourtex yourscript.pl arg-1 arg-2\n")
+end
+
+# somehow registration does not work out (at least not under windows)
+
+def registered?(filename)
+ return ENV['texmfstart.'+filename] != nil
+end
+
+def registered(filename)
+ return ENV['texmfstart.'+filename]
+end
+
+def register(filename,fullname)
+ if fullname && ! fullname.empty? then # && FileTest.file?(fullname)
+ ENV['texmfstart.'+filename] = fullname
+ return true
+ else
+ return false
+ end
+end
+
+def find(filename,program)
+ if registered?(filename) then
+ report("already located '#{filename}'")
+ return registered(filename)
+ end
+ # create suffix list
+ if filename =~ /^(.*)\.(.+)$/ then
+ filename = $1
+ suffixlist = [$2]
+ else
+ suffixlist = [$scriptlist.split('|'),$documentlist.split('|')].flatten
+ end
+ # first we honor a given path or
+ if filename =~ /[\\\/]/ then
+ report("trying to honor '#{filename}'")
+ suffixlist.each do |suffix|
+ fullname = filename+'.'+suffix
+ if FileTest.file?(fullname) && register(filename,fullname)
+ return shortpathname(fullname)
+ end
+ end
+ end
+ filename.sub!(/^.*[\\\/]/, '')
+ # next we look at the current path
+ suffixlist.each do |suffix|
+ report("locating '#{filename}.#{suffix}' in currentpath")
+ fullname = './'+filename+'.'+suffix
+ if FileTest.file?(fullname) && register(filename,fullname) then
+ report("'#{filename}.#{suffix}' located in currentpath")
+ return shortpathname(fullname)
+ end
+ end
+ # now we consult environment settings
+ fullname = nil
+ suffixlist.each do |suffix|
+ begin
+ break unless $suffixinputs[suffix]
+ environment = ENV[$suffixinputs[suffix]] || ENV[$suffixinputs[suffix]+".#{$program}"]
+ if ! environment || environment.empty? then
+ begin
+ environment = `kpsewhich -expand-path=\$#{$suffixinputs[suffix]}`.chomp
+ rescue
+ environment = nil
+ else
+ if environment && ! environment.empty? then
+ report("using kpsewhich variable #{$suffixinputs[suffix]}")
+ end
+ end
+ elsif environment && ! environment.empty? then
+ report("using environment variable #{$suffixinputs[suffix]}")
+ end
+ if environment && ! environment.empty? then
+ environment.split($separator).each do |e|
+ e.strip!
+ e = '.' if e == '\.' # somehow . gets escaped
+ e += '/' unless e =~ /[\\\/]$/
+ fullname = e + filename + '.' + suffix
+ report("testing '#{fullname}'")
+ if FileTest.file?(fullname) then
+ break
+ else
+ fullname = nil
+ end
+ end
+ end
+ rescue
+ report("environment string '#{$suffixinputs[suffix]}' cannot be used to locate '#{filename}'")
+ fullname = nil
+ else
+ return shortpathname(fullname) if register(filename,fullname)
+ end
+ end
+ return shortpathname(fullname) if register(filename,fullname)
+ # then we fall back on kpsewhich
+ suffixlist.each do |suffix|
+ # TDS script scripts location as per 2004
+ if suffix =~ /(#{$scriptlist})/ then
+ begin
+ report("using 'kpsewhich' to locate '#{filename}' in suffix space '#{suffix}' (1)")
+ fullname = `kpsewhich -progname=#{program} -format=texmfscripts #{filename}.#{suffix}`.chomp
+ rescue
+ report("kpsewhich cannot locate '#{filename}' in suffix space '#{suffix}' (1)")
+ fullname = nil
+ else
+ return shortpathname(fullname) if register(filename,fullname)
+ end
+ end
+ # old TDS location: .../texmf/context/...
+ begin
+ report("using 'kpsewhich' to locate '#{filename}' in suffix space '#{suffix}' (2)")
+ fullname = `kpsewhich -progname=#{program} -format="other text files" #{filename}.#{suffix}`.chomp
+ rescue
+ report("kpsewhich cannot locate '#{filename}' in suffix space '#{suffix}' (2)")
+ fullname = nil
+ else
+ return shortpathname(fullname) if register(filename,fullname)
+ end
+ end
+ return fullname if register(filename,fullname)
+ # bad luck, we need to search the tree ourselves
+ if (suffixlist.length == 1) && (suffixlist.first =~ /(#{$documentlist})/) then
+ report("aggressively locating '#{filename}' in document trees")
+ begin
+ texroot = `kpsewhich -expand-var=$SELFAUTOPARENT`.chomp
+ rescue
+ texroot = ''
+ else
+ texroot.sub!(/[\\\/][^\\\/]*?$/, '')
+ end
+ if not texroot.empty? then
+ sffxlst = suffixlist.join(',')
+ begin
+ report("locating '#{filename}' in document tree '#{texroot}/doc*'")
+ if (result = Dir.glob("#{texroot}/doc*/**/#{filename}.{#{sffxlst}}")) && result && result[0] && FileTest.file?(result[0]) then
+ fullname = result[0]
+ end
+ rescue
+ report("locating '#{filename}.#{suffix}' in tree '#{texroot}' aborted")
+ end
+ end
+ return shortpathname(fullname) if register(filename,fullname)
+ end
+ report("aggressively locating '#{filename}' in tex trees")
+ begin
+ textrees = `kpsewhich -expand-var=$TEXMF`.chomp
+ rescue
+ textrees = ''
+ end
+ if not textrees.empty? then
+ textrees.gsub!(/[\{\}\!]/, '')
+ textrees = textrees.split(',')
+ if (suffixlist.length == 1) && (suffixlist.first =~ /(#{$documentlist})/) then
+ speedup = ['doc**','**']
+ else
+ speedup = ['**']
+ end
+ sffxlst = suffixlist.join(',')
+ speedup.each do |speed|
+ textrees.each do |tt|
+ tt.gsub!(/[\\\/]$/, '')
+ if FileTest.directory?(tt) then
+ begin
+ report("locating '#{filename}' in tree '#{tt}/#{speed}/#{filename}.{#{sffxlst}}'")
+ if (result = Dir.glob("#{tt}/#{speed}/#{filename}.{#{sffxlst}}")) && result && result[0] && FileTest.file?(result[0]) then
+ fullname = result[0]
+ break
+ end
+ rescue
+ report("locating '#{filename}' in tree '#{tt}' aborted")
+ next
+ end
+ end
+ end
+ break if fullname && ! fullname.empty?
+ end
+ end
+ if register(filename,fullname) then
+ return shortpathname(fullname)
+ else
+ return ''
+ end
+end
+
+def run(fullname)
+ if ! fullname || fullname.empty? then
+ report("the file '#{$filename}' is not found")
+ elsif FileTest.file?(fullname) then
+ begin
+ case fullname
+ when /\.(#{$scriptlist})$/ then
+ return runoneof($1,fullname,false)
+ when /\.(#{$documentlist})$/ then
+ return runoneof($1,fullname,true)
+ else
+ return runoneof('unknown',fullname,false)
+ end
+ rescue
+ report("starting '#{$filename}' in program space '#{$program}' fails")
+ end
+ else
+ report("the file '#{$filename}' in program space '#{$program}' is not accessible")
+ end
+ return false
+end
+
+def make(filename,windows=false,linux=false)
+ basename = filename.dup
+ basename.sub!(/\.[^.]+?$/, '')
+ basename.sub!(/^.*[\\\/]/, '')
+ basename = $stubpath + '/' + basename unless $stubpath.empty?
+ if basename == filename then
+ report('nothing made')
+ else
+ program = nil
+ if filename =~ /[\\\/]/ && filename =~ /\.(#{$scriptlist})$/ then
+ program = $applications[$1]
+ end
+ filename = "\"#{filename}\"" if filename =~ /\s/
+ program = 'texmfstart' if $indirect || ! program || program.empty?
+ begin
+ if windows && f = open(basename+'.bat','w') then
+ f.puts("@echo off\n")
+ f.puts("#{program} #{filename} %*\n")
+ f.close
+ report("windows stub '#{basename}.bat' made")
+ end
+ if linux && f = open(basename,'w') then
+ f.puts("#!/bin/sh\n")
+ f.puts("#{program} #{filename} $@\n")
+ f.close
+ report("unix stub '#{basename}' made")
+ end
+ rescue
+ report("failed to make stub '#{basename}'")
+ else
+ return true
+ end
+ end
+ return false
+end
+
+$stdout.sync = true
+$directives = hashed(ARGV)
+
+$help = $directives['help'] || false
+$filename = $directives['file'] || ''
+$program = $directives['program'] || 'context'
+$page = $directives['page'] || 0
+$browser = $directives['browser'] || false
+$report = $directives['report'] || false
+$verbose = $directives['verbose'] || false
+$arguments = $directives['arguments'] || ''
+
+$make = $directives['make'] || false
+$unix = $directives['unix'] || false
+$windows = $directives['windows'] || false
+$stubpath = $directives['stubpath'] || ''
+$indirect = $directives['indirect'] || false
+
+$applications['unknown'] = ''
+$applications['perl'] = $applications['pl'] = 'perl'
+$applications['ruby'] = $applications['rb'] = 'ruby'
+$applications['python'] = $applications['py'] = 'python'
+$applications['java'] = $applications['jar'] = 'java'
+
+if $mswindows then
+ $applications['pdf'] = ['',"pdfopen --page #{$page} --file",'acroread']
+ $applications['html'] = ['','netscape','mozilla','opera','iexplore']
+ $applications['ps'] = ['','gview32','gv','gswin32','gs']
+else
+ $applications['pdf'] = ["pdfopen --page #{$page} --file",'acroread']
+ $applications['html'] = ['netscape','mozilla','opera']
+ $applications['ps'] = ['gview','gv','gs']
+end
+
+$applications['htm'] = $applications['html']
+$applications['eps'] = $applications['ps']
+
+if $help || ! $filename || $filename.empty? then
+ usage
+elsif $make then
+ if $windows then
+ make($filename,true,false)
+ elsif $unix then
+ make($filename,false,true)
+ else
+ make($filename,$mswindows,!$mswindows)
+ end
+elsif $browser && $filename =~ /^http\:\/\// then
+ launch($filename)
+else
+ # run(find($filename,$program))
+ run(find(shortpathname($filename),$program))
+end \ No newline at end of file
diff --git a/scripts/context/ruby/texsync.rb b/scripts/context/ruby/texsync.rb
new file mode 100644
index 000000000..457e13c05
--- /dev/null
+++ b/scripts/context/ruby/texsync.rb
@@ -0,0 +1,200 @@
+#!/usr/bin/env ruby
+
+# program : texsync
+# copyright : PRAGMA Advanced Document Engineering
+# version : 1.1 - 2003/2004
+# author : Hans Hagen
+
+# For the moment this script only handles the 'minimal' context
+# distribution. In due time I will add a few more options, like
+# synchronization of the iso image.
+
+banner = ['TeXSync', 'version 1.1', '2002/2004', 'PRAGMA ADE/POD']
+
+unless defined? ownpath
+ ownpath = $0.sub(/[\\\/]\w*?\.rb/i,'')
+ $: << ownpath
+end
+
+require 'xmpl/switch'
+require 'exa/logger'
+require 'rbconfig'
+
+class Commands
+
+ include CommandBase
+
+ @@formats = ['en','nl','de','cz','it','ro']
+ @@always = ['metafun','mptopdf','en','nl']
+ @@rsync = 'rsync -r -z -c --progress --stats "--exclude=*.fmt" "--exclude=*.efmt" "--exclude=*.mem"'
+
+ @@kpsewhich = Hash.new
+
+ @@kpsewhich['minimal'] = 'SELFAUTOPARENT'
+ @@kpsewhich['context'] = 'TEXMFLOCAL'
+ @@kpsewhich['documentation'] = 'TEXMFLOCAL'
+ @@kpsewhich['unknown'] = 'SELFAUTOPARENT'
+
+ def update
+
+ report
+
+ return unless destination = getdestination
+
+ texpaths = gettexpaths
+ address = option('address')
+ user = option('user')
+ tree = option('tree')
+ force = option('force')
+
+ ok = true
+ begin
+ report("synchronizing '#{tree}' from '#{address}' to '#{destination}'")
+ report
+ if texpaths then
+ texpaths.each do |path|
+ report("synchronizing path '#{path}' of '#{tree}' from '#{address}' to '#{destination}'")
+ command = "#{rsync} #{user}@#{address}::#{tree}/#{path} #{destination}/{path}"
+ ok = ok && system(command) if force
+ end
+ else
+ command = "#{@@rsync} #{user}@#{address}::#{tree} #{destination}"
+ ok = system(command) if force
+ end
+ rescue
+ report("error in running rsync")
+ ok = false
+ ensure
+ if force then
+ if ok then
+ if option('make') then
+ report("generating tex and metapost formats")
+ report
+ formats.delete_if do |f|
+ begin
+ `kpsewhich cont-#{f}`.chomp.empty?
+ rescue
+ end
+ end
+ str = [@@formats,@@always].flatten.uniq.join(' ')
+ begin
+ system("texexec --make --alone #{str}")
+ rescue
+ report("unable to generate formats '#{str}'")
+ else
+ report
+ end
+ else
+ report("regenerate the formats files if needed")
+ end
+ else
+ report("error in synchronizing '#{tree}'")
+ end
+ else
+ report("provide --force to execute '#{command}'") unless force
+ end
+ end
+
+ end
+
+ def list
+
+ report
+
+ address = option('address')
+ user = option('user')
+ result = nil
+
+ begin
+ report("fetching list of trees from '#{address}'")
+ command = "#{@@rsync} #{user}@#{address}::"
+ if option('force') then
+ result = `#{command}`.chomp
+ else
+ report("provide --force to execute '#{command}'")
+ end
+ rescue
+ result = nil
+ else
+ if result then
+ report("available trees:")
+ report
+ reportlines(result)
+ end
+ ensure
+ report("unable to fetch list") unless result
+ end
+
+ end
+
+ private
+
+ def gettexpaths
+ if option('full') then
+ texpaths = ['texmf','texmf-local','texmf-fonts','texmf-mswin','texmf-linux','texmf-macos']
+ elsif option('terse') then
+ texpaths = ['texmf','texmf-local','texmf-fonts']
+ case Config::CONFIG['host_os']
+ when /mswin/ then texpaths.push('texmf-mswin')
+ when /linux/ then texpaths.push('texmf-linux')
+ when /darwin/ then texpaths.push('texmf-macosx')
+ end
+ else
+ texpaths = nil
+ end
+ texpaths
+ end
+
+ def getdestination
+ if (destination = option('destination')) && ! destination.empty? then
+ begin
+ if @@kpsewhich.key?(destination) then
+ destination = @@kpsewhich[option('tree')] || @@kpsewhich['unknown']
+ destination = `kpsewhich --expand-var=$#{destination}`.chomp
+ elsif ! FileTest.directory?(destination) then
+ destination = nil
+ end
+ rescue
+ report("unable to determine destination tex root")
+ else
+ if ! destination || destination.empty? then
+ report("no destination is specified")
+ elsif not FileTest.directory?(destination) then
+ report("invalid destination '#{destination}'")
+ elsif not FileTest.writable?(destination) then
+ report("destination '#{destination}' is not writable")
+ else
+ report("using destination '#{destination}'")
+ return destination
+ end
+ end
+ else
+ report("unknown destination")
+ end
+ return nil
+ end
+
+end
+
+logger = EXA::ExaLogger.new(banner.shift)
+commandline = CommandLine.new
+
+commandline.registeraction('update', 'update installed tree')
+commandline.registeraction('list', 'list available trees')
+
+commandline.registerflag('terse', 'download as less as possible (esp binaries)')
+commandline.registerflag('full', 'download everything (all binaries)')
+commandline.registerflag('force', 'confirm action')
+commandline.registerflag('make', 'remake formats')
+
+commandline.registervalue('address', 'www.pragma-ade.com', 'adress of repository (www.pragma-ade)')
+commandline.registervalue('user', 'guest', 'user account (guest)')
+commandline.registervalue('tree', 'tex', 'tree to synchronize (tex)')
+commandline.registervalue('destination', nil, 'destination of tree (kpsewhich)')
+
+commandline.registeraction('help')
+commandline.registeraction('version')
+
+commandline.expand
+
+Commands.new(commandline,logger,banner).send(commandline.action || 'help') \ No newline at end of file
diff --git a/scripts/context/ruby/textools.rb b/scripts/context/ruby/textools.rb
new file mode 100644
index 000000000..24026d4df
--- /dev/null
+++ b/scripts/context/ruby/textools.rb
@@ -0,0 +1,666 @@
+#!/usr/bin/env ruby
+
+# program : textools
+# copyright : PRAGMA Advanced Document Engineering
+# version : 1.1 - 2002/2004
+# author : Hans Hagen
+
+# This script will harbor some handy manipulations on tex
+# related files.
+
+banner = ['TeXTools', 'version 1.2', '2002/2004', 'PRAGMA ADE/POD']
+
+unless defined? ownpath
+ ownpath = $0.sub(/[\\\/][a-z0-9\-]*?\.rb/i,'')
+ $: << ownpath
+end
+
+require 'ftools'
+require 'xmpl/switch'
+require 'exa/logger'
+
+# Remark
+#
+# The fixtexmftrees feature does not realy belong in textools, but
+# since it looks like no measures will be taken to make texlive (and
+# tetex) downward compatible with respect to fonts installed by
+# users, we provide this fixer. This option also moves script files
+# to their new location (only for context) in the TDS. Beware: when
+# locating scripts, the --format switch in kpsewhich should now use
+# 'texmfscripts' instead of 'other text files' (texmfstart is already
+# aware of this). Files will only be moved when --force is given. Let
+# me know if more fixes need to be made.
+
+class Commands
+
+ include CommandBase
+
+ def hidemapnames
+ report('hiding FontNames in map files')
+ xidemapnames(true)
+ end
+
+ def videmapnames
+ report('unhiding FontNames in map files')
+ xidemapnames(false)
+ end
+
+ def removemapnames
+
+ report('removing FontNames from map files')
+
+ if files = findfiles('map') then
+ report
+ files.sort.each do |fn|
+ gn = fn # + '.nonames'
+ hn = fn + '.original'
+ begin
+ if FileTest.file?(fn) && ! FileTest.file?(hn) then
+ if File.rename(fn,hn) then
+ if (fh = File.open(hn,'r')) && (gh = File.open(gn,'w')) then
+ report("processing #{fn}")
+ while str = fh.gets do
+ str.sub!(/^([^\%]+?)(\s+)([^\"\<\s]*?)(\s)/) do
+ $1 + $2 + " "*$3.length + $4
+ end
+ gh.puts(str)
+ end
+ fh.close
+ gh.close
+ else
+ report("no permissions to handle #{fn}")
+ end
+ else
+ report("unable to rename #{fn} to #{hn}")
+ end
+ else
+ report("not processing #{fn} due to presence of #{hn}")
+ end
+ rescue
+ report("error in handling #{fn}")
+ end
+ end
+ end
+
+ end
+
+ def restoremapnames
+
+ report('restoring FontNames in map files')
+
+ if files = findfiles('map') then
+ report
+ files.sort.each do |fn|
+ hn = fn + '.original'
+ begin
+ if FileTest.file?(hn) then
+ File.delete(fn) if FileTest.file?(fn)
+ report("#{fn} restored") if File.rename(hn,fn)
+ else
+ report("no original found for #{fn}")
+ end
+ rescue
+ report("error in restoring #{fn}")
+ end
+ end
+ end
+
+ end
+
+ def findfile
+
+ report('locating file in texmf tree')
+
+ # ! not in tree
+ # ? fuzzy
+ # . in tree
+ # > in tree and used
+
+ if filename = @commandline.argument('first') then
+ if filename && ! filename.empty? then
+ report
+ used = kpsefile(filename) || pathfile(filename)
+ if paths = texmfroots then
+ found, prefered = false, false
+ paths.each do |p|
+ if files = texmffiles(p,filename) then
+ found = true
+ files.each do |f|
+ # unreadable: report("#{if f == used then '>' else '.' end} #{f}")
+ if f == used then
+ prefered = true
+ report("> #{f}")
+ else
+ report(". #{f}")
+ end
+ end
+ end
+ end
+ if prefered then
+ report("! #{used}") unless found
+ else
+ report("> #{used}")
+ end
+ elsif used then
+ report("? #{used}")
+ else
+ report('no file found')
+ end
+ else
+ report('no file specified')
+ end
+ else
+ report('no file specified')
+ end
+
+ end
+
+ def unzipfiles
+
+ report('g-unzipping files')
+
+ if files = findfiles('gz') then
+ report
+ files.each do |f|
+ begin
+ system("gunzip -d #{f}")
+ rescue
+ report("unable to unzip file #{f}")
+ else
+ report("file #{f} is unzipped")
+ end
+ end
+ end
+
+ end
+
+ def fixafmfiles
+
+ report('fixing afm files')
+
+ if files = findfiles('afm') then
+ report
+ ok = false
+ files.each do |filename|
+ if filename =~ /\.afm$/io then
+ if f = File.open(filename) then
+ result = ''
+ done = false
+ while str = f.gets do
+ str.chomp!
+ str.strip!
+ if str.empty? then
+ # skip
+ elsif (str.length > 200) && (str =~ /^(comment|notice)\s(.*)\s*$/io) then
+ done = true
+ tag, words, len = $1, $2.split(' '), 0
+ result += tag
+ while words.size > 0 do
+ str = words.shift
+ len += str.length + 1
+ result += ' ' + str
+ if len > (70 - tag.length) then
+ result += "\n"
+ result += tag if words.size > 0
+ len = 0
+ end
+ end
+ result += "\n" if len>0
+ else
+ result += str + "\n"
+ end
+ end
+ f.close
+ if done then
+ ok = true
+ begin
+ if File.rename(filename,filename+'.original') then
+ if FileTest.file?(filename) then
+ report("something to fix in #{filename} but error in renaming (3)")
+ elsif f = File.open(filename,'w') then
+ f.puts(result)
+ f.close
+ report('file', filename, 'has been fixed')
+ else
+ report("something to fix in #{filename} but error in opening (4)")
+ File.rename(filename+'.original',filename) # gamble
+ end
+ else
+ report("something to fix in #{filename} but error in renaming (2)")
+ end
+ rescue
+ report("something to fix in #{filename} but error in renaming (1)")
+ end
+ else
+ report("nothing to fix in #{filename}")
+ end
+ else
+ report("error in opening #{filename}")
+ end
+ end
+ end
+ report('no files match the pattern') unless ok
+ end
+
+ end
+
+ def mactodos
+
+ report('fixing mac newlines')
+
+ if files = findfiles('tex') then
+ report
+ files.each do |filename|
+ begin
+ report("converting file #{filename}")
+ tmpfilename = filename + '.tmp'
+ if f = File.open(filename) then
+ if g = File.open(tmpfilename, 'w')
+ while str = f.gets do
+ g.puts(str.gsub(/\r/,"\n"))
+ end
+ if f.close && g.close && FileTest.file?(tmpfilename) then
+ File.delete(filename)
+ File.rename(tmpfilename,filename)
+ end
+ else
+ report("unable to open temporary file #{tmpfilename}")
+ end
+ else
+ report("unable to open #{filename}")
+ end
+ rescue
+ report("problems with fixing #{filename}")
+ end
+ end
+ end
+
+ end
+
+ def fixtexmftrees
+
+ if paths = @commandline.argument('first') then
+ paths = [paths] if ! paths.empty?
+ end
+ paths = texmfroots if paths.empty?
+
+ if paths then
+
+ moved = 0
+ force = @commandline.option('force')
+
+ report
+ report("checking TDS 2003 => TDS 2004 : map files")
+ # report
+
+ # move [map,enc] files from /texmf/[dvips,pdftex,dvipdfmx] -> /texmf/fonts/[*]
+
+ ['map','enc'].each do |suffix|
+ paths.each do |path|
+ ['dvips','pdftex','dvipdfmx'].each do |program|
+ report
+ report("checking #{suffix} files for #{program} on #{path}")
+ report
+ moved += movefiles("#{path}/#{program}","#{path}/fonts/#{suffix}/#{program}",suffix) do
+ # nothing
+ end
+ end
+ end
+ end
+
+ report
+ report("checking TDS 2003 => TDS 2004 : scripts")
+ # report
+
+ # move [rb,pl,py] files from /texmf/someplace -> /texmf/scripts/someplace
+
+ ['rb','pl','py'].each do |suffix|
+ paths.each do |path|
+ ['context'].each do |program|
+ report
+ report("checking #{suffix} files for #{program} on #{path}")
+ report
+ moved += movefiles("#{path}/#{program}","#{path}/scripts/#{program}",suffix) do |f|
+ f.gsub!(/\/(perl|ruby|python)tk\//o) do
+ "/#{$1}/"
+ end
+ end
+ end
+ end
+ end
+
+ begin
+ if moved>0 then
+ report
+ if force then
+ system('mktexlsr')
+ report
+ report("#{moved} files moved")
+ else
+ report("#{moved} files will be moved")
+ end
+ else
+ report('no files need to be moved')
+ end
+ rescue
+ report('you need to run mktexlsr')
+ end
+
+ end
+
+ end
+
+ def replace
+
+ if newname = @commandline.argument('first') then
+ if newname && ! newname.empty? then
+ report
+ report("replacing #{newname}")
+ report
+ oldname = kpsefile(File.basename(newname))
+ force = @commandline.option('force')
+ if oldname && ! oldname.empty? then
+ oldname = File.expand_path(oldname)
+ newname = File.expand_path(newname)
+ report("old: #{oldname}")
+ report("new: #{newname}")
+ report
+ if newname == oldname then
+ report('unable to replace itself')
+ elsif force then
+ begin
+ File.copy(newname,oldname)
+ rescue
+ report('error in replacing the old file')
+ end
+ else
+ report('the old file will be replaced (use --force)')
+ end
+ else
+ report('nothing to replace')
+ end
+ else
+ report('no file specified')
+ end
+ else
+ report('no file specified')
+ end
+
+ end
+
+ private # general
+
+ def texmfroots
+ begin
+ paths = `kpsewhich -expand-path=\$TEXMF`.chomp
+ rescue
+ else
+ return paths.split(/#{File::PATH_SEPARATOR}/) if paths && ! paths.empty?
+ end
+ return nil
+ end
+
+ def texmffiles(root, filename)
+ begin
+ files = Dir.glob("#{root}/**/#{filename}")
+ rescue
+ else
+ return files if files && files.length>0
+ end
+ return nil
+ end
+
+ def pathfile(filename)
+ used = nil
+ begin
+ if ! filename || filename.empty? then
+ return nil
+ else
+ ENV['PATH'].split(File::PATH_SEPARATOR).each do |path|
+ if FileTest.file?(File.join(path,filename)) then
+ used = File.join(path,filename)
+ break
+ end
+ end
+ end
+ rescue
+ used = nil
+ else
+ used = nil if used && used.empty?
+ end
+ return used
+ end
+
+ def kpsefile(filename)
+ used = nil
+ begin
+ if ! filename || filename.empty? then
+ return nil
+ else
+ used = `kpsewhich #{filename}`.chomp
+ end
+ if used && used.empty? then
+ used = `kpsewhich -progname=context #{filename}`.chomp
+ end
+ if used && used.empty? then
+ used = `kpsewhich -format=texmfscripts #{filename}`.chomp
+ end
+ if used && used.empty? then
+ used = `kpsewhich -progname=context -format=texmfscripts #{filename}`.chomp
+ end
+ if used && used.empty? then
+ used = `kpsewhich -format="other text files" #{filename}`.chomp
+ end
+ if used && used.empty? then
+ used = `kpsewhich -progname=context -format="other text files" #{filename}`.chomp
+ end
+ rescue
+ used = nil
+ else
+ used = nil if used && used.empty?
+ end
+ return used
+ end
+
+ def touchcontextfile
+ maincontextfile = 'context.tex'
+ unless FileTest.file?(maincontextfile) then
+ begin
+ maincontextfile = `kpsewhich -progname=context #{maincontextfile}`.chomp
+ rescue
+ maincontextfile = ''
+ end
+ end
+ touchfile(maincontextfile) unless maincontextfile.empty?
+ end
+
+ def downcasefilenames
+ if @commandline.option('recurse') then
+ files = Dir.glob('**/*')
+ else
+ files = Dir.glob('*')
+ end
+ if files && files.length>0 then
+ files.each do |oldname|
+ if FileTest.file?(oldname) then
+ newname = oldname.downcase
+ if oldname != newname then
+ begin
+ File.rename(oldname,newname)
+ rescue
+ report("#{oldname} == #{oldname}\n")
+ else
+ report("#{oldname} => #{newname}\n")
+ end
+ end
+ end
+ end
+ end
+ end
+
+ private # specific
+
+ def touchfile(filename)
+
+ if FileTest.file?(filename) then
+ if data = IO.read(filename) then
+ timestamp = Time.now.strftime('%Y.%d.%m')
+ begin
+ data.gsub!(/\\contextversion\{(\d+)\.(\d+)\.(\d+)\}/) do
+ "\\contextversion{#{timestamp}}"
+ end
+ rescue
+ else
+ begin
+ File.delete(filename+'.old')
+ rescue
+ end
+ begin
+ File.copy(filename,filename+'.old')
+ rescue
+ end
+ begin
+ if f = File.open(filename,'w') then
+ f.puts(data)
+ f.close
+ end
+ rescue
+ end
+ end
+ report("#{filename} is touched as #{timestamp}")
+ end
+ else
+ report("#{filename} is not found")
+ end
+
+ end
+
+ def movefiles(from_path,to_path,suffix,&block)
+ obsolete = 'obsolete'
+ force = @commandline.option('force')
+ moved = 0
+ if files = texmffiles(from_path, "*.#{suffix}") then
+ files.each do |filename|
+ newfilename = filename.sub(/^#{from_path}/, to_path)
+ yield(newfilename) if block
+ if FileTest.file?(newfilename) then
+ begin
+ File.rename(filename,filename+'.obsolete') if force
+ rescue
+ report("#{filename} cannot be made obsolete") if force
+ else
+ if force then
+ report("#{filename} is made obsolete")
+ else
+ report("#{filename} will become obsolete")
+ end
+ end
+ else
+ begin
+ File.makedirs(File.dirname(newfilename)) if force
+ rescue
+ end
+ begin
+ File.copy(filename,newfilename) if force
+ rescue
+ report("#{filename} cannot be copied to #{newfilename}")
+ else
+ begin
+ File.delete(filename) if force
+ rescue
+ report("#{filename} cannot be deleted") if force
+ else
+ if force then
+ report("#{filename} is moved to #{newfilename}")
+ moved += 1
+ else
+ report("#{filename} will be moved to #{newfilename}")
+ end
+ end
+ end
+ end
+ end
+ else
+ report('no matches found')
+ end
+ return moved
+ end
+
+ def xidemapnames(hide)
+
+ filter = /^([^\%]+?)(\s+)([^\"\<\s]*?)(\s)/
+ banner = '% textools:nn '
+
+ if files = findfiles('map') then
+ report
+ files.sort.each do |fn|
+ if fn.has_suffix?('map') then
+ begin
+ lines = IO.read(fn)
+ report("processing #{fn}")
+ if f = File.open(fn,'w') then
+ skip = false
+ if hide then
+ lines.each do |str|
+ if skip then
+ skip = false
+ elsif str =~ /#{banner}/ then
+ skip = true
+ elsif str =~ filter then
+ f.puts(banner+str)
+ str.sub!(filter) do
+ $1 + $2 + " "*$3.length + $4
+ end
+ end
+ f.puts(str)
+ end
+ else
+ lines.each do |str|
+ if skip then
+ skip = false
+ elsif str.sub!(/#{banner}/, '') then
+ f.puts(str)
+ skip = true
+ else
+ f.puts(str)
+ end
+ end
+ end
+ f.close
+ end
+ rescue
+ report("error in handling #{fn}")
+ end
+ end
+ end
+ end
+
+ end
+
+end
+
+logger = EXA::ExaLogger.new(banner.shift)
+commandline = CommandLine.new
+
+commandline.registeraction('touchcontextfile', '') # private
+commandline.registeraction('downcasefilenames', '') # private
+
+commandline.registeraction('removemapnames' , '[pattern] [--recurse]')
+commandline.registeraction('restoremapnames' , '[pattern] [--recurse]')
+commandline.registeraction('hidemapnames' , '[pattern] [--recurse]')
+commandline.registeraction('videmapnames' , '[pattern] [--recurse]')
+commandline.registeraction('findfile' , 'filename [--recurse]')
+commandline.registeraction('unzipfiles' , '[pattern] [--recurse]')
+commandline.registeraction('fixafmfiles' , '[pattern] [--recurse]')
+commandline.registeraction('mactodos' , '[pattern] [--recurse]')
+commandline.registeraction('fixtexmftrees' , '[texmfroot] [--force]')
+commandline.registeraction('replace' , 'filename [--force]')
+commandline.registeraction('help')
+commandline.registeraction('version')
+
+commandline.registerflag('recurse')
+commandline.registerflag('force')
+
+commandline.expand
+
+Commands.new(commandline,logger,banner).send(commandline.action || 'help')
diff --git a/scripts/context/ruby/xmltools.rb b/scripts/context/ruby/xmltools.rb
new file mode 100644
index 000000000..b92f159e3
--- /dev/null
+++ b/scripts/context/ruby/xmltools.rb
@@ -0,0 +1,346 @@
+#!/usr/bin/env ruby
+
+# program : xmltools
+# copyright : PRAGMA Advanced Document Engineering
+# version : 1.0 - 2002/2004
+# author : Hans Hagen
+
+# This script will harbor some handy manipulations on tex
+# related files.
+
+banner = ['XMLTools', 'version 1.1', '2002/2004', 'PRAGMA ADE/POD']
+
+unless defined? ownpath
+ ownpath = $0.sub(/[\\\/][a-z0-9\-]*?\.rb/i,'')
+ $: << ownpath
+end
+
+require 'xmpl/switch'
+require 'exa/logger'
+
+class String
+
+ def astring(n=10)
+ gsub(/(\d+)/o) do $1.to_s.rjust(n) end.gsub(/ /o, '0')
+ end
+
+ def xstring
+ if self =~ /\'/o then
+ "\"#{self.gsub(/\"/, '&quot;')}\""
+ else
+ "\'#{self}\'"
+ end
+ end
+
+end
+
+class Array
+
+ def asort(n=10)
+ sort {|x,y| x.astring(n) <=> y.astring(n)}
+ end
+
+end
+
+class Commands
+
+ include CommandBase
+
+ def dir
+
+ @xmlns = "xmlns='http://www.pragma-ade.com/rlg/xmldir.rng'"
+
+ pattern = @commandline.option('pattern')
+ recurse = @commandline.option('recurse')
+ stripname = @commandline.option('stripname')
+ longname = @commandline.option('longname')
+ url = @commandline.option('url')
+ outputfile = @commandline.option('output')
+ root = @commandline.option('root')
+
+ def generate(output,files,url,root,longname)
+
+ class << output
+ def xputs(str,n=0)
+ puts("#{' '*n}#{str}")
+ end
+ end
+
+ dirname = ''
+ output.xputs("<?xml version='1.0'?>\n\n")
+ if ! root || root.empty? then
+ rootatt = @xmlns
+ else
+ rootatt = " #{@xmlns} root='#{root}'"
+ end
+ if url.empty? then
+ output.xputs("<files #{rootatt}>\n")
+ else
+ output.xputs("<files url='#{url}'#{rootatt}>\n")
+ end
+ files.each do |f|
+ bn, dn = File.basename(f), File.dirname(f)
+ if dirname != dn then
+ output.xputs("</directory>\n", 2) if dirname != ''
+ output.xputs("<directory name='#{dn}'>\n", 2)
+ dirname = dn
+ end
+ if longname && dn != '.' then
+ output.xputs("<file name='#{dn}/#{bn}'>\n", 4)
+ else
+ output.xputs("<file name='#{bn}'>\n", 4)
+ end
+ output.xputs("<base>#{bn.sub(/\..*$/,'')}</base>\n", 6)
+ if File.stat(f).file? then
+ bt = bn.sub(/^.*\./,'')
+ if bt != bn then
+ output.xputs("<type>#{bt}</type>\n", 6)
+ end
+ output.xputs("<size>#{File.stat(f).size}</size>\n", 6)
+ end
+ output.xputs("<date>#{File.stat(f).mtime.strftime("%Y-%m-%d %H:%M")}</date>\n", 6)
+ output.xputs("</file>\n", 4)
+ end
+ output.xputs("</directory>\n", 2) if dirname != ''
+ output.xputs("</files>\n")
+
+ end
+
+ if pattern.empty? then
+ report('provide --pattern=')
+ return
+ end
+
+ unless outputfile.empty? then
+ begin
+ output = File.open(outputfile,'w')
+ rescue
+ report("unable to open #{outputfile}")
+ return
+ end
+ else
+ report('provide --output')
+ return
+ end
+
+ if stripname && pattern.class == String && ! pattern.empty? then
+ pattern = File.dirname(pattern)
+ end
+
+ pattern = '*' if pattern.empty?
+
+ unless root.empty? then
+ unless FileTest.directory?(root) then
+ report("unknown root #{root}")
+ return
+ end
+ begin
+ Dir.chdir(root)
+ rescue
+ report("unable to change to root #{root}")
+ return
+ end
+ end
+
+ generate(output, globbed(pattern, recurse), url, root, longname)
+
+ output.close if output
+
+ end
+
+ alias ls :dir
+
+ def mmlpages
+
+ file = @commandline.argument('first')
+ eps = @commandline.option('eps')
+ jpg = @commandline.option('jpg')
+ png = @commandline.option('png')
+ style = @commandline.option('style')
+ modes = @commandline.option('modes')
+
+ file = file.sub(/\.xml/io, '')
+ long = "#{file}-mmlpages"
+ if FileTest.file?(file+'.xml') then
+ style = "--arg=\"style=#{style}\"" unless style.empty?
+ modes = "--mode=#{modes}" unless modes.empty?
+ if system("texmfstart texexec.pl --batch --pdf --once --result=#{long} --use=mmlpag #{style} #{modes} #{file}.xml") then
+ if eps then
+ if f = open("#{file}-mmlpages.txt") then
+ while line = f.gets do
+ data = Hash.new
+ if fields = line.split then
+ fields.each do |fld|
+ key, value = fld.split('=')
+ data[key] = value if key && value
+ end
+ if data.key?('p') then
+ page = data['p']
+ name = "#{long}-#{page.to_i-1}"
+ if eps then
+ report("generating eps file #{name}")
+ if system("pdftops -eps -f #{page} -l #{page} #{long}.pdf #{name}.eps") then
+ if data.key?('d') then
+ if epsfile = IO.read("#{name}.eps") then
+ epsfile.sub!(/^(\%\%BoundingBox:.*?$)/i) do
+ newline = $1 + "\n%%Baseline: #{data['d']}\n"
+ if data.key?('w') && data.key?('h') then
+ newline += "%%PositionWidth: #{data['w']}\n"
+ newline += "%%PositionHeight: #{data['h']}\n"
+ newline += "%%PositionDepth: #{data['d']}"
+ end
+ newline
+ end
+ if g = File.open("#{name}.eps",'wb') then
+ g.write(epsfile)
+ g.close
+ end
+ end
+ end
+ else
+ report("error in generating eps from #{name}")
+ end
+ end
+ end
+ end
+ end
+ f.close
+ else
+ report("missing data log file #{file}")
+ end
+ end
+ if png then
+ report("generating png file for #{long}")
+ system("imagemagick #{long}.pdf #{long}-%d.png")
+ end
+ if jpg then
+ report("generating jpg files for #{long}")
+ system("imagemagick #{long}.pdf #{long}-%d.jpg")
+ end
+ else
+ report("error in processing file #{file}")
+ end
+ system("texmfstart texutil --purge")
+ else
+ report("error in processing file #{file}")
+ end
+
+ end
+
+ def analyze
+
+ file = @commandline.argument('first')
+ result = @commandline.option('output')
+
+ if FileTest.file?(file) then
+ if data = IO.read(file) then
+ report("xml file #{file} loaded")
+ elements = Hash.new
+ attributes = Hash.new
+ entities = Hash.new
+ data.scan(/<([^>\s\/\!\?]+)([^>]*?)>/o) do
+ element, attributelist = $1, $2
+ if elements.key?(element) then
+ elements[element] += 1
+ else
+ elements[element] = 1
+ end
+ attributelist.scan(/\s*([^\=]+)\=([\"\'])(.*?)(\2)/) do
+ key, value = $1, $3
+ attributes[element] = Hash.new unless attributes.key?(element)
+ attributes[element][key] = Hash.new unless attributes[element].key?(key)
+ if attributes[element][key].key?(value) then
+ attributes[element][key][value] += 1
+ else
+ attributes[element][key][value] = 1
+ end
+ end
+ end
+ data.scan(/\&([^\;]+)\;/o) do
+ entity = $1
+ if entities.key?(entity) then
+ entities[entity] += 1
+ else
+ entities[entity] = 1
+ end
+ end
+ result = file.gsub(/\..*?$/, '') + '.xlg' if result.empty?
+ if f = File.open(result,'w') then
+ report("saving report in #{result}")
+ f.puts "<?xml version='1.0'?>\n"
+ f.puts "<document>\n"
+ if entities.length>0 then
+ f.puts " <entities>\n"
+ entities.keys.asort.each do |entity|
+ f.puts " <entity name=#{entity.xstring} n=#{entities[entity].to_s.xstring}/>\n"
+ end
+ f.puts " </entities>\n"
+ end
+ if elements.length>0 then
+ f.puts " <elements>\n"
+ elements.keys.sort.each do |element|
+ if attributes.key?(element) then
+ f.puts " <element name=#{element.xstring} n=#{elements[element].to_s.xstring}>\n"
+ if attributes.key?(element) then
+ attributes[element].keys.asort.each do |attribute|
+ f.puts " <attribute name=#{attribute.xstring}>\n"
+ attributes[element][attribute].keys.asort.each do |value|
+ f.puts " <instance value=#{value.xstring} n=#{attributes[element][attribute][value].to_s.xstring}/>\n"
+ end
+ f.puts " </attribute>\n"
+ end
+ end
+ f.puts " </element>\n"
+ else
+ f.puts " <element name=#{element.xstring} n=#{elements[element].to_s.xstring}/>\n"
+ end
+ end
+ f.puts " </elements>\n"
+ end
+ f.puts "</document>\n"
+ else
+ report("unable to open file '#{result}'")
+ end
+ else
+ report("unable to load file '#{file}'")
+ end
+ else
+ report("unknown file '#{file}'")
+ end
+ end
+
+end
+
+logger = EXA::ExaLogger.new(banner.shift)
+commandline = CommandLine.new
+
+commandline.registeraction('dir', 'generate directory listing')
+commandline.registeraction('mmlpages','generate graphic from mathml')
+commandline.registeraction('analyze', 'report entities and elements')
+
+# commandline.registeraction('dir', 'filename --pattern= --output= [--recurse --stripname --longname --url --root]')
+# commandline.registeraction('mmlpages','filename [--eps --jpg --png --style= --mode=]')
+
+commandline.registeraction('ls')
+
+commandline.registeraction('help')
+commandline.registeraction('version')
+
+commandline.registerflag('stripname')
+commandline.registerflag('longname')
+commandline.registerflag('recurse')
+
+commandline.registervalue('pattern')
+commandline.registervalue('url')
+commandline.registervalue('output')
+commandline.registervalue('root')
+
+commandline.registerflag('eps')
+commandline.registerflag('png')
+commandline.registerflag('jpg')
+commandline.registervalue('style')
+commandline.registervalue('modes')
+
+commandline.expand
+
+Commands.new(commandline,logger,banner).send(commandline.action || 'help')
diff --git a/scripts/context/ruby/xmpl/switch.rb b/scripts/context/ruby/xmpl/switch.rb
new file mode 100644
index 000000000..c0fd1d624
--- /dev/null
+++ b/scripts/context/ruby/xmpl/switch.rb
@@ -0,0 +1,473 @@
+# module : xmpl/switch
+# copyright : PRAGMA Publishing On Demand
+# version : 1.00 - 2002
+# author : Hans Hagen
+#
+# project : eXaMpLe
+# concept : Hans Hagen
+# info : j.hagen@xs4all.nl
+# www : www.pragma-pod.com / www.pragma-ade.com
+
+# we cannot use getoptlong because we want to be more
+# tolerant; also we want to be case insensitive.
+
+# we could make each option a class itself, but this is
+# simpler; also we can put more in the array
+
+# beware: regexps/o in methods are optimized globally
+
+class String
+
+ def has_suffix?(suffix)
+ self =~ /\.#{suffix}$/i
+ end
+
+end
+
+module CommandBase
+
+ # this module can be used as a mixin in a command handler
+
+ $stdout.sync = true
+
+ def initialize(commandline,logger,banner)
+ @commandline, @logger, @banner = commandline, logger, banner
+ @forcenewline, @versiondone = false, false
+ version if @commandline.option('version')
+ end
+
+ def reportlines(*str)
+ @logger.reportlines(str)
+ end
+
+ # only works in 1.8
+ #
+ # def report(*str)
+ # @logger.report(str)
+ # end
+ #
+ # def version # just a bit of playing with defs
+ # report(@banner.join(' - '))
+ # def report(*str)
+ # @logger.report
+ # @logger.report(str)
+ # def report(*str)
+ # @logger.report(str)
+ # end
+ # end
+ # def version
+ # end
+ # end
+
+ def report(*str)
+ if @forcenewline then
+ @logger.report
+ @forcenewline = false
+ end
+ @logger.report(str)
+ end
+
+ def version # just a bit of playing with defs
+ unless @versiondone then
+ report(@banner.join(' - '))
+ @forcenewline = true
+ @versiondone = true
+ end
+ end
+
+ def help
+ version # is nilled when already given
+ @commandline.helpkeys.each do |k|
+ report("#{('--'+k).ljust(@commandline.helplength+2)} #{@commandline.helptext(k)}") if @commandline.help?(k)
+ end
+ end
+
+ def option(key)
+ @commandline.option(key)
+ end
+
+ private
+
+ def findfiles(suffix=nil)
+
+ if @commandline.arguments.length>1 then
+ return @commandline.arguments
+ else
+ pattern = @commandline.argument('first')
+ pattern = '*' if pattern.empty?
+ if suffix && ! pattern.match(/\..+$/o) then
+ suffix = '.' + suffix
+ pattern += suffix unless pattern =~ /#{suffix}$/
+ end
+ pattern = '**/' + pattern if @commandline.option('recurse')
+ files = Dir[pattern]
+ if files && files.length>0 then
+ return files
+ else
+ report("no files match pattern #{pattern}")
+ return nil
+ end
+ end
+
+ end
+
+ def globbed(pattern,recurse=false)
+
+ files = Array.new
+ pattern.split(' ').each do |p|
+ if recurse then
+ if p =~ /^(.*)(\/.*?)$/i then
+ p = $1 + '/**' + $2
+ else
+ p = '**/' + p
+ end
+ p.gsub!(/[\\\/]+/, '/')
+ end
+ files.push(Dir.glob(p))
+ end
+ files.flatten.sort do |a,b|
+ pathcompare(a,b)
+ end
+ end
+
+ def pathcompare(a,b)
+
+ aa, bb = a.split('/'), b.split('/')
+ if aa.length == bb.length then
+ aa.each_index do |i|
+ if aa[i]<bb[i] then
+ return -1
+ elsif aa[i]>bb[i] then
+ return +1
+ end
+ end
+ return 0
+ else
+ return aa.length <=> bb.length
+ end
+
+ end
+
+end
+
+class CommandLine
+
+ VALUE, FLAG = 1, 2
+
+ def initialize(prefix='-')
+
+ @registered = Array.new
+ @options = Hash.new
+ @unchecked = Hash.new
+ @arguments = Array.new
+ @original = ARGV.join(' ')
+ @helptext = Hash.new
+ @mandated = Hash.new
+ @provided = Hash.new
+ @prefix = prefix
+ @actions = Array.new
+
+ # The quotes in --switch="some value" get lost in ARGV, so we need to do some trickery here.
+
+ @original = ''
+ ARGV.each do |a|
+ aa = a.strip.gsub(/^([#{@prefix}]+\w+\=)([^\"].*?\s+.*[^\"])$/) do
+ $1 + "\"" + $2 + "\""
+ end
+ @original += if @original.empty? then '' else ' ' end + aa
+ end
+
+ end
+
+ def register (option,shortcut,kind,default=false,action=false,helptext='')
+ if kind == FLAG then
+ @options[option] = default
+ elsif not default then
+ @options[option] = ''
+ else
+ @options[option] = default
+ end
+ @registered.push([option,shortcut,kind])
+ @mandated[option] = false
+ # @provided[option] = false
+ @helptext[option] = helptext
+ @actions.push(option) if action
+ end
+
+ def registerflag(option,default=false,helptext='')
+ if default.class == String then
+ register(option,'',FLAG,false,false,default)
+ else
+ register(option,'',FLAG,false,false,helptext)
+ end
+ end
+
+ def registervalue(option,default='',helptext='')
+ register(option,'',VALUE,default,false,helptext)
+ end
+
+ def registeraction(option,helptext='')
+ register(option,'',FLAG,false,true,helptext)
+ end
+
+ def registermandate(*option)
+ [*option].each do |o|
+ [o].each do |oo|
+ @mandated[oo] = true
+ end
+ end
+ end
+
+ def actions
+ a = @actions.delete_if do |t|
+ ! option(t)
+ end
+ if a && a.length>0 then
+ return a
+ else
+ return nil
+ end
+ end
+
+ def action
+ @actions.each do |t|
+ return t if option(t)
+ end
+ return nil
+ end
+
+ def forgotten
+ @mandated.keys.sort - @provided.keys.sort
+ end
+
+ def registerhelp(option,text='')
+ @helptext['unknown'] = if text.empty? then option else text end
+ end
+
+ def helpkeys(option='.*')
+ @helptext.keys.sort.grep(/#{option}/)
+ end
+
+ def helptext(option)
+ @helptext.fetch(option,'')
+ end
+
+ def help?(option)
+ @helptext[option] && ! @helptext[option].empty?
+ end
+
+ def helplength
+ n = 0
+ @helptext.keys.each do |h|
+ n = h.length if h.length>n
+ end
+ return n
+ end
+
+ def expand
+
+ # todo : '' or false, depending on type
+ # @options.clear
+ # @arguments.clear
+
+ dirtyvalue(@original).split(' ').each do |arg|
+ case arg
+ when /^[#{@prefix}][#{@prefix}](.+?)\=(.*?)$/ then locatedouble($1,$2)
+ when /^[#{@prefix}][#{@prefix}](.+?)$/ then locatedouble($1,false)
+ when /^[#{@prefix}](.)\=(.)$/ then locatesingle($1,$2)
+ when /^[#{@prefix}](.+?)$/ then locateseries($1,false)
+ when /^[\+\-]+/o then # do nothing
+ else
+ arguments.push(arg)
+ end
+ end
+
+ @options or @unchecked or @arguments
+
+ end
+
+ def extend (str)
+ @original = @original + ' ' + str
+ end
+
+ def replace (str)
+ @original = str
+ end
+
+ def show
+ # print "-- options --\n"
+ @options.keys.sort.each do |key|
+ print "option: #{key} -> #{@options[key]}\n"
+ end
+ # print "-- arguments --\n"
+ @arguments.each_index do |key|
+ print "argument: #{key} -> #{@arguments[key]}\n"
+ end
+ end
+
+ def option(str)
+ @options[str] # @options.fetch(str,'')
+ end
+
+ def argument(n=0)
+ if n.class == String then
+ case n
+ when 'first' then argument(0)
+ when 'second' then argument(1)
+ when 'third' then argument(2)
+ else
+ argument(0)
+ end
+ elsif @arguments[n] then
+ @arguments[n]
+ else
+ ''
+ end
+ end
+
+ # a few local methods, cannot be defined nested (yet)
+
+ private
+
+ def dirtyvalue(value)
+ if value then
+ value.gsub(/([\"\'])(.*?)\1/) do
+ $2.gsub(/\s+/o, "\xFF")
+ end
+ else
+ ''
+ end
+ end
+
+ def cleanvalue(value)
+ if value then
+ # value.sub(/^([\"\'])(.*?)\1$/) { $2.gsub(/\xFF/o, ' ') }
+ value.gsub(/\xFF/o, ' ')
+ else
+ ''
+ end
+ end
+
+ def locatedouble (key, value)
+
+ foundkey, foundkind = nil, nil
+
+ @registered.each do |option, shortcut, kind|
+ if option == key then
+ foundkey, foundkind = option, kind
+ break
+ end
+ end
+ unless foundkey then
+ @registered.each do |option, shortcut, kind|
+ n = 0
+ if option =~ /^#{key}/i then
+ case n
+ when 0
+ foundkey, foundkind = option, kind
+ n = 1
+ when 1
+ # ambiguous matches, like --fix => --fixme --fixyou
+ foundkey, foundkind = nil, nil
+ break
+ end
+ end
+ end
+ end
+ if foundkey then
+ @provided[foundkey] = true
+ if value.class == FalseClass then
+ @options[foundkey] = true
+ else
+ @options[foundkey] = if foundkind == VALUE then cleanvalue(value) else true end
+ end
+ else
+ if value.class == FalseClass then
+ @unchecked[key] = true
+ else
+ @unchecked[key] = cleanvalue(value)
+ end
+ end
+
+ end
+
+ def locatesingle (key, value)
+
+ @registered.each do |option, shortcut, kind|
+ if shortcut == key then
+ @provided[option] = true
+ @options[option] = if kind == VALUE then '' else cleanvalue(value) end
+ break
+ end
+ end
+
+ end
+
+ def locateseries (series, value)
+
+ series.each do |key|
+ locatesingle(key,cleanvalue(value))
+ end
+
+ end
+
+ public
+
+ attr_reader :arguments, :options, :original, :unchecked
+
+end
+
+# options = CommandLine.new
+#
+# options.register("filename", "f", CommandLine::VALUE)
+# options.register("request" , "r", CommandLine::VALUE)
+# options.register("verbose" , "v", CommandLine::FLAG)
+#
+# options.expand
+# options.extend(str)
+# options.show
+#
+# c = CommandLine.new
+#
+# c.registervalue('aaaa')
+# c.registervalue('test')
+# c.registervalue('zzzz')
+#
+# c.registerhelp('aaaa','some aaaa to enter')
+# c.registerhelp('test','some text to enter')
+# c.registerhelp('zzzz','some zzzz to enter')
+#
+# c.registermandate('test')
+#
+# c.expand
+#
+# class CommandLine
+#
+# def showhelp (banner,*str)
+# if helpkeys(*str).length>0
+# print banner
+# helpkeys(*str).each do |h|
+# print helptext(h) + "\n"
+# end
+# true
+# else
+# false
+# end
+# end
+#
+# def showmandate(banner)
+# if forgotten.length>0
+# print banner
+# forgotten.each do |f|
+# print helptext(f) + "\n"
+# end
+# true
+# else
+# false
+# end
+# end
+#
+# end
+#
+# c.showhelp("you can provide:\n\n")
+# c.showmandate("you also need to provide:\n\n")