#!/usr/bin/env ruby <<'RDOC' === mk - a LaTeX maker === Synopsis mk - a LaTeX maker Usage: mk [options] [file] mk-specific options: -C, --Clean Remove all unnecessary files generated by latex and bibtex -c, --clean Same, except for the pdf or postscript files --ps Generate postscript version of document (default: pdf) --edit=STRING use STRING as the file to be edited -w, --[no-]warn After a successful run, print warnings found in the log file vpp-related options: -b, --batch=STRING run in batch using STRING for print command -p, --printer=STRING print to printer named STRING -d, --doublesided printer is double sided --[no-]view do [not] view the document --[no-]print do [not] offer printing interaction General options: -r, --rc=STRING use STRING as an rc file -V, --version print version and exit -v, --[no-]verbose be [not] verbose (quiet is the default) --[no-]check do [not] check the availability of executables -h, --help print this help and exit Defaults: --no-warn --print --view --no-verbose --no-check main Required gems (gem install -r): rubygems term-ansicolor Required other programs: CTAN: latex pdflatex vpp texi2dvi scriptingutils.rb === Copyright Copyright (C) 2009 Wybo Dekker (wybo@dekkerdocumenten.nl) This program is free software: you can redistribute it and/or modify it under the terms of the {GNU General Public License}[http://www.gnu.org/licenses/] as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but without any warranty; without even the implied warranty of merchantability or fitness for a particular purpose. See the {GNU General Public License}[http://www.gnu.org/licenses/] for more details. === Introduction _mk_ is a Ruby script that, in close collaboration with _vpp_, is helpful in the cyclic process of editing, viewing, and printing a _latex_ document. Having an existing _latex_ document, say main.tex (see the section 'Locating the source' for the creation of new documents and for other extensions than .tex), you run _mk_ by typing: mk main or, since main happens to be _mk_'s default filename: mk Now, if main.tex is a valid _latex_ source, _mk_ compiles it, including any table of contents, indices, bibliography references, included files, and so on and _vpp_ takes over and displays the resulting _PDF_ or, with the --ps option, _PostScript_ output. When you leave the viewer you will see a prompt: vpp command (h for help): If you are satisfied with the displayed output, you can now decide to print all or part of your document (see the section 'Page selection'), or you can simply quit by typing 'q'. On the other hand, if you decide that you want to change the source and have another try, you can edit the source by typing 'e' to get back to _mk_ and (re)edit your source. After saving your work and leaving your editor, another compilation and display cycle will be performed, based on the new source. Essentially, _mk_ uses texi2dvi for compilation. texi2dvi always runs TeX at least once, even though this may be unnecessary. Therefore, TeX will be run with the --recorder option, which reports all the target's dependencies in a .fls file. In every cycle, _mk_ analyses the .fls and the tex and bibtex log files to see if a compilation is needed. When errors have occurred, _mk_ uses the log files to find out which file has to be edited, and at which line. This can also be an \input-ed file, a style file, or any other file on which the target depend. However, files in the TEXMFMAIN tree are excluded. === Page selection As said in the introduction, after a successful compilation and display of the resulting _PDF_ or _PostScript_ output, the user is prompted with: vpp command (h for help): on typing 'h' _vpp_ displays examples of possible commands: Examples of print commands: 5 to print page 5 5- to print pages 5 through the end 5-7 to print pages 5, 6 and 7 -7 to print the first 7 pages 5-7,19- to print pages 5, 6, 7 and 19 through the end a to print the whole document - to print the whole document a x3 to print 3 copies of the document x3 the same 5 x3 to print 3 copies of page 5 t print the whole document two sided t 2- print two sided starting at page 2 b to print the whole document as an a5 size booklet b -12 to print the first 12 pages as an a5 size booklet Other commands: e (if called by mk) edit the tex source and rerun mk c (if called by mk) rerun mk v (re)view the ps/pdf file oxyz send pdf output to file xyz.pdf instead of printer pxyz print to printer xyz dx tell vpp printer is doublesided (x=t) or singlesided (x=f) h display this help ? display this help q quit With these examples, no further explanation should be necessary, except that, when twosided ('t') or booklet ('b') printing is selected for a single-sided printer, printing will be performed in two shifts, one for the front side and one for the backside. Between the shifts, another prompt appears: printer ready? then turn stack and type return You will have to arrange your printer such that, with the printed sides up, the first page printed will be at the bottom of the stack, and the last page printed will be on top. Normally you will then have your output come out the back of your printer. 'Turn the stack' then means: rotate it over the long side of the paper and feed it back into the printer for the other side to be printed. For further information on _vpp_, look in its manpage by typing vpp -h or read the _vpp_ documentation. === Locating the source _mk_ locates the _latex_ source in several steps: (here the source extension .tex is supposed, but .ltx, .drv and .dtx will also be tried) 1. If you supply no arguments, the file main.tex in the current directory is assumed. 2. If you supply an argument (say myfile), _mk_ adds a .tex extension if it isn't there and looks for myfile.tex in the current directory. 3. If myfile.tex is not found in the current directory, _mk_ looks in the 'alternate directory' (say /Documents) if you have defined one (see the section 'RC files'). 4. If the source was not found in /Documents, _mk_ thinks that you may have a subdirectory myfile in /Documents where the source may live under the name main.tex 5. If that file is not there, _mk_ now concludes that the source does not yet exist and reports this, telling at the same time which files have been tried. 6. Finally, if all the above did not lead to a source file, _mk_ dies. === The TeX format to be used _mk_ will try to find out what TeX format is is needed to compile the source. The most straightforward way to tell _mk_ what format to use is to insert a comment line with one of the following (case-insensitive) strings on a single line: %!pdflatex:: forces _pdflatex_ or, with the --ps option, _latex_ %!latex:: forces _latex_ (and sets the --ps option) %!xelatex:: forces _xelatex_ %!xetex:: forces _xetex_ If none of these is found, _mk_ looks for a \usepackage{fontspec} or \RequirePackage{fontspec} and, if found, uses _xelatex_. The \usepackage may have options, but they must be on one line. If still no decision could be made, _mk_ looks for \documentclass and chooses _pdflatex_ or, with the --ps option, _latex_ Finally, if no match was found, _pdftex_ is assumed or, with the --ps option, _tex_. === Options _mk_ comes with several options. Before evaluating any options, _mk_ will try to read a system rc file, a user rc file, and, finally an rc file in the current directory. The default values for most options can be set in these files. See the section 'RC files' for more information. You can also set option defaults in an alias. For example: alias mk='mk -no-verbose' [--help] Prints help information and lets you type 'm' to display the complete man page or anything else to quit. [--version] Prints name and (CVS-)version and then quits. [--quiet] Suppresses messages about the progress _mk_ is making. This is the default. [--rc=file] execute the specified file before processing. The contents of the file may override options specified before the --rc option, therefore it is a good idea to have the habit of specifying the --rc option first. [--batch=string] Prevents the --print option to interrogate the user about pages to be printed. Instead the document is printed according to the mandatory string. Also sets viewing off. Thus the command mk --batch '2-3 x3' test prints 3 copies of pages 2 and 3 of test.tex, without viewing. [--clean] Clean up (remove) all unnecessary files generated by _latex_ and _bibtex_ except for the _PDF_ or _PostScript_ files. [--Clean] Clean up (remove) all unnecessary files generated by _latex_ and _bibtex_ including the _PDF_ or _PostScript_ files. [--print] Present the print prompt. This is the default. This option is normally used to suppress the print prompt, for example when using _mk_ from other scripts that generate _latex_ documents that have only to be displayed or stored without even being displayed. [--ps] Generate _PostScript_ version of document. The default is to generate a _PDF_ document. [--view] Run the file viewer. This is the default. This option is normally used to suppress starting the viewer, for example when using _mk_ from other scripts that generate _latex_ documents that have only to be printed. [--edit=file] Normally, _mk_ lets you edit the main source file, but here you can specify another file to be edited instead. This is useful, for example, if you are are fixing a style file or another input file. [--warn] After a successful run, scan the log file for warnings and repeat those. The array @warnings_to_skip, which can be set in the rc files (see below) can be filled with regexp's that match warnings you don't want to see. === RC files and customization Unless the environment variable NORC has been set, three rc files are executed, if they exist, before reading the command line options, in the following order: /etc/mkrc:: the system rc file $HOME/.mkrc:: the user rc file ./.mkrc:: the local rc file You can use these rc files to set the default values for the options, by setting the global Ruby variable named after the long version of the options. For example: @verbose = true # run in verbose mode So if you usually like _mk_ to work in verbose mode, you can indicate so in your rc file and change your mind in some cases by using the --no-verbose option. Other variables, not having a corresponding command line option, that can be set in the rc files, and their default values, are: @skip_pattern='':: can be set to a file wild card pattern. Files matching this pattern on which the (La)TeX source file may depend will not be checked for changes. For example, if you use a write-protected TeX-tree in the directory mytextree it makes sense to set @skip_pattern='^\/mytextree'; unless you set @skip_pattern explicitly, it will be set to match the TEXMFMAIN tree. @altdir='':: If @altdir is non-empty and a file to be compiled does not exist in the current directory, it will be given another try after prefixing it with the contents of @altdir. So if you like to have your _latex_ file in /Documents/myfile.tex you can set @altdir to /Documents and run _mk_ from any directory with: mk myfile However, a directory like /Documents does not make much sense if many of your _latex_ documents do not consist of a single file, but are constituted of an ensemble of a main _latex_ source and one or more \included and \inputed files such as graphics. You will then probably prefer to have s subdirectory in /Documents for every _latex_ document. Therefore, if _mk_ does not find myfile.tex in the alternate directory, it will assume that myfile is a subdirectory with a main _latex_ source in it, called main.tex. @default='main':: This is the default for the base name of your _latex_ document. @warning_to_skip=[]:: When the --warn option is used, warnings appearing in the log file will be reported after a successful run. Warnings matching any of the rexgexp's in this array will be skipped, however. For example, one could enter here: @warnings_to_skip=[ 'Package hyperref Warning: Token not allowed in a PDFDocEncoded string', 'Package array Warning: Column [XY] is already defined on ' ] The first message appears when the _hyperref_ package is used and section titles contain \LaTeX-commands, the second message appears when the _ctable_ package is used, because it intentionally changes the X and Y column specifiers. === TeXWorks and mk _mk_ can can be used for one-click typesetting: edit -> preferences -> Typesetting add a new tool `mk' and give it three parameters: --noview --noprint $basename Deselect "Auto-hide output panel unless errors occur" _mk_ runs pdflatex with the --synctex=1 option, so you will be able to jump betwee source and pdf-ouput. === Bugs Currently, _mk_ is only available for _unix_. RDOC begin require 'scriptingutils' rescue LoadError raise LoadError,< targetmtime rm(basename+'.bbl') puts("newer than target: #{f}") if @verbose go = true break end end unless go tex_dep(basename).each do |f| if ! File.exist?(f) || File.mtime(f) > targetmtime puts("newer than target: #{f}") if @verbose go = true break end end end else go = true end break unless go sys(@texcommand,true).success || show_error_and_edit(basename,target) done = true end return done end def show_error_and_edit(basename,target) rm(target) if File.exist?(target) && ! @edit.empty? errorfile,linenum,message = texlog_extract(basename + '.log',@warnings_to_skip) message.sort.reverse.each do |f, messages| unless messages == [""] messages.unshift("Messages for file #{f}:".fil) unless f.empty? puts messages.join(@sep) end end quit(nil,0) if @edit.empty? errorfile ||= @edit; errorfile.sub!(/\{.*/,'') # file may have been reported # with {dependencyfiles} attached errorfile.sub!(/ +$/,'') if errorfile =~ /\.bbl$/ rm(errorfile) edit(bib_dep(basename)[0],1,true) else edit(errorfile,linenum,true) and quit end end def edit(file,linenum,err) if err puts "error in #{file}" puts "(Look in your bibliography file(s))}" if file =~ /\.bbl$/ return true unless STDOUT.isatty x = nil while ( x = readline("\n=====> e(dit) q(uit) ") ) !~ /^(q|e)$/ puts "you must type e or q" end return true if x == 'q' end linenum ||= 1 edfile = file.empty? ? @edit : file File.exist?(edfile.chomp) or quit("Could not edit #{edfile}; vanished?") sys("#{EDITOR} +#{linenum} #{edfile}",true) return false end # test presence and version of texi2dvi def testtexi2dvi m=<<-EOF Checkout the latest version with: cvs -d:pserver:anonymous@cvs.sv.gnu.org:/sources/texinfo co -p texinfo/util/texi2dvi >texi2dvi chmod texi2dvi Then move texi2dvi in your PATH so that it will be used EOF if !executable('texi2dvi') quit([" You need at least v1.152",m]) else v = `texi2dvi -v 2>&1`.split("\n")[0].split(/[\s.]/)[-2..-1].map{ |x| x.to_i } v[0]*10000+v[1] > 10152 or quit(["Your texi2dvi is too old (#{v[0]}.#{v[1]}), at least v1.152 is needed.".err,m]) end end RELEASE = "2.4" HOME = ENV['HOME'] || '.' @altdir = '.' @batch = nil @check = true @Clean = false @clean = false @default = 'main' @edit = nil @latex = nil @pdflatex = nil @print = true @ps = false @rc = nil @sep = "\n" @skip_pattern = nil @verbose = false @view = true @warn = false @warnings_to_skip = [] EDITEXIT = 99 COMPILEEXIT = 98 CLEANEXT = %w(tui tuo chk dvi log ent fls aux bbl blg hd ilg toc lof lot idx ind out glo gls tmp synctex.gz) init(:needs,:handle_options) e = ENV['EDITOR'] if !e || e.empty? puts "Environment variable EDITOR not set - using vi".war e = 'vi' end EDITOR = e testtexi2dvi @skip_pattern ||= "^#{`kpsewhich --expand-var '$TEXMFMAIN'`.strip}" @skip_pattern = Regexp.new(@skip_pattern) vppoptions = @verbose ? "--verbose" : "--no-verbose" vppoptions << ' --doublesided' if @doublesided vppoptions << " --printer=#{@printer}" if @printer if @batch # @batch must contain valid printing commands: @batch.split.each do |e| unless e =~ / ^(q| # n-m or n- or - b| # print a5 booklet t| # print twosided a| # print all x[0-9]+| # x3 -> lpr -#3 (([0-9]+-?[0-9]*|[0-9]*-?[0-9]+),?)+ )$| ^o # output to pdf /x then quit("Illegal argument for --batch option: #{@batch}\n" + "Use q if you want no printout") end end vppoptions += " --batch='#{@batch}'" end @view = false if @batch @clean ||= @Clean @print = false if @batch =~ /q$/ targetext = @ps ? 'dvi' : 'pdf' vpptargetext = @ps ? 'ps' : 'pdf' vppoptions += @print ? " --print" : " --no-print" vppoptions += @view ? " --view" : " --no-view" dirname,basename,ext,fullpath = findsource target = "#{basename}.#{targetext}" vpptarget = "#{basename}.#{vpptargetext}" basename or exit 1 at_exit { rm_rf("#{basename}.t2d") } @edit ||= fullpath unless @edit.empty? # if '', then no editing File.exist?(@edit) or quit("can't find file to be edited (#{@edit})") File.readable?(@edit) or quit("can't read file to be edited (#{@edit})") File.writable?(@edit) or quit("can't write file to be edited (#{@edit})") end Dir.chdir(dirname) # find out the tex format to use: @format = @ps ? 'tex' : 'pdftex' open(basename+ext) do |f| f.each do |l| l.sub!(/%[^!].*/,'') case l when /^%+!pdflatex/i @format = 'pdflatex' break when /^%+!latex/i @format = 'latex' @ps = true break when /^%+!xetex/i @format = 'xetex' break when /^%+!xelatex/i @format = 'xelatex' break when /\\(RequirePackage|usepackage)(\s*\[.*\])?\{(fontspec|polyglossia)\}/ @format = 'xelatex' break when /\\documentclass/ @format = @ps ? 'latex' : 'pdflatex' break end end if @format =~ /(pdf|xe)/ && @ps quit("You can not use the --ps option on a #{@format} source!") end end @texcommand = '' @texcommand << " LATEX='#{@format} -halt-on-error -recorder -synctex=1 " @texcommand << @extraoptions if @extraoptions @texcommand << "' texi2dvi --no-line-error #{@verbose ? '' : '--quiet'} #{basename+ext}" if @clean rm_rf(CLEANEXT.map{ |x| basename+'.'+x }<<'t2d') if @Clean # It may be useful to protect target, in order to prevent that they become # recompiled with changed style files: [target,vpptarget].uniq.each do |t| if File.exist?(t) if File.writable?(t) rm(t) else quit("#{t} is write-protected, so I'll keep it!") end end end end quit end loop do if File.exist?(target) && !File.writable?(target) puts "Target #{target} is write-protected, so I'll not re-compile it!" sleep 1 elsif target =~ /\s/ quit("mk does not (yet) handle filenames with spaces!") else done = compile(basename,target) if File.exist?(target) && File.size?(target) sys("dvips #{@verbose ? '-q' : ''} #{basename}") if targetext == 'dvi' elsif ! File.size?(target) puts "After compilation, an empty #{target} was found" done = false else puts "After compilation, no file #{target} was found" if targetext == 'pdf' puts "One possible cause is that your file pdftex.cfg" puts "contains 'output_format 0' instead of 'output_format 1'" end puts "Quitting..." quit end if done rerun = false # A glossary file, if it exists, is always rewritten in a compilation: if File.exist?(basename+'.glo') sys("makeindex -q -s gglo.ist -o #{basename}.gls #{basename}.glo") rerun = true end if File.exist?(basename+'.idx') # don't know how to find out if a non-standard index style is used, # so just check for a dtx extension and then suppose gind style if ext == '.dtx' sys("makeindex -q -s gind.ist -o #{basename}.ind #{basename}.idx") else sys("makeindex -q #{basename}") end rerun = true end if rerun sys(@texcommand,true).success || show_error_and_edit(basename,target) #sys("#{@ps ? '' : 'pdf'}latex -quiet -interaction=batchmode -recorder --synctex=1 #{basename+ext}") if rerun end end end if @view || @print h = sys("vpp #{vppoptions} #{vpptarget}",true) case h.status when EDITEXIT ready = edit(@edit,1,false) next unless ready when COMPILEEXIT rm(target) next when 0 break else ready = edit(@edit,1,true) next unless ready end end break end @edit = '' show_error_and_edit(basename,target) if @warn # $Id: mk,v 1.97 2012/02/11 11:41:43 wybo Exp $