diff options
| author | Hans Hagen <pragma@wxs.nl> | 2006-05-08 12:59:00 +0200 | 
|---|---|---|
| committer | Hans Hagen <pragma@wxs.nl> | 2006-05-08 12:59:00 +0200 | 
| commit | 88eab06af697b8d0fd8ef6d7762eae4901b191d2 (patch) | |
| tree | 5c89c6f759c1305287c55cfcc38ae0bf6e934796 /scripts | |
| parent | 7310101ce7739889fd4681864978f2c71722bbd6 (diff) | |
| download | context-88eab06af697b8d0fd8ef6d7762eae4901b191d2.tar.gz | |
stable 2006.05.08 12:59
Diffstat (limited to 'scripts')
48 files changed, 2017 insertions, 1554 deletions
| diff --git a/scripts/context/perl/texexec.pl b/scripts/context/perl/texexec.pl index ba12bf3a3..21595aa7b 100644 --- a/scripts/context/perl/texexec.pl +++ b/scripts/context/perl/texexec.pl @@ -3101,6 +3101,9 @@ $TotalTime = time - $TotalTime;  unless ($HelpAsked) { print "\n        total run time : $TotalTime seconds\n" } +print "\n" ; +print "               warning : use 'texmfstart texexec' instead\n" ; +  if ($Problems) { exit 1 }  __DATA__ diff --git a/scripts/context/perl/texutil.pl b/scripts/context/perl/texutil.pl index a20a7f6aa..ca3645015 100644 --- a/scripts/context/perl/texutil.pl +++ b/scripts/context/perl/texutil.pl @@ -2907,4 +2907,8 @@ elsif  ($FilterPages      ) { FilterPages      }  elsif  ($ProcessHelp      ) { ShowHelpInfo     } # redundant  else                        { ShowHelpInfo     } +print "\n" ; +print "                remark : 'texutil' is now part of 'texexec'\n" ; +print "               warning : use 'texmfstart texutil' instead\n" ; +  #D So far. diff --git a/scripts/context/ruby/base/kpseremote.rb b/scripts/context/ruby/base/kpseremote.rb index f1f3cb10f..d66e40e6f 100644 --- a/scripts/context/ruby/base/kpseremote.rb +++ b/scripts/context/ruby/base/kpseremote.rb @@ -1,12 +1,12 @@  require 'base/kpsefast' -class KpseRemote +case ENV['KPSEMETHOD'] +    when /soap/o then require 'base/kpse/soap' +    when /drb/o  then require 'base/kpse/drb' +    else              require 'base/kpse/drb' +end -    case ENV['KPSEMETHOD'] -        when /soap/o then require 'base/kpse/soap' -        when /drb/o  then require 'base/kpse/drb' -        else              require 'base/kpse/drb' -    end +class KpseRemote      @@port = ENV['KPSEPORT'] || 7000 @@ -34,9 +34,13 @@ class KpseRemote      end      def initialize(port=nil) -        begin -            @kpse, @tree = KpseRemote::start_client(port) -        rescue +        if KpseRemote::available? then +            begin +                @kpse, @tree = KpseRemote::start_client(port) +            rescue +                @kpse, @tree = nil, nil +            end +        else              @kpse, @tree = nil, nil          end      end diff --git a/scripts/context/ruby/base/mp.rb b/scripts/context/ruby/base/mp.rb new file mode 100644 index 000000000..a501b2903 --- /dev/null +++ b/scripts/context/ruby/base/mp.rb @@ -0,0 +1,161 @@ +# module    : base/mp +# copyright : PRAGMA Advanced Document Engineering +# version   : 2005-2006 +# author    : Hans Hagen +# +# project   : ConTeXt / eXaMpLe +# concept   : Hans Hagen +# info      : j.hagen@xs4all.nl +# www       : www.pragma-ade.com + +module MPTools + +    @@definitions, @@start, @@stop, @@before, @@after = Hash.new, Hash.new, Hash.new, Hash.new, Hash.new + +    @@definitions['plain'] = <<EOT +\\gdef\\mpxshipout{\\shipout\\hbox\\bgroup +  \\setbox0=\\hbox\\bgroup} + +\\gdef\\stopmpxshipout{\\egroup  \\dimen0=\\ht0 \\advance\\dimen0\\dp0 +  \\dimen1=\\ht0 \\dimen2=\\dp0 +  \\setbox0=\\hbox\\bgroup +    \\box0 +    \\ifnum\\dimen0>0 \\vrule width1sp height\\dimen1 depth\\dimen2 +    \\else \\vrule width1sp height1sp depth0sp\\relax +    \\fi\\egroup +  \\ht0=0pt \\dp0=0pt \\box0 \\egroup} +EOT + +    @@start ['plain'] = "" +    @@before['plain'] = "\\mpxshipout" +    @@after ['plain'] = "\\stopmpxshipout" +    @@stop  ['plain'] = "\\end{document}" + +    @@definitions['context'] = <<EOT +\\ifx\\startMPXpage\\undefined + +  \\gdef\\startMPXpage +    {\\shipout\\hbox +     \\bgroup +     \\setbox0=\\hbox +     \\bgroup} + +  \\gdef\\stopMPXpage +    {\\egroup +     \\dimen0=\\ht0 +     \\advance\\dimen0\\dp0 +     \\dimen1=\\ht0 +     \\dimen2=\\dp0 +     \\setbox0=\\hbox\\bgroup +       \\box0 +       \\ifnum\\dimen0>0 +         \\vrule width 1sp height \\dimen1 depth \\dimen2 +       \\else +         \\vrule width 1sp height 1sp depth 0sp \\relax +       \\fi +    \\egroup +    \\ht0=0pt +    \\dp0=0pt +    \\box0 +    \\egroup} + +\\fi + +\\ifx\\starttext\\undefined + +  \\let\\starttext\\relax +  \\def\\stoptext{\\end{document}} + +\\fi +EOT + +    @@start ['context'] = "\\starttext" +    @@before['context'] = "\\startMPXpage" +    @@after ['context'] = "\\stopMPXpage" +    @@stop  ['context'] = "\\stoptext" + +    # todo: \usemodule[m-mpx ] and test fo defined + +    def MPTools::mptotex(from,to=nil,method='plain') +        begin +            if from && data = IO.read(from) then +                f = if to then File.open(to,'w') else $stdout end +                f.puts("% file: #{from}") +                f.puts("") +                f.puts(@@definitions[method]) +                unless @@start[method].empty? then +                    f.puts("") +                    f.puts(@@start[method]) +                end +                data.gsub!(/%.*?$/mo) do +                    '' +                end +                data.scan(/(verbatim|b)tex\s*(.*?)\s*etex/mo) do +                    tag, text = $1, $2 +                    f.puts("") +                    if tag == 'b' then +                        f.puts(@@before[method]) +                        f.puts("#{text}%") +                        f.puts(@@after [method]) +                    else +                        f.puts("#{text}") +                    end +                    f.puts("") +                end +                f.puts("") +                f.puts(@@stop[method]) +                f.close +            else +                return false +            end +        rescue +            File.delete(to) rescue false +            return false +        else +            return true +        end +    end + +    @@splitMPlines = false + +    def MPTools::splitmplines(str) +        if @@splitMPlines then +            btex, verbatimtex, strings, result = Array.new, Array.new, Array.new, str.dup +            # protect texts +            result.gsub!(/btex\s*(.*?)\s*etex/) do +                btex << $1 +                "btex(#{btex.length-1})" +            end +            result.gsub!(/verbatimtex\s*(.*?)\s*etex/) do +                verbatimtex << $1 +                "verbatimtex(#{verbatimtex.length-1})" +            end +            result.gsub!(/\"(.*?)\"/) do +                strings << $1 +                "\"#{strings.length-1}\"" +            end +            result.gsub!(/\;/) do +                ";\n" +            end +            result.gsub!(/(.{80,})(\-\-\-|\-\-|\.\.\.|\.\.)/) do +                "#{$1}#{$2}\n" +            end +            result.gsub!(/\n[\s\n]+/mois) do +                "\n" +            end +            result.gsub!(/btex\((\d+)\)/) do +                "btex #{btex[$1.to_i]} etex" +            end +            result.gsub!(/verbatimtex\((\d+)\)/) do +                "verbatimtex #{verbatimtex[$1.to_i]} etex" +            end +            result.gsub!(/\"(\d+)\"/) do +                "\"#{strings[$1.to_i]}\"" +            end +            return result +        else +            return str +        end +    end + +end diff --git a/scripts/context/ruby/base/switch.rb b/scripts/context/ruby/base/switch.rb index 64b1abef0..5187a795f 100644 --- a/scripts/context/ruby/base/switch.rb +++ b/scripts/context/ruby/base/switch.rb @@ -33,49 +33,17 @@ end  class File -    # def File.needsupdate(oldname,newname) -        # begin -            # if $mswindows then # we cannot use != due to some rounding error -                # return File.stat(oldname).mtime > File.stat(newname).mtime -            # else -                # return File.stat(oldname).mtime != File.stat(newname).mtime -            # end -        # rescue -            # return true -        # end -    # end -      @@update_eps = 1 -    # def File.needsupdate(oldname,newname) -        # begin -            # oldtime = File.stat(oldname).mtime.to_i -            # newtime = File.stat(newname).mtime.to_i -            # if newtime >= oldtime -                # return false -            # elsif oldtime-newtime < @@update_eps then -                # return false -            # else -                # return true -            # end -        # rescue -            # return true -        # end -    # end -      def File.needsupdate(oldname,newname)          begin              oldtime = File.stat(oldname).mtime.to_i              newtime = File.stat(newname).mtime.to_i -# str =  "o:#{oldtime} n:#{newtime} d:#{newtime-oldtime}" -            if newtime >= oldtime -# puts "original is unchanged: #{str}" +            if newtime >= oldtime then                  return false              elsif oldtime-newtime < @@update_eps then -# puts "original is within range: #{str}"                  return false              else -# puts "original is updated: #{str}"                  return true              end          rescue diff --git a/scripts/context/ruby/base/tex.rb b/scripts/context/ruby/base/tex.rb index 9cb891009..165d370f9 100644 --- a/scripts/context/ruby/base/tex.rb +++ b/scripts/context/ruby/base/tex.rb @@ -20,6 +20,7 @@ require 'base/state'  require 'base/pdf'  require 'base/file'  require 'base/ctx' +require 'base/mp'  class String @@ -33,6 +34,12 @@ class String  end +# class String +    # def utf_bom? +        # self.match(/^\357\273\277/o).length>0 rescue false +    # end +# end +  class Array      def standard? @@ -56,6 +63,7 @@ class TEX      @@texengines = Hash.new      @@mpsengines = Hash.new      @@backends   = Hash.new +    @@mappaths   = Hash.new      @@runoptions = Hash.new      @@texformats = Hash.new      @@mpsformats = Hash.new @@ -72,15 +80,20 @@ class TEX      ['aleph','omega']                              .each do |e| @@texengines[e] = 'aleph'     end      ['xetex']                                      .each do |e| @@texengines[e] = 'xetex'     end -    ['metapost','mpost','standard']                .each do |e| @@mpsengines[e] = 'mpost'     end +    ['metapost','mpost', 'standard']               .each do |e| @@mpsengines[e] = 'mpost'     end      ['pdfetex','pdftex','pdf','pdftex','standard'] .each do |b| @@backends[b]   = 'pdftex'    end      ['dvipdfmx','dvipdfm','dpx','dpm']             .each do |b| @@backends[b]   = 'dvipdfmx'  end -    ['xetex','xtx']                                .each do |b| @@backends[b]   = 'xetex'     end +    ['xetex','xtx']                                .each do |b| @@backends[b]   = 'dvipdfmx'  end      ['dvips','ps']                                 .each do |b| @@backends[b]   = 'dvips'     end      ['dvipsone']                                   .each do |b| @@backends[b]   = 'dvipsone'  end      ['acrobat','adobe','distiller']                .each do |b| @@backends[b]   = 'acrobat'   end +    ['tex','standard']                             .each do |b| @@mappaths[b]   = 'dvips'     end +    ['pdftex','pdfetex']                           .each do |b| @@mappaths[b]   = 'pdftex'    end +    ['aleph','omega']                              .each do |b| @@mappaths[b]   = 'dvipdfm'   end +    ['xetex']                                      .each do |b| @@mappaths[b]   = 'dvipdfm'   end +      # todo norwegian (no)      ['plain']                                      .each do |f| @@texformats[f] = 'plain'     end @@ -116,7 +129,7 @@ class TEX      ['cont-en','cont-nl','cont-de','cont-it',       'cont-fr','cont-cz','cont-ro','cont-uk']      .each do |f| @@texprocstr[f] = "\\emergencyend"  end -    @@runoptions['xetex'] = ['--no-pdf'] +    # @@runoptions['xetex'] = ['--no-pdf'] # from now on we assume (x)dvipdfmx to be used      @@booleanvars = [          'batchmode', 'nonstopmode', 'fast', 'fastdisabled', 'silentmode', 'final', @@ -130,7 +143,7 @@ class TEX          'forcetexutil', 'texutil',          'globalfile', 'autopath',          'purge', 'purgeall', 'keep', 'autopdf', 'xpdf', 'simplerun', 'verbose', -        'nooptionfile', 'nobackend', 'noctx' +        'nooptionfile', 'nobackend', 'noctx', 'utfbom'      ]      @@stringvars = [          'modefile', 'result', 'suffix', 'response', 'path', @@ -580,7 +593,7 @@ class TEX                                  results.push('')                                  results.push("testing interface #{interface}")                                  flags = ['--noctx','--process','--batch','--once',"--interface=#{interface}",engineflag] -                                # result = Kpse.pipescript('newtexexec',tempfilename,flags) +                                # result = Kpse.pipescript('texexec',tempfilename,flags)                                  result = runtexexec([tempfilename], flags, 1)                                  if FileTest.file?("#{@@temprunfile}.log") then                                      logdata = IO.read("#{@@temprunfile}.log") @@ -679,13 +692,23 @@ class TEX          ['ctx','ctxfile'],          ['version','contextversion'],          ['format','texformats'], -        ['interface','texformats'] +        ['interface','texformats'],      ] +    @@re_utf_bom = /^\357\273\277/o +      def scantexpreamble(filename)          begin              if FileTest.file?(filename) and tex = File.open(filename) then +                bomdone = false                  while str = tex.gets and str.chomp! do +                    unless bomdone then +                        if str.sub!(@@re_utf_bom, '') +                            report("utf mode forced (bom found)") +                            setvariable('utfbom',true) +                        end +                        bomdone = true +                    end                      if str =~ /^\%\s*(.*)/o then                          vars = Hash.new                          $1.split(/\s+/o).each do |s| @@ -926,6 +949,9 @@ class TEX                  # local handies                  opt << "\% #{topname}\n"                  opt << "\\unprotect\n" +                if getvariable('utfbom') then +                    opt << "\\enableregime[utf]" +                end                  opt << "\\setupsystem[\\c!n=#{kindofrun},\\c!m=#{currentrun}]\n"                  opt << "\\def\\MPOSTformatswitch\{#{prognameflag('metafun')} #{formatflag('mpost')}=\}\n"                  if getvariable('batchmode') then @@ -945,7 +971,7 @@ class TEX                  elsif (str = getvariable('suffix')) && ! str.empty? then                      opt << "\\setupsystem[file=#{jobname}.#{str}]\n"                  end -                opt << "\\setupsystem[\\c!method=2]\n" # 1=oldtexexec 2=newtexexec +                opt << "\\setupsystem[\\c!method=2]\n" # 1=oldtexexec 2=newtexexec (obsolete)                  opt << "\\setupsystem[\\c!type=#{Tool.ruby_platform()}]\n"                  if (str = File.unixfied(getvariable('path'))) && ! str.empty? then                      opt << "\\usepath[#{str}]\n" unless str.empty? @@ -955,6 +981,8 @@ class TEX                  end                  if str = validbackend(getvariable('backend')) then                      opt << "\\setupoutput[#{str}]\n" +                elsif str = validbackend(getvariable('output')) then +                    opt << "\\setupoutput[#{str}]\n"                  end                  if getvariable('color') then                      opt << "\\setupcolors[\\c!state=\\v!start]\n" @@ -1131,7 +1159,7 @@ class TEX      end      def runtex(filename) -checktestversion +        checktestversion          texengine = validtexengine(getvariable('texengine'))          texformat = validtexformat(getarrayvariable('texformats').first)          progname  = validprogname(getvariable('progname')) @@ -1139,6 +1167,7 @@ checktestversion          report("tex format: #{texformat}")          report("progname: #{progname}")          if texengine && texformat && progname then +            fixbackendvars(@@mappaths[texengine])              command = [quoted(texengine),prognameflag(progname),formatflag(texengine,texformat),tcxflag,runoptions(texengine),filename,texprocextras(texformat)].join(' ')              report(command) if getvariable('verbose')              system(command) @@ -1148,15 +1177,15 @@ checktestversion          end      end -    def runmp(filename,mpx=false) -checktestversion +    def runmp(mpname,mpx=false) +        checktestversion          mpsengine = validmpsengine(getvariable('mpsengine'))          mpsformat = validmpsformat(getarrayvariable('mpsformats').first)          progname  = validprogname(getvariable('progname'))          if mpsengine && mpsformat && progname then              ENV["MPXCOMMAND"] = "0" unless mpx              # command = [quoted(mpsengine),prognameflag(progname),formatflag(mpsengine,mpsformat),tcxflag,runoptions(mpsengine),filename,mpsprocextras(mpsformat)].join(' ') -            command = [quoted(mpsengine),"-progname=mpost",formatflag(mpsengine,mpsformat),tcxflag,runoptions(mpsengine),filename,mpsprocextras(mpsformat)].join(' ') +            command = [quoted(mpsengine),"-progname=mpost",formatflag(mpsengine,mpsformat),tcxflag,runoptions(mpsengine),mpname,mpsprocextras(mpsformat)].join(' ')              report(command) if getvariable('verbose')              system(command)              true @@ -1166,17 +1195,17 @@ checktestversion      end      def runtexmp(filename,filetype='') -checktestversion -        mpfile = File.suffixed(filename,filetype,'mp') -        if File.atleast?(mpfile,25) then +        checktestversion +        mpname = File.suffixed(filename,filetype,'mp') +        if File.atleast?(mpname,25) then              # first run needed -            File.silentdelete(File.suffixed(mpfile,'mpt')) -            doruntexmp(mpfile) -            mpgraphics = checkmpgraphics(mpfile) -            mplabels = checkmplabels(mpfile) +            File.silentdelete(File.suffixed(mpname,'mpt')) +            doruntexmp(mpname) +            mpgraphics = checkmpgraphics(mpname) +            mplabels = checkmplabels(mpname)              if mpgraphics || mplabels then                  # second run needed -                doruntexmp(mpfile,mplabels) +                doruntexmp(mpname,mplabels)              else                  # no labels              end @@ -1184,9 +1213,9 @@ checktestversion      end      def runtexmpjob(filename,filetype='') -checktestversion -        mpfile = File.suffixed(filename,filetype,'mp') -        if File.atleast?(mpfile,25) && (data = File.silentread(mpfile)) then +        checktestversion +        mpname = File.suffixed(filename,filetype,'mp') +        if File.atleast?(mpname,25) && (data = File.silentread(mpname)) then              textranslation = if data =~ /^\%\s+translate.*?\=([\w\d\-]+)/io then $1 else '' end              mpjobname = if data =~ /collected graphics of job \"(.+?)\"/io then $1 else '' end              if ! mpjobname.empty? and File.unsuffixed(filename) =~ /#{mpjobname}/ then # don't optimize @@ -1197,8 +1226,9 @@ checktestversion                  options.push("--translate=#{textranslation}") unless textranslation.empty?                  options.push("--batch") if getvariable('batchmode')                  options.push("--nonstop") if getvariable('nonstopmode') -                options.push("--output=ps") -                return runtexexec(mpfile,options,2) +                options.push("--output=ps") # options.push("--dvi") +                options.push("--nobackend") +                return runtexexec(mpname,options,2)              end          end          return false @@ -1251,9 +1281,14 @@ checktestversion      end      def fixbackendvars(backend) -        ENV['backend']     = backend ; -        ENV['progname']    = backend unless validtexengine(backend) -        ENV['TEXFONTMAPS'] = ".;\$TEXMF/fonts/map/{#{backend},pdftex,dvips,}//" +        if backend then +            report("fixing backend map path for #{backend}") if getvariable('verbose') +            ENV['backend']     = backend ; +            ENV['progname']    = backend unless validtexengine(backend) +            ENV['TEXFONTMAPS'] = ".;\$TEXMF/fonts/map/{#{backend},pdftex,dvips,}//" +        else +            report("unable to fix backend map path") if getvariable('verbose') +        end      end      def runbackend(rawname) @@ -1263,8 +1298,12 @@ checktestversion                      fixbackendvars('dvipdfm')                      system("dvipdfmx -d 4 #{File.unsuffixed(rawname)}")                  when 'xetex'    then -                    fixbackendvars('xetex') -                    system("xdv2pdf #{File.suffixed(rawname,'xdv')}") +                    # xetex now runs its own backend +                    xdvfile = File.suffixed(rawname,'xdv') +                    if FileTest.file?(xdvfile) then +                        fixbackendvars('xetex') +                        system("xdvipdfmx #{xdvfile}") +                    end                  when 'dvips'    then                      fixbackendvars('dvips')                      mapfiles = '' @@ -1289,12 +1328,8 @@ checktestversion      def processfile          takeprecautions -        # checktestversion -          report("using search method '#{Kpse.searchmethod}'") if getvariable('verbose') -          rawname = getvariable('filename') -          jobname = getvariable('filename')          suffix  = getvariable('suffix')          result  = getvariable('result') @@ -1505,16 +1540,17 @@ checktestversion      def doruntexmp(mpname,mergebe=nil,context=true)          texfound = false -        mpfile = File.suffixed(mpname,'mp') -        mpcopy = File.suffixed(mpname,'copy','mp') -        setvariable('mp.file',mpfile) +        mpname = File.suffixed(mpname,'mp') +        mpcopy = File.suffixed(mpname,'mp.copy') +        mpkeep = File.suffixed(mpname,'mp.keep') +        setvariable('mp.file',mpname)          setvariable('mp.line','')          setvariable('mp.error','') -        if mpdata = File.silentread(mpfile) then +        if mpdata = File.silentread(mpname) then              mpdata.gsub!(/^\#.*\n/o,'') -            File.silentrename(mpfile,mpcopy) +            File.silentrename(mpname,mpcopy)              texfound = mergebe || (mpdata =~ /btex .*? etex/mo) -            if mp = openedfile(mpfile) then +            if mp = openedfile(mpname) then                  if mergebe then                      mpdata.gsub!(/beginfig\s*\((\d+)\)\s*\;(.+?)endfig\s*\;/mo) do                          n, str = $1, $2 @@ -1528,7 +1564,7 @@ checktestversion                          mp << mergebe['0'] if mergebe.key?('0')                      end                  end -                mp << splitmplines(mpdata) +                mp << MPTools::splitmplines(mpdata)                  mp << "\n"                  mp << "end"                  mp << "\n" @@ -1544,7 +1580,7 @@ checktestversion              end              # todo plain|mpost|metafun              ok = runmp(mpname) -            if f = File.silentopen(File.suffixed(mpfile,'log')) then +            if f = File.silentopen(File.suffixed(mpname,'log')) then                  while str = f.gets do                      if str =~ /^l\.(\d+)\s(.*?)\n/o then                          setvariable('mp.line',$1) @@ -1554,11 +1590,13 @@ checktestversion                  end                  f.close              end -            File.silentrename(mpfile, mpfile+'.keep') -            File.silentrename(mpcopy, mpfile) +            File.silentrename(mpname, mpkeep) +            File.silentrename(mpcopy, mpname)          end      end +    # todo: use internal mptotext function and/or turn all btex/etex into textexts +      def processmpx(mpname,force=false,context=true)          unless force then              mpname = File.suffixed(mpname,'mp') @@ -1574,10 +1612,17 @@ checktestversion                  mpdvi = File.suffixed(mpname,'temp','dvi')                  mplog = File.suffixed(mpname,'temp','log')                  mpmpx = File.suffixed(mpname,'mpx') -                command = "mpto #{mpname} > #{mptex}" -                report(command) if getvariable('verbose') -                ok = system(command) -                if ok && File.appended(mptex, "\\end\n") then +                File.silentdelete(mptex) +                if true then +                    report("using internal mptotex converter") +                    ok = MPTools::mptotex(mpname,mptex,'context') +                else +                    command = "mpto #{mpname} > #{mptex}" +                    report(command) if getvariable('verbose') +                    ok = system(command) +                end +                # not "ok && ..." because of potential problem with return code and redirect (>) +                if FileTest.file?(mptex) && File.appended(mptex, "\\end\n") then                      # to be replaced by runtexexec([filenames],options,1)                      if localjob = TEX.new(@logger) then                          localjob.setvariable('files',mptex) @@ -1663,42 +1708,4 @@ checktestversion          return nil      end -    # mp specific (todo: mp module) - -    def splitmplines(str) -        btex, verbatimtex, strings, result = Array.new, Array.new, Array.new, str.dup -        # protect texts -        result.gsub!(/btex\s*(.*?)\s*etex/) do -            btex << $1 -            "btex(#{btex.length-1})" -        end -        result.gsub!(/verbatimtex\s*(.*?)\s*etex/) do -            verbatimtex << $1 -            "verbatimtex(#{verbatimtex.length-1})" -        end -        result.gsub!(/\"(.*?)\"/) do -            strings << $1 -            "\"#{strings.length-1}\"" -        end -        result.gsub!(/\;/) do -            ";\n" -        end -        result.gsub!(/(.{80,})(\-\-\-|\-\-|\.\.\.|\.\.)/) do -            "#{$1}#{$2}\n" -        end -        result.gsub!(/\n[\s\n]+/mois) do -            "\n" -        end -        result.gsub!(/btex\((\d+)\)/) do -            "btex #{btex[$1.to_i]} etex" -        end -        result.gsub!(/verbatimtex\((\d+)\)/) do -            "verbatimtex #{verbatimtex[$1.to_i]} etex" -        end -        result.gsub!(/\"(\d+)\"/) do -            "\"#{strings[$1.to_i]}\"" -        end -        result -    end -  end diff --git a/scripts/context/ruby/base/texutil.rb b/scripts/context/ruby/base/texutil.rb index 5e935501b..0529f0ca1 100644 --- a/scripts/context/ruby/base/texutil.rb +++ b/scripts/context/ruby/base/texutil.rb @@ -915,7 +915,9 @@ end                              when /^r (.*)$/o then @plugins.reader('MyRegisters',$1.splitdata)                              when /^p (.*)$/o then @plugins.reader('MyPlugins',  $1.splitdata)                              when /^x (.*)$/o then @plugins.reader('MyKeys',     $1.splitdata) -                            else report("unknown entry #{line[0,1]} in line #{line.chomp}") +                            when /^r (.*)$/o then # nothing, not handled here +                        else +                            # report("unknown entry #{line[0,1]} in line #{line.chomp}")                          end                      end                      f.close diff --git a/scripts/context/ruby/ctxtools.rb b/scripts/context/ruby/ctxtools.rb index 6d36051fa..2092b346c 100644 --- a/scripts/context/ruby/ctxtools.rb +++ b/scripts/context/ruby/ctxtools.rb @@ -20,7 +20,7 @@  # Taco Hoekwater on patterns and lig building (see 'agr'):  #  # Any direct use of a ligature (as accessed by \char or through active -# characters) is wrong and will create faulty hypenation. Normally, +# characters) is wrong and will create faulty hyphenation. Normally,  # when TeX sees "office", it has six tokens, and it knows from the  # patterns that it can hyphenate between the "ff". It will build an  # internal list of four nodes, like this: @@ -56,6 +56,7 @@ require 'base/logger'  require 'base/system'  require 'rexml/document' +require 'net/http'  require 'ftools'  require 'kconv' @@ -414,10 +415,10 @@ class Commands      public -    def purgefiles(all=false) +    def purgefiles          pattern  = @commandline.arguments -        purgeall = @commandline.option("all") || all +        purgeall = @commandline.option("all")          recurse  = @commandline.option("recurse")          $dontaskprefixes.push(Dir.glob("mpx-*")) @@ -439,7 +440,7 @@ class Commands          if ! pattern || pattern.empty? then              globbed = if recurse then "**/*.*" else "*.*" end              files = Dir.glob(globbed) -            report("purging#{if all then ' all' end} temporary files : #{globbed}") +            report("purging#{if purgeall then ' all' end} temporary files : #{globbed}")          else              pattern.each do |pat|                  globbed = if recurse then "**/#{pat}-*.*" else "#{pat}-*.*" end @@ -506,10 +507,6 @@ class Commands      end -    def purgeallfiles -        purgefiles(true) # for old times sake -    end -      private      $removedfiles    = 0 @@ -787,6 +784,56 @@ end  #  # Maybe I'll make this hyptools.tex +class String + +    def markbraces +        level = 0 +        self.gsub(/([\{\}])/o) do |chr| +            if    chr == '{' +                level = level + 1 +                chr = "((+#{level}))" +            elsif chr == '}' +                chr = "((-#{level}))" +                level = level - 1 +            end +            chr +        end +    end + +    def unmarkbraces +        self.gsub(/\(\(\+\d+?\)\)/o) do +            "{" +        end.gsub(/\(\(\-\d+?\)\)/o) do +            "}" +        end +    end + +    def getargument(pattern) +        if self =~ /(#{pattern})\s*\(\(\+(\d+)\)\)(.*?)\(\(\-\2\)\)/ then # no /o +            return $3 +        else +            return "" +        end +    end + +    def withargument(pattern, &block) +        if self.markbraces =~ /^(.*)(#{pattern}\s*)\(\(\+(\d+)\)\)(.*?)\(\(\-\3\)\)(.*)$/m then # no /o +            "#{$1.unmarkbraces}#{$2}{#{yield($4.unmarkbraces)}}#{$5.unmarkbraces}" +        else +            self +        end +    end + +    def filterargument(pattern, &block) +        if self.markbraces =~ /^(.*)(#{pattern}\s*)\(\(\+(\d+)\)\)(.*?)\(\(\-\3\)\)(.*)$/m then # no /o +            yield($4.unmarkbraces) +        else +            self +        end +    end + +end +  class Language      include CommandBase @@ -829,10 +876,11 @@ class Language                          begin                              if fname = located(filename) then                                  data = IO.read(fname) -                                @data += data.gsub(/\%.*$/, '') +                                @data += data.gsub(/\%.*$/, '').gsub(/\\message\{.*?\}/, '')                                  data.gsub!(/(\\patterns|\\hyphenation)\s*\{.*/mo) do '' end                                  @read += "\n% preamble of file #{fname}\n\n#{data}\n"                                  report("file #{fname} is loaded") +                                @data.gsub!(/^[\s\n]+$/mois, '')                                  break # next fileset                              end                          rescue @@ -853,21 +901,29 @@ class Language          if @data then              n = 0              if true then -                @data.gsub!(/\\(patterns|hypenation)\{(.*?)\}/mois) do -                    command, content = $1, $2 -                    @remapping.each_index do |i| -                        from, to, m = @remapping[i][0], @remapping[i][1], 0 -                        content.gsub!(from) do -                            m += 1 -                            "[#{i}]" +                report("") +                ["\\patterns","\\hyphenation"].each do |what| +                    @data = @data.withargument(what) do |content| +                        report("converting #{what}") +                        report("") +                        done = false +                        @remapping.each_index do |i| +                            from, to, m = @remapping[i][0], @remapping[i][1], 0 +                            content.gsub!(from) do +                                done = true +                                m += 1 +                                "[#{i}]" +                            end +                            report("#{m.to_s.rjust(5)} entries remapped to #{to}") unless m == 0 +                            n += m                          end -                        report("#{m.to_s.rjust(5)} entries remapped to #{to}") unless m == 0 -                        n += m -                    end -                    content.gsub!(/\[(\d+)\]/) do -                        @remapping[$1.to_i][1] +                        content.gsub!(/\[(\d+)\]/o) do +                            @remapping[$1.to_i][1] +                        end +                        report("      nothing remapped") unless done +                        report("") +                        content.to_s                      end -                    "\\#{command}\{#{content}\}"                  end              else                  @remapping.each do |k| @@ -932,6 +988,7 @@ class Language      end      def triggerunicode +        return          if @commandline.option('utf8') then              "% xetex needs utf8 encoded patterns and for patterns\n" +              "% coded as such we need to enable this regime when\n" + @@ -1030,9 +1087,9 @@ class Language          begin              if f = File.open(patname,'w') then                  data = '' -                @data.scan(/\\patterns\s*\{\s*(.*?)\s*\}/m) do +                @data.filterargument('\\patterns') do |content|                      report("merging patterns") -                    data += $1 + "\n" +                    data += content.strip                  end                  data.gsub!(/(\s*\n\s*)+/mo, "\n") @@ -1056,9 +1113,9 @@ class Language          begin              if f = File.open(hypname,'w') then                  data = '' -                @data.scan(/\\hyphenation\s*\{\s*(.*?)\s*\}/m) do +                @data.filterargument('\\hyphenation') do |content|                      report("merging exceptions") -                    data += $1 + "\n" +                    data += content.strip                  end                  data.gsub!(/(\s*\n\s*)+/mo, "\n")                  f << banner @@ -1184,6 +1241,8 @@ class Language                  remap(/X/, "[aeligature]")                  remap(/Y/, "[ostroke]")                  remap(/Z/, "[aring]") +            when 'hu' then +              when 'ca' then                  remap(/\\c\{.*?\}/, "")              when 'de', 'deo' then @@ -1195,6 +1254,7 @@ class Language                  remap(/\"o/, "[odiaeresis]")                  remap(/\"u/, "[udiaeresis]")              when 'fr' then +                remap(/\\n\{\}/, "")                  remap(/\\ae/, "[adiaeresis]")                  remap(/\\oe/, "[odiaeresis]")              when 'la' then @@ -1405,12 +1465,14 @@ class Language                      data.scan(/\\definecharacter\s*([a-zA-Z]+)\s*(\d+)\s*/o) do                          name, number = $1, $2                          remap(/\^\^#{sprintf("%02x",number)}/, "[#{name}]") +                        if number.to_i > 127 then +                            remap(/#{sprintf("\\%03o",number)}/, "[#{name}]") +                        end                      end                  end              rescue              end          end -      end  end @@ -1545,8 +1607,12 @@ class Commands                                                  report("? #{File.basename(dpxfile)} - dvipdfm(x)")                                              end                                          else -                                            report("- #{File.basename(dpxfile)} - dvipdfm(x)") -                                            begin File.delete(dpxname) ; rescue ; end +                                            report("- #{File.basename(dpxfile)} - dvipdfm(x) - no entries") +                                            # begin File.delete(dpxname) ; rescue ; end +                                            if f = File.open(dpxfile,'w') then +                                                f.puts("% no map entries") +                                                f.close +                                            end                                          end                                      else                                          report(". #{File.basename(dpxfile)} - dvipdfm(x) - #{n}") @@ -2134,6 +2200,89 @@ class Commands  end +class Commands + +    include CommandBase + +    def updatecontext + +        def fetchfile(site, name, target=nil) +            begin +                http = Net::HTTP.new(site) +                resp, data = http.get(name.gsub(/^\/*/, '/')) +            rescue +                return false +            else +                begin +                    if data then +                        name = File.basename(name) +                        File.open(target || name, 'wb') do |f| +                            f << data +                        end +                    else +                        return false +                    end +                rescue +                    return false +                else +                    return true +                end +            end +        end + +        def locatedlocaltree +            return `kpsewhich --expand-var $TEXMFLOCAL`.chomp rescue nil +        end + +        def extractarchive(archive) +            if FileTest.file?(archive) then +                begin +                    system("unzip -uo #{archive}") +                rescue +                    return false +                else +                    return true +                end +            else +                return false +            end +        end + +        def remakeformats +            return system("texmfstart texexec --make --all") +        end + +        if localtree = locatedlocaltree then +            report("updating #{localtree}") +            begin +                Dir.chdir(localtree) +            rescue +                report("unable to change to #{localtree}") +            else +                archive = 'cont-tmf.zip' +                report("fetching #{archive}") +                unless fetchfile("www.pragma-ade.com","/context/latest/#{archive}") then +                    report("unable to fetch #{archive}") +                    return +                end +                report("extracting #{archive}") +                unless extractarchive(archive) then +                    report("unable to extract #{archive}") +                    return +                end +                report("remaking formats") +                unless remakeformats then +                    report("unable to remak formats") +                end +            end +        else +            report("unable to locate local tree") +        end + +    end + +end +  logger      = Logger.new(banner.shift)  commandline = CommandLine.new @@ -2147,14 +2296,13 @@ commandline.registeraction('translateinterface', 'generate interface files (xml)  commandline.registeraction('purgefiles'        , 'remove temporary files [--all --recurse] [basename]')  commandline.registeraction('documentation'     , 'generate documentation [--type=] [filename]')  commandline.registeraction('filterpages'       ) # no help, hidden temporary feature -commandline.registeraction('purgeallfiles'     ) # no help, compatibility feature -commandline.registeraction('purgefiles'        ) # no help, compatibility feature  commandline.registeraction('patternfiles'      , 'generate pattern files [--all --xml --utf8] [languagecode]')  commandline.registeraction('dpxmapfiles'       , 'convert pdftex mapfiles to dvipdfmx [--force] [texmfroot]')  commandline.registeraction('listentities'      , 'create doctype entity definition from enco-uc.tex')  commandline.registeraction('brandfiles'        , 'add context copyright notice [--force]')  commandline.registeraction('platformize'       , 'replace line-endings [--recurse --force] [pattern]')  commandline.registeraction('dependencies'      , 'analyze depedencies witin context [--compact] [rootfile]') +commandline.registeraction('updatecontext'     , 'download latest version and remake formats')  commandline.registervalue('type','') diff --git a/scripts/context/ruby/imgtopdf.rb b/scripts/context/ruby/imgtopdf.rb new file mode 100644 index 000000000..98a36c17f --- /dev/null +++ b/scripts/context/ruby/imgtopdf.rb @@ -0,0 +1,86 @@ +#!/usr/bin/env ruby + +# program   : newimgtopdf +# copyright : PRAGMA Advanced Document Engineering +# version   : 2002-2006 +# author    : Hans Hagen +# +# project   : ConTeXt / eXaMpLe +# concept   : Hans Hagen +# info      : j.hagen@xs4all.nl +# www       : www.pragma-ade.com + +unless defined? ownpath +  ownpath = $0.sub(/[\\\/]\w*?\.rb/i,'') +  $: << ownpath +end + +require 'base/switch' +require 'base/logger' + +require 'graphics/magick' + +banner = ['ImgToPdf', 'version 1.1.2', '2002-2006', 'PRAGMA ADE/POD'] + +class Commands + +    include CommandBase + +    # nowadays we would force a directive, but +    # for old times sake we handle default usage + +    def main +        filename = @commandline.argument('first') + +        if filename.empty? then +            help +        else +            convert +        end +    end + +    # actions + +    def convert + +        magick = Magick.new(session) + +        ['compression','depth','colorspace','quality','inputpath','outputpath'].each do |v| +            magick.setvariable(v,@commandline.option(v)) +        end + +        @commandline.arguments.each do |fullname| +            magick.setvariable('inputfile',fullname) +            magick.setvariable('outputfile',fullname.gsub(/(\..*?$)/io, '.pdf')) +            if @commandline.option('auto') then +                magick.autoconvert +            else +                magick.convert +            end +        end +    end + +end + +logger      = Logger.new(banner.shift) +commandline = CommandLine.new + +commandline.registerflag('auto') + +commandline.registervalue('compression') +commandline.registervalue('depth') +commandline.registervalue('colorspace') +commandline.registervalue('quality') + +commandline.registervalue('inputpath') +commandline.registervalue('outputpath') + + +commandline.registeraction('help') +commandline.registeraction('version') + +commandline.registeraction('convert', 'convert image into pdf') + +commandline.expand + +Commands.new(commandline,logger,banner).send(commandline.action || 'main') diff --git a/scripts/context/ruby/newimgtopdf.rb b/scripts/context/ruby/newimgtopdf.rb index 3c1636cf2..563ae5b80 100644 --- a/scripts/context/ruby/newimgtopdf.rb +++ b/scripts/context/ruby/newimgtopdf.rb @@ -1,86 +1,8 @@  #!/usr/bin/env ruby -# program   : newimgtopdf +# program   : imgtopdf  # copyright : PRAGMA Advanced Document Engineering  # version   : 2002-2005  # author    : Hans Hagen -# -# project   : ConTeXt / eXaMpLe -# concept   : Hans Hagen -# info      : j.hagen@xs4all.nl -# www       : www.pragma-ade.com -unless defined? ownpath -  ownpath = $0.sub(/[\\\/]\w*?\.rb/i,'') -  $: << ownpath -end - -require 'base/switch' -require 'base/logger' - -require 'graphics/magick' - -banner = ['ImgToPdf', 'version 1.1.1', '2002-2005', 'PRAGMA ADE/POD'] - -class Commands - -    include CommandBase - -    # nowadays we would force a directive, but -    # for old times sake we handle default usage - -    def main -        filename = @commandline.argument('first') - -        if filename.empty? then -            help -        else -            convert -        end -    end - -    # actions - -    def convert - -        magick = Magick.new(session) - -        ['compression','depth','colorspace','quality','inputpath','outputpath'].each do |v| -            magick.setvariable(v,@commandline.option(v)) -        end - -        @commandline.arguments.each do |fullname| -            magick.setvariable('inputfile',fullname) -            magick.setvariable('outputfile',fullname.gsub(/(\..*?$)/io, '.pdf')) -            if @commandline.option('auto') then -                magick.autoconvert -            else -                magick.convert -            end -        end -    end - -end - -logger      = Logger.new(banner.shift) -commandline = CommandLine.new - -commandline.registerflag('auto') - -commandline.registervalue('compression') -commandline.registervalue('depth') -commandline.registervalue('colorspace') -commandline.registervalue('quality') - -commandline.registervalue('inputpath') -commandline.registervalue('outputpath') - - -commandline.registeraction('help') -commandline.registeraction('version') - -commandline.registeraction('convert', 'convert image into pdf') - -commandline.expand - -Commands.new(commandline,logger,banner).send(commandline.action || 'main') +load(File.join(File.expand_path(File.dirname($0)),'imgtopdf.rb')) diff --git a/scripts/context/ruby/newpstopdf.rb b/scripts/context/ruby/newpstopdf.rb index 898f987cb..a45b4cab8 100644 --- a/scripts/context/ruby/newpstopdf.rb +++ b/scripts/context/ruby/newpstopdf.rb @@ -4,527 +4,5 @@  # copyright : PRAGMA Advanced Document Engineering  # version   : 2002-2005  # author    : Hans Hagen -# -# project   : ConTeXt / eXaMpLe -# concept   : Hans Hagen -# info      : j.hagen@xs4all.nl -# www       : www.pragma-ade.com -banner = ['PsToPdf', 'version 2.0.0', '2002-2005', 'PRAGMA ADE/POD'] - -unless defined? ownpath -    ownpath = $0.sub(/[\\\/]\w*?\.rb/i,'') -    $: << ownpath -end - -# todo: paden/prefix in magick and inkscape -# todo: clean up method handling (pass strings, no numbers) -# --method=crop|bounded|raw|... -# --resolution=low|normal|medium|high|printer|print|screen|ebook|default -# + downward compatible flag handling - -require 'base/switch' -require 'base/tool' -require 'base/logger' - -require 'graphics/gs' -require 'graphics/magick' -require 'graphics/inkscape' - -require 'rexml/document' - -exit if defined?(REQUIRE2LIB) - -class Commands - -    include CommandBase - -    # nowadays we would force a directive, but -    # for old times sake we handle default usage - -    def main -        filename = @commandline.argument('first') -        pattern  = @commandline.option('pattern') -        globfiles(pattern) if filename.empty? && ! pattern.empty? -        filename = @commandline.argument('first') -        if filename.empty? then -            help -        elsif filename =~ /\.exa$/ then -            request -        else -            convert -        end -    end - -    # actions - -    def convert - -        ghostscript = GhostScript.new(logger) -        magick      = ImageMagick.new(logger) -        inkscape    = InkScape.new(logger) - -        outpath = @commandline.option('outputpath') -        unless outpath.empty? then -            begin -                File.expand_path(outpath) -                outpath = File.makedirs(outpath) unless FileTest.directory?(outpath) -            rescue -                # sorry -            end -        end - -        @commandline.arguments.each do |filename| - -            filename = Tool.cleanfilename(filename,@commandline) -            inppath = @commandline.option('inputpath') -            if inppath.empty? then -               inppath = '.' -               fullname = filename # avoid duplicate './' -            else -               fullname = File.join(inppath,filename) -            end -            if FileTest.file?(fullname) then -                handle_whatever(ghostscript,inkscape,magick,filename) -            else -                report("file #{fullname} does not exist") -            end - -        end - -    end - -    def request - -        # <exa:request> -        #   <exa:application> -        #     <exa:command>pstopdf</exa:command> -        #     <exa:filename>E:/tmp/demo.ps</exa:filename> -        #   </exa:application> -        #   <exa:data> -        #     <exa:variable label='gs:DoThumbnails'>false</exa:variable> -        #     <exa:variable label='gs:ColorImageDepth'>-1</exa:variable> -        #   </exa:data> -        # </exa:request> - -        ghostscript = GhostScript.new(logger) -        magick      = ImageMagick.new(logger) -        inkscape    = InkScape.new(logger) - -        dataname = @commandline.argument('first')  || '' -        filename = @commandline.argument('second') || '' - -        if dataname.empty? || ! FileTest.file?(dataname) then -            report('provide valid exa file') -            return -        else -            begin -                request = REXML::Document.new(File.new(dataname)) -            rescue -                report('provide valid exa file (xml error)') -                return -            end -        end -        if filename.empty? then -            begin -                if filename = REXML::XPath.first(request.root,"exa:request/exa:application/exa:filename/text()") then -                    filename = filename.to_s -                else -                    report('no filename found in exa file') -                    return -                end -            rescue -                filename = '' -            end -        end -        if filename.empty? then -            report('provide valid filename') -            return -        elsif ! FileTest.file?(filename) then -            report("invalid filename #{filename}") -            return -        end - -        [ghostscript,inkscape,magick].each do |i| -            i.setvariable('inputfile',filename) -        end - -        # set ghostscript variables -        REXML::XPath.each(request.root,"/exa:request/exa:data/exa:variable") do |v| -            begin -                if (key = v.attributes['label']) and (value = v.text.to_s) then -                    case key -                        when /gs[\:\.](var[\:\.])*(offset)/io then ghostscript.setoffset(value) -                        when /gs[\:\.](var[\:\.])*(method)/io then ghostscript.setvariable('method',value) -                        when /gs[\:\.](var[\:\.])*(.*)/io     then ghostscript.setpsoption($2,value) -                    end -                end -            rescue -            end -        end - -        # no inkscape and magick variables (yet) - -        handle_whatever(ghostscript,inkscape,magick,filename) - -    end - -    def watch - -        ghostscript = GhostScript.new(logger) -        magick      = ImageMagick.new(logger) -        inkscape    = InkScape.new(logger) - -        pathname = commandline.option('watch') - -        unless pathname and not pathname.empty? then -            report('empty watchpath is not supported') -            exit -        end - -        if pathname == '.' then -            report("watchpath #{pathname} is not supported") -            exit -        end - -        if FileTest.directory?(pathname) then -            if Dir.chdir(pathname) then -                report("watching path #{pathname}") -            else -                report("unable to change to path #{pathname}") -                exit -            end -        else -            report("invalid path #{pathname}") -            exit -        end - -        waiting = false - -        loop do - -            if waiting then -                report("waiting #{getvariable('delay')}") -                waiting = false -                sleep(getvariable('delay').to_i) -            end - -            files = Dir.glob("**/*.*") - -            if files and files.length > 0 then - -                files.each do |fullname| - -                    next unless fullname - -                    if FileTest.directory?(fullname) then -                        debug('skipping path', fullname) -                        next -                    end - -                    unless magick.supported(fullname) then -                        debug('not supported', fullname) -                        next -                    end - -                    if (! FileTest.file?(fullname)) || (FileTest.size(fullname) < 100) then -                        debug("skipping small crap file #{fullname}") -                        next -                    end - -                    debug("handling file #{fullname}") - -                    begin -                        next unless File.rename(fullname,fullname) # access trick -                    rescue -                        next                                       # being written -                    end - -                    fullname = Tool.cleanfilename(fullname,@commandline) - -                    fullname.gsub!(/\\/io, '/') - -                    filename = File.basename(fullname) -                    filepath = File.dirname(fullname) - -                    next if filename =~ /gstemp.*/io - -                    if filepath !~ /(result|done|raw|crop|bound|bitmap)/io then -                        begin -                            File.makedirs(filepath+'/raw') -                            File.makedirs(filepath+'/bound') -                            File.makedirs(filepath+'/crop') -                            File.makedirs(filepath+'/bitmap') -                            debug("creating prefered input paths on #{filepath}") -                        rescue -                            debug("creating input paths on #{filepath} failed") -                        end -                    end - -                    if filepath =~ /^(.*\/|)(done|result)$/io then -                        debug("skipping file #{fullname}") -                    else -                        report("start processing file #{fullname}") -                        if filepath =~ /^(.*\/*)(raw|crop|bound)$/io then -                            donepath = $1 + 'done' -                            resultpath = $1 + 'result' -                            case $2 -                                when 'raw'   then method = 1 -                                when 'bound' then method = 2 -                                when 'crop'  then method = 3 -                                else              method = 2 -                            end -                            report("forcing method #{method}") -                        else -                            method = 2 -                            donepath = filepath + '/done' -                            resultpath = filepath + '/result' -                            report("default method #{method}") -                        end - -                        begin -                            File.makedirs(donepath) -                            File.makedirs(resultpath) -                        rescue -                            report('result path creation fails') -                        end - -                        if FileTest.directory?(donepath) && FileTest.directory?(resultpath) then - -                            resultname = resultpath + '/' + filename.sub(/\..*$/,'') + '.pdf' - -                            @commandline.setoption('inputpath',  filepath) -                            @commandline.setoption('outputpath', resultpath) -                            @commandline.setoption('method',     method) - -                            if ghostscript.psfile?(fullname) then -                                handle_ghostscript(ghostscript,filename) -                            else -                                handle_magick(magick,filename) -                            end - -                            sleep(1) # calm down - -                            if FileTest.file?(fullname) then -                                begin -                                    File.copy(fullname,donepath + '/' + filename) -                                    File.delete(fullname) -                                rescue -                                    report('cleanup fails') -                                end -                            end - -                        end - -                    end - -                end - -            end - -            waiting = true -        end - -    end - -    private - -    def handle_whatever(ghostscript,inkscape,magick,filename) -        if ghostscript.psfile?(filename) then -            # report("processing ps file #{filename}") -            ghostscript.setvariable('pipe',false) if @commandline.option('nopipe') -            # ghostscript.setvariable('pipe',not @commandline.option('nopipe')) -            ghostscript.setvariable('colormodel',@commandline.option('colormodel')) -            ghostscript.setvariable('offset',@commandline.option('offset')) -            handle_ghostscript(ghostscript,filename) -        elsif ghostscript.pdffile?(filename) && ghostscript.pdfmethod?(@commandline.option('method')) then -            # report("processing pdf file #{filename}") -            handle_ghostscript(ghostscript,filename) -        elsif inkscape.supported?(filename) then -            # report("processing non ps/pdf file #{filename}") -            handle_inkscape(inkscape,filename) -        elsif magick.supported?(filename) then -            # report("processing non ps/pdf file #{filename}") -            handle_magick(magick,filename) -        end -    end - -    def handle_magick(magick,filename) - -        report("converting non-ps file #{filename} into pdf") - -        inppath = @commandline.option('inputpath') -        outpath = @commandline.option('outputpath') - -        inppath = inppath + '/' if not inppath.empty? -        outpath = outpath + '/' if not outpath.empty? - -        prefix = @commandline.option('prefix') -        suffix = @commandline.option('suffix') - -        inpfilename = "#{inppath}#{filename}" -        outfilename = "#{outpath}#{prefix}#{filename.sub(/\.(.*?)$/, '')}#{suffix}.pdf" - -        magick.setvariable('inputfile' , inpfilename) -        magick.setvariable('outputfile', outfilename) - -        magick.autoconvert - -    end - -    def handle_inkscape(inkscape,filename) - -        report("converting svg(z) file #{filename} into pdf") - -        inppath = @commandline.option('inputpath') -        outpath = @commandline.option('outputpath') - -        inppath = inppath + '/' if not inppath.empty? -        outpath = outpath + '/' if not outpath.empty? - -        prefix = @commandline.option('prefix') -        suffix = @commandline.option('suffix') - -        inpfilename = "#{inppath}#{filename}" -        outfilename = "#{outpath}#{prefix}#{filename.sub(/\.(.*?)$/, '')}#{suffix}.pdf" - -        inkscape.setvariable('inputfile' , inpfilename) -        inkscape.setvariable('outputfile', outfilename) - -        if @commandline.option('verbose') || @commandline.option('debug') then -            logname = filename.gsub(/\.[^\.]*?$/, '.log') -            report("log info saved in #{logname}") -            inkscape.convert(logname) # logname ook doorgeven -        else -            inkscape.convert -        end - -    end - -    def handle_ghostscript(ghostscript,filename) - -        ghostscript.reset - -        method = ghostscript.method(@commandline.option('method')) -        force = ghostscript.method(@commandline.option('force')) - -        ghostscript.setvariable('method', method) -        ghostscript.setvariable('force', force) - -        # report("conversion method #{method}") - -        inppath = @commandline.option('inputpath') -        outpath = @commandline.option('outputpath') - -        inppath = inppath + '/' if not inppath.empty? -        outpath = outpath + '/' if not outpath.empty? - -        prefix = @commandline.option('prefix') -        suffix = @commandline.option('suffix') - -        ok = false - -        if ghostscript.pdfmethod?(method) then - -            report("converting pdf file #{filename} into pdf") - -            if prefix.empty? && suffix.empty? && inppath.empty? && outpath.empty? then -                prefix = ghostscript.pdfprefix(method) -            end - -            if ghostscript.pdffile?(filename) then - -                filename = filename.sub(/\.pdf$/, '') - -                inpfilename = "#{inppath}#{filename}.pdf" -                outfilename = "#{outpath}#{prefix}#{filename}#{suffix}.pdf" - -                ghostscript.setvariable('inputfile' ,inpfilename) -                ghostscript.setvariable('outputfile',outfilename) - -                if FileTest.file?(inpfilename) then -                    ok = ghostscript.convert -                else -                    report("no file found #{filename}") -                end - -            else -                report("no pdf file #{filename}") -            end - -        elsif ghostscript.psfile?(filename) then - -            if filename =~ /(.*)\.(.*?)$/io then -                filename, filesuffix = $1, $2 -            else -                filesuffix = 'eps' -            end - -            report("converting #{filesuffix} (ps) into pdf") - -            inpfilename = "#{inppath}#{filename}.#{filesuffix}" -            outfilename = "#{outpath}#{prefix}#{filename}#{suffix}.pdf" - -            ghostscript.setvariable('inputfile' , inpfilename) -            ghostscript.setvariable('outputfile', outfilename) - -            if FileTest.file?(inpfilename) then -                ok = ghostscript.convert -                if ! ok && FileTest.file?(outfilename) then -                    begin -                        File.delete(outfilename) -                    rescue -                    end -                end -            else -                report("no file with name #{filename} found") -            end - -        else -            report('file must be of type eps/ps/ai/pdf') -        end - -        return ok - -    end - -end - -# ook pdf -> pdf onder optie 0, andere kleurruimte - -logger      = Logger.new(banner.shift) -commandline = CommandLine.new - -commandline.registerflag('debug') -commandline.registerflag('verbose') -commandline.registerflag('nopipe') - -commandline.registervalue('method',2) -commandline.registervalue('offset',0) - -commandline.registervalue('prefix') -commandline.registervalue('suffix') - -commandline.registervalue('inputpath') -commandline.registervalue('outputpath') - -commandline.registerflag('watch') -commandline.registerflag('force') - -commandline.registervalue('delay',2) - -commandline.registervalue('colormodel','cmyk') -commandline.registervalue('pattern','') - -commandline.registeraction('help') -commandline.registeraction('version') - -commandline.registeraction('convert', 'convert ps into pdf') -commandline.registeraction('request', 'handles exa request file') -commandline.registeraction('watch',   'watch folders for conversions (untested)') - -commandline.expand - -logger.verbose if (commandline.option('verbose') || commandline.option('debug')) - -Commands.new(commandline,logger,banner).send(commandline.action || 'main') +load(File.join(File.expand_path(File.dirname($0)),'pstopdf.rb')) diff --git a/scripts/context/ruby/newtexexec.rb b/scripts/context/ruby/newtexexec.rb index a44cf1116..6b4db52dc 100644 --- a/scripts/context/ruby/newtexexec.rb +++ b/scripts/context/ruby/newtexexec.rb @@ -1,632 +1,8 @@ -banner = ['TeXExec', 'version 6.1.2', '1997-2006', 'PRAGMA ADE/POD'] +#!/usr/bin/env ruby -unless defined? ownpath -    ownpath = $0.sub(/[\\\/][a-z0-9\-]*?\.rb/i,'') -    $: << ownpath -end +# program   : texexec +# copyright : PRAGMA Advanced Document Engineering +# version   : 1997-2006 +# author    : Hans Hagen -require 'base/switch' -require 'base/logger' -require 'base/variables' -require 'base/system' - -require 'base/tex' -require 'base/texutil' - -require 'ftools'     # needed ? - -require 'base/kpse'  # needed ? -# require 'base/pdf'   # needed ? -require 'base/state' # needed ? -require 'base/file'  # needed ? - -class Commands - -    include CommandBase - -    def make -        if job = TEX.new(logger) then -            prepare(job) -            # bonus, overloads language switch ! -            job.setvariable('language','all') if @commandline.option('all') -            if @commandline.arguments.length > 0 then -                if @commandline.arguments.first == 'all' then -                    job.setvariable('texformats',job.defaulttexformats) -                    job.setvariable('mpsformats',job.defaultmpsformats) -                else -                    job.setvariable('texformats',@commandline.arguments) -                    job.setvariable('mpsformats',@commandline.arguments) -                end -            end -            job.makeformats -            job.inspect && Kpse.inspect if @commandline.option('verbose') -        end -    end - -    def check -        if job = TEX.new(logger) then -            job.checkcontext -            job.inspect && Kpse.inspect  if @commandline.option('verbose') -        end -    end - -    def main -        if @commandline.arguments.length>0 then -            process -        else -            help -        end -    end - -    def process -        if job = TEX.new(logger) then -            job.setvariable('files',@commandline.arguments) -            prepare(job) -            job.processtex -            job.inspect && Kpse.inspect if @commandline.option('verbose') -        end -    end - -    def mptex -        if job = TEX.new(logger) then -            job.setvariable('files',@commandline.arguments) -            prepare(job) -            job.processmptex -            job.inspect && Kpse.inspect  if @commandline.option('verbose') -        end -    end - -    def mpxtex -        if job = TEX.new(logger) then -            job.setvariable('files',@commandline.arguments) -            prepare(job) -            job.processmpxtex -            job.inspect && Kpse.inspect  if @commandline.option('verbose') -        end -    end - -    # hard coded goodies # to be redone as s-ctx-.. with vars passed as such - -    def listing -        if job = TEX.new(logger) then -            prepare(job) -            job.cleanuptemprunfiles -            files = @commandline.arguments.sort -            if files.length > 0 then -                if f = File.open(job.tempfilename('tex'),'w') then -                    backspace = @commandline.checkedoption('backspace', '1.5cm') -                    topspace  = @commandline.checkedoption('topspace', '1.5cm') -                    pretty    = @commandline.option('pretty') -                    f << "% interface=english\n" -                    f << "\\setupbodyfont[11pt,tt]\n" -                    f << "\\setuplayout\n" -                    f << "  [topspace=#{topspace},backspace=#{backspace},\n" -                    f << "   header=0cm,footer=1.5cm,\n" -                    f << "   width=middle,height=middle]\n" -                    f << "\\setuptyping[lines=yes]\n" -                    f << "\\setuptyping[option=color]\n" if pretty -                    f << "\\starttext\n"; -                    files.each do |filename| -                        report("list file: #{filename}") -                        cleanname = cleantexfilename(filename).downcase -                        f << "\\page\n" -                        f << "\\setupfootertexts[\\tttf #{cleanname}][\\tttf \\pagenumber]\n" -                        f << "\\typefile{#{filename}}\n" -                    end -                    f << "\\stoptext\n" -                    f.close -                    job.setvariable('interface','english') -                    job.setvariable('simplerun',true) -                    # job.setvariable('nooptionfile',true) -                    job.setvariable('files',[job.tempfilename]) -                    job.processtex -                else -                    report('no files to list') -                end -            else -                report('no files to list') -            end -            job.cleanuptemprunfiles -        end -    end - -    def figures -        # this one will be redone using rlxtools -        if job = TEX.new(logger) then -            prepare(job) -            job.cleanuptemprunfiles -            files = @commandline.arguments.sort -            if files.length > 0 then -                if f = File.open(job.tempfilename('tex'),'w') then -                    job.runtexutil(files,"--figures", true) -                    figures     = @commandline.checkedoption('method', 'a').downcase -                    paperoffset = @commandline.checkedoption('paperoffset', '0pt') -                    backspace   = @commandline.checkedoption('backspace', '1.5cm') -                    topspace    = @commandline.checkedoption('topspace', '1.5cm') -                    boxtype     = @commandline.checkedoption('boxtype','') -                    f << "% format=english\n"; -                    f << "\\setuplayout\n"; -                    f << "  [topspace=#{topspace},backspace=#{backspace},\n" -                    f << "   header=1.5cm,footer=0pt,\n"; -                    f << "   width=middle,height=middle]\n"; -                    if @commandline.option('fullscreen') then -                        f << "\\setupinteraction\n"; -                        f << "  [state=start]\n"; -                        f << "\\setupinteractionscreen\n"; -                        f << "  [option=max]\n"; -                    end -                    boxtype += "box" unless boxtype.empty? || (boxtype =~ /box$/io) -                    f << "\\starttext\n"; -                    f << "\\showexternalfigures[alternative=#{figures},offset=#{paperoffset},size=#{boxtype}]\n"; -                    f << "\\stoptext\n"; -                    f.close -                    job.setvariable('interface','english') -                    job.setvariable('simplerun',true) -                    # job.setvariable('nooptionfile',true) -                    job.setvariable('files',[job.tempfilename]) -                    job.processtex -                    File.silentdelete('texutil.tuf') -                else -                    report('no figures to show') -                end -            else -                report('no figures to show') -            end -            job.cleanuptemprunfiles -        end -    end - -    def modules -        if job = TEX.new(logger) then -            prepare(job) -            job.cleanuptemprunfiles -            files = @commandline.arguments.sort -            msuffixes = ['tex','mp','pl','pm','rb'] -            if files.length > 0 then -                files.each do |fname| -                    fnames = Array.new -                    if FileTest.file?(fname) then -                        fnames << fname -                    else -                        msuffixes.each do |fsuffix| -                            fnames << File.suffixed(fname,fsuffix) -                        end -                    end -                    fnames.each do |ffname| -                        if msuffixes.include?(File.splitname(ffname)[1]) && FileTest.file?(ffname) then -                            if mod = File.open(job.tempfilename('tex'),'w') then -                                # will become a call to ctxtools -                                job.runtexutil(ffname,"--documents", true) -                                if ted = File.silentopen(File.suffixed(ffname,'ted')) then -                                    firstline = ted.gets -                                    if firstline =~ /interface=/o then -                                        mod << firstline -                                    else -                                        mod << "% interface=en\n" -                                    end -                                    ted.close -                                else -                                    mod << "% interface=en\n" -                                end -                                mod << "\\usemodule[abr-01,mod-01]\n" -                                mod << "\\def\\ModuleNumber{1}\n" -                                mod << "\\starttext\n" -                                # todo: global file too -                                mod << "\\readlocfile{#{File.suffixed(ffname,'ted')}}{}{}\n" -                                mod << "\\stoptext\n" -                                mod.close -                                job.setvariable('interface','english') # redundant -                                job.setvariable('simplerun',true) -                                # job.setvariable('nooptionfile',true) -                                job.setvariable('files',[job.tempfilename]) -                                job.processtex -                                ["dvi", "pdf","tuo"].each do |s| -                                    File.silentrename(job.tempfilename(s),File.suffixed(ffname,s)); -                                end -                            end -                        end -                    end -                end -            else -                report('no modules to process') -            end -            job.cleanuptemprunfiles -        end -    end - -    def arrangeoutput -        if job = TEX.new(logger) then -            prepare(job) -            job.cleanuptemprunfiles -            files = @commandline.arguments.sort -            if files.length > 0 then -                if f = File.open(job.tempfilename('tex'),'w') then -                    emptypages  = @commandline.checkedoption('addempty', '') -                    paperoffset = @commandline.checkedoption('paperoffset', '0cm') -                    textwidth   = @commandline.checkedoption('textwidth', '0cm') -                    backspace   = @commandline.checkedoption('backspace', '0cm') -                    topspace    = @commandline.checkedoption('topspace', '0cm') -                    f << "\\definepapersize\n" -                    f << "  [offset=#{paperoffset}]\n" -                    f << "\\setuplayout\n" -                    f << "  [backspace=#{backspace},\n" -                    f << "    topspace=#{topspace},\n" -                    f << "     marking=on,\n" if @commandline.option('marking') -                    f << "       width=middle,\n" -                    f << "      height=middle,\n" -                    f << "    location=middle,\n" -                    f << "      header=0pt,\n" -                    f << "      footer=0pt]\n" -                    unless @commandline.option('noduplex') then -                        f << "\\setuppagenumbering\n" -                        f << "  [alternative=doublesided]\n" -                    end -                    f << "\\starttext\n" -                    files.each do |filename| -                        report("arranging file #{filename}") -                        f << "\\insertpages\n" -                        f << "  [#{filename}]\n" -                        f << "  [#{emptypages}]\n" unless emptypages.empty? -                        f << "  [width=#{textwidth}]\n" -                    end -                    f << "\\stoptext\n" -                    f.close -                    job.setvariable('interface','english') -                    job.setvariable('simplerun',true) -                    # job.setvariable('nooptionfile',true) -                    job.setvariable('files',[job.tempfilename]) -                    job.processtex -                else -                    report('no files to arrange') -                end -            else -                report('no files to arrange') -            end -            job.cleanuptemprunfiles -        end -    end - -    def selectoutput -        if job = TEX.new(logger) then -            prepare(job) -            job.cleanuptemprunfiles -            files = @commandline.arguments.sort -            if files.length > 0 then -                if f = File.open(job.tempfilename('tex'),'w') then -                    selection   = @commandline.checkedoption('selection', '') -                    paperoffset = @commandline.checkedoption('paperoffset', '0cm') -                    textwidth   = @commandline.checkedoption('textwidth', '0cm') -                    backspace   = @commandline.checkedoption('backspace', '0cm') -                    topspace    = @commandline.checkedoption('topspace', '0cm') -                    paperformat = @commandline.checkedoption('paperformat', 'A4*A4').split(/[\*x]/o) -                    from, to = paperformat[0] || 'A4', paperformat[1] || paperformat[0] || 'A4' -                    if from == 'fit' or to == 'fit' then -                        f << "\\getfiguredimensions[#{files.first}]\n" -                        if from == 'fit' then -                            f << "\\expanded{\\definepapersize[from-fit][width=\\figurewidth,height=\\figureheight]}\n" -                            from = 'from-fit' -                        end -                        if to == 'fit' then -                            f << "\\expanded{\\definepapersize[to-fit][width=\\figurewidth,height=\\figureheight]}\n" -                            to = 'to-fit' -                        end -                    end -                    job.setvariable('paperformat','') # else overloaded later on -                    f << "\\setuppapersize[#{from}][#{to}]\n" -                    f << "\\definepapersize\n"; -                    f << "  [offset=#{paperoffset}]\n"; -                    f << "\\setuplayout\n"; -                    f << "  [backspace=#{backspace},\n"; -                    f << "    topspace=#{topspace},\n"; -                    f << "     marking=on,\n" if @commandline.option('marking') -                    f << "       width=middle,\n"; -                    f << "      height=middle,\n"; -                    f << "    location=middle,\n"; -                    f << "      header=0pt,\n"; -                    f << "      footer=0pt]\n"; -                    f << "\\setupexternalfigures\n"; -                    f << "  [directory=]\n"; -                    f << "\\starttext\n"; -                    unless selection.empty? then -                        f << "\\filterpages\n" -                        f << "  [#{files.first}][#{selection}][width=#{textwidth}]\n" -                    end -                    f << "\\stoptext\n" -                    f.close -                    job.setvariable('interface','english') -                    job.setvariable('simplerun',true) -                    # job.setvariable('nooptionfile',true) -                    job.setvariable('files',[job.tempfilename]) -                    job.processtex -                else -                    report('no files to selectt') -                end -            else -                report('no files to select') -            end -            job.cleanuptemprunfiles -        end -    end - -    def copyoutput -        copyortrim(false,'copy') -    end - -    def trimoutput -        copyortrim(true,'trim') -    end - -    def copyortrim(trim=false,what='unknown') -        if job = TEX.new(logger) then -            prepare(job) -            job.cleanuptemprunfiles -            files = @commandline.arguments.sort -            if files.length > 0 then -                if f = File.open(job.tempfilename('tex'),'w') then -                    scale = @commandline.checkedoption('scale') -                    scale = (scale * 1000).to_i if scale < 10 -                    paperoffset = @commandline.checkedoption('paperoffset', '0cm') -                    f << "\\starttext\n" -                    files.each do |filename| -                        result = @commandline.checkedoption('result','texexec') -                        if (filename !~ /^texexec/io) && (filename !~ /^#{result}/) then -                            report("copying file: #{filename}") -                            f <<  "\\getfiguredimensions\n" -                            f <<  "  [#{filename}]\n" -                            f <<  "  [page=1" -                            f <<  ",\n   size=trimbox" if trim -                            f <<  "]\n" -                            f <<  "\\definepapersize\n" -                            f <<  "  [copy]\n" -                            f <<  "  [width=\\naturalfigurewidth,\n" -                            f <<  "   height=\\naturalfigureheight]\n" -                            f <<  "\\setuppapersize\n" -                            f <<  "  [copy][copy]\n" -                            f <<  "\\setuplayout\n" -                            f <<  "  [page]\n" -                            f <<  "\\setupexternalfigures\n" -                            f <<  "  [directory=]\n" -                            f <<  "\\copypages\n" -                            f <<  "  [#[filename}]\n" -                            f <<  "  [scale=#{scale},\n" -                            f <<  "   marking=on,\n" if @commandline.option('markings') -                            f <<  "   size=trimbox,\n" if trim -                            f <<  "   offset=#{paperoffset}]\n" -                        end -                    end -                    f << "\\stoptext\n" -                    f.close -                    job.setvariable('interface','english') -                    job.setvariable('simplerun',true) -                    # job.setvariable('nooptionfile',true) -                    job.setvariable('files',[job.tempfilename]) -                    job.processtex -                else -                    report("no files to #{what}") -                end -            else -                report("no files to #{what}") -            end -            job.cleanuptemprunfiles -        end -    end - -    def combineoutput -        if job = TEX.new(logger) then -            prepare(job) -            job.cleanuptemprunfiles -            files = @commandline.arguments.sort -            if files.length > 0 then -                if f = File.open(job.tempfilename('tex'),'w') then -                    paperoffset = @commandline.checkedoption('paperoffset', '0cm') -                    combination = @commandline.checkedoption('combination','2*2').split(/[\*x]/o) -                    paperformat = @commandline.checkedoption('paperoffset', 'A4*A4').split(/[\*x]/o) -                    nx, ny = combination[0] || '2', combination[1] || combination[0] || '2' -                    from, to = paperformat[0] || 'A4', paperformat[1] || paperformat[0] || 'A4' -                    f << "\\setuppapersize[#{from}][#{to}]\n" -                    f << "\\setuplayout\n" -                    f << "  [topspace=#{paperoffset},\n" -                    f << "   backspace=#{paperoffset},\n" -                    f << "   header=0pt,\n" -                    f << "   footer=1cm,\n" -                    f << "   width=middle,\n" -                    f << "   height=middle]\n" -                    if @commandline.option('nobanner') then -                        f << "\\setuplayout\n" -                        f << "  [footer=0cm]\n" -                    end -                    f << "\\setupexternalfigures\n" -                    f << "  [directory=]\n" -                    f << "\\starttext\n" -                    files.each do |filename| -                        result = @commandline.checkedoption('result','texexec') -                        if (filename !~ /^texexec/io) && (filename !~ /^#{result}/) then -                            report("combination file: #{filename}") -                            cleanname = cleantexfilename(filename).downcase -                            f << "\\setupfootertexts\n" -                            f << "  [\\tttf #{cleanname}\\quad\\quad\\currentdate\\quad\\quad\\pagenumber]\n" -                            f << "\\combinepages[#{filename}][nx=#{nx},ny=#{ny}]\n" -                            f << "\\page\n" -                        end -                    end -                    f << "\\stoptext\n" -                    f.close -                    job.setvariable('interface','english') -                    job.setvariable('simplerun',true) -                    # job.setvariable('nooptionfile',true) -                    job.setvariable('files',[job.tempfilename]) -                    job.processtex -                else -                    report('no files to list') -                end -            else -                report('no files to list') -            end -            job.cleanuptemprunfiles -        end -    end - -    private - -    def prepare(job) - -        job.booleanvars.each do |k| -            job.setvariable(k,@commandline.option(k)) -        end -        job.stringvars.each do |k| -            job.setvariable(k,@commandline.option(k)) -        end -        job.standardvars.each do |k| -            job.setvariable(k,@commandline.option(k)) -        end -        job.knownvars.each do |k| -            job.setvariable(k,@commandline.option(k)) unless @commandline.option(k).empty? -        end - -        if (str = @commandline.option('engine')) && ! str.standard? && ! str.empty? then -            job.setvariable('texengine',str) -        elsif @commandline.oneof('pdfetex','pdftex','pdf') then -            job.setvariable('texengine','pdfetex') -        elsif @commandline.oneof('xetex','xtx') then -            job.setvariable('texengine','xetex') -        elsif @commandline.oneof('aleph') then -            job.setvariable('texengine','aleph') -        else -            job.setvariable('texengine','standard') -        end - -        if (str = @commandline.option('backend')) && ! str.standard? && ! str.empty? then -            job.setvariable('backend',str) -        elsif @commandline.oneof('pdfetex','pdftex','pdf') then -            job.setvariable('backend','pdftex') -        elsif @commandline.oneof('dvipdfmx','dvipdfm','dpx','dpm') then -            job.setvariable('backend','dvipdfmx') -        elsif @commandline.oneof('xetex','xtx') then -            job.setvariable('backend','xetex') -        elsif @commandline.oneof('aleph') then -            job.setvariable('backend','dvipdfmx') -        elsif @commandline.oneof('dvips','ps') then -            job.setvariable('backend','dvips') -        else -            job.setvariable('backend','standard') -        end - -        if (str = @commandline.option('engine')) && ! str.standard? && ! str.empty? then -            job.setvariable('mpsengine',@commandline.option('engine')) -        else -            job.setvariable('mpsengine','standard') -        end - -    end - -    def cleantexfilename(filename) -        filename.gsub(/([\$\_\#])/) do "\\$1" end.gsub(/([\~])/) do "\\string$1" end -    end - -end - -# we will make this pluggable, i.e. load plugins from base/tex that -# extend the class and may even add switches -# -# commandline.load_plugins('base/tex') -# -# maybe it's too slow so for a while keep the --pdf* in here - -logger      = Logger.new(banner.shift) -commandline = CommandLine.new - -commandline.registeraction('make',    'make formats') -commandline.registeraction('check',   'check versions') -commandline.registeraction('process', 'process file') -commandline.registeraction('mptex',   'process mp file') -commandline.registeraction('mpxtex',  'process mpx file') - -commandline.registeraction('listing',    'list of file content') -commandline.registeraction('figures',    'generate overview of figures') -commandline.registeraction('modules',    'generate module documentation') -commandline.registeraction('pdfarrange', 'impose pages (booklets)') -commandline.registeraction('pdfselect',  'select pages from file(s)') -commandline.registeraction('pdfcopy',    'copy pages from file(s)') -commandline.registeraction('pdftrim',    'trim pages from file(s)') -commandline.registeraction('pdfcombine', 'combine multiple pages') - -# compatibility switch - -class Commands - -    include CommandBase - -    alias pdfarrange :arrangeoutput -    alias pdfselect  :selectoutput -    alias pdfcopy    :copyoutput -    alias pdftrim    :trimoutput -    alias pdfcombine :combineoutput - -end - -# so far for compatibility - -@@extrastringvars = [ -    'pages', 'background', 'backspace', 'topspace', 'boxtype', 'tempdir', -    'printformat', 'paperformat', 'method', 'scale', 'selection', -    'combination', 'paperoffset', 'textwidth', 'addempty', 'logfile', -    'startline', 'endline', 'startcolumn', 'endcolumn', 'scale' -] - -@@extrabooleanvars = [ -    'centerpage', 'noduplex', 'color', 'pretty', -    'fullscreen', 'screensaver', 'markings' -] - -if job = TEX.new(logger) then - -    job.setextrastringvars(@@extrastringvars) -    job.setextrabooleanvars(@@extrabooleanvars) - -    job.booleanvars.each do |k| -        commandline.registerflag(k) -    end -    job.stringvars.each do |k| -        commandline.registervalue(k,'') -    end -    job.standardvars.each do |k| -        commandline.registervalue(k,'standard') -    end -    job.knownvars.each do |k| -        commandline.registervalue(k,'') -    end - -end - -# todo: register flags -> first one true - -commandline.registerflag('pdf') -commandline.registerflag('pdftex') -commandline.registerflag('pdfetex') - -commandline.registerflag('dvipdfmx') -commandline.registerflag('dvipdfm') -commandline.registerflag('dpx') -commandline.registerflag('dpm') - -commandline.registerflag('dvips') -commandline.registerflag('ps') - -commandline.registerflag('xetex') -commandline.registerflag('xtx') - -commandline.registerflag('aleph') - -commandline.registerflag('all') -commandline.registerflag('fast') - -# generic - -commandline.registeraction('help') -commandline.registeraction('version') - -commandline.registerflag('verbose') - -commandline.expand - -Commands.new(commandline,logger,banner).send(commandline.action || 'main') +load(File.join(File.expand_path(File.dirname($0)),'texexec.rb')) diff --git a/scripts/context/ruby/newtexutil.rb b/scripts/context/ruby/newtexutil.rb index af003a8e7..d6dd06a71 100644 --- a/scripts/context/ruby/newtexutil.rb +++ b/scripts/context/ruby/newtexutil.rb @@ -1,96 +1,8 @@ -banner = ['TeXUtil  ', 'version 9.1.0', '1997-2005', 'PRAGMA ADE/POD'] +#!/usr/bin/env ruby -unless defined? ownpath -    ownpath = $0.sub(/[\\\/][a-z0-9\-]*?\.rb/i,'') -    $: << ownpath -end +# program   : texexec +# copyright : PRAGMA Advanced Document Engineering +# version   : 1997-2006 +# author    : Hans Hagen -require 'base/switch' -require 'base/logger' -require 'base/file' -require 'base/texutil' - -class Commands - -    include CommandBase - -    def references -        filename = @commandline.argument('first') -        if not filename.empty? and FileTest.file?(File.suffixed(filename,'tuo')) then -            if tu = TeXUtil::Converter.new(logger) and tu.loaded(filename) then -                tu.saved if tu.processed -            end -        end -    end - -    def main -        if @commandline.arguments.length>0 then -            references -        else -            help -        end -    end - -    def purgefiles -        system("texmfstart ctxtools --purge #{@commandline.argument.join(' ')}") -    end - -    def purgeallfiles -        system("texmfstart ctxtools --purgeall #{@commandline.argument.join(' ')}") -    end - -    def documentation -        system("texmfstart ctxtools --document #{@commandline.argument.join(' ')}") -    end - -    def analyzefile -        system("texmfstart pdftools --analyze #{@commandline.argument.join(' ')}") -    end - -    def filterpages # obsolete -        system("texmfstart ctxtools --purge #{@commandline.argument.join(' ')}") -    end - -    def figures -        report("this code is not yet converted from perl to ruby") -    end - -    def logfile -        report("this code is not yet converted from perl to ruby") -    end - -end - -logger      = Logger.new(banner.shift) -commandline = CommandLine.new - -# main feature - -commandline.registeraction('references', 'convert tui file into tuo file') - -# todo features - -commandline.registeraction('figures', 'generate figure dimensions file') -commandline.registeraction('logfile', 'filter essential log messages') - -# backward compatibility features - -commandline.registeraction('purgefiles', 'remove most temporary files') -commandline.registeraction('purgeallfiles', 'remove all temporary files') -commandline.registeraction('documentation', 'generate documentation file from source') -commandline.registeraction('analyzefile', 'analyze pdf file') - -# old feature, not needed any longer due to extension of pdftex - -commandline.registeraction('filterpages') - -# generic features - -commandline.registeraction('help') -commandline.registeraction('version') - -commandline.registerflag('verbose') - -commandline.expand - -Commands.new(commandline,logger,banner).send(commandline.action || 'main') +load(File.join(File.expand_path(File.dirname($0)),'texutil.rb')) diff --git a/scripts/context/ruby/pstopdf.rb b/scripts/context/ruby/pstopdf.rb new file mode 100644 index 000000000..96469beb4 --- /dev/null +++ b/scripts/context/ruby/pstopdf.rb @@ -0,0 +1,527 @@ +#!/usr/bin/env ruby + +# program   : pstopdf +# copyright : PRAGMA Advanced Document Engineering +# version   : 2002-2005 +# author    : Hans Hagen +# +# project   : ConTeXt / eXaMpLe +# concept   : Hans Hagen +# info      : j.hagen@xs4all.nl +# www       : www.pragma-ade.com + +banner = ['PsToPdf', 'version 2.0.1', '2002-2006', 'PRAGMA ADE/POD'] + +$: << File.expand_path(File.dirname($0)) + +# todo: paden/prefix in magick and inkscape +# todo: clean up method handling (pass strings, no numbers) +# --method=crop|bounded|raw|... +# --resolution=low|normal|medium|high|printer|print|screen|ebook|default +# + downward compatible flag handling + +require 'base/switch' +require 'base/tool' +require 'base/logger' + +require 'graphics/gs' +require 'graphics/magick' +require 'graphics/inkscape' + +require 'rexml/document' + +exit if defined?(REQUIRE2LIB) + +class Commands + +    include CommandBase + +    # nowadays we would force a directive, but +    # for old times sake we handle default usage + +    def main +        filename = @commandline.argument('first') +        pattern  = @commandline.option('pattern') +        globfiles(pattern) if filename.empty? && ! pattern.empty? +        filename = @commandline.argument('first') +        if filename.empty? then +            help +        elsif filename =~ /\.exa$/ then +            request +        else +            convert +        end +    end + +    # actions + +    def convert + +        ghostscript = GhostScript.new(logger) +        magick      = ImageMagick.new(logger) +        inkscape    = InkScape.new(logger) + +        outpath = @commandline.option('outputpath') +        unless outpath.empty? then +            begin +                File.expand_path(outpath) +                outpath = File.makedirs(outpath) unless FileTest.directory?(outpath) +            rescue +                # sorry +            end +        end + +        @commandline.arguments.each do |filename| + +            filename = Tool.cleanfilename(filename,@commandline) +            inppath = @commandline.option('inputpath') +            if inppath.empty? then +               inppath = '.' +               fullname = filename # avoid duplicate './' +            else +               fullname = File.join(inppath,filename) +            end +            if FileTest.file?(fullname) then +                handle_whatever(ghostscript,inkscape,magick,filename) +            else +                report("file #{fullname} does not exist") +            end + +        end + +    end + +    def request + +        # <exa:request> +        #   <exa:application> +        #     <exa:command>pstopdf</exa:command> +        #     <exa:filename>E:/tmp/demo.ps</exa:filename> +        #   </exa:application> +        #   <exa:data> +        #     <exa:variable label='gs:DoThumbnails'>false</exa:variable> +        #     <exa:variable label='gs:ColorImageDepth'>-1</exa:variable> +        #   </exa:data> +        # </exa:request> + +        ghostscript = GhostScript.new(logger) +        magick      = ImageMagick.new(logger) +        inkscape    = InkScape.new(logger) + +        dataname = @commandline.argument('first')  || '' +        filename = @commandline.argument('second') || '' + +        if dataname.empty? || ! FileTest.file?(dataname) then +            report('provide valid exa file') +            return +        else +            begin +                request = REXML::Document.new(File.new(dataname)) +            rescue +                report('provide valid exa file (xml error)') +                return +            end +        end +        if filename.empty? then +            begin +                if filename = REXML::XPath.first(request.root,"exa:request/exa:application/exa:filename/text()") then +                    filename = filename.to_s +                else +                    report('no filename found in exa file') +                    return +                end +            rescue +                filename = '' +            end +        end +        if filename.empty? then +            report('provide valid filename') +            return +        elsif ! FileTest.file?(filename) then +            report("invalid filename #{filename}") +            return +        end + +        [ghostscript,inkscape,magick].each do |i| +            i.setvariable('inputfile',filename) +        end + +        # set ghostscript variables +        REXML::XPath.each(request.root,"/exa:request/exa:data/exa:variable") do |v| +            begin +                if (key = v.attributes['label']) and (value = v.text.to_s) then +                    case key +                        when /gs[\:\.](var[\:\.])*(offset)/io then ghostscript.setoffset(value) +                        when /gs[\:\.](var[\:\.])*(method)/io then ghostscript.setvariable('method',value) +                        when /gs[\:\.](var[\:\.])*(.*)/io     then ghostscript.setpsoption($2,value) +                    end +                end +            rescue +            end +        end + +        # no inkscape and magick variables (yet) + +        handle_whatever(ghostscript,inkscape,magick,filename) + +    end + +    def watch + +        ghostscript = GhostScript.new(logger) +        magick      = ImageMagick.new(logger) +        inkscape    = InkScape.new(logger) + +        pathname = commandline.option('watch') + +        unless pathname and not pathname.empty? then +            report('empty watchpath is not supported') +            exit +        end + +        if pathname == '.' then +            report("watchpath #{pathname} is not supported") +            exit +        end + +        if FileTest.directory?(pathname) then +            if Dir.chdir(pathname) then +                report("watching path #{pathname}") +            else +                report("unable to change to path #{pathname}") +                exit +            end +        else +            report("invalid path #{pathname}") +            exit +        end + +        waiting = false + +        loop do + +            if waiting then +                report("waiting #{getvariable('delay')}") +                waiting = false +                sleep(getvariable('delay').to_i) +            end + +            files = Dir.glob("**/*.*") + +            if files and files.length > 0 then + +                files.each do |fullname| + +                    next unless fullname + +                    if FileTest.directory?(fullname) then +                        debug('skipping path', fullname) +                        next +                    end + +                    unless magick.supported(fullname) then +                        debug('not supported', fullname) +                        next +                    end + +                    if (! FileTest.file?(fullname)) || (FileTest.size(fullname) < 100) then +                        debug("skipping small crap file #{fullname}") +                        next +                    end + +                    debug("handling file #{fullname}") + +                    begin +                        next unless File.rename(fullname,fullname) # access trick +                    rescue +                        next                                       # being written +                    end + +                    fullname = Tool.cleanfilename(fullname,@commandline) + +                    fullname.gsub!(/\\/io, '/') + +                    filename = File.basename(fullname) +                    filepath = File.dirname(fullname) + +                    next if filename =~ /gstemp.*/io + +                    if filepath !~ /(result|done|raw|crop|bound|bitmap)/io then +                        begin +                            File.makedirs(filepath+'/raw') +                            File.makedirs(filepath+'/bound') +                            File.makedirs(filepath+'/crop') +                            File.makedirs(filepath+'/bitmap') +                            debug("creating prefered input paths on #{filepath}") +                        rescue +                            debug("creating input paths on #{filepath} failed") +                        end +                    end + +                    if filepath =~ /^(.*\/|)(done|result)$/io then +                        debug("skipping file #{fullname}") +                    else +                        report("start processing file #{fullname}") +                        if filepath =~ /^(.*\/*)(raw|crop|bound)$/io then +                            donepath = $1 + 'done' +                            resultpath = $1 + 'result' +                            case $2 +                                when 'raw'   then method = 1 +                                when 'bound' then method = 2 +                                when 'crop'  then method = 3 +                                else              method = 2 +                            end +                            report("forcing method #{method}") +                        else +                            method = 2 +                            donepath = filepath + '/done' +                            resultpath = filepath + '/result' +                            report("default method #{method}") +                        end + +                        begin +                            File.makedirs(donepath) +                            File.makedirs(resultpath) +                        rescue +                            report('result path creation fails') +                        end + +                        if FileTest.directory?(donepath) && FileTest.directory?(resultpath) then + +                            resultname = resultpath + '/' + filename.sub(/\..*$/,'') + '.pdf' + +                            @commandline.setoption('inputpath',  filepath) +                            @commandline.setoption('outputpath', resultpath) +                            @commandline.setoption('method',     method) + +                            if ghostscript.psfile?(fullname) then +                                handle_ghostscript(ghostscript,filename) +                            else +                                handle_magick(magick,filename) +                            end + +                            sleep(1) # calm down + +                            if FileTest.file?(fullname) then +                                begin +                                    File.copy(fullname,donepath + '/' + filename) +                                    File.delete(fullname) +                                rescue +                                    report('cleanup fails') +                                end +                            end + +                        end + +                    end + +                end + +            end + +            waiting = true +        end + +    end + +    private + +    def handle_whatever(ghostscript,inkscape,magick,filename) +        if ghostscript.psfile?(filename) then +            # report("processing ps file #{filename}") +            ghostscript.setvariable('pipe',false) if @commandline.option('nopipe') +            # ghostscript.setvariable('pipe',not @commandline.option('nopipe')) +            ghostscript.setvariable('colormodel',@commandline.option('colormodel')) +            ghostscript.setvariable('offset',@commandline.option('offset')) +            handle_ghostscript(ghostscript,filename) +        elsif ghostscript.pdffile?(filename) && ghostscript.pdfmethod?(@commandline.option('method')) then +            # report("processing pdf file #{filename}") +            handle_ghostscript(ghostscript,filename) +        elsif inkscape.supported?(filename) then +            # report("processing non ps/pdf file #{filename}") +            handle_inkscape(inkscape,filename) +        elsif magick.supported?(filename) then +            # report("processing non ps/pdf file #{filename}") +            handle_magick(magick,filename) +        end +    end + +    def handle_magick(magick,filename) + +        report("converting non-ps file #{filename} into pdf") + +        inppath = @commandline.option('inputpath') +        outpath = @commandline.option('outputpath') + +        inppath = inppath + '/' if not inppath.empty? +        outpath = outpath + '/' if not outpath.empty? + +        prefix = @commandline.option('prefix') +        suffix = @commandline.option('suffix') + +        inpfilename = "#{inppath}#{filename}" +        outfilename = "#{outpath}#{prefix}#{filename.sub(/\.(.*?)$/, '')}#{suffix}.pdf" + +        magick.setvariable('inputfile' , inpfilename) +        magick.setvariable('outputfile', outfilename) + +        magick.autoconvert + +    end + +    def handle_inkscape(inkscape,filename) + +        report("converting svg(z) file #{filename} into pdf") + +        inppath = @commandline.option('inputpath') +        outpath = @commandline.option('outputpath') + +        inppath = inppath + '/' if not inppath.empty? +        outpath = outpath + '/' if not outpath.empty? + +        prefix = @commandline.option('prefix') +        suffix = @commandline.option('suffix') + +        inpfilename = "#{inppath}#{filename}" +        outfilename = "#{outpath}#{prefix}#{filename.sub(/\.(.*?)$/, '')}#{suffix}.pdf" + +        inkscape.setvariable('inputfile' , inpfilename) +        inkscape.setvariable('outputfile', outfilename) + +        if @commandline.option('verbose') || @commandline.option('debug') then +            logname = filename.gsub(/\.[^\.]*?$/, '.log') +            report("log info saved in #{logname}") +            inkscape.convert(logname) # logname ook doorgeven +        else +            inkscape.convert +        end + +    end + +    def handle_ghostscript(ghostscript,filename) + +        ghostscript.reset + +        method = ghostscript.method(@commandline.option('method')) +        force = ghostscript.method(@commandline.option('force')) + +        ghostscript.setvariable('method', method) +        ghostscript.setvariable('force', force) + +        # report("conversion method #{method}") + +        inppath = @commandline.option('inputpath') +        outpath = @commandline.option('outputpath') + +        inppath = inppath + '/' if not inppath.empty? +        outpath = outpath + '/' if not outpath.empty? + +        prefix = @commandline.option('prefix') +        suffix = @commandline.option('suffix') + +        ok = false + +        if ghostscript.pdfmethod?(method) then + +            report("converting pdf file #{filename} into pdf") + +            if prefix.empty? && suffix.empty? && inppath.empty? && outpath.empty? then +                prefix = ghostscript.pdfprefix(method) +            end + +            if ghostscript.pdffile?(filename) then + +                filename = filename.sub(/\.pdf$/, '') + +                inpfilename = "#{inppath}#{filename}.pdf" +                outfilename = "#{outpath}#{prefix}#{filename}#{suffix}.pdf" + +                ghostscript.setvariable('inputfile' ,inpfilename) +                ghostscript.setvariable('outputfile',outfilename) + +                if FileTest.file?(inpfilename) then +                    ok = ghostscript.convert +                else +                    report("no file found #{filename}") +                end + +            else +                report("no pdf file #{filename}") +            end + +        elsif ghostscript.psfile?(filename) then + +            if filename =~ /(.*)\.(.*?)$/io then +                filename, filesuffix = $1, $2 +            else +                filesuffix = 'eps' +            end + +            report("converting #{filesuffix} (ps) into pdf") + +            inpfilename = "#{inppath}#{filename}.#{filesuffix}" +            outfilename = "#{outpath}#{prefix}#{filename}#{suffix}.pdf" + +            ghostscript.setvariable('inputfile' , inpfilename) +            ghostscript.setvariable('outputfile', outfilename) + +            if FileTest.file?(inpfilename) then +                ok = ghostscript.convert +                if ! ok && FileTest.file?(outfilename) then +                    begin +                        File.delete(outfilename) +                    rescue +                    end +                end +            else +                report("no file with name #{filename} found") +            end + +        else +            report('file must be of type eps/ps/ai/pdf') +        end + +        return ok + +    end + +end + +# ook pdf -> pdf onder optie 0, andere kleurruimte + +logger      = Logger.new(banner.shift) +commandline = CommandLine.new + +commandline.registerflag('debug') +commandline.registerflag('verbose') +commandline.registerflag('nopipe') + +commandline.registervalue('method',2) +commandline.registervalue('offset',0) + +commandline.registervalue('prefix') +commandline.registervalue('suffix') + +commandline.registervalue('inputpath') +commandline.registervalue('outputpath') + +commandline.registerflag('watch') +commandline.registerflag('force') + +commandline.registervalue('delay',2) + +commandline.registervalue('colormodel','cmyk') +commandline.registervalue('pattern','') + +commandline.registeraction('help') +commandline.registeraction('version') + +commandline.registeraction('convert', 'convert ps into pdf') +commandline.registeraction('request', 'handles exa request file') +commandline.registeraction('watch',   'watch folders for conversions (untested)') + +commandline.expand + +logger.verbose if (commandline.option('verbose') || commandline.option('debug')) + +Commands.new(commandline,logger,banner).send(commandline.action || 'main') diff --git a/scripts/context/ruby/runtools.rb b/scripts/context/ruby/runtools.rb index 9f6fd3328..7cb80f4ff 100644 --- a/scripts/context/ruby/runtools.rb +++ b/scripts/context/ruby/runtools.rb @@ -410,7 +410,7 @@ class Job      end      # runner = Runner.new -    # runner.texmfstart('newtexexec.rb','--help') +    # runner.texmfstart('texexec','--help')      def texmfstart(name,args,verbose=false)          command = ['texmfstart',"#{'--verbose' if verbose}",name,args].flatten.join(' ') diff --git a/scripts/context/ruby/texexec.rb b/scripts/context/ruby/texexec.rb new file mode 100644 index 000000000..e4de87b10 --- /dev/null +++ b/scripts/context/ruby/texexec.rb @@ -0,0 +1,637 @@ +banner = ['TeXExec', 'version 6.2.0', '1997-2006', 'PRAGMA ADE/POD'] + +unless defined? ownpath +    ownpath = $0.sub(/[\\\/][a-z0-9\-]*?\.rb/i,'') +    $: << ownpath +end + +require 'ftools'     # needed ? + +require 'base/switch' +require 'base/logger' +require 'base/variables' +require 'base/system' + +require 'base/state' # needed ? +require 'base/file'  # needed ? + +require 'base/tex' +require 'base/texutil' +require 'base/kpse' + +class Commands + +    include CommandBase + +    def make +        if job = TEX.new(logger) then +            prepare(job) +            # bonus, overloads language switch ! +            job.setvariable('language','all') if @commandline.option('all') +            if @commandline.arguments.length > 0 then +                if @commandline.arguments.first == 'all' then +                    job.setvariable('texformats',job.defaulttexformats) +                    job.setvariable('mpsformats',job.defaultmpsformats) +                else +                    job.setvariable('texformats',@commandline.arguments) +                    job.setvariable('mpsformats',@commandline.arguments) +                end +            end +            job.makeformats +            job.inspect && Kpse.inspect if @commandline.option('verbose') +        end +    end + +    def check +        if job = TEX.new(logger) then +            job.checkcontext +            job.inspect && Kpse.inspect  if @commandline.option('verbose') +        end +    end + +    def main +        if @commandline.arguments.length>0 then +            process +        else +            help +        end +    end + +    def process +        if job = TEX.new(logger) then +            job.setvariable('files',@commandline.arguments) +            prepare(job) +            job.processtex +            job.inspect && Kpse.inspect if @commandline.option('verbose') +        end +    end + +    def mptex +        if job = TEX.new(logger) then +            job.setvariable('files',@commandline.arguments) +            prepare(job) +            job.processmptex +            job.inspect && Kpse.inspect  if @commandline.option('verbose') +        end +    end + +    def mpxtex +        if job = TEX.new(logger) then +            job.setvariable('files',@commandline.arguments) +            prepare(job) +            job.processmpxtex +            job.inspect && Kpse.inspect  if @commandline.option('verbose') +        end +    end + +    # hard coded goodies # to be redone as s-ctx-.. with vars passed as such + +    def listing +        if job = TEX.new(logger) then +            prepare(job) +            job.cleanuptemprunfiles +            files = @commandline.arguments.sort +            if files.length > 0 then +                if f = File.open(job.tempfilename('tex'),'w') then +                    backspace = @commandline.checkedoption('backspace', '1.5cm') +                    topspace  = @commandline.checkedoption('topspace', '1.5cm') +                    pretty    = @commandline.option('pretty') +                    f << "% interface=english\n" +                    f << "\\setupbodyfont[11pt,tt]\n" +                    f << "\\setuplayout\n" +                    f << "  [topspace=#{topspace},backspace=#{backspace},\n" +                    f << "   header=0cm,footer=1.5cm,\n" +                    f << "   width=middle,height=middle]\n" +                    f << "\\setuptyping[lines=yes]\n" +                    f << "\\setuptyping[option=color]\n" if pretty +                    f << "\\starttext\n"; +                    files.each do |filename| +                        report("list file: #{filename}") +                        cleanname = cleantexfilename(filename).downcase +                        f << "\\page\n" +                        f << "\\setupfootertexts[\\tttf #{cleanname}][\\tttf \\pagenumber]\n" +                        f << "\\typefile{#{filename}}\n" +                    end +                    f << "\\stoptext\n" +                    f.close +                    job.setvariable('interface','english') +                    job.setvariable('simplerun',true) +                    # job.setvariable('nooptionfile',true) +                    job.setvariable('files',[job.tempfilename]) +                    job.processtex +                else +                    report('no files to list') +                end +            else +                report('no files to list') +            end +            job.cleanuptemprunfiles +        end +    end + +    def figures +        # this one will be redone using rlxtools +        if job = TEX.new(logger) then +            prepare(job) +            job.cleanuptemprunfiles +            files = @commandline.arguments.sort +            if files.length > 0 then +                if f = File.open(job.tempfilename('tex'),'w') then +                    job.runtexutil(files,"--figures", true) +                    figures     = @commandline.checkedoption('method', 'a').downcase +                    paperoffset = @commandline.checkedoption('paperoffset', '0pt') +                    backspace   = @commandline.checkedoption('backspace', '1.5cm') +                    topspace    = @commandline.checkedoption('topspace', '1.5cm') +                    boxtype     = @commandline.checkedoption('boxtype','') +                    f << "% format=english\n"; +                    f << "\\setuplayout\n"; +                    f << "  [topspace=#{topspace},backspace=#{backspace},\n" +                    f << "   header=1.5cm,footer=0pt,\n"; +                    f << "   width=middle,height=middle]\n"; +                    if @commandline.option('fullscreen') then +                        f << "\\setupinteraction\n"; +                        f << "  [state=start]\n"; +                        f << "\\setupinteractionscreen\n"; +                        f << "  [option=max]\n"; +                    end +                    boxtype += "box" unless boxtype.empty? || (boxtype =~ /box$/io) +                    f << "\\starttext\n"; +                    f << "\\showexternalfigures[alternative=#{figures},offset=#{paperoffset},size=#{boxtype}]\n"; +                    f << "\\stoptext\n"; +                    f.close +                    job.setvariable('interface','english') +                    job.setvariable('simplerun',true) +                    # job.setvariable('nooptionfile',true) +                    job.setvariable('files',[job.tempfilename]) +                    job.processtex +                    File.silentdelete('texutil.tuf') +                else +                    report('no figures to show') +                end +            else +                report('no figures to show') +            end +            job.cleanuptemprunfiles +        end +    end + +    def modules +        if job = TEX.new(logger) then +            prepare(job) +            job.cleanuptemprunfiles +            files = @commandline.arguments.sort +            msuffixes = ['tex','mp','pl','pm','rb'] +            if files.length > 0 then +                files.each do |fname| +                    fnames = Array.new +                    if FileTest.file?(fname) then +                        fnames << fname +                    else +                        msuffixes.each do |fsuffix| +                            fnames << File.suffixed(fname,fsuffix) +                        end +                    end +                    fnames.each do |ffname| +                        if msuffixes.include?(File.splitname(ffname)[1]) && FileTest.file?(ffname) then +                            if mod = File.open(job.tempfilename('tex'),'w') then +                                # will become a call to ctxtools +                                job.runtexutil(ffname,"--documents", true) +                                if ted = File.silentopen(File.suffixed(ffname,'ted')) then +                                    firstline = ted.gets +                                    if firstline =~ /interface=/o then +                                        mod << firstline +                                    else +                                        mod << "% interface=en\n" +                                    end +                                    ted.close +                                else +                                    mod << "% interface=en\n" +                                end +                                mod << "\\usemodule[abr-01,mod-01]\n" +                                mod << "\\def\\ModuleNumber{1}\n" +                                mod << "\\starttext\n" +                                # todo: global file too +                                mod << "\\readlocfile{#{File.suffixed(ffname,'ted')}}{}{}\n" +                                mod << "\\stoptext\n" +                                mod.close +                                job.setvariable('interface','english') # redundant +                                job.setvariable('simplerun',true) +                                # job.setvariable('nooptionfile',true) +                                job.setvariable('files',[job.tempfilename]) +                                job.processtex +                                ["dvi", "pdf","tuo"].each do |s| +                                    File.silentrename(job.tempfilename(s),File.suffixed(ffname,s)); +                                end +                            end +                        end +                    end +                end +            else +                report('no modules to process') +            end +            job.cleanuptemprunfiles +        end +    end + +    def arrangeoutput +        if job = TEX.new(logger) then +            prepare(job) +            job.cleanuptemprunfiles +            files = @commandline.arguments.sort +            if files.length > 0 then +                if f = File.open(job.tempfilename('tex'),'w') then +                    emptypages  = @commandline.checkedoption('addempty', '') +                    paperoffset = @commandline.checkedoption('paperoffset', '0cm') +                    textwidth   = @commandline.checkedoption('textwidth', '0cm') +                    backspace   = @commandline.checkedoption('backspace', '0cm') +                    topspace    = @commandline.checkedoption('topspace', '0cm') +                    f << "\\definepapersize\n" +                    f << "  [offset=#{paperoffset}]\n" +                    f << "\\setuplayout\n" +                    f << "  [backspace=#{backspace},\n" +                    f << "    topspace=#{topspace},\n" +                    f << "     marking=on,\n" if @commandline.option('marking') +                    f << "       width=middle,\n" +                    f << "      height=middle,\n" +                    f << "    location=middle,\n" +                    f << "      header=0pt,\n" +                    f << "      footer=0pt]\n" +                    unless @commandline.option('noduplex') then +                        f << "\\setuppagenumbering\n" +                        f << "  [alternative=doublesided]\n" +                    end +                    f << "\\starttext\n" +                    files.each do |filename| +                        report("arranging file #{filename}") +                        f << "\\insertpages\n" +                        f << "  [#{filename}]\n" +                        f << "  [#{emptypages}]\n" unless emptypages.empty? +                        f << "  [width=#{textwidth}]\n" +                    end +                    f << "\\stoptext\n" +                    f.close +                    job.setvariable('interface','english') +                    job.setvariable('simplerun',true) +                    # job.setvariable('nooptionfile',true) +                    job.setvariable('files',[job.tempfilename]) +                    job.processtex +                else +                    report('no files to arrange') +                end +            else +                report('no files to arrange') +            end +            job.cleanuptemprunfiles +        end +    end + +    def selectoutput +        if job = TEX.new(logger) then +            prepare(job) +            job.cleanuptemprunfiles +            files = @commandline.arguments.sort +            if files.length > 0 then +                if f = File.open(job.tempfilename('tex'),'w') then +                    selection   = @commandline.checkedoption('selection', '') +                    paperoffset = @commandline.checkedoption('paperoffset', '0cm') +                    textwidth   = @commandline.checkedoption('textwidth', '0cm') +                    backspace   = @commandline.checkedoption('backspace', '0cm') +                    topspace    = @commandline.checkedoption('topspace', '0cm') +                    paperformat = @commandline.checkedoption('paperformat', 'A4*A4').split(/[\*x]/o) +                    from, to = paperformat[0] || 'A4', paperformat[1] || paperformat[0] || 'A4' +                    if from == 'fit' or to == 'fit' then +                        f << "\\getfiguredimensions[#{files.first}]\n" +                        if from == 'fit' then +                            f << "\\expanded{\\definepapersize[from-fit][width=\\figurewidth,height=\\figureheight]}\n" +                            from = 'from-fit' +                        end +                        if to == 'fit' then +                            f << "\\expanded{\\definepapersize[to-fit][width=\\figurewidth,height=\\figureheight]}\n" +                            to = 'to-fit' +                        end +                    end +                    job.setvariable('paperformat','') # else overloaded later on +                    f << "\\setuppapersize[#{from}][#{to}]\n" +                    f << "\\definepapersize\n"; +                    f << "  [offset=#{paperoffset}]\n"; +                    f << "\\setuplayout\n"; +                    f << "  [backspace=#{backspace},\n"; +                    f << "    topspace=#{topspace},\n"; +                    f << "     marking=on,\n" if @commandline.option('marking') +                    f << "       width=middle,\n"; +                    f << "      height=middle,\n"; +                    f << "    location=middle,\n"; +                    f << "      header=0pt,\n"; +                    f << "      footer=0pt]\n"; +                    f << "\\setupexternalfigures\n"; +                    f << "  [directory=]\n"; +                    f << "\\starttext\n"; +                    unless selection.empty? then +                        f << "\\filterpages\n" +                        f << "  [#{files.first}][#{selection}][width=#{textwidth}]\n" +                    end +                    f << "\\stoptext\n" +                    f.close +                    job.setvariable('interface','english') +                    job.setvariable('simplerun',true) +                    # job.setvariable('nooptionfile',true) +                    job.setvariable('files',[job.tempfilename]) +                    job.processtex +                else +                    report('no files to selectt') +                end +            else +                report('no files to select') +            end +            job.cleanuptemprunfiles +        end +    end + +    def copyoutput +        copyortrim(false,'copy') +    end + +    def trimoutput +        copyortrim(true,'trim') +    end + +    def copyortrim(trim=false,what='unknown') +        if job = TEX.new(logger) then +            prepare(job) +            job.cleanuptemprunfiles +            files = @commandline.arguments.sort +            if files.length > 0 then +                if f = File.open(job.tempfilename('tex'),'w') then +                    scale = @commandline.checkedoption('scale') +                    scale = (scale * 1000).to_i if scale < 10 +                    paperoffset = @commandline.checkedoption('paperoffset', '0cm') +                    f << "\\starttext\n" +                    files.each do |filename| +                        result = @commandline.checkedoption('result','texexec') +                        if (filename !~ /^texexec/io) && (filename !~ /^#{result}/) then +                            report("copying file: #{filename}") +                            f <<  "\\getfiguredimensions\n" +                            f <<  "  [#{filename}]\n" +                            f <<  "  [page=1" +                            f <<  ",\n   size=trimbox" if trim +                            f <<  "]\n" +                            f <<  "\\definepapersize\n" +                            f <<  "  [copy]\n" +                            f <<  "  [width=\\naturalfigurewidth,\n" +                            f <<  "   height=\\naturalfigureheight]\n" +                            f <<  "\\setuppapersize\n" +                            f <<  "  [copy][copy]\n" +                            f <<  "\\setuplayout\n" +                            f <<  "  [page]\n" +                            f <<  "\\setupexternalfigures\n" +                            f <<  "  [directory=]\n" +                            f <<  "\\copypages\n" +                            f <<  "  [#[filename}]\n" +                            f <<  "  [scale=#{scale},\n" +                            f <<  "   marking=on,\n" if @commandline.option('markings') +                            f <<  "   size=trimbox,\n" if trim +                            f <<  "   offset=#{paperoffset}]\n" +                        end +                    end +                    f << "\\stoptext\n" +                    f.close +                    job.setvariable('interface','english') +                    job.setvariable('simplerun',true) +                    # job.setvariable('nooptionfile',true) +                    job.setvariable('files',[job.tempfilename]) +                    job.processtex +                else +                    report("no files to #{what}") +                end +            else +                report("no files to #{what}") +            end +            job.cleanuptemprunfiles +        end +    end + +    def combineoutput +        if job = TEX.new(logger) then +            prepare(job) +            job.cleanuptemprunfiles +            files = @commandline.arguments.sort +            if files.length > 0 then +                if f = File.open(job.tempfilename('tex'),'w') then +                    paperoffset = @commandline.checkedoption('paperoffset', '0cm') +                    combination = @commandline.checkedoption('combination','2*2').split(/[\*x]/o) +                    paperformat = @commandline.checkedoption('paperoffset', 'A4*A4').split(/[\*x]/o) +                    nx, ny = combination[0] || '2', combination[1] || combination[0] || '2' +                    from, to = paperformat[0] || 'A4', paperformat[1] || paperformat[0] || 'A4' +                    f << "\\setuppapersize[#{from}][#{to}]\n" +                    f << "\\setuplayout\n" +                    f << "  [topspace=#{paperoffset},\n" +                    f << "   backspace=#{paperoffset},\n" +                    f << "   header=0pt,\n" +                    f << "   footer=1cm,\n" +                    f << "   width=middle,\n" +                    f << "   height=middle]\n" +                    if @commandline.option('nobanner') then +                        f << "\\setuplayout\n" +                        f << "  [footer=0cm]\n" +                    end +                    f << "\\setupexternalfigures\n" +                    f << "  [directory=]\n" +                    f << "\\starttext\n" +                    files.each do |filename| +                        result = @commandline.checkedoption('result','texexec') +                        if (filename !~ /^texexec/io) && (filename !~ /^#{result}/) then +                            report("combination file: #{filename}") +                            cleanname = cleantexfilename(filename).downcase +                            f << "\\setupfootertexts\n" +                            f << "  [\\tttf #{cleanname}\\quad\\quad\\currentdate\\quad\\quad\\pagenumber]\n" +                            f << "\\combinepages[#{filename}][nx=#{nx},ny=#{ny}]\n" +                            f << "\\page\n" +                        end +                    end +                    f << "\\stoptext\n" +                    f.close +                    job.setvariable('interface','english') +                    job.setvariable('simplerun',true) +                    # job.setvariable('nooptionfile',true) +                    job.setvariable('files',[job.tempfilename]) +                    job.processtex +                else +                    report('no files to list') +                end +            else +                report('no files to list') +            end +            job.cleanuptemprunfiles +        end +    end + +    private + +    def prepare(job) + +        job.booleanvars.each do |k| +            job.setvariable(k,@commandline.option(k)) +        end +        job.stringvars.each do |k| +            job.setvariable(k,@commandline.option(k)) +        end +        job.standardvars.each do |k| +            job.setvariable(k,@commandline.option(k)) +        end +        job.knownvars.each do |k| +            job.setvariable(k,@commandline.option(k)) unless @commandline.option(k).empty? +        end + +        if (str = @commandline.option('engine')) && ! str.standard? && ! str.empty? then +            job.setvariable('texengine',str) +        elsif @commandline.oneof('pdfetex','pdftex','pdf') then +            job.setvariable('texengine','pdfetex') +        elsif @commandline.oneof('xetex','xtx') then +            job.setvariable('texengine','xetex') +        elsif @commandline.oneof('aleph') then +            job.setvariable('texengine','aleph') +        else +            job.setvariable('texengine','standard') +        end + +        if (str = @commandline.option('backend')) && ! str.standard? && ! str.empty? then +            job.setvariable('backend',str) +        elsif @commandline.oneof('pdfetex','pdftex','pdf') then +            job.setvariable('backend','pdftex') +        elsif @commandline.oneof('dvipdfmx','dvipdfm','dpx','dpm') then +            job.setvariable('backend','dvipdfmx') +        elsif @commandline.oneof('xetex','xtx') then +            job.setvariable('backend','dvipdfmx') +        elsif @commandline.oneof('aleph') then +            job.setvariable('backend','dvipdfmx') +        elsif @commandline.oneof('dvips','ps') then +            job.setvariable('backend','dvips') +        else +            case job.getvariable('texengine') +                when 'pdfetex' then job.setvariable('backend','pdftex') +                when 'xetex'   then job.setvariable('backend','dvipdfmx') +                when 'aleph'   then job.setvariable('backend','dvipdfmx') +            else +                job.setvariable('backend','standard') +            end +        end + +        if (str = @commandline.option('engine')) && ! str.standard? && ! str.empty? then +            job.setvariable('mpsengine',@commandline.option('engine')) +        else +            job.setvariable('mpsengine','standard') +        end + +    end + +    def cleantexfilename(filename) +        filename.gsub(/([\$\_\#])/) do "\\$1" end.gsub(/([\~])/) do "\\string$1" end +    end + +end + +# we will make this pluggable, i.e. load plugins from base/tex that +# extend the class and may even add switches +# +# commandline.load_plugins('base/tex') +# +# maybe it's too slow so for a while keep the --pdf* in here + +logger      = Logger.new(banner.shift) +commandline = CommandLine.new + +commandline.registeraction('make',    'make formats') +commandline.registeraction('check',   'check versions') +commandline.registeraction('process', 'process file') +commandline.registeraction('mptex',   'process mp file') +commandline.registeraction('mpxtex',  'process mpx file') + +commandline.registeraction('listing',    'list of file content') +commandline.registeraction('figures',    'generate overview of figures') +commandline.registeraction('modules',    'generate module documentation') +commandline.registeraction('pdfarrange', 'impose pages (booklets)') +commandline.registeraction('pdfselect',  'select pages from file(s)') +commandline.registeraction('pdfcopy',    'copy pages from file(s)') +commandline.registeraction('pdftrim',    'trim pages from file(s)') +commandline.registeraction('pdfcombine', 'combine multiple pages') + +# compatibility switch + +class Commands + +    include CommandBase + +    alias pdfarrange :arrangeoutput +    alias pdfselect  :selectoutput +    alias pdfcopy    :copyoutput +    alias pdftrim    :trimoutput +    alias pdfcombine :combineoutput + +end + +# so far for compatibility + +@@extrastringvars = [ +    'pages', 'background', 'backspace', 'topspace', 'boxtype', 'tempdir', +    'printformat', 'paperformat', 'method', 'scale', 'selection', +    'combination', 'paperoffset', 'textwidth', 'addempty', 'logfile', +    'startline', 'endline', 'startcolumn', 'endcolumn', 'scale' +] + +@@extrabooleanvars = [ +    'centerpage', 'noduplex', 'color', 'pretty', +    'fullscreen', 'screensaver', 'markings' +] + +if job = TEX.new(logger) then + +    job.setextrastringvars(@@extrastringvars) +    job.setextrabooleanvars(@@extrabooleanvars) + +    job.booleanvars.each do |k| +        commandline.registerflag(k) +    end +    job.stringvars.each do |k| +        commandline.registervalue(k,'') +    end +    job.standardvars.each do |k| +        commandline.registervalue(k,'standard') +    end +    job.knownvars.each do |k| +        commandline.registervalue(k,'') +    end + +end + +# todo: register flags -> first one true + +commandline.registerflag('pdf') +commandline.registerflag('pdftex') +commandline.registerflag('pdfetex') + +commandline.registerflag('dvipdfmx') +commandline.registerflag('dvipdfm') +commandline.registerflag('dpx') +commandline.registerflag('dpm') + +commandline.registerflag('dvips') +commandline.registerflag('ps') + +commandline.registerflag('xetex') +commandline.registerflag('xtx') + +commandline.registerflag('aleph') + +commandline.registerflag('all') +commandline.registerflag('fast') + +# generic + +commandline.registeraction('help') +commandline.registeraction('version') + +commandline.registerflag('verbose') + +commandline.expand + +Commands.new(commandline,logger,banner).send(commandline.action || 'main') diff --git a/scripts/context/ruby/texmfstart.rb b/scripts/context/ruby/texmfstart.rb index 676b4351c..bae921098 100644 --- a/scripts/context/ruby/texmfstart.rb +++ b/scripts/context/ruby/texmfstart.rb @@ -2,7 +2,7 @@  # program   : texmfstart  # copyright : PRAGMA Advanced Document Engineering -# version   : 1.8.5 - 2003/2006 +# version   : 1.9.0 - 2003/2006  # author    : Hans Hagen  #  # project   : ConTeXt / eXaMpLe @@ -38,28 +38,36 @@ $ownpath = File.expand_path(File.dirname($0)) unless defined? $ownpath  # ../../texmf/scripts/context/ruby  $: << $ownpath +$: << File.expand_path("#{$ownpath}/../lib")  $: << File.expand_path("#{$ownpath}/texmfstart-lib")  $: << File.expand_path("#{$ownpath}/../../texmf-local/scripts/context/ruby")  $: << File.expand_path("#{$ownpath}/../../texmf/scripts/context/ruby")  require "rbconfig" -['base/kpseremote','base/kpsedirect'].each do |basemodule| +$kpsereport, $kpseerror, $kpsemodules = "", false, ['base/kpseremote','base/kpsedirect','base/kpsefast'] + +$kpsemodules.each do |basemodule|      begin          require basemodule      rescue Exception -        puts("unable to locate #{basemodule} on library paths:\n\n") -        puts($:.join("\n") + "\n") -        puts("an option is to copy\n\n") -        puts("  <texmf-local or texmf>/scripts/context/ruby/base\n\n") -        puts("to e.g.\n\n") -        puts("  <path of texmfstart script>/texmfstart-lib/base") +        $kpseerror = true      end  end +if $kpseerror then +    $kpsereport << "unable to locate #{$kpsemodules.join('|')} on library paths:\n\n" +    $kpsereport << "  " + $:.join("\n  ") + "\n\n" +    $kpsereport << "an option is to copy\n\n" +    $kpsereport << "  <texmf-local or texmf>/scripts/context/ruby/base/kpse*\n\n" +    $kpsereport << "(including the kpse subpath) to e.g.\n\n" +    $kpsereport << "  #{$ownpath}/../lib/texmfstart/\n\n" +    $kpsereport << "or to use a stub instead\n\n" +end +  $mswindows = Config::CONFIG['host_os'] =~ /mswin/  $separator = File::PATH_SEPARATOR -$version   = "1.8.5" +$version   = "1.8.6"  if $mswindows then      require "win32ole" @@ -82,9 +90,10 @@ $suffixinputs['lua'] = 'LUAINPUTS'  $suffixinputs['jar'] = 'JAVAINPUTS'  $suffixinputs['pdf'] = 'PDFINPUTS' -$predefined['texexec']  = 'texexec.pl' -$predefined['texutil']  = 'texutil.pl' +$predefined['texexec']  = 'texexec.rb' +$predefined['texutil']  = 'texutil.rb'  $predefined['texfont']  = 'texfont.pl' +$predefined['texshow']  = 'texshow.pl'  $predefined['makempy']  = 'makempy.pl'  $predefined['mptopdf']  = 'mptopdf.pl' @@ -103,8 +112,8 @@ $predefined['mpstools'] = 'mpstools.rb'  $predefined['exatools'] = 'exatools.rb'  $predefined['xmltools'] = 'xmltools.rb' -$predefined['newpstopdf']   = 'newpstopdf.rb' -$predefined['newtexexec']   = 'newtexexec.rb' +$predefined['newpstopdf']   = 'pstopdf.rb' +$predefined['newtexexec']   = 'texexec.rb'  $predefined['pdftrimwhite'] = 'pdftrimwhite.pl'  $makelist = [ @@ -124,13 +133,15 @@ $makelist = [      'mpstools',      'tmftools',      'exatools', -    'runtools' +    'runtools', +    # +    'texmfstart'  ] -if ENV['TEXMFSTART_MODE'] = 'experimental' then -    $predefined['texexec'] = 'newtexexec.rb' -    $predefined['pstopdf'] = 'newpstopdf.rb' -end +# if ENV['TEXMFSTART_MODE'] = 'experimental' then +    # $predefined['texexec'] = 'newtexexec.rb' +    # $predefined['pstopdf'] = 'newpstopdf.rb' +# end  $scriptlist   = 'rb|pl|py|lua|jar'  $documentlist = 'pdf|ps|eps|htm|html' @@ -164,17 +175,26 @@ $kpse = nil  def check_kpse      if $kpse then          # already done -    elsif KpseRemote::available? then -        $kpse = KpseRemote.new -        if $kpse.okay? then -            puts("using remote kpse") if $verbose -        else -            $kpse = KpseDirect.new -            puts("forcing direct kpse") if $verbose -        end      else -        $kpse = KpseDirect.new -        puts("using direct kpse") if $verbose +        begin +            if KpseRemote::available? then +                $kpse = KpseRemote.new +                if $kpse.okay? then +                    puts("using remote kpse") if $verbose +                else +                    $kpse = KpseDirect.new +                    puts("forcing direct kpse") if $verbose +                end +            else +                $kpse = KpseDirect.new +                puts("using direct kpse") if $verbose +            end +        rescue +            if $verbose then +                puts("using kpse binary") +                puts($kpsereport) unless $kpsereport.empty? +            end +        end      end  end @@ -235,30 +255,43 @@ end  class File +    # def File.needsupdate(oldname,newname) +        # begin +            # if $mswindows then +                # return File.stat(oldname).mtime > File.stat(newname).mtime +            # else +                # return File.stat(oldname).mtime != File.stat(newname).mtime +            # end +        # rescue +            # return true +        # end +    # end + +    @@update_eps = 1 +      def File.needsupdate(oldname,newname)          begin -            if $mswindows then -                return File.stat(oldname).mtime > File.stat(newname).mtime +            oldtime = File.stat(oldname).mtime.to_i +            newtime = File.stat(newname).mtime.to_i +            if newtime >= oldtime then +                return false +            elsif oldtime-newtime < @@update_eps then +                return false              else -                return File.stat(oldname).mtime != File.stat(newname).mtime +                return true              end          rescue              return true          end      end -    def File.timestamp(name) -        begin -            "#{File.stat(name).mtime}" -        rescue -            return 'unknown' -        end -    end -      def File.syncmtimes(oldname,newname) +        return          begin              if $mswindows then -                # does not work (yet) +                # does not work (yet) / gives future timestamp +                # t = File.mtime(oldname) # i'm not sure if the time is frozen, so we do it here +                # File.utime(0,t,oldname,newname)              else                  t = File.mtime(oldname) # i'm not sure if the time is frozen, so we do it here                  File.utime(0,t,oldname,newname) @@ -267,6 +300,14 @@ class File          end      end +    def File.timestamp(name) +        begin +            "#{File.stat(name).mtime}" +        rescue +            return 'unknown' +        end +    end +  end  def hashed (arr=[]) @@ -468,16 +509,17 @@ def usage      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") +    print("           texmfstart --program=yourtex yourscript.rb arg-1 arg-2\n")      print("           texmfstart --direct xsltproc kpse:somefile.xsl somefile.xml\n")      print("           texmfstart bin:xsltproc env:somepreset path:somefile.xsl somefile.xml\n")      print("           texmfstart --iftouched=normal,lowres downsample.rb normal lowres\n")      print("           texmfstart texmfstart bin:scite kpse:texmf.cnf\n")      print("           texmfstart --exec bin:scite *.tex\n")      print("           texmfstart --edit texmf.cnf\n") -    print("           texmfstart --stubpath=/usr/local/bin --make texexec\n") -    print("           texmfstart --stubpath=auto --make all\n")      print("           texmfstart --serve\n") +    print("\n") +    print("           texmfstart --stubpath=/usr/local/bin [--make --remove] --verbose all\n") +    print("           texmfstart --stubpath=auto [--make --remove] all\n")  end  # somehow registration does not work out (at least not under windows) @@ -742,7 +784,7 @@ def edit(filename)      end  end -def make(filename,windows=false,linux=false) +def make(filename,windows=false,linux=false,remove=false)      basename = filename.dup      basename.sub!(/\.[^.]+?$/, '')      basename.sub!(/^.*[\\\/]/, '') @@ -752,32 +794,61 @@ def make(filename,windows=false,linux=false)          basename = $stubpath + '/' + basename unless $stubpath.empty?      end      if basename == filename then -        report('nothing made') +        report("nothing made (#{filename})")      else          program = nil          if filename =~ /[\\\/]/ && filename =~ /\.(#{$scriptlist})$/ then              program = $applications[$1]          end          filename = "\"#{filename}\"" if filename =~ /\s/ -        program = 'texmfstart' if $indirect || ! program || program.empty? +        if filename == 'texmfstart' then +            program = 'ruby' +            command = 'kpsewhich --format=texmfscripts --progname=context texmfstart.rb' +            filename = `#{command}`.chomp +            if filename.empty? then +                report("failure: #{command}") +                return +            elsif not remove then +                if windows then +                    ['bat','exe'].each do |suffix| +                        if FileTest.file?("#{basename}.#{suffix}") then +                            report("windows stub '#{basename}.#{suffix}' skipped (already present)") +                            return +                        end +                    end +                elsif linux && FileTest.file?(basename) then +                    report("unix stub '#{basename}' skipped (already present)") +                    return +                end +            end +        else +            program = 'texmfstart' if $indirect || ! program || program.empty? +        end          begin -            if windows && f = open(basename+'.bat','w') then -                f.binmode -                f.write("@echo off\015\012") -                # f.write("#{program} #{filename} %*\015\012") -                f.write("#{program} %~n0 %*\015\012") -                f.close -                report("windows stub '#{basename}.bat' made") -            elsif linux && f = open(basename,'w') then -                f.binmode -                f.write("#!/bin/sh\012") -                f.write("#{program} #{filename} $@\012") -                # f.write("#{program} `basename $0` $@\012") -                f.close -                report("unix stub '#{basename}' made") +            callname = $predefined[filename.sub(/\.*?$/,'')] || filename +            if remove then +                if windows && (File.delete(basename+'.bat') rescue false) then +                    report("windows stub '#{basename}.bat' removed (calls #{callname})") +                elsif linux && (File.delete(basename) rescue false) then +                    report("unix stub '#{basename}' removed (calls #{callname})") +                end +            else +                if windows && f = open(basename+'.bat','w') then +                    f.binmode +                    f.write("@echo off\015\012") +                    f.write("#{program} #{callname} %*\015\012") +                    f.close +                    report("windows stub '#{basename}.bat' made (calls #{callname})") +                elsif linux && f = open(basename,'w') then +                    f.binmode +                    f.write("#!/bin/sh\012") +                    f.write("#{program} #{callname} $@\012") +                    f.close +                    report("unix stub '#{basename}' made (calls #{callname})") +                end              end          rescue -            report("failed to make stub '#{basename}'") +            report("failed to make stub '#{basename}' #{$!}")          else              return true          end @@ -936,8 +1007,9 @@ def execute(arguments)      $environment = $directives['environment'] || ''      $make        = $directives['make']        || false +    $remove      = $directives['remove']      || $directives['delete'] || false      $unix        = $directives['unix']        || false -    $windows     = $directives['windows']     || false +    $windows     = $directives['windows']     || $directives['mswin'] || false      $stubpath    = $directives['stubpath']    || ''      $indirect    = $directives['indirect']    || false @@ -979,7 +1051,7 @@ def execute(arguments)      if $serve then          if ENV['KPSEMETHOD'] && ENV['KPSEPORT'] then -            require 'base/kpseremote' +            # require 'base/kpseremote'              begin                  KpseRemote::start_server              rescue @@ -999,7 +1071,7 @@ def execute(arguments)          loadtree($tree)          loadenvironment($environment)          show_environment() -        if $make then +        if $make || $remove then              if $filename == 'all' then                  makelist = $makelist              else @@ -1007,11 +1079,11 @@ def execute(arguments)              end              makelist.each do |filename|                  if $windows then -                    make(filename,true,false) +                    make(filename,true,false,$remove)                  elsif $unix then -                    make(filename,false,true) +                    make(filename,false,true,$remove)                  else -                    make(filename,$mswindows,!$mswindows) +                    make(filename,$mswindows,!$mswindows,$remove)                  end              end          elsif $browser && $filename =~ /^http\:\/\// then diff --git a/scripts/context/ruby/texutil.rb b/scripts/context/ruby/texutil.rb new file mode 100644 index 000000000..da9a19205 --- /dev/null +++ b/scripts/context/ruby/texutil.rb @@ -0,0 +1,96 @@ +banner = ['TeXUtil  ', 'version 9.1.0', '1997-2005', 'PRAGMA ADE/POD'] + +unless defined? ownpath +    ownpath = $0.sub(/[\\\/][a-z0-9\-]*?\.rb/i,'') +    $: << ownpath +end + +require 'base/switch' +require 'base/logger' +require 'base/file' +require 'base/texutil' + +class Commands + +    include CommandBase + +    def references +        filename = @commandline.argument('first') +        if not filename.empty? and FileTest.file?(File.suffixed(filename,'tuo')) then +            if tu = TeXUtil::Converter.new(logger) and tu.loaded(filename) then +                tu.saved if tu.processed +            end +        end +    end + +    def main +        if @commandline.arguments.length>0 then +            references +        else +            help +        end +    end + +    def purgefiles +        system("texmfstart ctxtools --purge #{@commandline.arguments.join(' ')}") +    end + +    def purgeallfiles +        system("texmfstart ctxtools --purge --all #{@commandline.arguments.join(' ')}") +    end + +    def documentation +        system("texmfstart ctxtools --document #{@commandline.arguments.join(' ')}") +    end + +    def analyzefile +        system("texmfstart pdftools --analyze #{@commandline.arguments.join(' ')}") +    end + +    def filterpages # obsolete +        system("texmfstart ctxtools --purge #{@commandline.arguments.join(' ')}") +    end + +    def figures +        report("this code is not yet converted from perl to ruby") +    end + +    def logfile +        report("this code is not yet converted from perl to ruby") +    end + +end + +logger      = Logger.new(banner.shift) +commandline = CommandLine.new + +# main feature + +commandline.registeraction('references', 'convert tui file into tuo file') + +# todo features + +commandline.registeraction('figures', 'generate figure dimensions file') +commandline.registeraction('logfile', 'filter essential log messages') + +# backward compatibility features + +commandline.registeraction('purgefiles', 'remove most temporary files') +commandline.registeraction('purgeallfiles', 'remove all temporary files') +commandline.registeraction('documentation', 'generate documentation file from source') +commandline.registeraction('analyzefile', 'analyze pdf file') + +# old feature, not needed any longer due to extension of pdftex + +commandline.registeraction('filterpages') + +# generic features + +commandline.registeraction('help') +commandline.registeraction('version') + +commandline.registerflag('verbose') + +commandline.expand + +Commands.new(commandline,logger,banner).send(commandline.action || 'main') diff --git a/scripts/context/stubs/mswin/ctxtools.bat b/scripts/context/stubs/mswin/ctxtools.bat new file mode 100755 index 000000000..f1f5e019e --- /dev/null +++ b/scripts/context/stubs/mswin/ctxtools.bat @@ -0,0 +1,2 @@ +@echo off +texmfstart ctxtools.rb %* diff --git a/scripts/context/stubs/mswin/exatools.bat b/scripts/context/stubs/mswin/exatools.bat new file mode 100755 index 000000000..57f798e82 --- /dev/null +++ b/scripts/context/stubs/mswin/exatools.bat @@ -0,0 +1,2 @@ +@echo off +texmfstart exatools.rb %* diff --git a/scripts/context/stubs/mswin/makempy.bat b/scripts/context/stubs/mswin/makempy.bat new file mode 100755 index 000000000..e339058c6 --- /dev/null +++ b/scripts/context/stubs/mswin/makempy.bat @@ -0,0 +1,2 @@ +@echo off +texmfstart makempy.pl %* diff --git a/scripts/context/stubs/mswin/mpstools.bat b/scripts/context/stubs/mswin/mpstools.bat new file mode 100755 index 000000000..df1732e17 --- /dev/null +++ b/scripts/context/stubs/mswin/mpstools.bat @@ -0,0 +1,2 @@ +@echo off +texmfstart mpstools.rb %* diff --git a/scripts/context/stubs/mswin/mptopdf.bat b/scripts/context/stubs/mswin/mptopdf.bat new file mode 100755 index 000000000..242854337 --- /dev/null +++ b/scripts/context/stubs/mswin/mptopdf.bat @@ -0,0 +1,2 @@ +@echo off +texmfstart mptopdf.pl %* diff --git a/scripts/context/stubs/mswin/pdftools.bat b/scripts/context/stubs/mswin/pdftools.bat new file mode 100755 index 000000000..adc48eacf --- /dev/null +++ b/scripts/context/stubs/mswin/pdftools.bat @@ -0,0 +1,2 @@ +@echo off +texmfstart pdftools.rb %* diff --git a/scripts/context/stubs/mswin/pstopdf.bat b/scripts/context/stubs/mswin/pstopdf.bat new file mode 100755 index 000000000..248e34caf --- /dev/null +++ b/scripts/context/stubs/mswin/pstopdf.bat @@ -0,0 +1,2 @@ +@echo off +texmfstart pstopdf.rb %* diff --git a/scripts/context/stubs/mswin/runtools.bat b/scripts/context/stubs/mswin/runtools.bat new file mode 100755 index 000000000..68a7b4f97 --- /dev/null +++ b/scripts/context/stubs/mswin/runtools.bat @@ -0,0 +1,2 @@ +@echo off +texmfstart runtools.rb %* diff --git a/scripts/context/stubs/mswin/texexec.bat b/scripts/context/stubs/mswin/texexec.bat new file mode 100755 index 000000000..02b297b9c --- /dev/null +++ b/scripts/context/stubs/mswin/texexec.bat @@ -0,0 +1,2 @@ +@echo off +texmfstart texexec.rb %* diff --git a/scripts/context/stubs/mswin/texfont.bat b/scripts/context/stubs/mswin/texfont.bat new file mode 100755 index 000000000..3134bf14c --- /dev/null +++ b/scripts/context/stubs/mswin/texfont.bat @@ -0,0 +1,2 @@ +@echo off +texmfstart texfont.pl %* diff --git a/scripts/context/stubs/mswin/texmfstart.bat b/scripts/context/stubs/mswin/texmfstart.bat new file mode 100755 index 000000000..287f9c4fa --- /dev/null +++ b/scripts/context/stubs/mswin/texmfstart.bat @@ -0,0 +1,2 @@ +@echo off +ruby c:\data\develop\context/ruby/texmfstart.rb %* diff --git a/scripts/context/stubs/mswin/textools.bat b/scripts/context/stubs/mswin/textools.bat new file mode 100755 index 000000000..727b4a36d --- /dev/null +++ b/scripts/context/stubs/mswin/textools.bat @@ -0,0 +1,2 @@ +@echo off +texmfstart textools.rb %* diff --git a/scripts/context/stubs/mswin/texutil.bat b/scripts/context/stubs/mswin/texutil.bat new file mode 100755 index 000000000..1e63639bb --- /dev/null +++ b/scripts/context/stubs/mswin/texutil.bat @@ -0,0 +1,2 @@ +@echo off +texmfstart texutil.rb %* diff --git a/scripts/context/stubs/mswin/tmftools.bat b/scripts/context/stubs/mswin/tmftools.bat new file mode 100755 index 000000000..c9c0c08bd --- /dev/null +++ b/scripts/context/stubs/mswin/tmftools.bat @@ -0,0 +1,2 @@ +@echo off +texmfstart tmftools.rb %* diff --git a/scripts/context/stubs/mswin/xmltools.bat b/scripts/context/stubs/mswin/xmltools.bat new file mode 100755 index 000000000..2de0e4457 --- /dev/null +++ b/scripts/context/stubs/mswin/xmltools.bat @@ -0,0 +1,2 @@ +@echo off +texmfstart xmltools.rb %* diff --git a/scripts/context/stubs/unix/ctxtools.bat b/scripts/context/stubs/unix/ctxtools.bat new file mode 100755 index 000000000..f1f5e019e --- /dev/null +++ b/scripts/context/stubs/unix/ctxtools.bat @@ -0,0 +1,2 @@ +@echo off +texmfstart ctxtools.rb %* diff --git a/scripts/context/stubs/unix/exatools.bat b/scripts/context/stubs/unix/exatools.bat new file mode 100755 index 000000000..57f798e82 --- /dev/null +++ b/scripts/context/stubs/unix/exatools.bat @@ -0,0 +1,2 @@ +@echo off +texmfstart exatools.rb %* diff --git a/scripts/context/stubs/unix/makempy.bat b/scripts/context/stubs/unix/makempy.bat new file mode 100755 index 000000000..e339058c6 --- /dev/null +++ b/scripts/context/stubs/unix/makempy.bat @@ -0,0 +1,2 @@ +@echo off +texmfstart makempy.pl %* diff --git a/scripts/context/stubs/unix/mpstools.bat b/scripts/context/stubs/unix/mpstools.bat new file mode 100755 index 000000000..df1732e17 --- /dev/null +++ b/scripts/context/stubs/unix/mpstools.bat @@ -0,0 +1,2 @@ +@echo off +texmfstart mpstools.rb %* diff --git a/scripts/context/stubs/unix/mptopdf.bat b/scripts/context/stubs/unix/mptopdf.bat new file mode 100755 index 000000000..242854337 --- /dev/null +++ b/scripts/context/stubs/unix/mptopdf.bat @@ -0,0 +1,2 @@ +@echo off +texmfstart mptopdf.pl %* diff --git a/scripts/context/stubs/unix/pdftools.bat b/scripts/context/stubs/unix/pdftools.bat new file mode 100755 index 000000000..adc48eacf --- /dev/null +++ b/scripts/context/stubs/unix/pdftools.bat @@ -0,0 +1,2 @@ +@echo off +texmfstart pdftools.rb %* diff --git a/scripts/context/stubs/unix/pstopdf.bat b/scripts/context/stubs/unix/pstopdf.bat new file mode 100755 index 000000000..248e34caf --- /dev/null +++ b/scripts/context/stubs/unix/pstopdf.bat @@ -0,0 +1,2 @@ +@echo off +texmfstart pstopdf.rb %* diff --git a/scripts/context/stubs/unix/runtools.bat b/scripts/context/stubs/unix/runtools.bat new file mode 100755 index 000000000..68a7b4f97 --- /dev/null +++ b/scripts/context/stubs/unix/runtools.bat @@ -0,0 +1,2 @@ +@echo off +texmfstart runtools.rb %* diff --git a/scripts/context/stubs/unix/texexec.bat b/scripts/context/stubs/unix/texexec.bat new file mode 100755 index 000000000..02b297b9c --- /dev/null +++ b/scripts/context/stubs/unix/texexec.bat @@ -0,0 +1,2 @@ +@echo off +texmfstart texexec.rb %* diff --git a/scripts/context/stubs/unix/texfont.bat b/scripts/context/stubs/unix/texfont.bat new file mode 100755 index 000000000..3134bf14c --- /dev/null +++ b/scripts/context/stubs/unix/texfont.bat @@ -0,0 +1,2 @@ +@echo off +texmfstart texfont.pl %* diff --git a/scripts/context/stubs/unix/texmfstart.bat b/scripts/context/stubs/unix/texmfstart.bat new file mode 100755 index 000000000..287f9c4fa --- /dev/null +++ b/scripts/context/stubs/unix/texmfstart.bat @@ -0,0 +1,2 @@ +@echo off +ruby c:\data\develop\context/ruby/texmfstart.rb %* diff --git a/scripts/context/stubs/unix/textools.bat b/scripts/context/stubs/unix/textools.bat new file mode 100755 index 000000000..727b4a36d --- /dev/null +++ b/scripts/context/stubs/unix/textools.bat @@ -0,0 +1,2 @@ +@echo off +texmfstart textools.rb %* diff --git a/scripts/context/stubs/unix/texutil.bat b/scripts/context/stubs/unix/texutil.bat new file mode 100755 index 000000000..1e63639bb --- /dev/null +++ b/scripts/context/stubs/unix/texutil.bat @@ -0,0 +1,2 @@ +@echo off +texmfstart texutil.rb %* diff --git a/scripts/context/stubs/unix/tmftools.bat b/scripts/context/stubs/unix/tmftools.bat new file mode 100755 index 000000000..c9c0c08bd --- /dev/null +++ b/scripts/context/stubs/unix/tmftools.bat @@ -0,0 +1,2 @@ +@echo off +texmfstart tmftools.rb %* diff --git a/scripts/context/stubs/unix/xmltools.bat b/scripts/context/stubs/unix/xmltools.bat new file mode 100755 index 000000000..2de0e4457 --- /dev/null +++ b/scripts/context/stubs/unix/xmltools.bat @@ -0,0 +1,2 @@ +@echo off +texmfstart xmltools.rb %* | 
