Debian Codegraph @

texmf-dist/doc/latex/ucs/unsupported/u2ps

raw
1 #!/usr/bin/perl
2
3 use strict;
4
5 use Getopt::Long;
6
7 use vars qw/$infile $outfile $code $tmpfile $fontencs $commands $r2lmode
8 $combine $charset $tolerant $default_fontencs $default_charset
9 $default_r2lmode $tolerant $tolerant_unknownchar @options @packages
10 $title $cleanup $view $escape $print $perhapsnofile
11 $fribidi_cmd
12 /;
13
14 $tmpfile = "u2ps-tmp";
15 $default_fontencs = 'local,X2,LGR,T1';
16 $default_charset = 'utf-8';
17 $default_r2lmode = 'mark';
18 $fribidi_cmd = "fribidi";
19
20
21 sub define($) {
22 my $str = shift;
23 return $str if defined $str;
24 return '';
25 }
26
27 sub showhelp($) {
28 my $topic = shift;
29 $topic =~ s/^--//;
30 if ($topic eq '') {
31 print
32 'Converts an UTF-8 plain text to postscript using LaTeX and the ucs package.
33 Usage: u2ps [options] [input file] [output file]
34 Available options:
35
36 --charset Select input character set
37 --combine Enables combining characters
38 --commands Specify additional LaTeX-code to execute
39 --escape Allow inline LaTeX code
40 --fontencs Specify fontencodings to use
41 --fontsize Specify font size
42 --fontstyle Specify font style
43 --options Unicode options
44 --package Load package
45 --print Print file
46 --r2l Enables right-to-left code
47 --tolerant Accept files with broken input encoding
48 --title Set document title
49 --view View file using gv
50 --help This page, --help=<option> gives detailed help.
51
52 Defaults for input and output file are stdin resp. stdout.
53 ';
54 } elsif ($topic eq 'escape') {
55 print 'Option --escape
56
57 Allow execution of inline LaTeX code. The code must be of the form
58 ^[{<code>}
59 where ^[ is U+001B (ESC) and <code> a piece of LaTeX code, properly
60 nested with respect to braces.
61
62 Example: a ^[{\bgroup\Huge}Huge^[{\egroup} word
63 ';
64 } elsif ($topic eq 'print') {
65 print 'Option --print[=<printer>]
66
67 Print output (using lpr). If no output file is explicitly given, do not
68 create an output file.
69
70 If a printer is given, print with lpr -P<printer>.
71 ';
72 } elsif ($topic eq 'view') {
73 print 'Option --view
74
75 View output (using gv). If no output file is explicitly given, do not
76 create an output file.
77 ';
78 } elsif ($topic eq 'options') {
79 print 'Option --options=<option>:
80
81 These are the Unicode options to be activated. They are passed as
82 options to the package ucs.
83
84 You can specify a priority by saying e.g. cjkjis=123. Options without
85 specified priority get one less than the preceding option, the first
86 getting 99 (one less than the priority for the option \'document\').
87 ';
88 } elsif ($topic eq 'package') {
89 print "Option --package <string>:
90
91 Specifies a package to load. The following syntaxes for <string> are
92 allowed:
93
94 packagename
95 {packagename}
96 [options]{packagename}
97
98 This option can be given several times to load different packages.
99 ";
100 } elsif ($topic eq 'title') {
101 print "Option --title <string> (default: name of input file):
102
103 Specifies a title for the document. It is stored in the structured
104 comments of the resulting postscript file.
105
106 In future, the title may be also used in other contexts like headings
107 etc.
108 ";
109 } elsif ($topic eq 'fontencs') {
110 print "Option --fontencs <string> (default: $default_fontencs):".'
111
112 The keywords given to this option are directly passed to the package autofe.
113
114 This package takes the same options as fontenc, i.e. you have to give a list
115 of all needed fontencodings, whereby the last should be the fontencoding
116 used mainly in the document.
117
118 If some ASCII characters are rendered incorrectly, try using a font
119 encoding beginning with T (e.g. T1, T2A, ...) as the last
120 fontencodingand perhaps additionally the option \'local\'.
121
122 You may give the fontencodings as a comma-separated list or by
123 multiple calls of --fontencs.
124
125 Some usefull fontencodings are:
126 T1 Most latin scripts
127 T2A Cyrillic scripts like russian
128 T2B Other cyrillic scripts
129 T2C Other cyrillic scripts
130 T3 IPA
131 T5 Vietnamese
132
133 The following fontencodings should be combined with local and T1
134 (e.g. local,X2,T1):
135
136 LGR Greek
137 LHE Hebrew
138 TS1 Some symbols
139 X2 All supported cyrillic scripts
140
141 If you are unsure, try running without any additional fontencodings and
142 read the hints in the error messages.
143 ';
144 } elsif ($topic eq 'commands') {
145 print 'Option --commands <string>:
146
147 The commands given to --commands will be executed as LaTeX-code before
148 rendering the input file.
149
150 You may call --commands several times.
151 ';
152 } elsif ($topic eq 'fontstyle') {
153 print 'Option --fontstyle <string>
154
155 This specifies the style of the fonts which are used to render the document.
156 Available arguments are:
157
158 bold (short: bf)
159 italic (short: it)
160 sansserif (short: sf)
161 slanted (short: sl)
162 smallcaps (short: sc)
163 typewriter (short: tt)
164
165 You may call --fontstyle several times to combine styles. No warning
166 will be uttered, if you choose a disallowed combination like
167 italic and slanted.
168 ';
169 } elsif ($topic eq 'fontstyle') {
170 print 'Option --fontsize <string>
171
172 This specifies the size of the fonts which are used to render the document.
173 Available arguments are:
174
175 tiny scriptsize footnotesize smallcaps normal large Large LARGE huge Huge
176
177 The semantics are as with LaTeX
178 ';
179 } elsif ($topic eq 'r2l') {
180 print "Option --r2l[=<mode>] (default <mode>: $default_r2lmode):".'
181
182 This enables preprocessing the input via the Unicode bidi algorithm to
183 support right-to-left text. <mode> can be one of:
184
185 reorder Reorders the characters of each line into visual order
186 mark Inserts LROs/RLOs/PDFs into the text to indicate the directions
187
188 To use \'reorder\', the program fribidi must be installed and in the
189 path. Combining accents work incorrectly with this mode. Line breaks
190 done by LaTeX may show improper right-to-left behaviour.
191
192 If you use \'mark\', you need to have rlmark in your path. Further
193 e-LaTeX is used instead of LaTeX.
194
195 Each line of the input is processed separately.
196
197 If this option is not given, right-to-left text will be displayed in
198 the wrong direction without warning.
199 ';
200 } elsif ($topic eq 'combine') {
201 print 'Option --combine:
202
203 This enables combining characters. You have to use this option, if
204 your text contains non-precomposed characters, i.e. characters with
205 accents, which are given as a sequence of code positions.
206
207 Warning: Enabling this option will disable kerning and ligatures.
208
209 If you are unsure, wether you need this option, try without. You will
210 get the message
211 ! Package ucs Error: Please activate option \'combine\'.
212 if this option is needed.
213 ';
214 } elsif ($topic eq 'help') {
215 print 'Option --help[=<option>]:
216
217 Gives a summary of options or, with some option name
218 (e.g. --help=r2l), an explanation of that option.
219 ';
220 } elsif ($topic eq 'tolerant') {
221 print 'Option --tolerant[=<replacement>]
222
223 Be tolerant with respect to broken input encodings. This passes the
224 switch -c to iconv(1). Additionally the option warnunknown is passed
225 to LaTeX, i.e. the document is rendered even if unknown characters
226 appear.
227
228 If <replacement> is given, this LaTeX-code is executed in place of
229 unknown characters. #1 gets replaced by the code position of the
230 character (as a TeX-number, prefix by \number if you want to render it).
231 ';
232 } elsif ($topic eq 'charset') {
233 print 'Option --charset=<string> (default: $default_charset):
234
235 Selects the character set of the input. Everything accepted by
236 iconv(1) can be specified. Run iconv -l for a list.
237 ';
238 } else {
239 print "No help provided for given topic\n";
240 }
241 exit 0;
242 }
243
244 sub parseopts() {
245 my %opt;
246 Getopt::Long::Configure(qw/bundling no_ignore_case/);
247 unless (GetOptions(\%opt,qw/
248 fontencs=s@
249 title=s
250 commands=s@
251 fontstyle=s@
252 fontsize=s
253 r2l:s
254 combine
255 help|h:s
256 tolerant:s
257 charset=s
258 options=s@
259 package=s@
260 cleanup!
261 view!
262 print:s
263 escape!
264 /)) {
265 die "Bad command line options";
266 }
267 $view = $opt{view};
268 $print = $opt{print};
269 $perhapsnofile = $view || defined $print;
270 showhelp($opt{help}) if defined $opt{help};
271 if ($#ARGV >= 2) {
272 die "Give input and output file, not more";
273 }
274 $infile = $ARGV[0];
275 $outfile = $ARGV[1];
276 $outfile = "$tmpfile.ps" if ($perhapsnofile && !define $outfile);
277 if (defined $infile && !defined $outfile) {
278 $outfile = $infile;
279 $outfile =~ s/\.[^.]+$//;
280 $outfile .= ".ps";
281 } elsif (!defined $infile) {
282 $infile = "/dev/stdin";
283 $outfile = "/dev/stdout" if !defined $outfile;
284 }
285 if (!-r $infile) {
286 die "Input file $infile is not readable";
287 }
288 $fontencs = join ',', @{$opt{fontencs}} if defined $opt{fontencs};
289 $fontencs = $default_fontencs unless defined $fontencs;
290 $commands = $opt{commands};
291 $commands = [] unless defined $commands;
292
293 my %fontsizes =
294 ('large' => '\large',
295 'Large' => '\Large',
296 'tiny' => '\tiny',
297 'scriptsize' => '\scriptsize',
298 'footnotesize' => '\footnotesize',
299 'normal' => '',
300 'normalfont' => '',
301 'small' => '\small',
302 'huge' => '\huge',
303 'Huge' => '\Huge');
304 my %fontstyles =
305 ('typewriter' => '\ttfamily',
306 'tt' => '\ttfamily',
307 'bold' => '\bfseries',
308 'bf' => '\bfseries',
309 'italic' => '\itshape',
310 'it' => '\itshape',
311 'slanted' => '\slshape',
312 'sl' => '\slshape',
313 'sansserif' => '\sffamily',
314 'sf' => '\sffamily',
315 'smallcaps' => '\scshape',
316 'sc' => '\scshape',
317 );
318 if (defined $opt{fontsize}) {
319 die "Unknown fontsize '$opt{fontsize}'"
320 unless defined $fontsizes{$opt{fontsize}};
321 push @$commands, $fontsizes{$opt{fontsize}};
322 }
323 for my $fs (@{$opt{fontstyle}}) {
324 die "Unknown fontstyle '$fs'"
325 unless defined $fontstyles{$fs};
326 push @$commands, $fontstyles{$fs};
327 }
328 $tolerant = 1 if defined $opt{tolerant};
329 $tolerant_unknownchar = $opt{tolerant} if define($opt{tolerant}) ne '';
330 if ($tolerant_unknownchar) {
331 push @$commands, '\def\unicode@invalidglyph#1{'.
332 $tolerant_unknownchar.'}';
333 }
334 $r2lmode = 'reorder' if defined $opt{r2l} && $opt{r2l} eq '';
335 $r2lmode = $opt{r2l} unless defined $r2lmode;
336 $r2lmode = 'none' unless defined $r2lmode;
337 $combine = '';
338 $combine = '\SetUnicodeOption{combine}' if $opt{combine};
339 $charset = $default_charset;
340 $charset = $opt{charset} if defined $opt{charset};
341 my $options = $opt{options};
342 $options = [] unless defined $options;
343 push @$options, 'warnunknown' if defined $tolerant;
344 $options = join ',',@$options;
345 my $oprio = 99;
346 for my $o (split ',', $options) {
347 my ($on,$prio) = ($o =~ /^(.+?)(?:=([0-9]+))?$/);
348 $prio = $oprio unless defined $prio;
349 push @$commands, "\\SetUnicodeOption[$prio]{$on}";
350 $oprio = $prio-1;
351 }
352 @packages = @{$opt{package}} if $opt{package};
353 $title = $infile;
354 $title = $opt{title} if defined $opt{title};
355 $commands = join "\n", @$commands;
356 $cleanup = $opt{cleanup};
357 $cleanup = 1 unless defined $cleanup;
358 $escape = $opt{escape};
359 }
360
361 $code = '
362 \documentclass{article}
363 \usepackage{ucs}
364 \usepackage[utf8x]{inputenc}
365 \let\oldgimel\gimel
366 \usepackage[@@@[FONTENCS]]{autofe}
367 \let\gimel\oldgimel
368 %\usepackage{verbatim}
369 @@@[PACKAGES]
370 \usepackage{geometry}
371
372 \nofiles
373
374 \makeatletter
375
376 \toks255\expandafter{\try@load@fontshape}
377 \edef\try@load@fontshape{\begingroup\noexpand\uni@resetcatcodes\the\toks255\endgroup}
378
379 \newdimen\parfirst
380 \newdimen\parsecond
381 \newif\ifescape
382
383 \def\setchar#1#2{%
384 \catcode\count255=13\relax
385 \begingroup
386 \uccode`\~#1 %SPACE
387 \uppercase{%
388 \endgroup
389 \edef~}%
390 {#2}}
391
392 \def\escape{\unicodecombine\begingroup\uni@resetcatcodes\@escape}
393 \def\@escape#1{\endgroup#1}
394
395 \def\loadfile{%
396 \bgroup
397 \count255=1
398 \loop\ifnum\count255<128\relax
399 \setchar{\count255}{\noexpand\unichar{\number\count255}}
400 \advance\count255by1\relax
401 \repeat
402 \setchar{13}{\noexpand\unicodecombine
403 \noexpand\noindent
404 \noexpand\null
405 \noexpand\\\\%
406 \noexpand\leavevmode}
407 \setchar{32}{\noexpand\unicodecombine\noexpand\unichar{32}}
408 \setchar{12}{\noexpand\unicodecombine\noexpand\newpage}
409 \setchar{27}{\noexpand\ifescape\noexpand\expandafter\noexpand\escape\noexpand\else\noexpand\unichar{27}\noexpand\fi}
410 @@@[COMBINE]%
411 \input{@@@[FILE]}%
412 \unicodecombine
413 \egroup
414 }
415
416 \def\parindentstuff{%
417 \let\temp@a\undefined
418 \ifnum\parfirst=0\else\let\temp@a1\fi
419 \ifnum\parsecond=0\else\let\temp@a1\fi
420 \ifx\temp@a1%
421 \parindent=\parfirst\advance\parindent by-\parsecond
422 \everypar{%
423 \@tempdima\linewidth\advance\@tempdima by-\parsecond
424 \parshape\@ne\parsecond\@tempdima}
425 \fi
426 }
427
428 \DeclareUnicodeCharacter{9}{\space\space\space\space\space\space\space\space}
429
430 \begin{document}
431
432 \frenchspacing
433 \parindent=0pt
434 \thispagestyle{empty}
435 \raggedright
436 @@@[SWITCHES]
437 @@@[CMDS]
438 \parindentstuff
439 \loadfile
440
441 \end{document}
442 ';
443
444 sub makecode() {
445 my $code = $code;
446 $code =~ s/\Q@@@[FILE]/$tmpfile.txt/;
447 $code =~ s/\Q@@@[FONTENCS]/$fontencs/;
448 $code =~ s/\Q@@@[CMDS]/$commands/;
449 $code =~ s/\Q@@@[COMBINE]/$combine/;
450 my $packages = join "\n", map {
451 my ($opts,$pkg) = /^(?:\[(.*?)\])?\{?(.*?)\}?$/;
452 if (defined $opts) { $opts = "[$opts]" } else { $opts = '' };
453 "\\usepackage${opts}"."{$pkg}";
454 } @packages;
455 $code =~ s/\Q@@@[PACKAGES]/$packages/;
456 my $switches = '';
457 $switches .= '\escapetrue' if $escape;
458 $code =~ s/\Q@@@[SWITCHES]/$switches/;
459 # $code =~ s/\Q@@@[OPTIONS]/$options/;
460 open MASTER, ">$tmpfile.tex" or
461 die "Could not open $tmpfile.tex for writing: $!";
462 print MASTER $code or
463 die "Could not write to $tmpfile.tex";
464 close MASTER;
465 }
466
467 sub _fribidi_call($) {
468 my $option = shift;
469 my $rc = system("$fribidi_cmd $option </dev/null &>/dev/null");
470 die "$fribidi_cmd could not be started: $!" if $rc == -1;
471 $rc /= 256;
472 # print "fribidi $option => $rc\n";
473 return !$rc;
474 }
475
476 sub fribidi_call() {
477 # _fribidi_call('') or
478 # die "$fribidi_cmd cannot be executed";
479 my %opts = (charset => 'UTF-8',
480 nopad => {},
481 nobreak => {},
482 clean => {},
483 swapnsm => {},
484 );
485 my $opts = '';
486 while (my ($k,$v) = each %opts) {
487 $opts .= " --$k"; $opts .= " $v" unless ref $v; };
488 unless (_fribidi_call($opts)) {
489 my $o = '--';
490 _fribidi_call('-charset UTF-8') and $o = '-';
491 for my $a (keys %opts) {
492 unless (_fribidi_call($o.$a.((ref $opts{$a})?'':" $opts{$a}"))) {
493 warn "WARNING: $fribidi_cmd does not support option $o$a";
494 delete $opts{$a};
495 }
496 }
497 $opts = '';
498 while (my ($k,$v) = each %opts) {
499 $opts .= " --$k"; $opts .= " $v" unless ref $v; };
500 }
501 my $cmd = "$fribidi_cmd $opts";
502 #print "[[[$cmd]]]\n";
503 return $cmd;
504 }
505
506 sub copyfile() {
507 my @ops;
508 # <''\Q$infile\E >$tmpfile.txt
509 push @ops, "cat <''\Q$infile\E";
510 if ($charset ne 'utf-8' || $tolerant) {
511 my $c = '';
512 $c = '-c' if $tolerant;
513 push @ops, "iconv $c -f ''\Q$charset\E -t utf-8";
514 }
515 if ($r2lmode eq 'none') {
516 } elsif ($r2lmode eq 'reorder') {
517 # push @ops, "fribidi --nopad --nobreak ".
518 # "--charset UTF-8 --clean";
519 push @ops, fribidi_call();
520 } elsif ($r2lmode eq 'mark') {
521 push @ops, "rlmark";
522 } else {
523 die "Internal error: Unknown R2L mode '$r2lmode'";
524 }
525 my $cmd = (join ' | ', @ops)." >\Q$tmpfile.txt\E";
526 system($cmd) and
527 die "Could not copy/convert file using\n$cmd";
528 }
529
530 sub latex() {
531 makecode;
532 copyfile;
533 my $latex = 'latex';
534 $latex = 'elatex' if ($r2lmode eq 'mark');
535 system("$latex -interaction nonstopmode ''\Q$tmpfile.tex\E >/dev/stderr")
536 and die "$latex returned an error";
537 # system("cat $tmpfile.tex >/dev/stderr");
538 my $t = $title; $t =~ s/\\/\\\\/g; $t =~ s/[^\x20-\x7e\xa0-\xff]/
539 sprintf "\\%03o", ord($&)/gei;
540 system("dvips -o /dev/stdout ''\Q$tmpfile.dvi\E | ".
541 "sed -e 's/^%%Title: .*\\.dvi\$/%%Title: \Q$t\E/' ".
542 " -e 's/^%%Creator: /%%Creator: u2ps and /' ".
543 ">''\Q$outfile\E") and
544 die "dvips returned an error";
545 }
546
547 sub view() {
548 my $cmd = "gv -antialias -watch ''\Q$outfile\E";
549 system($cmd) and
550 die "Could not run '$cmd'";
551 }
552
553 sub printfile() {
554 my $printer = '';
555 $printer = "-P $print" unless $print eq '';
556 my $cmd = "lpr $printer -J ''\Q$title\E ''\Q$outfile\E";
557 system($cmd) and
558 die "Could not run '$cmd'";
559 }
560
561 sub cleanup() {
562 my $suffixes = 'dvi,log,tex,txt';
563 $suffixes .= ',ps' if $outfile eq "$tmpfile.ps";
564 system("rm $tmpfile.{$suffixes} >/dev/stderr") and
565 die "Could not clean up";
566 }
567
568 sub main() {
569 parseopts;
570 latex;
571 view if $view;
572 printfile if defined $print;
573 cleanup if $cleanup;
574 }
575
576 &main;